text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { arrayBuffer } from "stream/consumers"; import { ReadableStream } from "stream/web"; import { TextDecoder, TextEncoder } from "util"; import { Clock, Storage, StoredKeyMeta, assertInRequest, defaultClock, millisToSeconds, viewToArray, viewToBuffer, waitForOpenInputGate, waitForOpenOutputGate, } from "@miniflare/shared"; const MIN_CACHE_TTL = 60; /* 60s */ const MAX_LIST_KEYS = 1000; const MAX_KEY_SIZE = 512; /* 512B */ const MAX_VALUE_SIZE = 25 * 1024 * 1024; /* 25MiB */ const MAX_METADATA_SIZE = 1024; /* 1KiB */ const keyTypeError = " on 'KvNamespace': parameter 1 is not of type 'string'."; const encoder = new TextEncoder(); const decoder = new TextDecoder(); export type KVValue<Value> = Promise<Value | null>; export type KVValueMeta<Value, Meta> = Promise<{ value: Value | null; metadata: Meta | null; }>; export type KVGetValueType = "text" | "json" | "arrayBuffer" | "stream"; export type KVGetOptions<Type extends KVGetValueType = KVGetValueType> = { type: Type; cacheTtl?: number; }; const getValueTypes = new Set(["text", "json", "arrayBuffer", "stream"]); export type KVPutValueType = | string | ArrayBuffer | ArrayBufferView | ReadableStream; export interface KVPutOptions<Meta = unknown> { expiration?: string | number; expirationTtl?: string | number; metadata?: Meta; } export interface KVListOptions { prefix?: string; limit?: number; cursor?: string; } export interface KVListResult<Meta = unknown> { keys: StoredKeyMeta<Meta>[]; cursor: string; list_complete: boolean; } type Method = "GET" | "PUT" | "DELETE"; function throwKVError(method: Method, status: number, message: string) { throw new Error(`KV ${method} failed: ${status} ${message}`); } function validateKey(method: Method, key: string): void { // Check key name is allowed if (key === "") throw new TypeError("Key name cannot be empty."); if (key === ".") throw new TypeError('"." is not allowed as a key name.'); if (key === "..") throw new TypeError('".." is not allowed as a key name.'); // Check key isn't too long const keyLength = encoder.encode(key).byteLength; if (keyLength > MAX_KEY_SIZE) { throwKVError( method, 414, `UTF-8 encoded length of ${keyLength} exceeds key length limit of ${MAX_KEY_SIZE}.` ); } } /** * Normalises type, ignoring cacheTtl as there is only one "edge location": * the user's computer */ function validateGetOptions( options?: KVGetValueType | Partial<KVGetOptions> ): KVGetValueType { const string = typeof options === "string"; const type = string ? options : options?.type ?? "text"; const cacheTtl = string ? undefined : options?.cacheTtl; if (cacheTtl && (isNaN(cacheTtl) || cacheTtl < MIN_CACHE_TTL)) { throwKVError( "GET", 400, `Invalid cache_ttl of ${cacheTtl}. Cache TTL must be at least ${MIN_CACHE_TTL}.` ); } if (!getValueTypes.has(type)) { throw new TypeError( 'Unknown response type. Possible types are "text", "arrayBuffer", "json", and "stream".' ); } return type; } /** Returns value as an integer or undefined if it isn't one */ function normaliseInt(value: string | number | undefined): number | undefined { switch (typeof value) { case "string": return parseInt(value); case "number": return Math.round(value); } } function convertStoredToGetValue(stored: Uint8Array, type: KVGetValueType) { switch (type) { case "text": return decoder.decode(stored); case "arrayBuffer": return viewToBuffer(stored); case "json": return JSON.parse(decoder.decode(stored)); case "stream": return new ReadableStream<Uint8Array>({ type: "bytes" as any, // Delay enqueuing chunk until it's actually requested so we can wait // for the input gate to open before delivering it async pull(controller) { await waitForOpenInputGate(); controller.enqueue(stored); controller.close(); }, }); } } export interface InternalKVNamespaceOptions { clock?: Clock; blockGlobalAsyncIO?: boolean; } export class KVNamespace { readonly #storage: Storage; readonly #clock: Clock; readonly #blockGlobalAsyncIO: boolean; constructor( storage: Storage, { clock = defaultClock, blockGlobalAsyncIO = false, }: InternalKVNamespaceOptions = {} ) { this.#storage = storage; this.#clock = clock; this.#blockGlobalAsyncIO = blockGlobalAsyncIO; } get( key: string, options?: "text" | Partial<KVGetOptions<"text">> ): KVValue<string>; get<Value = unknown>( key: string, options: "json" | KVGetOptions<"json"> ): KVValue<Value>; get( key: string, options: "arrayBuffer" | KVGetOptions<"arrayBuffer"> ): KVValue<ArrayBuffer>; get( key: string, options: "stream" | KVGetOptions<"stream"> ): KVValue<ReadableStream<Uint8Array>>; async get<Value = unknown>( key: string, options?: KVGetValueType | Partial<KVGetOptions> ): KVValue<KVPutValueType | Value> { if (this.#blockGlobalAsyncIO) assertInRequest(); // noinspection SuspiciousTypeOfGuard if (typeof key !== "string") { throw new TypeError("Failed to execute 'get'" + keyTypeError); } // Validate key and options validateKey("GET", key); const type = validateGetOptions(options); // Get value without metadata, returning null if not found const stored = await this.#storage.get(key, true); await waitForOpenInputGate(); if (stored === undefined) return null; // Return correctly typed value return convertStoredToGetValue(stored.value, type); } getWithMetadata<Metadata = unknown>( key: string, options?: "text" | Partial<KVGetOptions<"text">> ): KVValueMeta<string, Metadata>; getWithMetadata<Value = unknown, Metadata = unknown>( key: string, options: "json" | KVGetOptions<"json"> ): KVValueMeta<Value, Metadata>; getWithMetadata<Metadata = unknown>( key: string, options: "arrayBuffer" | KVGetOptions<"arrayBuffer"> ): KVValueMeta<ArrayBuffer, Metadata>; getWithMetadata<Metadata = unknown>( key: string, options: "stream" | KVGetOptions<"stream"> ): KVValueMeta<ReadableStream<Uint8Array>, Metadata>; async getWithMetadata<Value = unknown, Metadata = unknown>( key: string, options?: KVGetValueType | Partial<KVGetOptions> ): KVValueMeta<KVPutValueType | Value, Metadata> { if (this.#blockGlobalAsyncIO) assertInRequest(); // noinspection SuspiciousTypeOfGuard if (typeof key !== "string") { throw new TypeError("Failed to execute 'getWithMetadata'" + keyTypeError); } // Validate key and options validateKey("GET", key); const type = validateGetOptions(options); // Get value with metadata, returning nulls if not found const storedValue = await this.#storage.get<Metadata>(key); await waitForOpenInputGate(); if (storedValue === undefined) return { value: null, metadata: null }; const { value, metadata = null } = storedValue; // Return correctly typed value with metadata return { value: convertStoredToGetValue(value, type), metadata }; } async put<Meta = unknown>( key: string, value: KVPutValueType, options: KVPutOptions<Meta> = {} ): Promise<void> { if (this.#blockGlobalAsyncIO) assertInRequest(); // noinspection SuspiciousTypeOfGuard if (typeof key !== "string") { throw new TypeError("Failed to execute 'put'" + keyTypeError); } validateKey("PUT", key); // Convert value to Uint8Array let stored: Uint8Array; if (typeof value === "string") { stored = encoder.encode(value); } else if (value instanceof ReadableStream) { // @ts-expect-error @types/node stream/consumers doesn't accept ReadableStream stored = new Uint8Array(await arrayBuffer(value)); } else if (value instanceof ArrayBuffer) { stored = new Uint8Array(value); } else if (ArrayBuffer.isView(value)) { stored = viewToArray(value); } else { throw new TypeError( "KV put() accepts only strings, ArrayBuffers, ArrayBufferViews, and ReadableStreams as values." ); } // Normalise and validate expiration const now = millisToSeconds(this.#clock()); let expiration = normaliseInt(options.expiration); const expirationTtl = normaliseInt(options.expirationTtl); if (expirationTtl !== undefined) { if (isNaN(expirationTtl) || expirationTtl <= 0) { throwKVError( "PUT", 400, `Invalid expiration_ttl of ${options.expirationTtl}. Please specify integer greater than 0.` ); } if (expirationTtl < MIN_CACHE_TTL) { throwKVError( "PUT", 400, `Invalid expiration_ttl of ${options.expirationTtl}. Expiration TTL must be at least ${MIN_CACHE_TTL}.` ); } expiration = now + expirationTtl; } else if (expiration !== undefined) { if (isNaN(expiration) || expiration <= now) { throwKVError( "PUT", 400, `Invalid expiration of ${options.expiration}. Please specify integer greater than the current number of seconds since the UNIX epoch.` ); } if (expiration < now + MIN_CACHE_TTL) { throwKVError( "PUT", 400, `Invalid expiration of ${options.expiration}. Expiration times must be at least ${MIN_CACHE_TTL} seconds in the future.` ); } } // Validate value and metadata size if (stored.byteLength > MAX_VALUE_SIZE) { throwKVError( "PUT", 413, `Value length of ${stored.byteLength} exceeds limit of ${MAX_VALUE_SIZE}.` ); } const metadataLength = options.metadata && encoder.encode(JSON.stringify(options.metadata)).byteLength; if (metadataLength && metadataLength > MAX_METADATA_SIZE) { throwKVError( "PUT", 413, `Metadata length of ${metadataLength} exceeds limit of ${MAX_METADATA_SIZE}.` ); } // Store value with expiration and metadata await waitForOpenOutputGate(); await this.#storage.put(key, { value: stored, expiration, metadata: options.metadata, }); await waitForOpenInputGate(); } async delete(key: string): Promise<void> { if (this.#blockGlobalAsyncIO) assertInRequest(); // noinspection SuspiciousTypeOfGuard if (typeof key !== "string") { throw new TypeError("Failed to execute 'delete'" + keyTypeError); } validateKey("DELETE", key); await waitForOpenOutputGate(); await this.#storage.delete(key); await waitForOpenInputGate(); } async list<Meta = unknown>({ prefix = "", limit = MAX_LIST_KEYS, cursor, }: KVListOptions = {}): Promise<KVListResult<Meta>> { if (this.#blockGlobalAsyncIO) assertInRequest(); // Validate options if (isNaN(limit) || limit < 1) { throwKVError( "GET", 400, `Invalid key_count_limit of ${limit}. Please specify an integer greater than 0.` ); } if (limit > MAX_LIST_KEYS) { throwKVError( "GET", 400, `Invalid key_count_limit of ${limit}. Please specify an integer less than ${MAX_LIST_KEYS}.` ); } const res = await this.#storage.list<Meta>({ prefix, limit, cursor }); await waitForOpenInputGate(); return { keys: res.keys, cursor: res.cursor, list_complete: res.cursor === "", }; } }
the_stack
import { Dictionary, ArrayLike, KeyOfDistributive } from './types'; import { GradientObject } from '../graphic/Gradient'; import { ImagePatternObject } from '../graphic/Pattern'; // 用于处理merge时无法遍历Date等对象的问题 const BUILTIN_OBJECT: {[key: string]: boolean} = { '[object Function]': true, '[object RegExp]': true, '[object Date]': true, '[object Error]': true, '[object CanvasGradient]': true, '[object CanvasPattern]': true, // For node-canvas '[object Image]': true, '[object Canvas]': true }; const TYPED_ARRAY: {[key: string]: boolean} = { '[object Int8Array]': true, '[object Uint8Array]': true, '[object Uint8ClampedArray]': true, '[object Int16Array]': true, '[object Uint16Array]': true, '[object Int32Array]': true, '[object Uint32Array]': true, '[object Float32Array]': true, '[object Float64Array]': true }; const objToString = Object.prototype.toString; const arrayProto = Array.prototype; const nativeForEach = arrayProto.forEach; const nativeFilter = arrayProto.filter; const nativeSlice = arrayProto.slice; const nativeMap = arrayProto.map; // In case some env may redefine the global variable `Function`. const ctorFunction = function () {}.constructor; const protoFunction = ctorFunction ? ctorFunction.prototype : null; const protoKey = '__proto__'; // Avoid assign to an exported constiable, for transforming to cjs. const methods: {[key: string]: Function} = {}; export function $override(name: string, fn: Function) { methods[name] = fn; } let idStart = 0x0907; /** * Generate unique id */ export function guid(): number { return idStart++; } export function logError(...args: any[]) { if (typeof console !== 'undefined') { console.error.apply(console, args); } } /** * Those data types can be cloned: * Plain object, Array, TypedArray, number, string, null, undefined. * Those data types will be assgined using the orginal data: * BUILTIN_OBJECT * Instance of user defined class will be cloned to a plain object, without * properties in prototype. * Other data types is not supported (not sure what will happen). * * Caution: do not support clone Date, for performance consideration. * (There might be a large number of date in `series.data`). * So date should not be modified in and out of echarts. */ export function clone<T extends any>(source: T): T { if (source == null || typeof source !== 'object') { return source; } let result = source as any; const typeStr = <string>objToString.call(source); if (typeStr === '[object Array]') { if (!isPrimitive(source)) { result = [] as any; for (let i = 0, len = (source as any[]).length; i < len; i++) { result[i] = clone((source as any[])[i]); } } } else if (TYPED_ARRAY[typeStr]) { if (!isPrimitive(source)) { /* eslint-disable-next-line */ const Ctor = source.constructor as typeof Float32Array; if (Ctor.from) { result = Ctor.from(source as Float32Array); } else { result = new Ctor((source as Float32Array).length); for (let i = 0, len = (source as Float32Array).length; i < len; i++) { result[i] = clone((source as Float32Array)[i]); } } } } else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) { result = {} as any; for (let key in source) { // Check if key is __proto__ to avoid prototype pollution if (source.hasOwnProperty(key) && key !== protoKey) { result[key] = clone(source[key]); } } } return result; } export function merge< T extends Dictionary<any>, S extends Dictionary<any> >(target: T, source: S, overwrite?: boolean): T & S; export function merge< T extends any, S extends any >(target: T, source: S, overwrite?: boolean): T | S; export function merge(target: any, source: any, overwrite?: boolean): any { // We should escapse that source is string // and enter for ... in ... if (!isObject(source) || !isObject(target)) { return overwrite ? clone(source) : target; } for (let key in source) { // Check if key is __proto__ to avoid prototype pollution if (source.hasOwnProperty(key) && key !== protoKey) { const targetProp = target[key]; const sourceProp = source[key]; if (isObject(sourceProp) && isObject(targetProp) && !isArray(sourceProp) && !isArray(targetProp) && !isDom(sourceProp) && !isDom(targetProp) && !isBuiltInObject(sourceProp) && !isBuiltInObject(targetProp) && !isPrimitive(sourceProp) && !isPrimitive(targetProp) ) { // 如果需要递归覆盖,就递归调用merge merge(targetProp, sourceProp, overwrite); } else if (overwrite || !(key in target)) { // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况 // NOTE,在 target[key] 不存在的时候也是直接覆盖 target[key] = clone(source[key]); } } } return target; } /** * @param targetAndSources The first item is target, and the rests are source. * @param overwrite * @return Merged result */ export function mergeAll(targetAndSources: any[], overwrite?: boolean): any { let result = targetAndSources[0]; for (let i = 1, len = targetAndSources.length; i < len; i++) { result = merge(result, targetAndSources[i], overwrite); } return result; } export function extend< T extends Dictionary<any>, S extends Dictionary<any> >(target: T, source: S): T & S { // @ts-ignore if (Object.assign) { // @ts-ignore Object.assign(target, source); } else { for (let key in source) { // Check if key is __proto__ to avoid prototype pollution if (source.hasOwnProperty(key) && key !== protoKey) { (target as S & T)[key] = (source as T & S)[key]; } } } return target as T & S; } export function defaults< T extends Dictionary<any>, S extends Dictionary<any> >(target: T, source: S, overlay?: boolean): T & S { const keysArr = keys(source); for (let i = 0; i < keysArr.length; i++) { let key = keysArr[i]; if ((overlay ? source[key] != null : (target as T & S)[key] == null)) { (target as S & T)[key] = (source as T & S)[key]; } } return target as T & S; } export const createCanvas = function (): HTMLCanvasElement { return methods.createCanvas(); }; methods.createCanvas = function (): HTMLCanvasElement { return document.createElement('canvas'); }; /** * 查询数组中元素的index */ export function indexOf<T>(array: T[] | readonly T[] | ArrayLike<T>, value: T): number { if (array) { if ((array as T[]).indexOf) { return (array as T[]).indexOf(value); } for (let i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } } return -1; } /** * 构造类继承关系 * * @param clazz 源类 * @param baseClazz 基类 */ export function inherits(clazz: Function, baseClazz: Function) { const clazzPrototype = clazz.prototype; function F() {} F.prototype = baseClazz.prototype; clazz.prototype = new (F as any)(); for (let prop in clazzPrototype) { if (clazzPrototype.hasOwnProperty(prop)) { clazz.prototype[prop] = clazzPrototype[prop]; } } clazz.prototype.constructor = clazz; (clazz as any).superClass = baseClazz; } export function mixin<T, S>(target: T | Function, source: S | Function, override?: boolean) { target = 'prototype' in target ? target.prototype : target; source = 'prototype' in source ? source.prototype : source; // If build target is ES6 class. prototype methods is not enumerable. Use getOwnPropertyNames instead // TODO: Determine if source is ES6 class? if (Object.getOwnPropertyNames) { const keyList = Object.getOwnPropertyNames(source); for (let i = 0; i < keyList.length; i++) { const key = keyList[i]; if (key !== 'constructor') { if ((override ? (source as any)[key] != null : (target as any)[key] == null)) { (target as any)[key] = (source as any)[key]; } } } } else { defaults(target, source, override); } } /** * Consider typed array. * @param data */ export function isArrayLike(data: any): data is ArrayLike<any> { if (!data) { return false; } if (typeof data === 'string') { return false; } return typeof data.length === 'number'; } /** * 数组或对象遍历 */ export function each<I extends Dictionary<any> | any[] | readonly any[] | ArrayLike<any>, Context>( arr: I, cb: ( this: Context, // Use unknown to avoid to infer to "any", which may disable typo check. value: I extends (infer T)[] | readonly (infer T)[] | ArrayLike<infer T> ? T // Use Dictionary<infer T> may cause infer fail when I is an interface. // So here use a Record to infer type. : I extends Dictionary<any> ? I extends Record<infer K, infer T> ? T : unknown : unknown, index?: I extends any[] | readonly any[] | ArrayLike<any> ? number : keyof I & string, // keyof Dictionary will return number | string arr?: I ) => void, context?: Context ) { if (!(arr && cb)) { return; } if ((arr as any).forEach && (arr as any).forEach === nativeForEach) { (arr as any).forEach(cb, context); } else if (arr.length === +arr.length) { for (let i = 0, len = arr.length; i < len; i++) { // FIXME: should the elided item be travelled? like `[33,,55]`. cb.call(context, (arr as any[])[i], i as any, arr); } } else { for (let key in arr) { if (arr.hasOwnProperty(key)) { cb.call(context, (arr as Dictionary<any>)[key], key as any, arr); } } } } /** * Array mapping. * @typeparam T Type in Array * @typeparam R Type Returned * @return Must be an array. */ export function map<T, R, Context>( arr: readonly T[], cb: (this: Context, val: T, index?: number, arr?: readonly T[]) => R, context?: Context ): R[] { // Take the same behavior with lodash when !arr and !cb, // which might be some common sense. if (!arr) { return []; } if (!cb) { return slice(arr) as unknown[] as R[]; } if (arr.map && arr.map === nativeMap) { return arr.map(cb, context); } else { const result = []; for (let i = 0, len = arr.length; i < len; i++) { // FIXME: should the elided item be travelled, like `[33,,55]`. result.push(cb.call(context, arr[i], i, arr)); } return result; } } export function reduce<T, S, Context>( arr: readonly T[], cb: (this: Context, previousValue: S, currentValue: T, currentIndex?: number, arr?: readonly T[]) => S, memo?: S, context?: Context ): S { if (!(arr && cb)) { return; } for (let i = 0, len = arr.length; i < len; i++) { memo = cb.call(context, memo, arr[i], i, arr); } return memo; } /** * Array filtering. * @return Must be an array. */ export function filter<T, Context>( arr: readonly T[], cb: (this: Context, value: T, index: number, arr: readonly T[]) => boolean, context?: Context ): T[] { // Take the same behavior with lodash when !arr and !cb, // which might be some common sense. if (!arr) { return []; } if (!cb) { return slice(arr); } if (arr.filter && arr.filter === nativeFilter) { return arr.filter(cb, context); } else { const result = []; for (let i = 0, len = arr.length; i < len; i++) { // FIXME: should the elided items be travelled? like `[33,,55]`. if (cb.call(context, arr[i], i, arr)) { result.push(arr[i]); } } return result; } } /** * 数组项查找 */ export function find<T, Context>( arr: readonly T[], cb: (this: Context, value: T, index?: number, arr?: readonly T[]) => boolean, context?: Context ): T { if (!(arr && cb)) { return; } for (let i = 0, len = arr.length; i < len; i++) { if (cb.call(context, arr[i], i, arr)) { return arr[i]; } } } /** * Get all object keys * * Will return an empty array if obj is null/undefined */ export function keys<T extends object>(obj: T): (KeyOfDistributive<T> & string)[] { if (!obj) { return []; } // Return type should be `keyof T` but exclude `number`, becuase // `Object.keys` only return string rather than `number | string`. type TKeys = KeyOfDistributive<T> & string; if (Object.keys) { return Object.keys(obj) as TKeys[]; } let keyList: TKeys[] = []; for (let key in obj) { if (obj.hasOwnProperty(key)) { keyList.push(key as any); } } return keyList; } // Remove this type in returned function. Or it will conflicts wicth callback with given context. Like Eventful. // According to lib.es5.d.ts /* eslint-disable max-len*/ export type Bind1<F, Ctx> = F extends (this: Ctx, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Bind2<F, Ctx, T1> = F extends (this: Ctx, a: T1, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Bind3<F, Ctx, T1, T2> = F extends (this: Ctx, a: T1, b: T2, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Bind4<F, Ctx, T1, T2, T3> = F extends (this: Ctx, a: T1, b: T2, c: T3, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Bind5<F, Ctx, T1, T2, T3, T4> = F extends (this: Ctx, a: T1, b: T2, c: T3, d: T4, ...args: infer A) => infer R ? (...args: A) => R : unknown; type BindFunc<Ctx> = (this: Ctx, ...arg: any[]) => any interface FunctionBind { <F extends BindFunc<Ctx>, Ctx>(func: F, ctx: Ctx): Bind1<F, Ctx> <F extends BindFunc<Ctx>, Ctx, T1 extends Parameters<F>[0]>(func: F, ctx: Ctx, a: T1): Bind2<F, Ctx, T1> <F extends BindFunc<Ctx>, Ctx, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1]>(func: F, ctx: Ctx, a: T1, b: T2): Bind3<F, Ctx, T1, T2> <F extends BindFunc<Ctx>, Ctx, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1], T3 extends Parameters<F>[2]>(func: F, ctx: Ctx, a: T1, b: T2, c: T3): Bind4<F, Ctx, T1, T2, T3> <F extends BindFunc<Ctx>, Ctx, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1], T3 extends Parameters<F>[2], T4 extends Parameters<F>[3]>(func: F, ctx: Ctx, a: T1, b: T2, c: T3, d: T4): Bind5<F, Ctx, T1, T2, T3, T4> } function bindPolyfill<Ctx, Fn extends(...args: any) => any>( func: Fn, context: Ctx, ...args: any[] ): (...args: Parameters<Fn>) => ReturnType<Fn> { return function (this: Ctx) { return func.apply(context, args.concat(nativeSlice.call(arguments))); }; } export const bind: FunctionBind = (protoFunction && isFunction(protoFunction.bind)) ? protoFunction.call.bind(protoFunction.bind) : bindPolyfill; export type Curry1<F, T1> = F extends (a: T1, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Curry2<F, T1, T2> = F extends (a: T1, b: T2, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Curry3<F, T1, T2, T3> = F extends (a: T1, b: T2, c: T3, ...args: infer A) => infer R ? (...args: A) => R : unknown; export type Curry4<F, T1, T2, T3, T4> = F extends (a: T1, b: T2, c: T3, d: T4, ...args: infer A) => infer R ? (...args: A) => R : unknown; type CurryFunc = (...arg: any[]) => any function curry<F extends CurryFunc, T1 extends Parameters<F>[0]>(func: F, a: T1): Curry1<F, T1> function curry<F extends CurryFunc, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1]>(func: F, a: T1, b: T2): Curry2<F, T1, T2> function curry<F extends CurryFunc, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1], T3 extends Parameters<F>[2]>(func: F, a: T1, b: T2, c: T3): Curry3<F, T1, T2, T3> function curry<F extends CurryFunc, T1 extends Parameters<F>[0], T2 extends Parameters<F>[1], T3 extends Parameters<F>[2], T4 extends Parameters<F>[3]>(func: F, a: T1, b: T2, c: T3, d: T4): Curry4<F, T1, T2, T3, T4> function curry(func: Function, ...args: any[]): Function { return function (this: any) { return func.apply(this, args.concat(nativeSlice.call(arguments))); }; } export {curry}; /* eslint-enable max-len*/ export function isArray(value: any): value is any[] { if (Array.isArray) { return Array.isArray(value); } return objToString.call(value) === '[object Array]'; } export function isFunction(value: any): value is Function { return typeof value === 'function'; } export function isString(value: any): value is string { // Faster than `objToString.call` several times in chromium and webkit. // And `new String()` is rarely used. return typeof value === 'string'; } export function isStringSafe(value: any): value is string { return objToString.call(value) === '[object String]'; } export function isNumber(value: any): value is number { // Faster than `objToString.call` several times in chromium and webkit. // And `new Number()` is rarely used. return typeof value === 'number'; } // Usage: `isObject(xxx)` or `isObject(SomeType)(xxx)` // Generic T can be used to avoid "ts type gruards" casting the `value` from its original // type `Object` implicitly so that loose its original type info in the subsequent code. export function isObject<T = unknown>(value: T): value is (object & T) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. const type = typeof value; return type === 'function' || (!!value && type === 'object'); } export function isBuiltInObject(value: any): boolean { return !!BUILTIN_OBJECT[objToString.call(value)]; } export function isTypedArray(value: any): boolean { return !!TYPED_ARRAY[objToString.call(value)]; } export function isDom(value: any): value is HTMLElement { return typeof value === 'object' && typeof value.nodeType === 'number' && typeof value.ownerDocument === 'object'; } export function isGradientObject(value: any): value is GradientObject { return (value as GradientObject).colorStops != null; } export function isImagePatternObject(value: any): value is ImagePatternObject { return (value as ImagePatternObject).image != null; } export function isRegExp(value: unknown): value is RegExp { return objToString.call(value) === '[object RegExp]'; } /** * Whether is exactly NaN. Notice isNaN('a') returns true. */ export function eqNaN(value: any): boolean { /* eslint-disable-next-line no-self-compare */ return value !== value; } /** * If value1 is not null, then return value1, otherwise judget rest of values. * Low performance. * @return Final value */ export function retrieve<T>(...args: T[]): T { for (let i = 0, len = args.length; i < len; i++) { if (args[i] != null) { return args[i]; } } } export function retrieve2<T, R>(value0: T, value1: R): T | R { return value0 != null ? value0 : value1; } export function retrieve3<T, R, W>(value0: T, value1: R, value2: W): T | R | W { return value0 != null ? value0 : value1 != null ? value1 : value2; } type SliceParams = Parameters<typeof nativeSlice>; export function slice<T>(arr: ArrayLike<T>, ...args: SliceParams): T[] { return nativeSlice.apply(arr, args as any[]); } /** * Normalize css liked array configuration * e.g. * 3 => [3, 3, 3, 3] * [4, 2] => [4, 2, 4, 2] * [4, 3, 2] => [4, 3, 2, 3] */ export function normalizeCssArray(val: number | number[]) { if (typeof (val) === 'number') { return [val, val, val, val]; } const len = val.length; if (len === 2) { // vertical | horizontal return [val[0], val[1], val[0], val[1]]; } else if (len === 3) { // top | horizontal | bottom return [val[0], val[1], val[2], val[1]]; } return val; } export function assert(condition: any, message?: string) { if (!condition) { throw new Error(message); } } /** * @param str string to be trimed * @return trimed string */ export function trim(str: string): string { if (str == null) { return null; } else if (typeof str.trim === 'function') { return str.trim(); } else { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } } const primitiveKey = '__ec_primitive__'; /** * Set an object as primitive to be ignored traversing children in clone or merge */ export function setAsPrimitive(obj: any) { obj[primitiveKey] = true; } export function isPrimitive(obj: any): boolean { return obj[primitiveKey]; } /** * @constructor * @param {Object} obj Only apply `ownProperty`. */ export class HashMap<T, KEY extends string | number = string | number> { data: {[key in KEY]: T} = {} as {[key in KEY]: T}; constructor(obj?: HashMap<T, KEY> | { [key in KEY]?: T } | KEY[]) { const isArr = isArray(obj); // Key should not be set on this, otherwise // methods get/set/... may be overrided. this.data = {} as {[key in KEY]: T}; const thisMap = this; (obj instanceof HashMap) ? obj.each(visit) : (obj && each(obj, visit)); function visit(value: any, key: any) { isArr ? thisMap.set(value, key) : thisMap.set(key, value); } } // Do not provide `has` method to avoid defining what is `has`. // (We usually treat `null` and `undefined` as the same, different // from ES6 Map). get(key: KEY): T { return this.data.hasOwnProperty(key) ? this.data[key] : null; } set(key: KEY, value: T): T { // Comparing with invocation chaining, `return value` is more commonly // used in this case: `const someVal = map.set('a', genVal());` return (this.data[key] = value); } // Although util.each can be performed on this hashMap directly, user // should not use the exposed keys, who are prefixed. each<Context>( cb: (this: Context, value?: T, key?: KEY) => void, context?: Context ) { for (let key in this.data) { if (this.data.hasOwnProperty(key)) { cb.call(context, this.data[key], key); } } } keys(): KEY[] { return keys(this.data); } // Do not use this method if performance sensitive. removeKey(key: KEY) { delete this.data[key]; } } export function createHashMap<T, KEY extends string | number = string | number>( obj?: HashMap<T, KEY> | { [key in KEY]?: T } | KEY[] ) { return new HashMap<T, KEY>(obj); } export function concatArray<T, R>(a: ArrayLike<T>, b: ArrayLike<R>): ArrayLike<T | R> { const newArray = new (a as any).constructor(a.length + b.length); for (let i = 0; i < a.length; i++) { newArray[i] = a[i]; } const offset = a.length; for (let i = 0; i < b.length; i++) { newArray[i + offset] = b[i]; } return newArray; } export function createObject<T>(proto?: object, properties?: T): T { // Performance of Object.create // https://jsperf.com/style-strategy-proto-or-others let obj: T; if (Object.create) { obj = Object.create(proto); } else { const StyleCtor = function () {}; StyleCtor.prototype = proto; obj = new (StyleCtor as any)(); } if (properties) { extend(obj, properties); } return obj; } export function hasOwn(own: object, prop: string): boolean { return own.hasOwnProperty(prop); } export function noop() {}
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * An Anthos node pool running on Azure. * * For more information, see: * * [Multicloud overview](https://cloud.google.com/anthos/clusters/docs/multi-cloud) * ## Example Usage * ### Basic_azure_node_pool * A basic example of a containerazure azure node pool * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const versions = gcp.container.getAzureVersions({ * project: "my-project-name", * location: "us-west1", * }); * const basic = new gcp.container.AzureClient("basic", { * applicationId: "12345678-1234-1234-1234-123456789111", * location: "us-west1", * tenantId: "12345678-1234-1234-1234-123456789111", * project: "my-project-name", * }); * const primaryAzureCluster = new gcp.container.AzureCluster("primaryAzureCluster", { * authorization: { * adminUsers: [{ * username: "mmv2@google.com", * }], * }, * azureRegion: "westus2", * client: pulumi.interpolate`projects/my-project-number/locations/us-west1/azureClients/${basic.name}`, * controlPlane: { * sshConfig: { * authorizedKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers", * }, * subnetId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-byo/providers/Microsoft.Network/virtualNetworks/my--dev-vnet/subnets/default", * version: versions.then(versions => versions.validVersions?[0]), * }, * fleet: { * project: "my-project-number", * }, * location: "us-west1", * networking: { * podAddressCidrBlocks: ["10.200.0.0/16"], * serviceAddressCidrBlocks: ["10.32.0.0/24"], * virtualNetworkId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-byo/providers/Microsoft.Network/virtualNetworks/my--dev-vnet", * }, * resourceGroupId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-cluster", * project: "my-project-name", * }); * const primaryAzureNodePool = new gcp.container.AzureNodePool("primaryAzureNodePool", { * autoscaling: { * maxNodeCount: 3, * minNodeCount: 2, * }, * cluster: primaryAzureCluster.name, * config: { * sshConfig: { * authorizedKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers", * }, * rootVolume: { * sizeGib: 32, * }, * tags: { * owner: "mmv2", * }, * vmSize: "Standard_DS2_v2", * }, * location: "us-west1", * maxPodsConstraint: { * maxPodsPerNode: 110, * }, * subnetId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-byo/providers/Microsoft.Network/virtualNetworks/my--dev-vnet/subnets/default", * version: versions.then(versions => versions.validVersions?[0]), * annotations: { * "annotation-one": "value-one", * }, * project: "my-project-name", * }); * ``` * * ## Import * * NodePool can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:container/azureNodePool:AzureNodePool default projects/{{project}}/locations/{{location}}/azureClusters/{{cluster}}/azureNodePools/{{name}} * ``` * * ```sh * $ pulumi import gcp:container/azureNodePool:AzureNodePool default {{project}}/{{location}}/{{cluster}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:container/azureNodePool:AzureNodePool default {{location}}/{{cluster}}/{{name}} * ``` */ export class AzureNodePool extends pulumi.CustomResource { /** * Get an existing AzureNodePool resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: AzureNodePoolState, opts?: pulumi.CustomResourceOptions): AzureNodePool { return new AzureNodePool(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:container/azureNodePool:AzureNodePool'; /** * Returns true if the given object is an instance of AzureNodePool. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is AzureNodePool { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AzureNodePool.__pulumiType; } /** * Optional. Annotations on the node pool. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ public readonly annotations!: pulumi.Output<{[key: string]: string} | undefined>; /** * Required. Autoscaler configuration for this node pool. */ public readonly autoscaling!: pulumi.Output<outputs.container.AzureNodePoolAutoscaling>; /** * Optional. The Azure availability zone of the nodes in this nodepool. When unspecified, it defaults to `1`. */ public readonly azureAvailabilityZone!: pulumi.Output<string>; /** * The azureCluster for the resource */ public readonly cluster!: pulumi.Output<string>; /** * Required. The node configuration of the node pool. */ public readonly config!: pulumi.Output<outputs.container.AzureNodePoolConfig>; /** * Output only. The time at which this node pool was created. */ public /*out*/ readonly createTime!: pulumi.Output<string>; /** * Allows clients to perform consistent read-modify-writes through optimistic concurrency control. May be sent on update * and delete requests to ensure the client has an up-to-date value before proceeding. */ public /*out*/ readonly etag!: pulumi.Output<string>; /** * The location for the resource */ public readonly location!: pulumi.Output<string>; /** * Required. The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool. */ public readonly maxPodsConstraint!: pulumi.Output<outputs.container.AzureNodePoolMaxPodsConstraint>; /** * The name of this resource. */ public readonly name!: pulumi.Output<string>; /** * The project for the resource */ public readonly project!: pulumi.Output<string>; /** * Output only. If set, there are currently pending changes to the node pool. */ public /*out*/ readonly reconciling!: pulumi.Output<boolean>; /** * Output only. The current state of the node pool. Possible values: STATE_UNSPECIFIED, PROVISIONING, RUNNING, RECONCILING, * STOPPING, ERROR, DEGRADED */ public /*out*/ readonly state!: pulumi.Output<string>; /** * Required. The ARM ID of the subnet where the node pool VMs run. Make sure it's a subnet under the virtual network in the cluster configuration. */ public readonly subnetId!: pulumi.Output<string>; /** * Output only. A globally unique identifier for the node pool. */ public /*out*/ readonly uid!: pulumi.Output<string>; /** * Output only. The time at which this node pool was last updated. */ public /*out*/ readonly updateTime!: pulumi.Output<string>; /** * Required. The Kubernetes version (e.g. `1.19.10-gke.1000`) running on this node pool. */ public readonly version!: pulumi.Output<string>; /** * Create a AzureNodePool resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: AzureNodePoolArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AzureNodePoolArgs | AzureNodePoolState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AzureNodePoolState | undefined; inputs["annotations"] = state ? state.annotations : undefined; inputs["autoscaling"] = state ? state.autoscaling : undefined; inputs["azureAvailabilityZone"] = state ? state.azureAvailabilityZone : undefined; inputs["cluster"] = state ? state.cluster : undefined; inputs["config"] = state ? state.config : undefined; inputs["createTime"] = state ? state.createTime : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["location"] = state ? state.location : undefined; inputs["maxPodsConstraint"] = state ? state.maxPodsConstraint : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["reconciling"] = state ? state.reconciling : undefined; inputs["state"] = state ? state.state : undefined; inputs["subnetId"] = state ? state.subnetId : undefined; inputs["uid"] = state ? state.uid : undefined; inputs["updateTime"] = state ? state.updateTime : undefined; inputs["version"] = state ? state.version : undefined; } else { const args = argsOrState as AzureNodePoolArgs | undefined; if ((!args || args.autoscaling === undefined) && !opts.urn) { throw new Error("Missing required property 'autoscaling'"); } if ((!args || args.cluster === undefined) && !opts.urn) { throw new Error("Missing required property 'cluster'"); } if ((!args || args.config === undefined) && !opts.urn) { throw new Error("Missing required property 'config'"); } if ((!args || args.location === undefined) && !opts.urn) { throw new Error("Missing required property 'location'"); } if ((!args || args.maxPodsConstraint === undefined) && !opts.urn) { throw new Error("Missing required property 'maxPodsConstraint'"); } if ((!args || args.subnetId === undefined) && !opts.urn) { throw new Error("Missing required property 'subnetId'"); } if ((!args || args.version === undefined) && !opts.urn) { throw new Error("Missing required property 'version'"); } inputs["annotations"] = args ? args.annotations : undefined; inputs["autoscaling"] = args ? args.autoscaling : undefined; inputs["azureAvailabilityZone"] = args ? args.azureAvailabilityZone : undefined; inputs["cluster"] = args ? args.cluster : undefined; inputs["config"] = args ? args.config : undefined; inputs["location"] = args ? args.location : undefined; inputs["maxPodsConstraint"] = args ? args.maxPodsConstraint : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["subnetId"] = args ? args.subnetId : undefined; inputs["version"] = args ? args.version : undefined; inputs["createTime"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["reconciling"] = undefined /*out*/; inputs["state"] = undefined /*out*/; inputs["uid"] = undefined /*out*/; inputs["updateTime"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AzureNodePool.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AzureNodePool resources. */ export interface AzureNodePoolState { /** * Optional. Annotations on the node pool. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Required. Autoscaler configuration for this node pool. */ autoscaling?: pulumi.Input<inputs.container.AzureNodePoolAutoscaling>; /** * Optional. The Azure availability zone of the nodes in this nodepool. When unspecified, it defaults to `1`. */ azureAvailabilityZone?: pulumi.Input<string>; /** * The azureCluster for the resource */ cluster?: pulumi.Input<string>; /** * Required. The node configuration of the node pool. */ config?: pulumi.Input<inputs.container.AzureNodePoolConfig>; /** * Output only. The time at which this node pool was created. */ createTime?: pulumi.Input<string>; /** * Allows clients to perform consistent read-modify-writes through optimistic concurrency control. May be sent on update * and delete requests to ensure the client has an up-to-date value before proceeding. */ etag?: pulumi.Input<string>; /** * The location for the resource */ location?: pulumi.Input<string>; /** * Required. The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool. */ maxPodsConstraint?: pulumi.Input<inputs.container.AzureNodePoolMaxPodsConstraint>; /** * The name of this resource. */ name?: pulumi.Input<string>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Output only. If set, there are currently pending changes to the node pool. */ reconciling?: pulumi.Input<boolean>; /** * Output only. The current state of the node pool. Possible values: STATE_UNSPECIFIED, PROVISIONING, RUNNING, RECONCILING, * STOPPING, ERROR, DEGRADED */ state?: pulumi.Input<string>; /** * Required. The ARM ID of the subnet where the node pool VMs run. Make sure it's a subnet under the virtual network in the cluster configuration. */ subnetId?: pulumi.Input<string>; /** * Output only. A globally unique identifier for the node pool. */ uid?: pulumi.Input<string>; /** * Output only. The time at which this node pool was last updated. */ updateTime?: pulumi.Input<string>; /** * Required. The Kubernetes version (e.g. `1.19.10-gke.1000`) running on this node pool. */ version?: pulumi.Input<string>; } /** * The set of arguments for constructing a AzureNodePool resource. */ export interface AzureNodePoolArgs { /** * Optional. Annotations on the node pool. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Required. Autoscaler configuration for this node pool. */ autoscaling: pulumi.Input<inputs.container.AzureNodePoolAutoscaling>; /** * Optional. The Azure availability zone of the nodes in this nodepool. When unspecified, it defaults to `1`. */ azureAvailabilityZone?: pulumi.Input<string>; /** * The azureCluster for the resource */ cluster: pulumi.Input<string>; /** * Required. The node configuration of the node pool. */ config: pulumi.Input<inputs.container.AzureNodePoolConfig>; /** * The location for the resource */ location: pulumi.Input<string>; /** * Required. The constraint on the maximum number of pods that can be run simultaneously on a node in the node pool. */ maxPodsConstraint: pulumi.Input<inputs.container.AzureNodePoolMaxPodsConstraint>; /** * The name of this resource. */ name?: pulumi.Input<string>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Required. The ARM ID of the subnet where the node pool VMs run. Make sure it's a subnet under the virtual network in the cluster configuration. */ subnetId: pulumi.Input<string>; /** * Required. The Kubernetes version (e.g. `1.19.10-gke.1000`) running on this node pool. */ version: pulumi.Input<string>; }
the_stack
import { Editor as CoreEditor } from "slate"; import EditTable from 'slate-uui-table-plugin'; import * as React from "react"; import { Table } from "./Table"; import { TableRow } from "./TableRow"; import { TableCell } from "./TableCell"; import { TableHeaderCell } from "./TableHeaderCell"; import { Editor } from "slate-react"; import { ReactComponent as TableIcon } from "../../icons/table-add.svg"; import { ToolbarButton } from '../../implementation/ToolbarButton'; import {getBlockDesirialiser, isTextSelected} from '../../helpers'; import { mergeCellsPlugin } from '../tableMergePlugin/tableMergePlugin'; export const tablePlugin = () => { const editTable = EditTable(); const renderBlock = (props: any, editor: CoreEditor, next: () => any) => { switch (props.node.type) { case 'table': return <Table { ...props } editor={ editor } />; case 'table_row': return <TableRow { ...props } />; case 'table_cell': return <TableCell { ...props } editor={ editor } />; case 'table_header_cell': return <TableHeaderCell { ...props } editor={ editor } />; } return next(); }; const onKeyDown = (event: KeyboardEvent, editor: Editor, next: () => any) => { let parentNode: any = editor.value.document.getParent(editor.value.focusBlock.key); if ((event.key === 'Backspace' || event.key === 'Delete') && parentNode.type === 'table_cell' && parentNode.nodes.toArray().length === 1 && editor.value.focusBlock.text === '') { return; } next(); }; const getCellIndex = (editor: any, elem: any) => { let counter = 0; let elemPosition = 0; const elemParent = editor.value.document.getParent(elem.key); (editor.value.document as any).getParent(elemParent.key).nodes.forEach((elem: any) => { elem.key === elemParent.key ? elemPosition = counter : counter += 1; }); return elemPosition; }; // Add new column to the table on correct new column position const addNewColumn = (editor: CoreEditor, props: any, position?: 'before' | 'after') => { let startBlockIndex = getCellIndex(editor, editor.value.startBlock); const parentElem: any = editor.value.document.getParent(editor.value.document.getPath(editor.value.startBlock.key)); if (position !== 'before') { startBlockIndex++; } if (parentElem.data !== undefined && parentElem.data.get('colSpan') > 1 && position !== 'before') { startBlockIndex += parentElem.data.get('colSpan') - 1; } (editor as any).insertColumn(startBlockIndex, {typeHeaderCell: 'table_header_cell'}); }; const removeSelectedColumn = (editor: CoreEditor, props: any) => { let startBlockIndex = getCellIndex(editor, editor.value.startBlock); const selectedCell: any = editor.value.document.getParent(editor.value.document.getPath(editor.value.startBlock.key)); const selectedRow: any = editor.value.document.getParent(editor.value.document.getPath(selectedCell.key)); const selectedTable: any = editor.value.document.getParent(editor.value.document.getPath(selectedRow.key)); let cellColspan = selectedCell.data.get('colSpan'); if (selectedRow.nodes.size === 1) { return; } if (cellColspan > 1) { for (let i = 0; i < cellColspan; i++) { (editor as any).removeColumn(startBlockIndex); } } else { selectedTable.nodes.toArray().map((row: any) => { row.nodes.toArray().map((cell: any, cellIndex: number, rows: any[]) => { let colspan = cell.data.get('colSpan'); if (startBlockIndex === cellIndex && colspan > 1) { let nextCell = rows[cellIndex + 1]; editor.setNodeByKey(nextCell.key, { ...nextCell, data: { colSpan: colspan - 1, }, }); } else if (colspan > 1 && (startBlockIndex > cellIndex && startBlockIndex < cellIndex + colspan)) { editor.setNodeByKey(cell.key, { ...cell, data: { colSpan: colspan - 1, }, }); } }); }); let cellSizes = selectedTable.data.get('cellSizes').filter((item: any, index: number) => index != startBlockIndex); const newData = selectedTable.data.set('cellSizes', cellSizes); editor.setNodeByKey(selectedTable.key, { ...selectedTable as any, data: newData, }); (editor as any).removeColumn(startBlockIndex); } }; // Add new row to the table on correct new row position const getRowIndex = (editor: any) => { let rowSpanIndex = 0; let rowIndex = 0; const selectedCell: any = editor.value.document.getParent(editor.value.document.getPath(editor.value.startBlock.key)); const selectedRow: any = editor.value.document.getParent(editor.value.document.getPath(selectedCell.key)); const selectedTable: any = editor.value.document.getParent(editor.value.document.getPath(selectedRow.key)); for (let i = 0; i < selectedTable.nodes.toArray().length; i++) { if (selectedTable.nodes.toArray()[i].key === selectedRow.key) { rowIndex = i; } } for (let i = 0; i < selectedRow.nodes.toArray().length; i++) { if (selectedRow.nodes.toArray()[i].data !== undefined && selectedRow.nodes.toArray()[i].data.get('rowSpan') > 1 && selectedRow.nodes.toArray()[i].data.get('rowSpan') > rowSpanIndex) { rowSpanIndex = selectedRow.nodes.toArray()[i].data.get('rowSpan'); } } return { rowIndex, rowSpanIndex, }; }; // Add new row to the table on correct new row position const addNewRow = (editor: CoreEditor, props: any, position?: 'before' | 'after') => { let { rowIndex, rowSpanIndex } = getRowIndex(editor); const selectedCell: any = editor.value.document.getParent(editor.value.document.getPath(editor.value.startBlock.key)); const selectedRow: any = editor.value.document.getParent(editor.value.document.getPath(selectedCell.key)); const selectedTable: any = editor.value.document.getParent(editor.value.document.getPath(selectedRow.key)); let currentRowIndex = rowIndex; let maxRowClospan = 1; let shouldHideCells = false; if (position === 'before' && selectedCell.type === 'table_header_cell' && selectedTable.nodes.size === 1) { return; } while (selectedTable.nodes.toArray()[currentRowIndex].nodes.toArray().some((item: any) => item.data.get('style') === 'none') && currentRowIndex > 0) { currentRowIndex--; } if (currentRowIndex !== rowIndex) { selectedTable.nodes.toArray()[currentRowIndex].nodes.toArray().map((item: any) => { let cellRowSpan = item.data.get('rowSpan'); let isArterPasteValid = position !== 'before' && cellRowSpan > rowIndex - currentRowIndex + 1; let isBeforePasteValid = position === 'before' && cellRowSpan > rowIndex - currentRowIndex; if (cellRowSpan && (isArterPasteValid || isBeforePasteValid)) { editor.setNodeByKey(item.key, { ...item, data: { rowSpan: cellRowSpan + 1, }, }); shouldHideCells = true; } }); } else { selectedRow.nodes.toArray().map((item: any) => { let cellRowSpan = item.data.get('rowSpan'); if (cellRowSpan && cellRowSpan > 1 && position !== 'before') { editor.setNodeByKey(item.key, { ...item, data: { rowSpan: cellRowSpan + 1, }, }); shouldHideCells = true; } }); } position !== 'before' ? rowIndex += rowSpanIndex : null; let insertIndex = position === 'before' ? rowIndex : rowIndex + 1; let editorAfterInsert = insertIndex === 0 && selectedCell.type === 'table_cell' ? (editor as any).insertHeaderRow(insertIndex) : selectedCell.type === 'table_header_cell' && selectedTable.nodes.toArray()[rowIndex + 1] ? (editor as any).insertHeaderRow(insertIndex) : (editor as any).insertRow(insertIndex); if (shouldHideCells) { const currentCell: any = editorAfterInsert.value.document.getParent(editorAfterInsert.value.document.getPath(editorAfterInsert.value.anchorBlock.key)); const newRow: any = editorAfterInsert.value.document.getParent(editorAfterInsert.value.document.getPath(currentCell.key)); newRow.nodes.toArray().map((item: any, index: number) => { if (index < maxRowClospan) { editor.setNodeByKey(item.key, { ...item, data: { style: 'none', }, }); } }); } }; const removeSelectedRow = (editor: CoreEditor, props: any) => { let { rowIndex } = getRowIndex(editor); const selectedCell: any = editor.value.document.getParent(editor.value.document.getPath(editor.value.startBlock.key)); let rowSpanIndex = selectedCell.data.get('rowSpan'); const selectedRow: any = editor.value.document.getParent(editor.value.document.getPath(selectedCell.key)); const selectedTable: any = editor.value.document.getParent(editor.value.document.getPath(selectedRow.key)); if (selectedTable.nodes.size === 1) { return; } if (rowSpanIndex > 1) { for (let i = 0; i < rowSpanIndex; i++) { (editor as any).removeRow(rowIndex); } } else { let currentRowIndex = rowIndex; while (selectedTable.nodes.toArray()[currentRowIndex].nodes.toArray().some((item: any) => item.data.get('style') === 'none')) { currentRowIndex--; } if (currentRowIndex !== rowIndex) { selectedTable.nodes.toArray()[currentRowIndex].nodes.toArray().map((item: any) => { let cellRowSpan = item.data.get('rowSpan'); cellRowSpan && cellRowSpan > 1 ? editor.setNodeByKey(item.key, { ...item, data: { rowSpan: cellRowSpan - 1, }, }) : null; }); } else { let rowSpansInRow: any[] = []; let rowSpansInRowIndex: any[] = []; selectedRow.nodes.toArray().map((item: any, index: number) => { let cellRowSpan = item.data.get('rowSpan'); if (cellRowSpan > 1) { rowSpansInRow.push(cellRowSpan); rowSpansInRowIndex.push(index); } }); if (rowSpansInRow.length > 0) { let nextRow = selectedTable.nodes.toArray()[rowIndex + 1]; rowSpansInRowIndex.map((rowIndex: any, arrayIndex: number) => { editor.setNodeByKey(nextRow.nodes.toArray()[rowIndex].key, { ...nextRow.nodes.toArray()[rowIndex], data: { rowSpan: rowSpansInRow[arrayIndex] - 1, }, }); }); } } (editor as any).removeRow(rowIndex); } }; const insertTableIn = (editor: CoreEditor) => { const currentKey = editor.value.focusBlock.key; (editor as any).insertEmptyBlock(); (editor as any).insertTableByKey(currentKey, 0, 2, 2); }; return { ...editTable, ...mergeCellsPlugin(), normalizeNode: null, schema: null, renderBlock, sidebarButtons: [TableButton], onKeyDown, commands: { ...editTable.commands, addNewColumn, addNewRow, removeSelectedRow, removeSelectedColumn, insertTableIn, }, serializers: [tableCellDesializer, tableDesializer, tableHeaderCellDesializer], makeSerializerRules: null, }; }; export const TableButton = (props: { editor: Editor }) => { return <ToolbarButton isDisabled={ isTextSelected(props.editor) } onClick={ () => ((props.editor as any).insertTableIn()) } icon={ TableIcon } />; }; const TABLE_TAGS: any = { table: 'table', tr: 'table_row', }; const tableCellDesializer = (el: any, next: any) => { if (el.tagName.toLowerCase() === 'td') { return { object: 'block', type: 'table_cell', nodes: next(el.childNodes), data: { colSpan: el.getAttribute('colspan'), rowSpan: el.getAttribute('rowspan'), }, }; } }; const tableHeaderCellDesializer = (el: any, next: any) => { if (el.tagName.toLowerCase() === 'th') { return { object: 'block', type: 'table_header_cell', nodes: next(el.childNodes), data: { colSpan: el.getAttribute('colspan'), rowSpan: el.getAttribute('rowspan'), }, }; } }; const tableDesializer = getBlockDesirialiser(TABLE_TAGS);
the_stack
import { StyleBuilderDefinitions, StaticStyles } from "./types"; import { StyleSheet } from "react-native"; import { UnionToIntersection } from "utility-types"; export class DefinitionKebabCase { protected startIndex: number = -1; constructor(protected readonly definition: string) {} peek(): string { const index = this.definition.indexOf("-", this.startIndex + 1); if (index < 0) { return this.definition.slice(this.startIndex + 1); } return this.definition.slice(this.startIndex + 1, index); } read(): string { const index = this.definition.indexOf("-", this.startIndex + 1); if (index < 0) { return this.flush(); } const result = this.definition.slice(this.startIndex + 1, index); this.startIndex = index; return result; } flush(): string { const result = this.definition.slice(this.startIndex + 1); this.startIndex = this.definition.length - 1; return result; } segments(): string[] { return this.definition.split("-"); } reset() { this.startIndex = -1; } } export class StyleBuilder< Custom extends Record<string, unknown>, Colors extends Record<string, string>, Widths extends Record<string, string | number>, Heights extends Record<string, string | number>, PaddingSizes extends Record<string, string | number>, MarginSizes extends Record<string, string | number>, BorderWidths extends Record<string, number>, BorderRadiuses extends Record<string, number>, Opacities extends Record<string, number> > { protected static readonly ReservedWords: { [word: string]: boolean | undefined; } = { color: true, padding: true, margin: true, top: true, bottom: true, left: true, right: true, x: true, y: true, width: true, height: true, radius: true, flex: true, min: true, max: true, opacity: true, solid: true, dotted: true, dashed: true, }; static readonly checkReservedWord = (config: Record<string, any>) => { for (const key in config) { const segments = new DefinitionKebabCase(key).segments(); for (const segment of segments) { if (StyleBuilder.ReservedWords[segment]) { throw new Error(`Confg (${key}) has reserved word (${segment})`); } } } }; protected readonly staticStyles: Record<string, unknown>; protected readonly cached: Map<string, any> = new Map(); constructor( protected readonly configs: { custom: Custom; colors: Colors; widths: Widths; heights: Heights; paddingSizes: PaddingSizes; marginSizes: MarginSizes; borderWidths: BorderWidths; borderRadiuses: BorderRadiuses; opacities: Opacities; } ) { // TODO: Disable checking on the production environment. // Don't need to check the static styles because it is prioritized than dynamic styles. StyleBuilder.checkReservedWord(configs.colors); StyleBuilder.checkReservedWord(configs.widths); StyleBuilder.checkReservedWord(configs.heights); StyleBuilder.checkReservedWord(configs.paddingSizes); StyleBuilder.checkReservedWord(configs.marginSizes); StyleBuilder.checkReservedWord(configs.borderWidths); StyleBuilder.checkReservedWord(configs.borderRadiuses); StyleBuilder.checkReservedWord(configs.opacities); this.staticStyles = { ...configs.custom, ...StaticStyles, }; } flatten< D extends StyleBuilderDefinitions< Custom, Colors, Widths, Heights, PaddingSizes, MarginSizes, BorderWidths, BorderRadiuses, Opacities >, K extends keyof D >(definitions: K[]): UnionToIntersection<D[K]>; flatten< D extends StyleBuilderDefinitions< Custom, Colors, Widths, Heights, PaddingSizes, MarginSizes, BorderWidths, BorderRadiuses, Opacities >, K extends keyof D, ConditionalK extends keyof D >( definitions: K[], conditionalDefinitions: (ConditionalK | null | undefined | boolean)[] ): UnionToIntersection<D[K]> & Partial<UnionToIntersection<D[ConditionalK]>>; flatten< D extends StyleBuilderDefinitions< Custom, Colors, Widths, Heights, PaddingSizes, MarginSizes, BorderWidths, BorderRadiuses, Opacities >, K extends keyof D, ConditionalK extends keyof D >( definitions: K[], conditionalDefinitions: (ConditionalK | null | undefined | boolean)[] = [] ): UnionToIntersection<D[K]> & Partial<UnionToIntersection<D[ConditionalK]>> { const styles: any[] = []; for (const definition of definitions) { styles.push(this.get<D, K>(definition)); } for (const definition of conditionalDefinitions) { if (definition && definition !== true) { styles.push(this.get<D, K>((definition as unknown) as K)); } } return StyleSheet.flatten(styles); } get< D extends StyleBuilderDefinitions< Custom, Colors, Widths, Heights, PaddingSizes, MarginSizes, BorderWidths, BorderRadiuses, Opacities >, K extends keyof D >(definition: K): D[K] { return this.getAndCache(definition as string, this.compute); } protected readonly compute = (definition: string): any => { if (definition in this.staticStyles) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return this.staticStyles[definition]; } const segment = new DefinitionKebabCase(definition as string); switch (segment.read()) { case "color": return { color: this.configs.colors[segment.flush()], }; case "background": if (segment.read() === "color") { return { backgroundColor: this.configs.colors[segment.flush()], }; } throw new Error(`Failed to get style of ${definition}`); case "width": return { width: this.configs.widths[segment.flush()], }; case "height": return { height: this.configs.heights[segment.flush()], }; case "min": switch (segment.read()) { case "width": return { minWidth: this.configs.widths[segment.flush()], }; case "height": return { minHeight: this.configs.heights[segment.flush()], }; } throw new Error(`Failed to get style of ${definition}`); case "max": switch (segment.read()) { case "width": return { maxWidth: this.configs.widths[segment.flush()], }; case "height": return { maxHeight: this.configs.heights[segment.flush()], }; } throw new Error(`Failed to get style of ${definition}`); case "border": switch (segment.read()) { case "color": return { borderColor: this.configs.colors[segment.flush()], }; case "width": switch (segment.peek()) { case "left": segment.read(); return { borderLeftWidth: this.configs.borderWidths[segment.flush()], }; case "right": segment.read(); return { borderRightWidth: this.configs.borderWidths[segment.flush()], }; case "top": segment.read(); return { borderTopWidth: this.configs.borderWidths[segment.flush()], }; case "bottom": segment.read(); return { borderBottomWidth: this.configs.borderWidths[segment.flush()], }; } return { borderWidth: this.configs.borderWidths[segment.flush()], }; case "radius": switch (segment.peek()) { case "top": segment.read(); switch (segment.read()) { case "left": { return { borderTopLeftRadius: this.configs.borderRadiuses[ segment.flush() ], }; } case "right": { return { borderTopRightRadius: this.configs.borderRadiuses[ segment.flush() ], }; } } throw new Error(`Failed to get style of ${definition}`); case "bottom": segment.read(); switch (segment.read()) { case "left": { return { borderBottomLeftRadius: this.configs.borderRadiuses[ segment.flush() ], }; } case "right": { return { borderBottomRightRadius: this.configs.borderRadiuses[ segment.flush() ], }; } } throw new Error(`Failed to get style of ${definition}`); } const borderRadius = this.configs.borderRadiuses[segment.flush()]; return { borderTopLeftRadius: borderRadius, borderTopRightRadius: borderRadius, borderBottomLeftRadius: borderRadius, borderBottomRightRadius: borderRadius, }; } throw new Error(`Failed to get style of ${definition}`); case "padding": switch (segment.peek()) { case "left": segment.read(); return { paddingLeft: this.configs.paddingSizes[segment.flush()], }; case "right": segment.read(); return { paddingRight: this.configs.paddingSizes[segment.flush()], }; case "top": segment.read(); return { paddingTop: this.configs.paddingSizes[segment.flush()], }; case "bottom": segment.read(); return { paddingBottom: this.configs.paddingSizes[segment.flush()], }; case "x": segment.read(); const keyX = segment.flush(); return { paddingLeft: this.configs.paddingSizes[keyX], paddingRight: this.configs.paddingSizes[keyX], }; case "y": segment.read(); const keyY = segment.flush(); return { paddingTop: this.configs.paddingSizes[keyY], paddingBottom: this.configs.paddingSizes[keyY], }; } const padding = this.configs.paddingSizes[segment.flush()]; return { paddingTop: padding, paddingBottom: padding, paddingLeft: padding, paddingRight: padding, }; case "margin": switch (segment.peek()) { case "left": segment.read(); return { marginLeft: this.configs.marginSizes[segment.flush()], }; case "right": segment.read(); return { marginRight: this.configs.marginSizes[segment.flush()], }; case "top": segment.read(); return { marginTop: this.configs.marginSizes[segment.flush()], }; case "bottom": segment.read(); return { marginBottom: this.configs.marginSizes[segment.flush()], }; case "x": segment.read(); const keyX = segment.flush(); return { marginLeft: this.configs.marginSizes[keyX], marginRight: this.configs.marginSizes[keyX], }; case "y": segment.read(); const keyY = segment.flush(); return { marginTop: this.configs.marginSizes[keyY], marginBottom: this.configs.marginSizes[keyY], }; } const margin = this.configs.marginSizes[segment.flush()]; return { marginTop: margin, marginBottom: margin, marginLeft: margin, marginRight: margin, }; case "opacity": return { opacity: this.configs.opacities[segment.flush()], }; } throw new Error(`Failed to get style of ${definition}`); }; protected getAndCache(key: string, creator: (key: string) => any): any { let value = this.cached.get(key); if (value) { return value; } value = creator(key); this.cached.set(key, value); return value; } }
the_stack
import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import * as strings from 'vs/base/common/strings'; import { ITextModel } from 'vs/editor/common/model'; import { DEFAULT_WORD_REGEXP, ensureValidWordDefinition } from 'vs/editor/common/core/wordHelper'; import { EnterAction, FoldingRules, IAutoClosingPair, IndentationRule, LanguageConfiguration, AutoClosingPairs, CharacterPair, ExplicitLanguageConfiguration } from 'vs/editor/common/languages/languageConfiguration'; import { createScopedLineTokens, ScopedLineTokens } from 'vs/editor/common/languages/supports'; import { CharacterPairSupport } from 'vs/editor/common/languages/supports/characterPair'; import { BracketElectricCharacterSupport } from 'vs/editor/common/languages/supports/electricCharacter'; import { IndentRulesSupport } from 'vs/editor/common/languages/supports/indentRules'; import { OnEnterSupport } from 'vs/editor/common/languages/supports/onEnter'; import { RichEditBrackets } from 'vs/editor/common/languages/supports/richEditBrackets'; import { EditorAutoIndentStrategy } from 'vs/editor/common/config/editorOptions'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; import { PLAINTEXT_LANGUAGE_ID } from 'vs/editor/common/languages/modesRegistry'; import { LanguageBracketsConfiguration } from 'vs/editor/common/languages/supports/languageBracketsConfiguration'; /** * Interface used to support insertion of mode specific comments. */ export interface ICommentsConfiguration { lineCommentToken?: string; blockCommentStartToken?: string; blockCommentEndToken?: string; } export interface ILanguageConfigurationService { readonly _serviceBrand: undefined; onDidChange: Event<LanguageConfigurationServiceChangeEvent>; /** * @param priority Use a higher number for higher priority */ register(languageId: string, configuration: LanguageConfiguration, priority?: number): IDisposable; getLanguageConfiguration(languageId: string): ResolvedLanguageConfiguration; } export class LanguageConfigurationServiceChangeEvent { constructor(public readonly languageId: string | undefined) { } public affects(languageId: string): boolean { return !this.languageId ? true : this.languageId === languageId; } } export const ILanguageConfigurationService = createDecorator<ILanguageConfigurationService>('languageConfigurationService'); export class LanguageConfigurationService extends Disposable implements ILanguageConfigurationService { _serviceBrand: undefined; private readonly _registry = this._register(new LanguageConfigurationRegistry()); private readonly onDidChangeEmitter = this._register(new Emitter<LanguageConfigurationServiceChangeEvent>()); public readonly onDidChange = this.onDidChangeEmitter.event; private readonly configurations = new Map<string, ResolvedLanguageConfiguration>(); constructor( @IConfigurationService private readonly configurationService: IConfigurationService, @ILanguageService private readonly languageService: ILanguageService ) { super(); const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys)); this._register(this.configurationService.onDidChangeConfiguration((e) => { const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k) ); const localConfigChanged = e.change.overrides .filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k)) ) .map(([overrideLangName]) => overrideLangName); if (globalConfigChanged) { this.configurations.clear(); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(undefined)); } else { for (const languageId of localConfigChanged) { if (this.languageService.isRegisteredLanguageId(languageId)) { this.configurations.delete(languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId)); } } } })); this._register(this._registry.onDidChange((e) => { this.configurations.delete(e.languageId); this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId)); })); } public register(languageId: string, configuration: LanguageConfiguration, priority?: number): IDisposable { return this._registry.register(languageId, configuration, priority); } public getLanguageConfiguration(languageId: string): ResolvedLanguageConfiguration { let result = this.configurations.get(languageId); if (!result) { result = computeConfig(languageId, this._registry, this.configurationService, this.languageService); this.configurations.set(languageId, result); } return result; } } function computeConfig( languageId: string, registry: LanguageConfigurationRegistry, configurationService: IConfigurationService, languageService: ILanguageService, ): ResolvedLanguageConfiguration { let languageConfig = registry.getLanguageConfiguration(languageId); if (!languageConfig) { if (!languageService.isRegisteredLanguageId(languageId)) { throw new Error(`Language id "${languageId}" is not configured nor known`); } languageConfig = new ResolvedLanguageConfiguration(languageId, {}); } const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService); const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]); const config = new ResolvedLanguageConfiguration(languageConfig.languageId, data); return config; } const customizedLanguageConfigKeys = { brackets: 'editor.language.brackets', colorizedBracketPairs: 'editor.language.colorizedBracketPairs' }; function getCustomizedLanguageConfig(languageId: string, configurationService: IConfigurationService): LanguageConfiguration { const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, { overrideIdentifier: languageId, }); const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, { overrideIdentifier: languageId, }); return { brackets: validateBracketPairs(brackets), colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs), }; } function validateBracketPairs(data: unknown): CharacterPair[] | undefined { if (!Array.isArray(data)) { return undefined; } return data.map(pair => { if (!Array.isArray(pair) || pair.length !== 2) { return undefined; } return [pair[0], pair[1]] as CharacterPair; }).filter((p): p is CharacterPair => !!p); } export function getIndentationAtPosition(model: ITextModel, lineNumber: number, column: number): string { const lineText = model.getLineContent(lineNumber); let indentation = strings.getLeadingWhitespace(lineText); if (indentation.length > column - 1) { indentation = indentation.substring(0, column - 1); } return indentation; } export function getScopedLineTokens(model: ITextModel, lineNumber: number, columnNumber?: number): ScopedLineTokens { model.tokenization.forceTokenization(lineNumber); const lineTokens = model.tokenization.getLineTokens(lineNumber); const column = (typeof columnNumber === 'undefined' ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1); return createScopedLineTokens(lineTokens, column); } class ComposedLanguageConfiguration { private readonly _entries: LanguageConfigurationContribution[]; private _order: number; private _resolved: ResolvedLanguageConfiguration | null = null; constructor(public readonly languageId: string) { this._entries = []; this._order = 0; this._resolved = null; } public register( configuration: LanguageConfiguration, priority: number ): IDisposable { const entry = new LanguageConfigurationContribution( configuration, priority, ++this._order ); this._entries.push(entry); this._resolved = null; return toDisposable(() => { for (let i = 0; i < this._entries.length; i++) { if (this._entries[i] === entry) { this._entries.splice(i, 1); this._resolved = null; break; } } }); } public getResolvedConfiguration(): ResolvedLanguageConfiguration | null { if (!this._resolved) { const config = this._resolve(); if (config) { this._resolved = new ResolvedLanguageConfiguration( this.languageId, config ); } } return this._resolved; } private _resolve(): LanguageConfiguration | null { if (this._entries.length === 0) { return null; } this._entries.sort(LanguageConfigurationContribution.cmp); return combineLanguageConfigurations(this._entries.map(e => e.configuration)); } } function combineLanguageConfigurations(configs: LanguageConfiguration[]): LanguageConfiguration { let result: ExplicitLanguageConfiguration = { comments: undefined, brackets: undefined, wordPattern: undefined, indentationRules: undefined, onEnterRules: undefined, autoClosingPairs: undefined, surroundingPairs: undefined, autoCloseBefore: undefined, folding: undefined, colorizedBracketPairs: undefined, __electricCharacterSupport: undefined, }; for (const entry of configs) { result = { comments: entry.comments || result.comments, brackets: entry.brackets || result.brackets, wordPattern: entry.wordPattern || result.wordPattern, indentationRules: entry.indentationRules || result.indentationRules, onEnterRules: entry.onEnterRules || result.onEnterRules, autoClosingPairs: entry.autoClosingPairs || result.autoClosingPairs, surroundingPairs: entry.surroundingPairs || result.surroundingPairs, autoCloseBefore: entry.autoCloseBefore || result.autoCloseBefore, folding: entry.folding || result.folding, colorizedBracketPairs: entry.colorizedBracketPairs || result.colorizedBracketPairs, __electricCharacterSupport: entry.__electricCharacterSupport || result.__electricCharacterSupport, }; } return result; } class LanguageConfigurationContribution { constructor( public readonly configuration: LanguageConfiguration, public readonly priority: number, public readonly order: number ) { } public static cmp(a: LanguageConfigurationContribution, b: LanguageConfigurationContribution) { if (a.priority === b.priority) { // higher order last return a.order - b.order; } // higher priority last return a.priority - b.priority; } } export class LanguageConfigurationChangeEvent { constructor(public readonly languageId: string) { } } export class LanguageConfigurationRegistry extends Disposable { private readonly _entries = new Map<string, ComposedLanguageConfiguration>(); private readonly _onDidChange = this._register(new Emitter<LanguageConfigurationChangeEvent>()); public readonly onDidChange: Event<LanguageConfigurationChangeEvent> = this._onDidChange.event; constructor() { super(); this._register(this.register(PLAINTEXT_LANGUAGE_ID, { brackets: [ ['(', ')'], ['[', ']'], ['{', '}'], ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '<', close: '>' }, { open: '\"', close: '\"' }, { open: '\'', close: '\'' }, { open: '`', close: '`' }, ], colorizedBracketPairs: [], folding: { offSide: true } }, 0)); } /** * @param priority Use a higher number for higher priority */ public register(languageId: string, configuration: LanguageConfiguration, priority: number = 0): IDisposable { let entries = this._entries.get(languageId); if (!entries) { entries = new ComposedLanguageConfiguration(languageId); this._entries.set(languageId, entries); } const disposable = entries.register(configuration, priority); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); return toDisposable(() => { disposable.dispose(); this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId)); }); } public getLanguageConfiguration(languageId: string): ResolvedLanguageConfiguration | null { const entries = this._entries.get(languageId); return entries?.getResolvedConfiguration() || null; } } /** * Immutable. */ export class ResolvedLanguageConfiguration { private _brackets: RichEditBrackets | null; private _electricCharacter: BracketElectricCharacterSupport | null; private readonly _onEnterSupport: OnEnterSupport | null; public readonly comments: ICommentsConfiguration | null; public readonly characterPair: CharacterPairSupport; public readonly wordDefinition: RegExp; public readonly indentRulesSupport: IndentRulesSupport | null; public readonly indentationRules: IndentationRule | undefined; public readonly foldingRules: FoldingRules; public readonly bracketsNew: LanguageBracketsConfiguration; constructor( public readonly languageId: string, public readonly underlyingConfig: LanguageConfiguration ) { this._brackets = null; this._electricCharacter = null; this._onEnterSupport = this.underlyingConfig.brackets || this.underlyingConfig.indentationRules || this.underlyingConfig.onEnterRules ? new OnEnterSupport(this.underlyingConfig) : null; this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig); this.characterPair = new CharacterPairSupport(this.underlyingConfig); this.wordDefinition = this.underlyingConfig.wordPattern || DEFAULT_WORD_REGEXP; this.indentationRules = this.underlyingConfig.indentationRules; if (this.underlyingConfig.indentationRules) { this.indentRulesSupport = new IndentRulesSupport( this.underlyingConfig.indentationRules ); } else { this.indentRulesSupport = null; } this.foldingRules = this.underlyingConfig.folding || {}; this.bracketsNew = new LanguageBracketsConfiguration( languageId, this.underlyingConfig ); } public getWordDefinition(): RegExp { return ensureValidWordDefinition(this.wordDefinition); } public get brackets(): RichEditBrackets | null { if (!this._brackets && this.underlyingConfig.brackets) { this._brackets = new RichEditBrackets( this.languageId, this.underlyingConfig.brackets ); } return this._brackets; } public get electricCharacter(): BracketElectricCharacterSupport | null { if (!this._electricCharacter) { this._electricCharacter = new BracketElectricCharacterSupport( this.brackets ); } return this._electricCharacter; } public onEnter( autoIndent: EditorAutoIndentStrategy, previousLineText: string, beforeEnterText: string, afterEnterText: string ): EnterAction | null { if (!this._onEnterSupport) { return null; } return this._onEnterSupport.onEnter( autoIndent, previousLineText, beforeEnterText, afterEnterText ); } public getAutoClosingPairs(): AutoClosingPairs { return new AutoClosingPairs(this.characterPair.getAutoClosingPairs()); } public getAutoCloseBeforeSet(): string { return this.characterPair.getAutoCloseBeforeSet(); } public getSurroundingPairs(): IAutoClosingPair[] { return this.characterPair.getSurroundingPairs(); } private static _handleComments( conf: LanguageConfiguration ): ICommentsConfiguration | null { const commentRule = conf.comments; if (!commentRule) { return null; } // comment configuration const comments: ICommentsConfiguration = {}; if (commentRule.lineComment) { comments.lineCommentToken = commentRule.lineComment; } if (commentRule.blockComment) { const [blockStart, blockEnd] = commentRule.blockComment; comments.blockCommentStartToken = blockStart; comments.blockCommentEndToken = blockEnd; } return comments; } } registerSingleton(ILanguageConfigurationService, LanguageConfigurationService);
the_stack
import { RequestOptions as HttpsRequestOptions } from "https"; import { RequestOptions as HttpRequestOptions } from "http"; import { RawSourceMap, SourceMapGenerator } from "source-map"; /** * Shared options passed when initializing a new instance of CleanCSS that returns either a promise or output */ interface OptionsBase { /** * Controls compatibility mode used; defaults to ie10+ using `'*'`. * Compatibility hash exposes the following properties: `colors`, `properties`, `selectors`, and `units` */ compatibility?: "*" | "ie9" | "ie8" | "ie7" | CleanCSS.CompatibilityOptions | undefined; /** * Controls a function for handling remote requests; Defaults to the build in `loadRemoteResource` function */ fetch?: ((uri: string, inlineRequest: HttpRequestOptions | HttpsRequestOptions, inlineTimeout: number, done: (message: string | number, body: string) => void) => void) | undefined; /** * Controls output CSS formatting; defaults to `false`. * Format hash exposes the following properties: `breaks`, `breakWith`, `indentBy`, `indentWith`, `spaces`, and `wrapAt`. */ format?: "beautify" | "keep-breaks" | CleanCSS.FormatOptions | false | undefined; /** * inline option whitelists which @import rules will be processed. Defaults to `'local'` * Accepts the following values: * 'local': enables local inlining; * 'remote': enables remote inlining; * 'none': disables all inlining; * 'all': enables all inlining, same as ['local', 'remote']; * '[uri]': enables remote inlining from the specified uri; * '![url]': disables remote inlining from the specified uri; */ inline?: ReadonlyArray<string> | false | undefined; /** * Controls extra options for inlining remote @import rules */ inlineRequest?: HttpRequestOptions | HttpsRequestOptions | undefined; /** * Controls number of milliseconds after which inlining a remote @import fails; defaults to `5000`; */ inlineTimeout?: number | undefined; /** * Controls optimization level used; defaults to `1`. * Level hash exposes `1`, and `2`. */ level?: 0 | 1 | 2 | CleanCSS.OptimizationsOptions | undefined; /** * Controls URL rebasing; defaults to `true`; */ rebase?: boolean | undefined; /** * controls a directory to which all URLs are rebased, most likely the directory under which the output file * will live; defaults to the current directory; */ rebaseTo?: string | undefined; /** * Controls whether an output source map is built; defaults to `false` */ sourceMap?: boolean | undefined; /** * Controls embedding sources inside a source map's `sourcesContent` field; defaults to `false` */ sourceMapInlineSources?: boolean | undefined; } declare namespace CleanCSS { /** * Output returned when calling minify functions */ interface Output { /** * Optimized output CSS as a string */ styles: string; /** * Output source map if requested with `sourceMap` option */ sourceMap: SourceMapGenerator; /** * A list of errors raised */ errors: string[]; /** * A list of warnings raised */ warnings: string[]; /** * Contains statistics on the minify process */ stats: { /** * Original content size after import inlining */ originalSize: number; /** * Optimized content size */ minifiedSize: number; /** * Time spent on optimizations in milliseconds */ timeSpent: number; /** * `(originalSize - minifiedSize) / originalSize`, e.g. 0.25 if size is reduced from 100 bytes to 75 bytes */ efficiency: number; }; } /** * Fine grained configuration for compatibility option */ interface CompatibilityOptions { /** * A hash of compatibility options related to color */ colors?: { /** * Controls `rgba()` / `hsla()` color support; defaults to `true` */ opacity?: boolean | undefined; } | undefined; /** * A hash of properties that can be set with compatibility */ properties?: { /** * Controls background-clip merging into shorthand; defaults to `true` */ backgroundClipMerging?: boolean | undefined; /** * Controls background-origin merging into shorthand; defaults to `true` */ backgroundOriginMerging?: boolean | undefined; /** * Controls background-size merging into shorthand; defaults to `true` */ backgroundSizeMerging?: boolean | undefined; /** * controls color optimizations; defaults to `true` */ colors?: boolean | undefined, /** * Controls keeping IE bang hack; defaults to `false` */ ieBangHack?: boolean | undefined; /** * Controls keeping IE `filter` / `-ms-filter`; defaults to `false` */ ieFilters?: boolean | undefined; /** * Controls keeping IE prefix hack; defaults to `false` */ iePrefixHack?: boolean | undefined; /** * Controls keeping IE suffix hack; defaults to `false` */ ieSuffixHack?: boolean | undefined; /** * Controls property merging based on understandably; defaults to `true` */ merging?: boolean | undefined; /** * Controls shortening pixel units into `pc`, `pt`, or `in` units; defaults to `false` */ shorterLengthUnits?: false | undefined; /** * Controls keeping space after closing brace - `url() no-repeat` into `url()no-repeat`; defaults to `true` */ spaceAfterClosingBrace?: true | undefined; /** * Controls keeping quoting inside `url()`; defaults to `false` */ urlQuotes?: boolean | undefined; /** * Controls removal of units `0` value; defaults to `true` */ zeroUnits?: boolean | undefined; } | undefined; /** * A hash of options related to compatibility of selectors */ selectors?: { /** * Controls extra space before `nav` element; defaults to `false` */ adjacentSpace?: boolean | undefined; /** * Controls removal of IE7 selector hacks, e.g. `*+html...`; defaults to `true` */ ie7Hack?: boolean | undefined; /** * Controls a whitelist of mergeable pseudo classes; defaults to `[':active', ...]` */ mergeablePseudoClasses?: ReadonlyArray<string> | undefined; /** * Controls a whitelist of mergeable pseudo elements; defaults to `['::after', ...]` */ mergeablePseudoElements: ReadonlyArray<string>; /** * Controls maximum number of selectors in a single rule (since 4.1.0); defaults to `8191` */ mergeLimit: number; /** * Controls merging of rules with multiple pseudo classes / elements (since 4.1.0); defaults to `true` */ multiplePseudoMerging: boolean; } | undefined; /** * A hash of options related to comparability of supported units */ units?: { /** * Controls treating `ch` as a supported unit; defaults to `true` */ ch?: boolean | undefined; /** * Controls treating `in` as a supported unit; defaults to `true` */ in?: boolean | undefined; /** * Controls treating `pc` as a supported unit; defaults to `true` */ pc?: boolean | undefined; /** * Controls treating `pt` as a supported unit; defaults to `true` */ pt?: boolean | undefined; /** * Controls treating `rem` as a supported unit; defaults to `true` */ rem?: boolean | undefined; /** * Controls treating `vh` as a supported unit; defaults to `true` */ vh?: boolean | undefined; /** * Controls treating `vm` as a supported unit; defaults to `true` */ vm?: boolean | undefined; /** * Controls treating `vmax` as a supported unit; defaults to `true` */ vmax?: boolean | undefined; /** * Controls treating `vmin` as a supported unit; defaults to `true` */ vmin?: boolean | undefined; } | undefined; } /** * Fine grained options for configuring the CSS formatting */ interface FormatOptions { /** * Controls where to insert breaks */ breaks?: { /** * Controls if a line break comes after an at-rule; e.g. `@charset`; defaults to `false` */ afterAtRule?: boolean | undefined; /** * Controls if a line break comes after a block begins; e.g. `@media`; defaults to `false` */ afterBlockBegins?: boolean | undefined; /** * Controls if a line break comes after a block ends, defaults to `false` */ afterBlockEnds?: boolean | undefined; /** * Controls if a line break comes after a comment; defaults to `false` */ afterComment?: boolean | undefined; /** * Controls if a line break comes after a property; defaults to `false` */ afterProperty?: boolean | undefined; /** * Controls if a line break comes after a rule begins; defaults to `false` */ afterRuleBegins?: boolean | undefined; /** * Controls if a line break comes after a rule ends; defaults to `false` */ afterRuleEnds?: boolean | undefined; /** * Controls if a line break comes before a block ends; defaults to `false` */ beforeBlockEnds?: boolean | undefined; /** * Controls if a line break comes between selectors; defaults to `false` */ betweenSelectors?: boolean | undefined; } | undefined; /** * Controls the new line character, can be `'\r\n'` or `'\n'`(aliased as `'windows'` and `'unix'` * or `'crlf'` and `'lf'`); defaults to system one, so former on Windows and latter on Unix */ breakWith?: string | undefined; /** * Controls number of characters to indent with; defaults to `0` */ indentBy?: number | undefined; /** * Controls a character to indent with, can be `'space'` or `'tab'`; defaults to `'space'` */ indentWith?: "space" | "tab" | undefined; /** * Controls where to insert spaces */ spaces?: { /** * Controls if spaces come around selector relations; e.g. `div > a`; defaults to `false` */ aroundSelectorRelation?: boolean | undefined; /** * Controls if a space comes before a block begins; e.g. `.block {`; defaults to `false` */ beforeBlockBegins?: boolean | undefined; /** * Controls if a space comes before a value; e.g. `width: 1rem`; defaults to `false` */ beforeValue?: boolean | undefined; } | undefined; /** * Controls maximum line length; defaults to `false` */ wrapAt?: false | number | undefined; /** * Controls removing trailing semicolons in rule; defaults to `false` - means remove */ semicolonAfterLastProperty?: boolean | undefined; } /** * Fine grained options for configuring optimizations */ interface OptimizationsOptions { 1?: { /** * Sets all optimizations at this level unless otherwise specified */ all?: boolean | undefined; /** * Controls `@charset` moving to the front of a stylesheet; defaults to `true` */ cleanupCharsets?: boolean | undefined; /** * Controls URL normalization; defaults to `true` */ normalizeUrls?: boolean | undefined; /** * Controls `background` property optimizations; defaults to `true` */ optimizeBackground?: boolean | undefined; /** * Controls `border-radius` property optimizations; defaults to `true` */ optimizeBorderRadius?: boolean | undefined; /** * Controls `filter` property optimizations; defaults to `true` */ optimizeFilter?: boolean | undefined; /** * Controls `font` property optimizations; defaults to `true` */ optimizeFont?: boolean | undefined; /** * Controls `font-weight` property optimizations; defaults to `true` */ optimizeFontWeight?: boolean | undefined; /** * Controls `outline` property optimizations; defaults to `true` */ optimizeOutline?: boolean | undefined; /** * Controls removing empty rules and nested blocks; defaults to `true` */ removeEmpty?: boolean | undefined; /** * Controls removing negative paddings; defaults to `true` */ removeNegativePaddings?: boolean | undefined; /** * Controls removing quotes when unnecessary; defaults to `true` */ removeQuotes?: boolean | undefined; /** * Controls removing unused whitespace; defaults to `true` */ removeWhitespace?: boolean | undefined; /** * Contols removing redundant zeros; defaults to `true` */ replaceMultipleZeros?: boolean | undefined; /** * Controls replacing time units with shorter values; defaults to `true` */ replaceTimeUnits?: boolean | undefined; /** * Controls replacing zero values with units; defaults to `true` */ replaceZeroUnits?: boolean | undefined; /** * Rounds pixel values to `N` decimal places; `false` disables rounding; defaults to `false` */ roundingPrecision?: boolean | undefined; /** * denotes selector sorting method; can be `'natural'` or `'standard'`, `'none'`, or false (the last two * since 4.1.0); defaults to `'standard'` */ selectorsSortingMethod?: "standard" | "natural" | "none" | undefined; /** * denotes a number of /*! ... * / comments preserved; defaults to `all` */ specialComments?: string | undefined; /** * Controls at-rules (e.g. `@charset`, `@import`) optimizing; defaults to `true` */ tidyAtRules?: boolean | undefined; /** * Controls block scopes (e.g. `@media`) optimizing; defaults to `true` */ tidyBlockScopes?: boolean | undefined; /** * Controls selectors optimizing; defaults to `true` */ tidySelectors?: boolean | undefined; /** * Defines a callback for fine-grained property optimization; defaults to no-op */ transform?: ((propertyName: string, propertyValue: string, selector?: string) => string) | undefined; } | undefined; 2?: { /** * Sets all optimizations at this level unless otherwise specified */ all?: boolean | undefined; /** * Controls adjacent rules merging; defaults to true */ mergeAdjacentRules?: boolean | undefined; /** * Controls merging properties into shorthands; defaults to true */ mergeIntoShorthands?: boolean | undefined; /** * Controls `@media` merging; defaults to true */ mergeMedia?: boolean | undefined; /** * Controls non-adjacent rule merging; defaults to true */ mergeNonAdjacentRules?: boolean | undefined; /** * Controls semantic merging; defaults to false */ mergeSemantically?: boolean | undefined; /** * Controls property overriding based on understandably; defaults to true */ overrideProperties?: boolean | undefined; /** * Controls removing empty rules and nested blocks; defaults to `true` */ removeEmpty?: boolean | undefined; /** * Controls non-adjacent rule reducing; defaults to true */ reduceNonAdjacentRules?: boolean | undefined; /** * Controls duplicate `@font-face` removing; defaults to true */ removeDuplicateFontRules?: boolean | undefined; /** * Controls duplicate `@media` removing; defaults to true */ removeDuplicateMediaBlocks?: boolean | undefined; /** * Controls duplicate rules removing; defaults to true */ removeDuplicateRules?: boolean | undefined; /** * Controls unused at rule removing; defaults to false (available since 4.1.0) */ removeUnusedAtRules?: boolean | undefined; /** * Controls rule restructuring; defaults to false */ restructureRules?: boolean | undefined; /** * Controls which properties won't be optimized, defaults to `[]` which means all will be optimized (since 4.1.0) */ skipProperties?: ReadonlyArray<string> | undefined; } | undefined; } /** * Hash of input source(s). Passing an array of hashes allows you to explicitly specify the order in which the input files * are concatenated. Whereas when you use a single hash the order is determined by the traversal order of object properties */ interface Source { /** * Path to file */ [path: string]: { /** * The contents of the file, should be css */ styles: string; /** * The source map of the file, if needed */ sourceMap?: RawSourceMap | string | undefined; }; } /** * Callback type when fetch is used */ type FetchCallback = (message: string | number, body: string) => void; /** * Union of all types acceptable as input for the minify function */ type Sources = string | ReadonlyArray<string> | Source | ReadonlyArray<Source> | Buffer; /** * Union type for both types of minifier functions */ type Minifier = MinifierOutput | MinifierPromise; /** * Interface exposed when a new CleanCSS object is created */ interface MinifierOutput { minify(sources: Sources, callback?: (error: any, output: Output) => void): Output; minify(sources: Sources, sourceMap: RawSourceMap | string, callback?: (error: any, output: Output) => void): Output; } /** * Interface exposed when a new CleanCSS object is created with returnPromise set to true */ interface MinifierPromise { minify(sources: Sources, sourceMap?: RawSourceMap | string): Promise<Output>; } /** * Options when returning a promise */ type OptionsPromise = OptionsBase & { /** * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` */ returnPromise: true }; /** * Options when returning an output */ type OptionsOutput = OptionsBase & { /** * If you prefer clean-css to return a Promise object then you need to explicitly ask for it; defaults to `false` */ returnPromise?: false | undefined }; /** * Discriminant union of both sets of options types. If you initialize without setting `returnPromise: true` * and want to return a promise, you will need to cast to the correct options type so that TypeScript * knows what the expected return type will be: * `(options = options as CleanCSS.OptionsPromise).returnPromise = true` */ type Options = OptionsPromise | OptionsOutput; /** * Constructor interface for CleanCSS */ interface Constructor { new(options: OptionsPromise): MinifierPromise; new(options?: OptionsOutput): MinifierOutput; } } /** * Creates a new CleanCSS object which can be used to minify css */ declare const CleanCSS: CleanCSS.Constructor; export = CleanCSS;
the_stack
import { assert, ASTNode, CompileResult, ContractDefinition, FunctionDefinition, ParameterList, PragmaDirective, SourceUnit, SrcRangeMap, StructuredDocumentation, VariableDeclaration } from "solc-typed-ast"; import { Range, SrcTriple } from "./location"; import { getOr } from "./misc"; import { dedup, MacroFile } from "."; import { PropertyMetaData } from "../instrumenter/annotations"; import { InstrumentationContext } from "../instrumenter/instrumentation_context"; import { DbgIdsMap } from "../instrumenter/transpiling_context"; import { AnnotationType } from "../spec-lang/ast/declarations/annotation"; import { NodeLocation } from "../spec-lang/ast/node"; type TargetType = "function" | "variable" | "contract" | "statement"; /// An original JSON location is either a src tripple, or a pair of src trippls (corresponding to an instantiated macro) export type OriginalJSONLoc = string | [string, string]; /** * JSON interface describing an element of the `propertyMap` filed of the * instrumentation metadata */ interface PropertyDesc { /// Unique identifier of the property id: number; /// Name of the contract in which this property is applied (either on the contract or on an element in the countract) contract: string; /// Name of the original file where the property was written filename: string; /// Source tripple (start:len:fileIndx) in the _original_ file where just the expression of the annotation is located propertySource: OriginalJSONLoc; /// Source tripple (start:len:fileIndx) in the _original_ file where just the whole annotation is located annotationSource: OriginalJSONLoc; /// Type of the target to which the annotation is applied (e.g contract, function, etc.) target: TargetType; /// Type of the annotation (e.g. if_succeeds, invariant, etc.) type: AnnotationType; /// Name of the target to which the property is applied targetName: string; /// A list of tuples `[locations, type]` describing what each field in the /// AssertionFailedData bytecode array refers to. The N-th tuple `[locations, type]` /// describes what the N-th value of the debug data describes. `locations` is the list of /// source locations in the original file to which the data applies, and `type` is the type of the data. debugEventEncoding: Array<[OriginalJSONLoc[], string]>; /// The user-readable message assoicated with the original annotation (if none then its "") message: string; /// List of source locations in the _instrumented_ file that are part of the instrumentation /// for this property instrumentationRanges: string[]; /// List of locations in the _instrumented_ file that correspond to executing the check /// of this property. These locations can be used to check if this property has been reached checkRanges: string[]; /// List of locations in the _instrumented_ file that correspond to code executed when /// this property has failed. assertionRanges: string[]; } export type PropertyMap = PropertyDesc[]; export type SrcToSrcMap = Array<[string, OriginalJSONLoc]>; export type InstrumentationMetaData = { propertyMap: PropertyMap; instrToOriginalMap: SrcToSrcMap; otherInstrumentation: string[]; originalSourceList: string[]; instrSourceList: string[]; scribbleVersion: string; }; /** * Convert a line/column source range into an offset range */ export function rangeToSrcTriple(r: Range, srcList: string[]): SrcTriple { const fileInd = srcList.indexOf(r.start.file.fileName); return [r.start.offset, r.end.offset - r.start.offset, fileInd]; } export function nodeLocToJSONNodeLoc(n: NodeLocation, srcList: string[]): OriginalJSONLoc { if (n instanceof Array) { const macroLoc = ppSrcTripple(rangeToSrcTriple(n[0], srcList)); const instLoc = ppSrcTripple(rangeToSrcTriple(n[1], srcList)); return [macroLoc, instLoc]; } return ppSrcTripple(rangeToSrcTriple(n, srcList)); } /** * Type describes a location in a source file * - The first element is the starting offset of code fragment. * - The second element is the length of the code fragment. * - The third element is the file index of the source file containing the fragment in the source list. */ export function parseSrcTriple(src: string): SrcTriple { return src.split(":").map((sNum) => Number.parseInt(sNum)) as SrcTriple; } export function ppSrcTripple(src: SrcTriple): string { return `${src[0]}:${src[1]}:${src[2]}`; } /** * Returns true if and only if the source range a contains the source range b. */ export function contains(a: SrcTriple | string, b: SrcTriple | string): boolean { if (typeof a === "string") { a = parseSrcTriple(a); } if (typeof b === "string") { b = parseSrcTriple(b); } return a[2] == b[2] && a[0] <= b[0] && a[0] + a[1] >= b[0] + b[1]; } export function reNumber(src: string, to: number): string { const t = parseSrcTriple(src); t[2] = to; return ppSrcTripple(t); } function getInstrFileIdx( node: ASTNode, mode: "files" | "flat" | "json", instrSourceList: string[] ): number { // In flat/json mode there is a single instrumented unit output if (mode !== "files") { return 0; } const unit = node instanceof SourceUnit ? node : node.getClosestParentByType(SourceUnit); assert(unit !== undefined, "No source unit for {0}", node); const idx = instrSourceList.indexOf(unit.absolutePath); assert( idx !== -1, "Unit {0} missing from instrumented source list {1}", unit.absolutePath, instrSourceList ); return idx; } function generateSrcMap2SrcMap( ctx: InstrumentationContext, changedUnits: SourceUnit[], newSrcMap: SrcRangeMap, instrSourceList: string[], originalSourceList: string[] ): [SrcToSrcMap, string[]] { const src2SrcMap: SrcToSrcMap = []; const otherInstrumentation = []; for (const unit of changedUnits) { unit.walkChildren((node) => { // Skip new nodes if (node.src === "0:0:0") { return; } // Skip structured documentation in instrumented code - its not executable // and causes annyoing failures in src2srcmap.spec.ts if (node instanceof StructuredDocumentation) { return; } const newSrc = newSrcMap.get(node); if (newSrc === undefined) { assert( (node instanceof ParameterList && node.vParameters.length == 0) || node instanceof PragmaDirective, `Missing new source for node ${node.constructor.name}#${node.id}` ); return; } const instrFileIdx = getInstrFileIdx(unit, ctx.outputMode, instrSourceList); src2SrcMap.push([`${newSrc[0]}:${newSrc[1]}:${instrFileIdx}`, node.src]); }); } for (const [property, assertions] of ctx.instrumentedCheck) { const annotationLoc = nodeLocToJSONNodeLoc( property.parsedAnnot.src as NodeLocation, originalSourceList ); for (const assertion of assertions) { const assertionSrc = newSrcMap.get(assertion); const instrFileIdx = getInstrFileIdx(assertion, ctx.outputMode, instrSourceList); assert( assertionSrc !== undefined, `Missing new source for assertion of property ${property.original}` ); src2SrcMap.push([ `${assertionSrc[0]}:${assertionSrc[1]}:${instrFileIdx}`, annotationLoc ]); } } for (const node of ctx.generalInstrumentationNodes) { const nodeSrc = newSrcMap.get(node); if (nodeSrc === undefined) { assert( nodeSrc !== undefined, "Missing new source for general instrumentation node", node ); } const instrFileIdx = getInstrFileIdx(node, ctx.outputMode, instrSourceList); otherInstrumentation.push(`${nodeSrc[0]}:${nodeSrc[1]}:${instrFileIdx}`); } return [src2SrcMap, dedup(otherInstrumentation)]; } function generatePropertyMap( ctx: InstrumentationContext, newSrcMap: SrcRangeMap, originalSourceList: string[], instrSourceList: string[] ): PropertyMap { const result: PropertyMap = []; for (const annotation of ctx.annotations) { // Skip user functions from the property map. if (!(annotation instanceof PropertyMetaData)) { continue; } let contract: ContractDefinition; let targetType: TargetType; if (annotation.target instanceof FunctionDefinition) { assert( annotation.target.vScope instanceof ContractDefinition, "Instrumenting free functions is not supported yet" ); contract = annotation.target.vScope; targetType = "function"; } else if (annotation.target instanceof VariableDeclaration) { assert( annotation.target.vScope instanceof ContractDefinition, "Instrumenting is supported for state variables only" ); contract = annotation.target.vScope; targetType = "variable"; } else if (annotation.target instanceof ContractDefinition) { contract = annotation.target; targetType = "contract"; } else { contract = annotation.target.getClosestParentByType( ContractDefinition ) as ContractDefinition; targetType = "statement"; } const targetName = annotation.targetName; const filename = annotation.originalFileName; const encodingData = ctx.debugEventsEncoding.get(annotation.id); const encoding: DbgIdsMap = encodingData !== undefined ? encodingData : new DbgIdsMap(); const srcEncoding: Array<[string[], string]> = []; for (const [, [ids, , type]] of encoding.entries()) { const srcMapList: string[] = []; for (const id of ids) { const idSrc = rangeToSrcTriple(id.requiredRange, originalSourceList); srcMapList.push(ppSrcTripple(idSrc)); } srcEncoding.push([srcMapList, type.pp()]); } const propertySource = nodeLocToJSONNodeLoc( annotation.parsedAnnot.expression.src as NodeLocation, originalSourceList ); const annotationSource = nodeLocToJSONNodeLoc( annotation.parsedAnnot.src as NodeLocation, originalSourceList ); const evalStmts = getOr(ctx.evaluationStatements, annotation, []); const instrumentationRanges = dedup( evalStmts.map((node) => { const src = newSrcMap.get(node); assert( src !== undefined, "Missing source for instrumentation node {0} of annotation {1}", node, annotation.original ); const instrFileIdx = getInstrFileIdx(node, ctx.outputMode, instrSourceList); return `${src[0]}:${src[1]}:${instrFileIdx}`; }) ); const annotationChecks = getOr(ctx.instrumentedCheck, annotation, []); const checkRanges: string[] = dedup( annotationChecks.map((check) => { const range = newSrcMap.get(check); const annotationFileIdx = getInstrFileIdx(check, ctx.outputMode, instrSourceList); assert( range !== undefined, "Missing src range for annotation check node {0} of {1}", check, annotation.original ); return `${range[0]}:${range[1]}:${annotationFileIdx}`; }) ); const failureStatements = getOr(ctx.failureStatements, annotation, []); const failureRanges = dedup( failureStatements.map((check) => { const range = newSrcMap.get(check); const annotationFileIdx = getInstrFileIdx(check, ctx.outputMode, instrSourceList); assert( range !== undefined, "Missing src range for annotation check node {0} of {1}", check, annotation.original ); return `${range[0]}:${range[1]}:${annotationFileIdx}`; }) ); result.push({ id: annotation.id, contract: contract.name, filename, propertySource, annotationSource, target: targetType, type: annotation.type, targetName, debugEventEncoding: srcEncoding, message: annotation.message, instrumentationRanges, checkRanges, assertionRanges: failureRanges }); } return result; } export function generateInstrumentationMetadata( ctx: InstrumentationContext, newSrcMap: SrcRangeMap, originalUnits: SourceUnit[], changedUnits: SourceUnit[], arm: boolean, scribbleVersion: string, outputFile?: string ): InstrumentationMetaData { let originalSourceList: string[] = originalUnits.map((unit) => unit.absolutePath); // Collect any macro files that were used and add them to the originalSourceList const macroFiles = new Set<MacroFile>( ctx.annotations .map((annot) => annot.parsedAnnot.requiredRange.start.file) .filter((file) => file instanceof MacroFile) ); originalSourceList.push(...[...macroFiles].map((file) => file.fileName)); let instrSourceList: string[]; if (ctx.outputMode === "files") { instrSourceList = changedUnits.map((unit) => unit.absolutePath); } else { assert(outputFile !== undefined, `Must provide output file in ${ctx.outputMode} mode`); instrSourceList = [outputFile]; } const [src2srcMap, otherInstrumentation] = generateSrcMap2SrcMap( ctx, changedUnits, newSrcMap, instrSourceList, originalSourceList ); const propertyMap = generatePropertyMap(ctx, newSrcMap, originalSourceList, instrSourceList); instrSourceList = instrSourceList.map((name) => name === "--" || (ctx.outputMode === "files" && name === ctx.utilsUnit.absolutePath) ? name : name + ".instrumented" ); if (arm) { originalSourceList = originalSourceList.map((name) => name + ".original"); } return { instrToOriginalMap: src2srcMap, otherInstrumentation, propertyMap, originalSourceList, instrSourceList, scribbleVersion }; } /** * Add the actual source code to the compiled artifcat's AST data */ function addSrcToContext(r: CompileResult): any { for (const [fileName] of Object.entries(r.data["sources"])) { r.data["sources"][fileName]["source"] = r.files.get(fileName); } return r.data["sources"]; } export function buildOutputJSON( ctx: InstrumentationContext, flatCompiled: CompileResult, allUnits: SourceUnit[], changedUnits: SourceUnit[], newSrcMap: SrcRangeMap, scribbleVersion: string, outputFile: string, arm: boolean ): any { const result: any = {}; if ("errors" in flatCompiled.data) { result["errors"] = flatCompiled.data.errors; } result["sources"] = addSrcToContext(flatCompiled); result["contracts"] = flatCompiled.data["contracts"]; result["instrumentationMetadata"] = generateInstrumentationMetadata( ctx, newSrcMap, allUnits, changedUnits, arm, scribbleVersion, outputFile ); return result; }
the_stack
import { homedir } from 'os' import path from 'path' import readline from 'readline' import { randomBytes } from 'crypto' import { ensureDirSync, readFileSync, removeSync } from 'fs-extra' import { Server as RPCServer } from 'jayson/promise' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { _getInitializedChains } from '@ethereumjs/common/dist/chains' import { Address, toBuffer } from 'ethereumjs-util' import { parseMultiaddrs, parseGenesisState, parseCustomParams, inspectParams } from '../lib/util' import EthereumClient from '../lib/client' import { Config } from '../lib/config' import { Logger } from '../lib/logging' import { RPCManager } from '../lib/rpc' import * as modules from '../lib/rpc/modules' import { Event } from '../lib/types' import type { Chain as IChain, GenesisState } from '@ethereumjs/common/dist/types' const level = require('level') const networks = Object.entries(_getInitializedChains().names) const args = require('yargs') .options({ network: { describe: `Network`, choices: networks.map((n) => n[1]), default: 'mainnet', }, 'network-id': { describe: `Network ID`, choices: networks.map((n) => parseInt(n[0])), default: undefined, }, syncmode: { describe: 'Blockchain sync mode (light sync experimental)', choices: ['light', 'full'], default: Config.SYNCMODE_DEFAULT, }, lightserv: { describe: 'Serve light peer requests', boolean: true, default: Config.LIGHTSERV_DEFAULT, }, datadir: { describe: 'Data directory for the blockchain', default: `${homedir()}/Library/Ethereum/ethereumjs`, }, customChain: { describe: 'Path to custom chain parameters json file (@ethereumjs/common format)', coerce: path.resolve, }, customGenesisState: { describe: 'Path to custom genesis state json file (@ethereumjs/common format)', coerce: path.resolve, }, gethGenesis: { describe: 'Import a geth genesis file for running a custom network', coerce: path.resolve, }, transports: { describe: 'Network transports', default: Config.TRANSPORTS_DEFAULT, array: true, }, bootnodes: { describe: 'Network bootnodes', array: true, }, port: { describe: 'RLPx listening port', default: Config.PORT_DEFAULT, }, multiaddrs: { describe: 'Network multiaddrs', array: true, }, rpc: { describe: 'Enable the JSON-RPC server', boolean: true, default: Config.RPC_DEFAULT, }, rpcport: { describe: 'HTTP-RPC server listening port', number: true, default: Config.RPCPORT_DEFAULT, }, rpcaddr: { describe: 'HTTP-RPC server listening interface', default: Config.RPCADDR_DEFAULT, }, rpcEngine: { describe: 'Enable merge Engine API RPC endpoints', boolean: true, default: Config.RPC_ENGINE_DEFAULT, }, rpcStubGetLogs: { describe: 'Stub eth_getLogs with empty response until method is implemented', boolean: true, default: false, }, helprpc: { describe: 'Display the JSON RPC help with a list of all RPC methods implemented (and exit)', boolean: true, }, loglevel: { describe: 'Logging verbosity', choices: ['error', 'warn', 'info', 'debug'], default: Config.LOGLEVEL_DEFAULT, }, rpcDebug: { describe: 'Additionally log complete RPC calls on log level debug (i.e. --loglevel=debug)', boolean: true, default: Config.RPCDEBUG_DEFAULT, }, maxPerRequest: { describe: 'Max items per block or header request', number: true, default: Config.MAXPERREQUEST_DEFAULT, }, minPeers: { describe: 'Peers needed before syncing', number: true, default: Config.MINPEERS_DEFAULT, }, maxPeers: { describe: 'Maximum peers to sync with', number: true, default: Config.MAXPEERS_DEFAULT, }, dnsAddr: { describe: 'IPv4 address of DNS server to use when acquiring peer discovery targets', string: true, default: Config.DNSADDR_DEFAULT, }, dnsNetworks: { describe: 'EIP-1459 ENR tree urls to query for peer discovery targets', array: true, }, debugCode: { describe: 'Generate code for local debugging (internal usage mostly)', boolean: true, default: Config.DEBUGCODE_DEFAULT, }, discDns: { describe: 'Query EIP-1459 DNS TXT records for peer discovery', boolean: true, }, discV4: { describe: 'Use v4 ("findneighbour" node requests) for peer discovery', boolean: true, }, mine: { describe: 'Enable private custom network mining (beta)', boolean: true, default: false, }, unlock: { describe: 'Comma separated list of accounts to unlock - currently only the first account is used (for sealing PoA blocks and as the default coinbase). Beta, you will be promped for a 0x-prefixed private key until keystore functionality is added - FOR YOUR SAFETY PLEASE DO NOT USE ANY ACCOUNTS HOLDING SUBSTANTIAL AMOUNTS OF ETH', array: true, }, dev: { describe: 'Start an ephemeral PoA blockchain with a single miner and prefunded accounts', choices: [undefined, false, true, 'poa', 'pow'], }, minerCoinbase: { describe: 'Address for mining rewards (etherbase). If not provided, defaults to the primary account', string: true, }, }) .locale('en_EN').argv let logger: Logger | null = null /** * Initializes and starts a Node and reacts on the * main client lifecycle events * * @param config */ async function runNode(config: Config) { const chainDataDir = config.getChainDataDirectory() ensureDirSync(chainDataDir) const stateDataDir = config.getStateDataDirectory() ensureDirSync(stateDataDir) config.logger.info(`Data directory: ${config.datadir}`) config.logger.info('Initializing Ethereumjs client...') if (config.lightserv) { config.logger.info(`Serving light peer requests`) } const client = new EthereumClient({ config, chainDB: level(chainDataDir), stateDB: level(stateDataDir), }) client.config.events.on(Event.SERVER_ERROR, (err) => config.logger.error(err)) client.config.events.on(Event.SERVER_LISTENING, (details) => { config.logger.info(`Listener up transport=${details.transport} url=${details.url}`) }) config.events.on(Event.SYNC_SYNCHRONIZED, (height) => { client.config.logger.info(`Synchronized blockchain at height ${height}`) }) config.logger.info(`Connecting to network: ${config.chainCommon.chainName()}`) await client.open() config.logger.info('Synchronizing blockchain...') await client.start() return client } function runRpcServer(client: EthereumClient, config: Config) { const { rpcport, rpcaddr } = config const manager = new RPCManager(client, config) const server = new RPCServer(manager.getMethods()) config.logger.info(`RPC HTTP endpoint opened: http://${rpcaddr}:${rpcport}`) server.http().listen(rpcport) server.on('request', (request) => { let msg = '' if (config.rpcDebug) { msg += `${request.method} called with params:\n${inspectParams(request.params)}` } else { msg += `${request.method} called with params: ${inspectParams(request.params, 125)}` } config.logger.debug(msg) }) const handleResponse = (request: any, response: any, batchAddOn = '') => { let msg = '' if (config.rpcDebug) { msg = `${request.method}${batchAddOn} responded with:\n${inspectParams(response)}` } else { msg = `${request.method}${batchAddOn} responded with: ` if (response.result) { msg += inspectParams(response, 125) } if (response.error) { msg += `error: ${response.error.message}` } } config.logger.debug(msg) } server.on('response', (request, response) => { // Batch request if (request.length !== undefined) { if (response.length === undefined || response.length !== request.length) { config.logger.debug('Invalid batch request received.') return } for (let i = 0; i < request.length; i++) { handleResponse(request[i], response[i], ' (batch request)') } } else { handleResponse(request, response) } }) return server } /** * Main entry point to start a client */ async function run() { if (args.helprpc) { // Display RPC help and exit console.log('-'.repeat(27)) console.log('JSON-RPC: Supported Methods') console.log('-'.repeat(27)) console.log() for (const modName of modules.list) { console.log(`${modName}:`) const methods = RPCManager.getMethodNames((modules as any)[modName]) for (const methodName of methods) { if (methodName === 'getLogs' && !args.rpcStubGetLogs) { continue } console.log(`-> ${modName.toLowerCase()}_${methodName}`) } console.log() } console.log() process.exit() } // give network id precedence over network name const chain = args.networkId ?? args.network ?? Chain.Mainnet // configure accounts for mining and prefunding in a local devnet const accounts: [address: Address, privateKey: Buffer][] = [] if (args.unlock) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }) // Hide key input ;(rl as any).input.on('keypress', function () { // get the number of characters entered so far: const len = (rl as any).line.length // move cursor back to the beginning of the input: readline.moveCursor((rl as any).output, -len, 0) // clear everything to the right of the cursor: readline.clearLine((rl as any).output, 1) // replace the original input with asterisks: for (let i = 0; i < len; i++) { // eslint-disable-next-line no-extra-semi ;(rl as any).output.write('*') } }) const question = (text: string) => { return new Promise<string>((resolve) => { rl.question(text, resolve) }) } try { for (const addressString of args.unlock) { const address = Address.fromString(addressString) const inputKey = await question( `Please enter the 0x-prefixed private key to unlock ${address}:\n` ) ;(rl as any).history = (rl as any).history.slice(1) const privKey = toBuffer(inputKey) const derivedAddress = Address.fromPrivateKey(privKey) if (address.equals(derivedAddress)) { accounts.push([address, privKey]) } else { console.error( `Private key does not match for ${address} (address derived: ${derivedAddress})` ) process.exit() } } } catch (e: any) { console.error(`Encountered error unlocking account:\n${e.message}`) process.exit() } rl.close() } let common = new Common({ chain, hardfork: Hardfork.Chainstart }) if (args.dev) { args.discDns = false if (accounts.length === 0) { // If generating new keys delete old chain data to prevent genesis block mismatch removeSync(`${args.datadir}/devnet`) // Create new account const privKey = randomBytes(32) const address = Address.fromPrivateKey(privKey) accounts.push([address, privKey]) console.log('='.repeat(50)) console.log('Account generated for mining blocks:') console.log(`Address: ${address}`) console.log(`Private key: 0x${privKey.toString('hex')}`) console.log('WARNING: Do not use this account for mainnet funds') console.log('='.repeat(50)) } const prefundAddress = accounts[0][0].toString().slice(2) const consensusConfig = args.dev === 'pow' ? { ethash: true } : { clique: { period: 10, epoch: 30000, }, } const defaultChainData = { config: { chainId: 123456, homesteadBlock: 0, eip150Block: 0, eip150Hash: '0x0000000000000000000000000000000000000000000000000000000000000000', eip155Block: 0, eip158Block: 0, byzantiumBlock: 0, constantinopleBlock: 0, petersburgBlock: 0, istanbulBlock: 0, berlinBlock: 0, londonBlock: 0, ...consensusConfig, }, nonce: '0x0', timestamp: '0x614b3731', gasLimit: '0x47b760', difficulty: '0x1', mixHash: '0x0000000000000000000000000000000000000000000000000000000000000000', coinbase: '0x0000000000000000000000000000000000000000', number: '0x0', gasUsed: '0x0', parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000', baseFeePerGas: 7, } const extraData = '0x' + '0'.repeat(64) + prefundAddress + '0'.repeat(130) const chainData = { ...defaultChainData, extraData, alloc: { [prefundAddress]: { balance: '0x10000000000000000000' } }, } const chainParams = await parseCustomParams(chainData, 'devnet') const genesisState = await parseGenesisState(chainData) const customChainParams: [IChain, GenesisState][] = [[chainParams, genesisState]] common = new Common({ chain: 'devnet', customChains: customChainParams, hardfork: Hardfork.London, }) } // configure common based on args given if ( (args.customChainParams || args.customGenesisState || args.gethGenesis) && (!(args.network === 'mainnet') || args.networkId) ) { console.error('cannot specify both custom chain parameters and preset network ID') process.exit() } // Use custom chain parameters file if specified if (args.customChain) { if (!args.customGenesisState) { console.error('cannot have custom chain parameters without genesis state') process.exit() } try { const customChainParams = JSON.parse(readFileSync(args.customChain, 'utf-8')) const genesisState = JSON.parse(readFileSync(args.customGenesisState, 'utf-8')) common = new Common({ chain: customChainParams.name, customChains: [[customChainParams, genesisState]], }) } catch (err: any) { console.error(`invalid chain parameters: ${err.message}`) process.exit() } } else if (args.gethGenesis) { // Use geth genesis parameters file if specified const genesisFile = JSON.parse(readFileSync(args.gethGenesis, 'utf-8')) const chainName = path.parse(args.gethGenesis).base.split('.')[0] const genesisParams = await parseCustomParams(genesisFile, chainName) const genesisState = genesisFile.alloc ? await parseGenesisState(genesisFile) : {} common = new Common({ chain: genesisParams.name, customChains: [[genesisParams, genesisState]], }) } if (args.mine && accounts.length === 0) { console.error( 'Please provide an account to mine blocks with `--unlock [address]` or use `--dev` to generate' ) process.exit() } const datadir = args.datadir ?? Config.DATADIR_DEFAULT const configDirectory = `${datadir}/${common.chainName()}/config` ensureDirSync(configDirectory) const key = await Config.getClientKey(datadir, common) const config = new Config({ common, syncmode: args.syncmode, lightserv: args.lightserv, datadir, key, transports: args.transports, bootnodes: args.bootnodes ? parseMultiaddrs(args.bootnodes) : undefined, port: args.port, multiaddrs: args.multiaddrs ? parseMultiaddrs(args.multiaddrs) : undefined, rpc: args.rpc, rpcport: args.rpcport, rpcaddr: args.rpcaddr, rpcEngine: args.rpcEngine, loglevel: args.loglevel, rpcDebug: args.rpcDebug, rpcStubGetLogs: args.rpcStubGetLogs, maxPerRequest: args.maxPerRequest, minPeers: args.minPeers, maxPeers: args.maxPeers, dnsAddr: args.dnsAddr, dnsNetworks: args.dnsNetworks, debugCode: args.debugCode, discDns: args.discDns, discV4: args.discV4, mine: args.mine || args.dev, accounts, minerCoinbase: args.minerCoinbase, }) logger = config.logger config.events.setMaxListeners(50) const client = await runNode(config) const server = config.rpc ? runRpcServer(client, config) : null process.on('SIGINT', async () => { config.logger.info('Caught interrupt signal. Shutting down...') if (server) server.http().close() await client.stop() config.logger.info('Exiting.') process.exit() }) } run().catch((err) => logger?.error(err) ?? console.error(err))
the_stack
namespace sensors { /** * Makecode package for the TSL2591 Light sensor. * * More details here: https://ams.com/documents/20143/36005/TSL2591_DS000338_6-00.pdf/090eb50d-bb18-5b45-4938-9b3672f86b80 */ const TSL2591_I2C_ADDRESS = 0x29 //I2C address of the TSL2591 (Page 28) //See Page 13 for full register description of TSL2591 const TSL2591_REGISTER_COMMAND = 0xA0 // Select Command Register. CMD: Must write as 1 when addressing COMMAND register + TRANSACTION: 01 Normal Operation (1010 0000) const TSL2591_REGISTER_COMMAND_SET_INT = 0xE4 // Interrupt set – forces an interrupt (11100100) const TSL2591_REGISTER_COMMAND_CLEAR_ALS_INT = 0xE6 // Clears ALS interrupt (11100110) const TSL2591_REGISTER_COMMAND_CLEAR_ALS_NO_PERS_INT = 0xE7 // Clears ALS and no persist ALS interrupt (11100111) const TSL2591_REGISTER_COMMAND_CLEAR_NO_PERS_INT = 0xEA // Clears no persist ALS interrupt (11101010) const TSL2591_REGISTER_ENABLE = 0x00 // The ENABLE register is used to power the device on/off, enable functions and interrupts.. const TSL2591_REGISTER_NPIEN_ENABLE = 0x80 // No Persist Interrupt Enable. When asserted NP Threshold conditions will generate an interrupt, bypassing the persist filter. const TSL2591_REGISTER_SAI_ENABLE = 0x40 // Sleep after interrupt. When asserted, the device will power down at the end of an ALS cycle if an interrupt has been generated. const TSL2591_REGISTER_AIEN_ENABLE = 0x10 // ALS Interrupt Enable. When asserted permits ALS interrupts to be generated, subject to the persist filter. const TSL2591_REGISTER_AEN_ENABLE = 0x02 // ALS Enable. This field activates ALS function. Writing a one activates the ALS. Writing a zero disables the ALS. const TSL2591_REGISTER_PON_ENABLE = 0x01 // Power ON. This field activates the internal oscillator to permit the timers and ADC channels to operate. Writing a one activates the oscillator. Writing a zero disables the oscillator. const TSL2591_REGISTER_POFF_ENABLE = 0x00 // Power OFF. This field activates the internal oscillator to permit the timers and ADC channels to operate. Writing a one activates the oscillator. Writing a zero disables the oscillator. const TSL2591_REGISTER_CONTROL = 0x01 // The CONTROL register is used to configure the ALS gain and integration time. In addition, a system reset is provided. Upon power up, the CONTROL register resets to 0x00. const TSL2591_REGISTER_CONTROL_SRESET = 0x80 // System reset. When asserted, the device will reset equivalent to a power-on reset. SRESET is self-clearing. const TSL2591_REGISTER_PID = 0x11 // The PID register provides an identification of the devices package. This register is a read-only register whose value never changes. const TSL2591_REGISTER_ID = 0x12 // The ID register provides the device identification. This register is a read-only register whose value never changes. const TSL2591_REGISTER_STATUS = 0x13 // The Status Register provides the internal status of the device. This register is read only. const TSL2591_REGISTER_STATUS_NPINTR = 0x20 // No-persist Interrupt. Indicates that the device has encountered a no-persist interrupt condition. const TSL2591_REGISTER_STATUS_AINT = 0x10 // ALS Interrupt. Indicates that the device is asserting an ALS interrupt. const TSL2591_REGISTER_STATUS_AVALID = 0x01 // ALS Valid. Indicates that the ADC channels have completed an integration cycle since the AEN bit was asserted. const TSL2591_REGISTER_C0DATAL = 0x14 // ALS CH0 data low byte const TSL2591_REGISTER_C0DATAH = 0x15 // ALS CH0 data high byte const TSL2591_REGISTER_C1DATAL = 0x16 // ALS CH1 data low byte const TSL2591_REGISTER_C1DATAH = 0x17 // ALS CH1 data high byte const TSL2591_REGISTER_AILTL = 0x04 // ALS low threshold lower byte const TSL2591_REGISTER_AILTH = 0x05 // ALS low threshold upper byte const TSL2591_REGISTER_AIHTL = 0x06 // ALS high threshold lower byte const TSL2591_REGISTER_AIHTH = 0x07 // ALS high threshold upper byte const TSL2591_REGISTER_NPAILTL = 0x08 // No Persist ALS low threshold lower byte const TSL2591_REGISTER_NPAILTH = 0x09 // No Persist ALS low threshold upper byte const TSL2591_REGISTER_NPAIHTL = 0x0A // No Persist ALS high threshold lower byte const TSL2591_REGISTER_NPAIHTH = 0x0B // No Persist ALS high threshold upper byte const TSL2591_REGISTER_PERSIST = 0x0B // The Interrupt persistence filter sets the number of consecutive out-of-range ALS cycles necessary to generate an interrupt. Out-of-range is determined by comparing C0DATA (0x14 and 0x15) to the interrupt threshold registers (0x04 - 0x07). Note that the no-persist ALS interrupt is not affected by the interrupt persistence filter. Upon power up, the interrupt persistence filter register resets to 0x00. /* #region Enums for Modes, etc */ // ALS gain sets the gain of the internal integration amplifiers for both photodiode channels. enum TSL2591_AGAIN { AGAIN_LOW = 0x00, // Low gain mode AGAIN_MEDIUM = 0x10, // Medium gain mode AGAIN_HIGH = 0x20, // High gain mode AGAIN_MAX = 0x30 // Maximum gain mode } // ALS time sets the internal ADC integration time for both photodiode channels. enum TSL2591_ATIME { ATIME_100_MS = 0x00, // 100 ms ATIME_200_MS = 0x01, // 200 ms ATIME_300_MS = 0x02, // 300 ms ATIME_400_MS = 0x03, // 400 ms ATIME_500_MS = 0x04, // 500 ms ATIME_600_MS = 0x05 // 600 ms } export class TSL2591 extends sensors.LightSpectrumSensor { private TSL2591_I2C_ADDR: number; private isConnected: boolean; private atimeIntegrationValue: TSL2591_ATIME; private gainSensorValue: TSL2591_AGAIN; constructor(id: number) { super(id); this.atimeIntegrationValue = TSL2591_ATIME.ATIME_100_MS, this.gainSensorValue = TSL2591_AGAIN.AGAIN_HIGH, this.TSL2591_I2C_ADDR = TSL2591_I2C_ADDRESS; this.isConnected = false; this.initSensor(); } private initSensor() { //REGISTER FORMAT: CMD | TRANSACTION | ADDRESS //REGISTER READ: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ID (0x12) let device_id = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ID) //Check that device Identification = 0x50 (Page 19) this.isConnected = (device_id == 0x50); this.configureSensor(); } setAtime(atime: TSL2591_ATIME) { this.atimeIntegrationValue = atime; this.configureSensor(); } setGain(gain: TSL2591_AGAIN) { this.gainSensorValue = gain; this.configureSensor(); } private configureSensor() { //Always make sure the sensor is connected. Useful for cases when this block is used but the sensor wasn't set randomly. if (!this.isConnected) return; //Turn sensor on this.enableSensor(); //REGISTER FORMAT: CMD | TRANSACTION | ADDRESS //REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_CONTROL (0x01) //REGISTER WRITE: atimeIntegrationValue | gainSensorValue pins.i2cWriteRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_CONTROL, this.atimeIntegrationValue | this.gainSensorValue); } private enableSensor() { //1 - First set the command bit to 1, to let the device be set //2 - Next, turn it on, then enable ALS, enable ALS Interrupt, and enable No Persist Interrupt if (this.isConnected) //REGISTER FORMAT: CMD | TRANSACTION | ADDRESS //REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ENABLE (0x00) //REGISTER WRITE: TSL2591_REGISTER_PON_ENABLE (0x01) | TSL2591_REGISTER_AEN_ENABLE (0x02) | TSL2591_REGISTER_AIEN_ENABLE (0x10) | TSL2591_REGISTER_NPIEN_ENABLE (0x80) pins.i2cWriteRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ENABLE, TSL2591_REGISTER_PON_ENABLE | TSL2591_REGISTER_AEN_ENABLE /*| TSL2591_REGISTER_AIEN_ENABLE | TSL2591_REGISTER_NPIEN_ENABLE*/) } disableSensor() { //1 - First set the command bit to 1, to let the device be set //2 - Next, turn it off if (this.isConnected) //REGISTER FORMAT: CMD | TRANSACTION | ADDRESS //REGISTER VALUE: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_ENABLE (0x00) //REGISTER WRITE: TSL2591_REGISTER_POFF_ENABLE (0x00) pins.i2cWriteRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_ENABLE, TSL2591_REGISTER_POFF_ENABLE) } protected readSpectrum(): LightSpectrum { let retVal: LightSpectrum = new LightSpectrum(); if (this.isConnected) { // this.enableSensor(); // basic.pause(100); //REGISTER FORMAT: CMD | TRANSACTION | ADDRESS //REGISTER READ: TSL2591_REGISTER_COMMAND (0x80) | TSL2591_REGISTER_COMMAND_NORMAL (0x20) | TSL2591_REGISTER_C1DATAL (0x16) const channel0l = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C0DATAL); const channel0h = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C0DATAH); const channel1l = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C1DATAL); const channel1h = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C1DATAH); // const channel1 = pins.i2cReadRegister(this.TSL2591_I2C_ADDR, TSL2591_REGISTER_COMMAND | TSL2591_REGISTER_C1DATAL, NumberFormat.UInt16LE); if (channel0l !== undefined && channel0h !== undefined && channel1l !== undefined && channel1h !== undefined) { const full = channel0l | (channel0h << 8); const ir = channel1l | (channel1h << 8); // catch overflow condition when ir and full are equal (max value) let visible = (full != ir) ? full - ir : full; // control.dmesg("RAW C0:"); // control.dmesg(channel0l.toString()); // control.dmesg(channel0h.toString()); // control.dmesg("RAW C1:"); // control.dmesg(channel1l.toString()); // control.dmesg(channel1h.toString()); // control.dmesg("PROC:"); // control.dmesg(full.toString()); // control.dmesg(ir.toString()); // control.dmesg(visible.toString()); retVal.full = full; retVal.infrared = ir; retVal.visible = visible; retVal.normalized = Math.map(visible, 0, 37888, 0, 1024); } else control.dmesg("LSBAD"); } else this.initSensor(); return retVal } } }
the_stack
import { Util } from './util' export class Special { public readonly acceptsBooleans: boolean constructor( public readonly type: Special.Type, public readonly propertyName: string, public readonly attributeName: string, public readonly attributeNamespace: string | null = null, public readonly mustUseProperty: boolean = false, public readonly sanitizeURL: boolean = false, public readonly removeEmptyString: boolean = false, ) { this.acceptsBooleans = type === Special.Type.BOOLEAN || type === Special.Type.BOOLEANISH_STRING || type === Special.Type.OVERLOADED_BOOLEAN } } export namespace Special { export enum Type { /** * A simple string attribute. * * Attributes that aren't in the filter are presumed to have this type. */ STRING, /** * A string attribute that accepts booleans. In HTML, these are called * "enumerated" attributes with "true" and "false" as possible values. * * When true, it should be set to a "true" string. * * When false, it should be set to a "false" string. */ BOOLEANISH_STRING, /** * A real boolean attribute. * * When true, it should be present (set either to an empty string or its name). * * When false, it should be omitted. */ BOOLEAN, /** * An attribute that can be used as a flag as well as with a value. * * When true, it should be present (set either to an empty string or its name). * * When false, it should be omitted. * * For any other value, should be present with that value. */ OVERLOADED_BOOLEAN, /** * An attribute that must be numeric or parse as a numeric. * * When falsy, it should be removed. */ NUMERIC, /** * An attribute that must be positive numeric or parse as a positive numeric. * * When falsy, it should be removed. */ POSITIVE_NUMERIC, } } export namespace Special { export const specials: Record<string, Special> = {} export function get(name: string) { return specials[name] || null } } export namespace Special { const arr = [ 'vector:data', 'aria-activedescendant', 'aria-atomic', 'aria-autocomplete', 'aria-busy', 'aria-checked', 'aria-colcount', 'aria-colindex', 'aria-colspan', 'aria-controls', 'aria-current', 'aria-describedby', 'aria-details', 'aria-disabled', 'aria-dropeffect', 'aria-errormessage', 'aria-expanded', 'aria-flowto', 'aria-grabbed', 'aria-haspopup', 'aria-hidden', 'aria-invalid', 'aria-keyshortcuts', 'aria-label', 'aria-labelledby', 'aria-level', 'aria-live', 'aria-modal', 'aria-multiline', 'aria-multiselectable', 'aria-orientation', 'aria-owns', 'aria-placeholder', 'aria-posinset', 'aria-pressed', 'aria-readonly', 'aria-relevant', 'aria-required', 'aria-roledescription', 'aria-rowcount', 'aria-rowindex', 'aria-rowspan', 'aria-selected', 'aria-setsize', 'aria-sort', 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext', ] arr.forEach((attributeName) => { const name = Util.camelCase(attributeName) specials[name] = specials[attributeName] = new Special( Type.STRING, name, attributeName, null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { const arr = [ 'accessKey', 'contextMenu', 'radioGroup', 'autoCapitalize', 'autoCorrect', 'autoSave', 'itemProp', 'itemType', 'itemID', 'itemRef', 'input-modalities', 'inputMode', 'referrerPolicy', 'formEncType', 'formMethod', 'formTarget', 'dateTime', 'autoComplete', 'encType', 'allowTransparency', 'frameBorder', 'marginHeight', 'marginWidth', 'srcDoc', 'crossOrigin', 'srcSet', 'useMap', 'enterKeyHint', 'maxLength', 'minLength', 'keyType', 'keyParams', 'hrefLang', 'charSet', 'controlsList', 'mediaGroup', 'classID', 'cellPadding', 'cellSpacing', 'dirName', 'srcLang', ] arr.forEach((attributeName) => { specials[attributeName] = specials[attributeName.toLowerCase()] = new Special( Type.STRING, attributeName, attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // A few string attributes have a different name. const arr = ['accept-charset', 'http-equiv'] arr.forEach((attributeName) => { const name = Util.camelCase(attributeName) specials[name] = specials[attributeName] = new Special( Type.STRING, name, attributeName, // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are HTML boolean attributes. const arr = [ 'allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). 'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', 'itemScope', ] arr.forEach((name) => { specials[name] = specials[name.toLowerCase()] = new Special( Type.BOOLEAN, name, name.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are "enumerated" HTML attributes that accept "true" and "false". // We can pass `true` and `false` even though technically ese aren't // boolean attributes (they are coerced to strings). const arr = ['contentEditable', 'draggable', 'spellCheck', 'value'] arr.forEach((name) => { specials[name] = specials[name.toLowerCase()] = new Special( Type.BOOLEANISH_STRING, name, name.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are "enumerated" SVG attributes that accept "true" and "false". // We can pass `true` and `false` even though technically these aren't // boolean attributes (they are coerced to strings). // Since these are SVG attributes, their attribute names are case-sensitive. const arr = [ 'autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha', ] arr.forEach((name) => { specials[name] = new Special( Type.BOOLEANISH_STRING, name, name, // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are the few props that we set as DOM properties // rather than attributes. These are all booleans. const arr = [ 'checked', // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. 'multiple', 'muted', 'selected', ] arr.forEach((name) => { specials[name] = new Special( Type.BOOLEAN, name, name.toLowerCase(), // attributeName null, // attributeNamespace true, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are HTML attributes that are "overloaded booleans": they behave like // booleans, but can also accept a string value. const arr = ['capture', 'download'] arr.forEach((name) => { specials[name] = new Special( Type.OVERLOADED_BOOLEAN, name, name.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are HTML attributes that must be positive numbers. const arr = ['cols', 'rows', 'size', 'span'] arr.forEach((name) => { specials[name] = new Special( Type.POSITIVE_NUMERIC, name, name.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These are HTML attributes that must be numbers. const arr = ['tabIndex', 'rowSpan', 'colSpan', 'start'] arr.forEach((name) => { specials[name] = specials[name.toLowerCase()] = new Special( Type.NUMERIC, name, name.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // This is a list of all SVG attributes that need special casing, namespacing, // or boolean value assignment. Regular attributes that just accept strings // and have the same names are omitted, just like in the HTML attribute filter. // Some of these attributes can be hard to find. This list was created by // scraping the MDN documentation. const arr1 = [ 'accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height', ] arr1.forEach((attributeName) => { const name = Util.camelCase(attributeName) specials[name] = specials[attributeName] = new Special( Type.STRING, name, attributeName, null, // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) // String SVG attributes with the xlink namespace. const arr2 = [ 'xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', ] arr2.forEach((attributeName) => { const name = Util.camelCase(attributeName) specials[attributeName] = specials[name] = new Special( Type.STRING, name, attributeName, 'http://www.w3.org/1999/xlink', false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) // String SVG attributes with the xml namespace. const arr3 = ['xml:base', 'xml:lang', 'xml:space'] arr3.forEach((attributeName) => { const name = Util.camelCase(attributeName) specials[attributeName] = specials[name] = new Special( Type.STRING, name, attributeName, 'http://www.w3.org/XML/1998/namespace', // attributeNamespace false, // mustUseProperty false, // sanitizeURL false, // removeEmptyString ) }) } export namespace Special { // These attributes accept URLs. These must not allow javascript: URLS. // These will also need to accept Trusted Types object in the future. const arr = ['xlinkHref', 'xlink:href'] arr.forEach((name) => { specials[name] = new Special( Type.STRING, name, 'xlink:href', 'http://www.w3.org/1999/xlink', false, // mustUseProperty true, // sanitizeURL true, // removeEmptyString ) }) } export namespace Special { const arr = ['src', 'href', 'action', 'formAction'] arr.forEach((attributeName) => { specials[attributeName] = specials[attributeName.toLowerCase()] = new Special( Type.STRING, attributeName, attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // mustUseProperty true, // sanitizeURL true, // removeEmptyString ) }) }
the_stack
import test from "ava"; import { Indexer, TransactionCollector } from "@ckb-lumos/indexer"; import { CacheManager, getBalance } from "../src"; import { HDCache, getDefaultInfos, CellCollector, CellCollectorWithQueryOptions, publicKeyToMultisigArgs, } from "../src/index"; import { Cell, QueryOptions, TransactionWithStatus, HexString, } from "@ckb-lumos/base"; const mockTxs: TransactionWithStatus[] = [ { transaction: { version: "0", hash: "0xfd69760e8062dca9142a6802d7f42f82204e1b266719e34a17cc1f5c0bd03b97", header_deps: [], cell_deps: [], inputs: [ { previous_output: { tx_hash: "0x58a29007f29ede069d49221f468107681c1a4d8d341de1d053b9b60596d6b233", index: "0x0", }, since: "0x0", }, ], outputs: [ { capacity: "0x" + BigInt(1000 * 10 ** 8).toString(16), lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0x89cba48c68b3978f185df19f31634bb870e94639", }, }, ], outputs_data: ["0x"], witnesses: [], }, tx_status: { status: "committed", block_hash: "0x8df4763d10cf22509845f8ec728d56d1027d4dfe633cb91abf0d751ed5d45d68", }, }, { transaction: { version: "0", hash: "78a2d0c8da6daaa9e9cb7b2f69f90f3492719bb566e039d5c7d6a1534fcb301b", header_deps: [], cell_deps: [], inputs: [ { previous_output: { tx_hash: "0xfd69760e8062dca9142a6802d7f42f82204e1b266719e34a17cc1f5c0bd03b97", index: "0x0", }, since: "0x0", }, ], outputs: [ { capacity: "0x" + BigInt(200 * 10 ** 8).toString(16), lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0x0ce445e32d7f91c9392485ddb9bc6885ce46ad64", }, }, { capacity: "0x" + BigInt(300 * 10 ** 8).toString(16), lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0xaa5aa575dedb6f5d7a5c835428c3b4a3ea7ba1eb", }, }, { capacity: "0x" + BigInt(400 * 10 ** 8).toString(16), lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0xfa7b46aa28cb233db373e5712e16edcaaa4c4999", }, }, // master public key { capacity: "0x" + BigInt(50 * 10 ** 8).toString(16), lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0xa6ee79109863906e75668acd75d6c6adbd56469c", }, }, ], outputs_data: ["0x1234", "0x", "0x"], witnesses: [], }, tx_status: { status: "committed", block_hash: "0x8df4763d10cf22509845f8ec728d56d1027d4dfe633cb91abf0d751ed5d45d68", }, }, ]; class MockRpc { constructor() {} async get_header(blockHash: HexString) { return { compact_target: "0x1e083126", dao: "0xb5a3e047474401001bc476b9ee573000c0c387962a38000000febffacf030000", epoch: "0x7080018000001", hash: blockHash, nonce: "0x0", number: "0x400", parent_hash: "0xae003585fa15309b30b31aed3dcf385e9472c3c3e93746a6c4540629a6a1ed2d", proposals_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", timestamp: "0x5cd2b117", transactions_root: "0xc47d5b78b3c4c4c853e2a32810818940d0ee403423bea9ec7b8e566d9595206c", uncles_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", version: "0x0", }; } } const rpc: any = new MockRpc(); class MockIndexer { async tip() { return { block_hash: "0xb97f00e2d023a9be5b38cc0dabcfdfa149597a3c5f6bc89b013c2cb69e186432", block_number: "0x10", }; } } HDCache.receivingKeyInitCount = 3; HDCache.changeKeyInitCount = 2; HDCache.receivingKeyThreshold = 2; HDCache.changeKeyThreshold = 1; // Private Key: 0x37d25afe073a6ba17badc2df8e91fc0de59ed88bcad6b9a0c2210f325fafca61 // Public Key: 0x020720a7a11a9ac4f0330e2b9537f594388ea4f1cd660301f40b5a70e0bc231065 // blake160: 0xa6ee79109863906e75668acd75d6c6adbd56469c const mnemonic = "tank planet champion pottery together intact quick police asset flower sudden question"; /** * receiving keys blake160: * 0: 0x89cba48c68b3978f185df19f31634bb870e94639 * 1: 0x0ce445e32d7f91c9392485ddb9bc6885ce46ad64 * 2: 0xc337da539e4d0b89daad1370b945f7210fad4c43 * 3: 0xd9a188cc1985a7d4a31f141f4ebb61f241aec182 * 4: 0xebf9befcd8396e88cab8fcb920ab149231658f4b * * change keys blake160: * 0: 0xaa5aa575dedb6f5d7a5c835428c3b4a3ea7ba1eb * 1: 0xfa7b46aa28cb233db373e5712e16edcaaa4c4999 * 2: 0xbba6e863e838bae614fd6df9828f3bf1eed57964 * 3: 0x57a81755c7229decb0f21f93d73c1c7e1c0afe95 */ class MockTransactionCollector extends TransactionCollector { async *collect(): any { const lock = (this as any).lock.script; const args = lock.args; if (args === "0x89cba48c68b3978f185df19f31634bb870e94639") { yield mockTxs[0]; } if ( [ "0x89cba48c68b3978f185df19f31634bb870e94639", "0x0ce445e32d7f91c9392485ddb9bc6885ce46ad64", "0xaa5aa575dedb6f5d7a5c835428c3b4a3ea7ba1eb", "0xfa7b46aa28cb233db373e5712e16edcaaa4c4999", // master key "0xa6ee79109863906e75668acd75d6c6adbd56469c", ].includes(args) ) { yield mockTxs[1]; } } } const indexer = new MockIndexer(); const cacheManager = CacheManager.fromMnemonic( indexer as Indexer, mnemonic, getDefaultInfos(), { TransactionCollector: MockTransactionCollector, rpc, } ); test("derive threshold", async (t) => { const cacheManager = CacheManager.fromMnemonic( indexer as Indexer, mnemonic, getDefaultInfos(), { TransactionCollector: MockTransactionCollector, rpc, } ); t.is(cacheManager.getReceivingKeys().length, 3); t.is(cacheManager.getChangeKeys().length, 2); // @ts-ignore await cacheManager.cache.loop(); t.is(cacheManager.getReceivingKeys().length, 5); t.is(cacheManager.getChangeKeys().length, 3); t.deepEqual( cacheManager.getReceivingKeys().map((key) => key.index), Array.from({ length: 5 }).map((_, i) => i) ); t.deepEqual( cacheManager.getChangeKeys().map((key) => key.index), Array.from({ length: 3 }).map((_, i) => i) ); }); test("getNextReceivingPublicKeyInfo", async (t) => { // @ts-ignore await cacheManager.cache.loop(); t.is( cacheManager.getNextReceivingPublicKeyInfo().blake160, "0xc337da539e4d0b89daad1370b945f7210fad4c43" ); }); test("getNextChangePublicKeyInfo", async (t) => { // @ts-ignore await cacheManager.cache.loop(); t.is( cacheManager.getNextChangePublicKeyInfo().blake160, "0xbba6e863e838bae614fd6df9828f3bf1eed57964" ); }); test("getMasterPublicKeyInfo, default", async (t) => { // @ts-ignore await cacheManager.cache.loop(); t.false(!!cacheManager.getMasterPublicKeyInfo()); }); test("getMasterPublicKeyInfo, needMasterPublicKey", async (t) => { const cacheManager = CacheManager.fromMnemonic( indexer as Indexer, mnemonic, getDefaultInfos(), { TransactionCollector: MockTransactionCollector, rpc, needMasterPublicKey: true, } ); // @ts-ignore await cacheManager.cache.loop(); t.true(!!cacheManager.getMasterPublicKeyInfo()); t.is( cacheManager.getMasterPublicKeyInfo()!.publicKey, "0x020720a7a11a9ac4f0330e2b9537f594388ea4f1cd660301f40b5a70e0bc231065" ); }); test("loadFromKeystore, ckb-cli", async (t) => { const cacheManager = CacheManager.loadFromKeystore( indexer as Indexer, __dirname + "/fixtures/ckb_cli_keystore.json", "aaaaaa", getDefaultInfos(), { TransactionCollector: MockTransactionCollector, } ); // @ts-ignore await cacheManager.cache.loop(); t.true(!!cacheManager.getMasterPublicKeyInfo()); }); test("CellCollector", async (t) => { // @ts-ignore await cacheManager.cache.loop(); const cellCollector = new CellCollector(cacheManager); const cells: Cell[] = []; for await (const cell of cellCollector.collect()) { cells.push(cell); } t.is(cells.length, 3); t.deepEqual( cells.map((cell) => BigInt(cell.cell_output.capacity)), [BigInt(200 * 10 ** 8), BigInt(300 * 10 ** 8), BigInt(400 * 10 ** 8)] ); const firstCell = cells[0]; t.is(firstCell.block_number, "0x400"); t.is( firstCell.block_hash, "0x8df4763d10cf22509845f8ec728d56d1027d4dfe633cb91abf0d751ed5d45d68" ); }); test("CellCollectorWithQueryOptions", async (t) => { // @ts-ignore await cacheManager.cache.loop(); const queryOptions: QueryOptions = { lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0x0ce445e32d7f91c9392485ddb9bc6885ce46ad64", }, }; const cellCollector = new CellCollectorWithQueryOptions( new CellCollector(cacheManager), queryOptions ); const cells: Cell[] = []; for await (const cell of cellCollector.collect()) { cells.push(cell); } t.is(cells.length, 1); t.deepEqual( cells.map((cell) => BigInt(cell.cell_output.capacity)), [BigInt(200 * 10 ** 8)] ); }); test("CellCollectorWithQueryOptions, skip", async (t) => { // @ts-ignore await cacheManager.cache.loop(); const queryOptions: QueryOptions = { skip: 1, }; const cellCollector = new CellCollectorWithQueryOptions( new CellCollector(cacheManager), queryOptions ); const cells: Cell[] = []; for await (const cell of cellCollector.collect()) { cells.push(cell); } t.is(cells.length, 2); t.deepEqual( cells.map((cell) => BigInt(cell.cell_output.capacity)), [BigInt(300 * 10 ** 8), BigInt(400 * 10 ** 8)] ); }); test("getBalance", async (t) => { // @ts-ignore await cacheManager.cache.loop(); const balance = await getBalance(new CellCollector(cacheManager)); t.is(BigInt(balance), BigInt(900 * 10 ** 8)); }); test("getBalance, needMasterPublicKey", async (t) => { const cacheManager = CacheManager.fromMnemonic( indexer as Indexer, mnemonic, getDefaultInfos(), { TransactionCollector: MockTransactionCollector, rpc, needMasterPublicKey: true, } ); // @ts-ignore await cacheManager.cache.loop(); const balance = await getBalance(new CellCollector(cacheManager)); t.is(BigInt(balance), BigInt(950 * 10 ** 8)); }); test("publicKeyToMultisigArgs", (t) => { const publicKey = "0x024a501efd328e062c8675f2365970728c859c592beeefd6be8ead3d901330bc01"; const multisigArgs = "0x56f281b3d4bb5fc73c751714af0bf78eb8aba0d8"; t.is(publicKeyToMultisigArgs(publicKey), multisigArgs); });
the_stack
import { ethers, waffle } from "hardhat"; import { Signer, BigNumber } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { AlpacaToken, FairLaunch, FairLaunch__factory, MockContractContext, MockContractContext__factory, MockERC20, MockERC20__factory, MockWBNB, PancakePair, PancakePair__factory, MdexWorker02__factory, SimpleVaultConfig, Vault, Vault__factory, WNativeRelayer, MdexWorker02, MdexFactory, MdexRouter, BSCPool, MdxToken, MdexRestrictedStrategyAddBaseTokenOnly, MdexRestrictedStrategyAddTwoSidesOptimal, MdexRestrictedStrategyWithdrawMinimizeTrading, MdexRestrictedStrategyLiquidate, MdexRestrictedStrategyPartialCloseLiquidate, MdexRestrictedStrategyPartialCloseMinimizeTrading, BSCPool__factory, SwapMining, Oracle, WaultSwapToken__factory, MdxToken__factory, } from "../../../../../typechain"; import * as TimeHelpers from "../../../../helpers/time"; import * as AssertHelpers from "../../../../helpers/assert"; import { DeployHelper } from "../../../../helpers/deploy"; import { SwapHelper } from "../../../../helpers/swap"; import { Worker02Helper } from "../../../../helpers/worker"; chai.use(solidity); const { expect } = chai; describe("Vault - MdexWorker02", () => { const FOREVER = "2000000000"; const ALPACA_BONUS_LOCK_UP_BPS = 7000; const ALPACA_REWARD_PER_BLOCK = ethers.utils.parseEther("5000"); const MDX_REWARD_PER_BLOCK = ethers.utils.parseEther("0.076"); const REINVEST_BOUNTY_BPS = "100"; // 1% reinvest bounty const RESERVE_POOL_BPS = "1000"; // 10% reserve pool const KILL_PRIZE_BPS = "1000"; // 10% Kill prize const INTEREST_RATE = "3472222222222"; // 30% per year const MIN_DEBT_SIZE = ethers.utils.parseEther("1"); // 1 BTOKEN min debt size const WORK_FACTOR = "7000"; const KILL_FACTOR = "8000"; const MAX_REINVEST_BOUNTY: string = "500"; const DEPLOYER = "0xC44f82b07Ab3E691F826951a6E335E1bC1bB0B51"; const BENEFICIALVAULT_BOUNTY_BPS = "1000"; const REINVEST_THRESHOLD = ethers.utils.parseEther("1"); // If pendingCake > 1 $MDX, then reinvest const KILL_TREASURY_BPS = "100"; const POOL_IDX = 0; /// Mdex-related instance(s) let mdexFactory: MdexFactory; let mdexRouter: MdexRouter; let swapMining: SwapMining; let oracle: Oracle; let wbnb: MockWBNB; let lp: PancakePair; let mdxBnbLp: PancakePair; /// Token-related instance(s) let baseToken: MockERC20; let farmToken: MockERC20; let mdx: MdxToken; /// Strategy-ralted instance(s) let addStrat: MdexRestrictedStrategyAddBaseTokenOnly; let twoSidesStrat: MdexRestrictedStrategyAddTwoSidesOptimal; let liqStrat: MdexRestrictedStrategyLiquidate; let minimizeStrat: MdexRestrictedStrategyWithdrawMinimizeTrading; let partialCloseStrat: MdexRestrictedStrategyPartialCloseLiquidate; let partialCloseMinimizeStrat: MdexRestrictedStrategyPartialCloseMinimizeTrading; /// Vault-related instance(s) let simpleVaultConfig: SimpleVaultConfig; let wNativeRelayer: WNativeRelayer; let vault: Vault; /// FairLaunch-related instance(s) let fairLaunch: FairLaunch; let alpacaToken: AlpacaToken; /// MdexBSCPool-related instance(s) let bscPool: BSCPool; let mdexWorker: MdexWorker02; /// Timelock instance(s) let whitelistedContract: MockContractContext; let evilContract: MockContractContext; // Accounts let deployer: Signer; let alice: Signer; let bob: Signer; let eve: Signer; let deployerAddress: string; let aliceAddress: string; let bobAddress: string; let eveAddress: string; // Contract Signer let baseTokenAsAlice: MockERC20; let baseTokenAsBob: MockERC20; let mdxTokenAsDeployer: MdxToken; let farmTokenAsAlice: MockERC20; let fairLaunchAsAlice: FairLaunch; let lpAsAlice: PancakePair; let lpAsBob: PancakePair; let bscPoolAsAlice: BSCPool; let bscPoolAsBob: BSCPool; let mdexWorkerAsEve: MdexWorker02; let mdexWorkerAsDeployer: MdexWorker02; let vaultAsAlice: Vault; let vaultAsBob: Vault; let vaultAsEve: Vault; // Test Helper let swapHelper: SwapHelper; let workerHelper: Worker02Helper; async function fixture() { [deployer, alice, bob, eve] = await ethers.getSigners(); [deployerAddress, aliceAddress, bobAddress, eveAddress] = await Promise.all([ deployer.getAddress(), alice.getAddress(), bob.getAddress(), eve.getAddress(), ]); const deployHelper = new DeployHelper(deployer); // Setup MockContractContext const MockContractContext = (await ethers.getContractFactory( "MockContractContext", deployer )) as MockContractContext__factory; whitelistedContract = await MockContractContext.deploy(); await whitelistedContract.deployed(); evilContract = await MockContractContext.deploy(); await evilContract.deployed(); /// Setup token stuffs [baseToken, farmToken] = await deployHelper.deployBEP20([ { name: "BTOKEN", symbol: "BTOKEN", decimals: "18", holders: [ { address: deployerAddress, amount: ethers.utils.parseEther("1000") }, { address: aliceAddress, amount: ethers.utils.parseEther("1000") }, { address: bobAddress, amount: ethers.utils.parseEther("1000") }, ], }, { name: "FTOKEN", symbol: "FTOKEN", decimals: "18", holders: [ { address: deployerAddress, amount: ethers.utils.parseEther("1000") }, { address: aliceAddress, amount: ethers.utils.parseEther("1000") }, { address: bobAddress, amount: ethers.utils.parseEther("1000") }, ], }, ]); wbnb = await deployHelper.deployWBNB(); [mdexFactory, mdexRouter, mdx, bscPool, swapMining] = await deployHelper.deployMdex( wbnb, MDX_REWARD_PER_BLOCK, [{ address: deployerAddress, amount: ethers.utils.parseEther("100") }], farmToken.address ); [alpacaToken, fairLaunch] = await deployHelper.deployAlpacaFairLaunch( ALPACA_REWARD_PER_BLOCK, ALPACA_BONUS_LOCK_UP_BPS, 132, 137 ); [vault, simpleVaultConfig, wNativeRelayer] = await deployHelper.deployVault( wbnb, { minDebtSize: MIN_DEBT_SIZE, interestRate: INTEREST_RATE, reservePoolBps: RESERVE_POOL_BPS, killPrizeBps: KILL_PRIZE_BPS, killTreasuryBps: KILL_TREASURY_BPS, killTreasuryAddress: DEPLOYER, }, fairLaunch, baseToken ); // Setup strategies [addStrat, liqStrat, twoSidesStrat, minimizeStrat, partialCloseStrat, partialCloseMinimizeStrat] = await deployHelper.deployMdexStrategies(mdexRouter, vault, wbnb, wNativeRelayer, mdx); // whitelisted contract to be able to call work await simpleVaultConfig.setWhitelistedCallers([whitelistedContract.address], true); // whitelisted to be able to call kill await simpleVaultConfig.setWhitelistedLiquidators([await alice.getAddress(), await eve.getAddress()], true); // Set approved add strategies await simpleVaultConfig.setApprovedAddStrategy([addStrat.address, twoSidesStrat.address], true); // Setup BTOKEN-FTOKEN pair on Pancakeswap // Add lp to bscPool's pool await mdexFactory.createPair(baseToken.address, farmToken.address); await mdexFactory.createPair(mdx.address, wbnb.address); lp = PancakePair__factory.connect(await mdexFactory.getPair(farmToken.address, baseToken.address), deployer); mdxBnbLp = PancakePair__factory.connect(await mdexFactory.getPair(mdx.address, wbnb.address), deployer); await bscPool.add(1, lp.address, true); // set swapMining to router await mdexRouter.setSwapMining(swapMining.address); // Add lp to bscPool's pool await swapMining.addPair(0, lp.address, false); await swapMining.addPair(100, mdxBnbLp.address, false); await swapMining.addWhitelist(baseToken.address); await swapMining.addWhitelist(farmToken.address); await swapMining.addWhitelist(mdx.address); await swapMining.addWhitelist(wbnb.address); /// Setup MdexWorker02 mdexWorker = await deployHelper.deployMdexWorker02( vault, baseToken, bscPool, mdexRouter, POOL_IDX, WORK_FACTOR, KILL_FACTOR, addStrat, liqStrat, REINVEST_BOUNTY_BPS, [eveAddress], DEPLOYER, [mdx.address, wbnb.address, baseToken.address], [twoSidesStrat.address, minimizeStrat.address, partialCloseStrat.address, partialCloseMinimizeStrat.address], simpleVaultConfig ); swapHelper = new SwapHelper( mdexFactory.address, mdexRouter.address, BigNumber.from(9975), BigNumber.from(10000), deployer ); await swapHelper.addMdexLiquidities([ { token0: baseToken, token1: farmToken, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("0.1"), }, { token0: mdx, token1: wbnb, amount0desired: ethers.utils.parseEther("0.1"), amount1desired: ethers.utils.parseEther("1"), }, { token0: baseToken, token1: wbnb, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("1"), }, { token0: farmToken, token1: wbnb, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("1"), }, ]); // Contract signer baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); mdxTokenAsDeployer = MdxToken__factory.connect(mdx.address, deployer); farmTokenAsAlice = MockERC20__factory.connect(farmToken.address, alice); lpAsAlice = PancakePair__factory.connect(lp.address, alice); lpAsBob = PancakePair__factory.connect(lp.address, bob); fairLaunchAsAlice = FairLaunch__factory.connect(fairLaunch.address, alice); bscPoolAsAlice = BSCPool__factory.connect(bscPool.address, alice); bscPoolAsBob = BSCPool__factory.connect(bscPool.address, bob); vaultAsAlice = Vault__factory.connect(vault.address, alice); vaultAsBob = Vault__factory.connect(vault.address, bob); vaultAsEve = Vault__factory.connect(vault.address, eve); mdexWorkerAsEve = MdexWorker02__factory.connect(mdexWorker.address, eve); mdexWorkerAsDeployer = MdexWorker02__factory.connect(mdexWorker.address, deployer); } beforeEach(async () => { await waffle.loadFixture(fixture); // reassign SwapHelper here due to provider will be different for each test-case workerHelper = new Worker02Helper(mdexWorker.address, bscPool.address); }); context("when worker is initialized", async () => { it("should has FTOKEN as a farmingToken in MdexWorker02", async () => { expect(farmToken.address).to.be.equal(await mdexWorker.farmingToken()); }); it("should initialized the correct feeDenom", async () => { expect("10000").to.be.eq(await mdexWorker.feeDenom()); }); it("should give rewards out when you stake LP tokens", async () => { // Deployer sends some LP tokens to Alice and Bob await lp.transfer(aliceAddress, ethers.utils.parseEther("0.05")); await lp.transfer(bobAddress, ethers.utils.parseEther("0.05")); // Alice and Bob stake 0.01 LP tokens and waits for 1 day await lpAsAlice.approve(bscPool.address, ethers.utils.parseEther("0.01")); await lpAsBob.approve(bscPool.address, ethers.utils.parseEther("0.02")); await bscPoolAsAlice.deposit(POOL_IDX, ethers.utils.parseEther("0.01")); await bscPoolAsBob.deposit(POOL_IDX, ethers.utils.parseEther("0.02")); // alice +1 Reward // Alice and Bob withdraw stake from the pool await bscPoolAsBob.withdraw(POOL_IDX, ethers.utils.parseEther("0.02")); // alice +1/3 Reward Bob + 2/3 Reward await bscPoolAsAlice.withdraw(POOL_IDX, ethers.utils.parseEther("0.01")); // alice +1 Reward AssertHelpers.assertAlmostEqual( (await mdx.balanceOf(aliceAddress)).toString(), MDX_REWARD_PER_BLOCK.mul(BigNumber.from(7)).div(BigNumber.from(3)).toString() ); AssertHelpers.assertAlmostEqual( (await mdx.balanceOf(bobAddress)).toString(), MDX_REWARD_PER_BLOCK.mul(2).div(3).toString() ); }); }); context("when owner is setting worker", async () => { describe("#reinvestConfig", async () => { it("should set reinvest config correctly", async () => { await expect(mdexWorker.setReinvestConfig(250, ethers.utils.parseEther("1"), [mdx.address, baseToken.address])) .to.be.emit(mdexWorker, "SetReinvestConfig") .withArgs(deployerAddress, 250, ethers.utils.parseEther("1"), [mdx.address, baseToken.address]); expect(await mdexWorker.reinvestBountyBps()).to.be.eq(250); expect(await mdexWorker.reinvestThreshold()).to.be.eq(ethers.utils.parseEther("1")); expect(await mdexWorker.getReinvestPath()).to.deep.eq([mdx.address, baseToken.address]); }); it("should revert when owner set reinvestBountyBps > max", async () => { await expect(mdexWorker.setReinvestConfig(1000, "0", [mdx.address, baseToken.address])).to.be.revertedWith( "MdexWorker02::setReinvestConfig:: _reinvestBountyBps exceeded maxReinvestBountyBps" ); expect(await mdexWorker.reinvestBountyBps()).to.be.eq(100); }); it("should revert when owner set reinvest path that doesn't start with $MDX and end with $BTOKN", async () => { await expect(mdexWorker.setReinvestConfig(200, "0", [baseToken.address, mdx.address])).to.be.revertedWith( "MdexWorker02::setReinvestConfig:: _reinvestPath must start with MDX, end with BTOKEN" ); }); }); describe("#setMaxReinvestBountyBps", async () => { it("should set max reinvest bounty", async () => { await mdexWorker.setMaxReinvestBountyBps(200); expect(await mdexWorker.maxReinvestBountyBps()).to.be.eq(200); }); it("should revert when new max reinvest bounty over 30%", async () => { await expect(mdexWorker.setMaxReinvestBountyBps("3001")).to.be.revertedWith( "MdexWorker02::setMaxReinvestBountyBps:: _maxReinvestBountyBps exceeded 30%" ); expect(await mdexWorker.maxReinvestBountyBps()).to.be.eq("500"); }); }); describe("#setTreasuryConfig", async () => { it("should successfully set a treasury account", async () => { const aliceAddr = aliceAddress; await mdexWorker.setTreasuryConfig(aliceAddr, REINVEST_BOUNTY_BPS); expect(await mdexWorker.treasuryAccount()).to.eq(aliceAddr); }); it("should successfully set a treasury bounty", async () => { await mdexWorker.setTreasuryConfig(DEPLOYER, 499); expect(await mdexWorker.treasuryBountyBps()).to.eq(499); }); it("should revert when a new treasury bounty > max reinvest bounty bps", async () => { await expect(mdexWorker.setTreasuryConfig(DEPLOYER, parseInt(MAX_REINVEST_BOUNTY) + 1)).to.revertedWith( "MdexWorker02::setTreasuryConfig:: _treasuryBountyBps exceeded maxReinvestBountyBps" ); expect(await mdexWorker.treasuryBountyBps()).to.eq(REINVEST_BOUNTY_BPS); }); }); describe("#setStrategyOk", async () => { it("should set strat ok", async () => { await mdexWorker.setStrategyOk([aliceAddress], true); expect(await mdexWorker.okStrats(aliceAddress)).to.be.eq(true); }); }); }); context("when user uses LYF", async () => { context("when user is contract", async () => { it("should revert if evil contract try to call onlyEOAorWhitelisted function", async () => { await expect( evilContract.executeTransaction( vault.address, 0, "work(uint256,address,uint256,uint256,uint256,bytes)", ethers.utils.defaultAbiCoder.encode( ["uint256", "address", "uint256", "uint256", "uint256", "bytes"], [ 0, mdexWorker.address, ethers.utils.parseEther("0.3"), "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ), ] ) ) ).to.be.revertedWith("not eoa"); }); it("should allow whitelisted contract to open position without debt", async () => { // Deployer deposit 3 BTOKEN to the vault await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Deployer funds whitelisted contract await baseToken.transfer(whitelistedContract.address, ethers.utils.parseEther("1")); // whitelisted contract approve Alpaca to to take BTOKEN await whitelistedContract.executeTransaction( baseToken.address, "0", "approve(address,uint256)", ethers.utils.defaultAbiCoder.encode(["address", "uint256"], [vault.address, ethers.utils.parseEther("0.3")]) ); expect(await baseToken.allowance(whitelistedContract.address, vault.address)).to.be.eq( ethers.utils.parseEther("0.3") ); // whitelisted contract should able to open position with 0 debt await whitelistedContract.executeTransaction( vault.address, 0, "work(uint256,address,uint256,uint256,uint256,bytes)", ethers.utils.defaultAbiCoder.encode( ["uint256", "address", "uint256", "uint256", "uint256", "bytes"], [ 0, mdexWorker.address, ethers.utils.parseEther("0.3"), "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ), ] ) ); const [worker, owner] = await vault.positions(1); expect(owner).to.be.eq(whitelistedContract.address); expect(worker).to.be.eq(mdexWorker.address); }); it("should revert if evil contract try to call onlyWhitelistedLiquidators function", async () => { await expect( evilContract.executeTransaction( vault.address, 0, "kill(uint256)", ethers.utils.defaultAbiCoder.encode(["uint256"], [0]) ) ).to.be.revertedWith("!whitelisted liquidator"); }); }); context("when user is EOA", async () => { context("#work", async () => { it("should allow to open a position without debt", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice can take 0 debt ok await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("0"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); it("should not allow to open a position with debt less than MIN_DEBT_SIZE", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice cannot take 0.3 debt because it is too small await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await expect( vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("0.3"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("too small debt size"); }); it("should not allow to open the position with bad work factor", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice cannot take 1 BTOKEN loan because she only put 0.3 BTOKEN as a collateral await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await expect( vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("bad work factor"); }); it("should not allow positions if Vault has less BaseToken than requested loan", async () => { // Alice cannot take 1 BTOKEN loan because the contract does not have it await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await expect( vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("insufficient funds in the vault"); }); it("should not able to liquidate healthy position", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 BTOKEN health (minus some small trading fee) await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation // You can't liquidate her position yet await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); }); it("should work", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) expect(await mdexWorker.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); // Eve comes and trigger reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); AssertHelpers.assertAlmostEqual( MDX_REWARD_PER_BLOCK.mul("2").mul(REINVEST_BOUNTY_BPS).div("10000").toString(), (await mdx.balanceOf(eveAddress)).toString() ); await vault.deposit(0); // Random action to trigger interest computation const healthDebt = await vault.positionInfo("1"); expect(healthDebt[0]).to.be.above(ethers.utils.parseEther("2")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(healthDebt[1].toString(), interest.add(loan).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(loan).toString() ); AssertHelpers.assertAlmostEqual((await vault.vaultDebtVal()).toString(), interest.add(loan).toString()); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); }); it("should work when worker fee has changed to 20", async () => { // Deployer deposits 3 BTOKEN to the bank await mdexFactory.setFeeRateNumerator(20); const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) // To find health of the position, derive following variables: // totalBaseToken = 2.999999999999999958 // totalFarmingToken = 0.1 // userBaseToken = 1.267216253674334111 // userFarmingToken = 0.042240541789144470 // health = amount of underlying of lp after converted to BTOKEN // = userBaseToken + userFarmingTokenAfterSellToBaseToken // Find userFarmingTokenAfterSellToBaseToken from // mktSellAMount // = [(userFarmingToken * 9980) * (totalBaseToken - userBaseToken)] / [((totalFarmingToken - userFarmingToken) * 10000) + (userFarmingToken * 9980)] // = [(0.042240541789144470 * 9980) * (2.999999999999999958 - 1.267216253674334111)] / [((0.1 - 0.042240541789144470) * 10000) + (0.042240541789144470 * 9980)] // = 0.731091001597324380 // health = userBaseToken + userFarmingTokenAfterSellToBaseToken // = 1.267216253674334111 + 0.731091001597324380 // = 1.998307255271658491 expect(await mdexWorker.health(1)).to.be.eq(ethers.utils.parseEther("1.998307255271658491")); // Eve comes and trigger reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); AssertHelpers.assertAlmostEqual( MDX_REWARD_PER_BLOCK.mul("2").mul(REINVEST_BOUNTY_BPS).div("10000").toString(), (await mdx.balanceOf(eveAddress)).toString() ); await vault.deposit(0); // Random action to trigger interest computation const healthDebt = await vault.positionInfo("1"); expect(healthDebt[0]).to.be.above(ethers.utils.parseEther("2")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(healthDebt[1].toString(), interest.add(loan).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(loan).toString() ); AssertHelpers.assertAlmostEqual((await vault.vaultDebtVal()).toString(), interest.add(loan).toString()); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); }); it("should has correct interest rate growth", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); }); it("should close position correctly when user holds multiple positions", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size,close position correctly when user holds "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Set Reinvest bounty to 10% of the reward await mdexWorker.setReinvestConfig("100", "0", [mdx.address, wbnb.address, baseToken.address]); const [path, reinvestPath] = await Promise.all([mdexWorker.getPath(), mdexWorker.getReinvestPath()]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await mdexWorker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeBefore = await mdx.balanceOf(eveAddress); let deployerCakeBefore = await mdx.balanceOf(DEPLOYER); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("2"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeAfter = await mdx.balanceOf(eveAddress); let deployerCakeAfter = await mdx.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} MDX as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's MDX to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); deployerCakeBefore = await mdx.balanceOf(DEPLOYER); eveCakeBefore = await mdx.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await mdexWorkerAsEve.reinvest(); deployerCakeAfter = await mdx.balanceOf(DEPLOYER); eveCakeAfter = await mdx.balanceOf(eveAddress); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's MDX to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [bob2Health, bob2DebtToShare] = await vault.positionInfo("2"); const bob2ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), baseToken.address, farmToken.address ); expect(bob2Health, `expect Pos#2 health = ${bob2ExpectedHealth}`).to.be.eq(bob2ExpectedHealth); expect(bob2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("2").toString(), bob2DebtToShare.toString()); let bobBefore = await baseToken.balanceOf(bobAddress); let bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, mdexWorker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let bobAfter = await baseToken.balanceOf(bobAddress); let bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); expect(bobAfter).to.be.gt(bobBefore); // Bob add another 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 2, mdexWorker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobBefore = await baseToken.balanceOf(bobAddress); bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#2 await vaultAsBob.work( 2, mdexWorker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobAfter = await baseToken.balanceOf(bobAddress); bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as she earned from leverage yield farm without getting liquidated expect(bobAfter).to.be.gt(bobBefore); expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); }); it("should close position correctly when user holds mix positions of leveraged and non-leveraged", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); const [path, reinvestPath] = await Promise.all([mdexWorker.getPath(), mdexWorker.getReinvestPath()]); // Set Reinvest bounty to 10% of the reward await mdexWorker.setReinvestConfig("100", "0", [mdx.address, wbnb.address, baseToken.address]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await mdexWorker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeBefore = await mdx.balanceOf(eveAddress); let deployerCakeBefore = await mdx.balanceOf(DEPLOYER); // Position#2: Bob open 1x position with 3 BTOKEN await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("3")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("3"), "0", "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeAfter = await mdx.balanceOf(eveAddress); let deployerCakeAfter = await mdx.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} MDX as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's MDX to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); deployerCakeBefore = await mdx.balanceOf(DEPLOYER); eveCakeBefore = await mdx.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await mdexWorkerAsEve.reinvest(); deployerCakeAfter = await mdx.balanceOf(DEPLOYER); eveCakeAfter = await mdx.balanceOf(eveAddress); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's MDX to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [bob2Health, bob2DebtToShare] = await vault.positionInfo("2"); const bob2ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), baseToken.address, farmToken.address ); expect(bob2Health, `expect Pos#2 health = ${bob2ExpectedHealth}`).to.be.eq(bob2ExpectedHealth); expect(bob2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual("0", bob2DebtToShare.toString()); let bobBefore = await baseToken.balanceOf(bobAddress); let bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, mdexWorker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let bobAfter = await baseToken.balanceOf(bobAddress); let bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); expect(bobAfter).to.be.gt(bobBefore); // Bob add another 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 2, mdexWorker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobBefore = await baseToken.balanceOf(bobAddress); bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#2 await vaultAsBob.work( 2, mdexWorker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobAfter = await baseToken.balanceOf(bobAddress); bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as she earned from leverage yield farm without getting liquidated // But bob shouldn't earn more ALPACAs from closing position#2 expect(bobAfter).to.be.gt(bobBefore); expect(bobAlpacaAfter).to.be.eq(bobAlpacaBefore); }); }); context("#kill", async () => { it("should not allow user not whitelisted to liquidate", async () => { await expect(vaultAsBob.kill("1")).to.be.revertedWith("!whitelisted liquidator"); }); it("should be able to liquidate bad position", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Calculate the expected result. // set interest rate to be 0 to be easy for testing. await simpleVaultConfig.setParams( MIN_DEBT_SIZE, 0, RESERVE_POOL_BPS, KILL_PRIZE_BPS, wbnb.address, wNativeRelayer.address, fairLaunch.address, KILL_TREASURY_BPS, deployerAddress ); const toBeLiquidatedValue = await mdexWorker.health(1); const liquidationBounty = toBeLiquidatedValue.mul(KILL_PRIZE_BPS).div(10000); const treasuryKillFees = toBeLiquidatedValue.mul(KILL_TREASURY_BPS).div(10000); const totalLiquidationFees = liquidationBounty.add(treasuryKillFees); const eveBalanceBefore = await baseToken.balanceOf(eveAddress); const aliceAlpacaBefore = await alpacaToken.balanceOf(aliceAddress); const aliceBalanceBefore = await baseToken.balanceOf(aliceAddress); const vaultBalanceBefore = await baseToken.balanceOf(vault.address); const deployerBalanceBefore = await baseToken.balanceOf(deployerAddress); const vaultDebtVal = await vault.vaultDebtVal(); const debt = await vault.debtShareToVal((await vault.positions(1)).debtShare); const left = debt.gte(toBeLiquidatedValue.sub(totalLiquidationFees)) ? ethers.constants.Zero : toBeLiquidatedValue.sub(totalLiquidationFees).sub(debt); // Now eve kill the position await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); // Getting balances after killed const eveBalanceAfter = await baseToken.balanceOf(eveAddress); const aliceBalanceAfter = await baseToken.balanceOf(aliceAddress); const vaultBalanceAfter = await baseToken.balanceOf(vault.address); const deployerBalanceAfter = await baseToken.balanceOf(deployerAddress); AssertHelpers.assertAlmostEqual( deposit.add(interest).add(interest.mul(13).div(10)).add(interest.mul(13).div(10)).toString(), (await baseToken.balanceOf(vault.address)).toString() ); expect(await vault.vaultDebtVal()).to.be.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( reservePool.add(reservePool.mul(13).div(10)).add(reservePool.mul(13).div(10)).toString(), (await vault.reservePool()).toString() ); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); expect(eveBalanceAfter.sub(eveBalanceBefore), "expect Eve to get her liquidation bounty").to.be.eq( liquidationBounty ); expect( deployerBalanceAfter.sub(deployerBalanceBefore), "expect Deployer to get treasury liquidation fees" ).to.be.eq(treasuryKillFees); expect(aliceBalanceAfter.sub(aliceBalanceBefore), "expect Alice to get her leftover back").to.be.eq(left); expect(vaultBalanceAfter.sub(vaultBalanceBefore), "expect Vault to get its funds + interest").to.be.eq( vaultDebtVal ); expect((await vault.positions(1)).debtShare, "expect Pos#1 debt share to be 0").to.be.eq(0); expect( await alpacaToken.balanceOf(aliceAddress), "expect Alice to get some ALPACA from holding LYF position" ).to.be.gt(aliceAlpacaBefore); // Alice creates a new position again await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // She can close position await vaultAsAlice.work( 2, mdexWorker.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); it("should liquidate user position correctly", async () => { // Bob deposits 20 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("20")); await vaultAsBob.deposit(ethers.utils.parseEther("20")); // Position#1: Alice borrows 10 BTOKEN loan await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await farmToken.mint(deployerAddress, ethers.utils.parseEther("100")); await farmToken.approve(mdexRouter.address, ethers.utils.parseEther("100")); // Price swing 10% // Add more token to the pool equals to sqrt(10*((0.1)**2) / 9) - 0.1 = 0.005409255338945984, (0.1 is the balance of token in the pool) await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("0.005409255338945984"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 20% // Add more token to the pool equals to // sqrt(10*((0.10540925533894599)**2) / 8) - 0.10540925533894599 = 0.012441874858811944 // (0.10540925533894599 is the balance of token in the pool) await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("0.012441874858811944"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 23.43% // Existing token on the pool = 0.10540925533894599 + 0.012441874858811944 = 0.11785113019775793 // Add more token to the pool equals to // sqrt(10*((0.11785113019775793)**2) / 7.656999999999999) - 0.11785113019775793 = 0.016829279312591913 await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("0.016829279312591913"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 30% // Existing token on the pool = 0.11785113019775793 + 0.016829279312591913 = 0.13468040951034985 // Add more token to the pool equals to // sqrt(10*((0.13468040951034985)**2) / 7) - 0.13468040951034985 = 0.026293469053292218 await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("0.026293469053292218"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Now you can liquidate because of the price fluctuation const eveBefore = await baseToken.balanceOf(eveAddress); await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); expect(await baseToken.balanceOf(eveAddress)).to.be.gt(eveBefore); }); }); context("#onlyApprovedHolder", async () => { it("should be not allow user to emergencyWithdraw debtToken on FairLaunch", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await mdexWorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Alice emergencyWithdraw from FairLaunch await expect(fairLaunchAsAlice.emergencyWithdraw(0)).to.be.revertedWith("only funder"); const eveBefore = await baseToken.balanceOf(eveAddress); // Now you can liquidate because of the insane interest rate await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); expect(await baseToken.balanceOf(eveAddress)).to.be.gt(eveBefore); AssertHelpers.assertAlmostEqual( deposit.add(interest).add(interest.mul(13).div(10)).add(interest.mul(13).div(10)).toString(), (await baseToken.balanceOf(vault.address)).toString() ); expect(await vault.vaultDebtVal()).to.be.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( reservePool.add(reservePool.mul(13).div(10)).add(reservePool.mul(13).div(10)).toString(), (await vault.reservePool()).toString() ); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Alice creates a new position again await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // She can close position await vaultAsAlice.work( 2, mdexWorker.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); }); context("#deposit-#withdraw", async () => { it("should deposit and withdraw BTOKEN from Vault (bad debt case)", async () => { // Deployer deposits 10 BTOKEN to the Vault const deposit = ethers.utils.parseEther("10"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); expect(await vault.balanceOf(deployerAddress)).to.be.equal(deposit); // Bob borrows 2 BTOKEN loan const loan = ethers.utils.parseEther("2"); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), loan, "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); expect(await baseToken.balanceOf(vault.address)).to.be.equal(deposit.sub(loan)); expect(await vault.vaultDebtVal()).to.be.equal(loan); expect(await vault.totalToken()).to.be.equal(deposit); // Alice deposits 2 BTOKEN const aliceDeposit = ethers.utils.parseEther("2"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("2")); await vaultAsAlice.deposit(aliceDeposit); AssertHelpers.assertAlmostEqual( deposit.sub(loan).add(aliceDeposit).toString(), (await baseToken.balanceOf(vault.address)).toString() ); // check Alice ibBTOKEN balance = 2/10 * 10 = 2 ibBTOKEN AssertHelpers.assertAlmostEqual(aliceDeposit.toString(), (await vault.balanceOf(aliceAddress)).toString()); AssertHelpers.assertAlmostEqual(deposit.add(aliceDeposit).toString(), (await vault.totalSupply()).toString()); // Simulate BTOKEN price is very high by swap FTOKEN to BTOKEN (reduce BTOKEN supply) await farmToken.mint(deployerAddress, ethers.utils.parseEther("100")); await farmToken.approve(mdexRouter.address, ethers.utils.parseEther("100")); await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("100"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Alice liquidates Bob position#1 let aliceBefore = await baseToken.balanceOf(aliceAddress); await expect(vaultAsAlice.kill("1")).to.emit(vaultAsAlice, "Kill"); let aliceAfter = await baseToken.balanceOf(aliceAddress); // Bank balance is increase by liquidation AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("10.002702699312215556").toString(), (await baseToken.balanceOf(vault.address)).toString() ); // Alice is liquidator, Alice should receive 10% Kill prize // BTOKEN back from liquidation 0.00300199830261993, 10% of it is 0.000300199830261993 AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("0.000300199830261993").toString(), aliceAfter.sub(aliceBefore).toString() ); // Alice withdraws 2 BOKTEN aliceBefore = await baseToken.balanceOf(aliceAddress); await vaultAsAlice.withdraw(await vault.balanceOf(aliceAddress)); aliceAfter = await baseToken.balanceOf(aliceAddress); // alice gots 2/12 * 10.002702699312215556 = 1.667117116552036 AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("1.667117116552036").toString(), aliceAfter.sub(aliceBefore).toString() ); }); }); context("#reinvest", async () => { it("should reinvest correctly", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Set Reinvest bounty to 10% of the reward await mdexWorker.setReinvestConfig("100", "0", [mdx.address, wbnb.address, baseToken.address]); const [path, reinvestPath] = await Promise.all([mdexWorker.getPath(), mdexWorker.getReinvestPath()]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await mdexWorker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeBefore = await mdx.balanceOf(eveAddress); let deployerCakeBefore = await mdx.balanceOf(DEPLOYER); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("2"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); let eveCakeAfter = await mdx.balanceOf(eveAddress); let deployerCakeAfter = await mdx.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} MDX as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's MDX to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); deployerCakeBefore = await mdx.balanceOf(DEPLOYER); eveCakeBefore = await mdx.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await mdexWorkerAsEve.reinvest(); deployerCakeAfter = await mdx.balanceOf(DEPLOYER); eveCakeAfter = await mdx.balanceOf(eveAddress); [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, MDX_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await mdexWorker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await mdexWorker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's MDX to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [alice2Health, alice2DebtToShare] = await vault.positionInfo("2"); const alice2ExpectedHealth = await swapHelper.computeLpHealth( await mdexWorker.shareToBalance(await mdexWorker.shares(2)), baseToken.address, farmToken.address ); expect(alice2Health, `expect Pos#2 health = ${alice2ExpectedHealth}`).to.be.eq(alice2ExpectedHealth); expect(alice2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("2").toString(), alice2DebtToShare.toString()); const bobBefore = await baseToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, mdexWorker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAfter).to.be.gt(bobBefore); // Alice add another 10 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsAlice.work( 2, mdexWorker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const aliceBefore = await baseToken.balanceOf(aliceAddress); // Alice close position#2 await vaultAsAlice.work( 2, mdexWorker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const aliceAfter = await baseToken.balanceOf(aliceAddress); // Check Alice account, Alice must be richer as she earned from leverage yield farm without getting liquidated expect(aliceAfter).to.be.gt(aliceBefore); }); }); context("#partialclose", async () => { context("#liquidate", async () => { context("when maxReturn is lessDebt", async () => { // back cannot be less than lessDebt as less debt is Min(debt, back, maxReturn) = maxReturn it("should pay debt 'maxReturn' BTOKEN and return 'liquidatedAmount - maxReturn' BTOKEN to user", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); const [path, reinvestPath] = await Promise.all([mdexWorker.getPath(), mdexWorker.getReinvestPath()]); // Set Reinvest bounty to 1% of the reward await mdexWorker.setReinvestConfig("100", "0", [mdx.address, wbnb.address, baseToken.address]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN loan and supply another 10 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 20 BTOKEN needs to swap 3.587061715703192586 BTOKEN to FTOKEN // new reserve after swap will be 4.587061715703192586 0.021843151027158060 // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 16.412938284296807414 BTOKEN - 0.078156848972841940 FTOKEN // new reserve after adding liquidity 21.000000000000000000 BTOKEN - 0.100000000000000000 FTOKEN // lp amount from adding liquidity will be 1.131492691639043045 LP const borrowedAmount = ethers.utils.parseEther("10"); const principalAmount = ethers.utils.parseEther("10"); let [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, principalAmount, borrowedAmount, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); const [expectedLp, debrisBtoken] = await swapHelper.computeOneSidedOptimalLp( borrowedAmount.add(principalAmount), path ); expect(workerLpAfter.sub(workerLpBefore)).to.eq(expectedLp); const deployerCakeBefore = await mdx.balanceOf(DEPLOYER); const bobBefore = await baseToken.balanceOf(bobAddress); const [bobHealthBefore] = await vault.positionInfo("1"); const lpUnderBobPosition = await mdexWorker.shareToBalance(await mdexWorker.shares(1)); const liquidatedLp = lpUnderBobPosition.div(2); const returnDebt = ethers.utils.parseEther("6"); [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); // Pre-compute await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); // Compute reinvest const [reinvestFees, reinvestLp] = await swapHelper.computeReinvestLp( workerLpBefore, debrisBtoken, MDX_REWARD_PER_BLOCK, BigNumber.from(REINVEST_BOUNTY_BPS), reinvestPath, path, BigNumber.from(1) ); // Compute liquidate const [btokenAmount, ftokenAmount] = await swapHelper.computeRemoveLiquidiy( baseToken.address, farmToken.address, liquidatedLp ); const sellFtokenAmounts = await swapHelper.computeSwapExactTokensForTokens( ftokenAmount, await mdexWorker.getReversedPath(), true ); const liquidatedBtoken = sellFtokenAmounts[sellFtokenAmounts.length - 1] .add(btokenAmount) .sub(returnDebt); await vaultAsBob.work( 1, mdexWorker.address, "0", "0", returnDebt, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [liquidatedLp, returnDebt, liquidatedBtoken] ), ] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); const deployerCakeAfter = await mdx.balanceOf(DEPLOYER); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect Deployer to get ${reinvestFees}`).to.be.eq( reinvestFees ); expect(bobAfter.sub(bobBefore), `expect Bob get ${liquidatedBtoken}`).to.be.eq(liquidatedBtoken); // Check Bob position info const [bobHealth, bobDebtToShare] = await vault.positionInfo("1"); // Bob's health after partial close position must be 50% less than before // due to he exit half of lp under his position expect(bobHealth).to.be.lt(bobHealthBefore.div(2)); // Bob's debt should be left only 4 BTOKEN due he said he wants to return at max 4 BTOKEN expect(bobDebtToShare).to.be.eq(borrowedAmount.sub(returnDebt)); // Check LP deposited by Worker on MasterChef [workerLpAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); // LP tokens + 0.000207570473714694 LP from reinvest of worker should be decreased by lpUnderBobPosition/2 // due to Bob execute StrategyClosePartialLiquidate expect(workerLpAfter).to.be.eq(workerLpBefore.add(reinvestLp).sub(lpUnderBobPosition.div(2))); }); }); context("when debt is lessDebt", async () => { // back cannot be less than lessDebt as less debt is Min(debt, back, maxReturn) = debt it("should pay back all debt and return 'liquidatedAmount - debt' BTOKEN to user", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN loan and supply another 10 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 20 BTOKEN needs to swap 3.587061715703192586 BTOKEN to FTOKEN // new reserve after swap will be 4.587061715703192586 0.021843151027158060 // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 16.412938284296807414 BTOKEN - 0.078156848972841940 FTOKEN // new reserve after adding liquidity 21.000000000000000000 BTOKEN - 0.100000000000000000 FTOKEN // lp amount from adding liquidity will be 1.131492691639043045 LP let [workerLPBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let [workerLPAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); expect(workerLPAfter.sub(workerLPBefore)).to.eq(ethers.utils.parseEther("1.131492691639043045")); // Bob think he made enough. He now wants to close position partially. // He close 50% of his position and return all debt const bobBefore = await baseToken.balanceOf(bobAddress); const [bobHealthBefore] = await vault.positionInfo("1"); const lpUnderBobPosition = await mdexWorker.shareToBalance(await mdexWorker.shares(1)); [workerLPBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); // Bob think he made enough. He now wants to close position partially. // After calling `work()`, the `_reinvest()` is invoked // since 1 blocks have passed since approve and work now reward will be 0.076 * 1 =~ 0.075999999998831803 ~ MDX // reward without bounty will be 0.075999999998831803 - 0.000759999999988318 =~ 0.0752399999988435 MDX // 0.0752399999988435 MDX can be converted into: // (0.0752399999988435 * 0.9975 * 1) / (0.1 + 0.0752399999988435 * 0.9975) = 0.428740847712892766 WBNB // 0.428740847712892766 WBNB can be converted into (0.428740847712892766 * 0.9975 * 1) / (1 + 0.428740847712892766 * 0.9975) = 0.299557528330150526 BTOKEN // based on optimal swap formula, 0.299557528330150526 BTOKEN needs to swap 0.149435199790075736 BTOKEN // new reserve after swap will be 21.149435199790075736 BTOKEN - 0.099295185694161018 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 0.150122328540074790 BTOKEN - 0.000704814305838982 FTOKEN // new reserve after adding liquidity receiving from `_reinvest()` is 21.299557528330150526 BTOKEN - 0.100000000000000000 FTOKEN // more LP amount after executing add strategy will be 0.010276168801924356 LP // accumulated LP of the worker will be 1.131492691639043045 + 0.010276168801924356 = 1.1417688604409675 LP // bob close 50% of his position, thus he will close 1.131492691639043045 * (1.131492691639043045 / (1.131492691639043045)) =~ 1.131492691639043045 / 2 = 0.5657463458195215 LP // 0.5657463458195215 LP will be converted into 8.264866063854500749 BTOKEN - 0.038802994160144191 FTOKEN // 0.038802994160144191 FTOKEN will be converted into (0.038802994160144191 * 0.9975 * 13.034691464475649777) / (0.061197005839855809 + 0.038802994160144191 * 0.9975) = 5.050104921127982573 BTOKEN // thus, Bob will receive 8.264866063854500749 + 5.050104921127982573 = 13.314970984982483322 BTOKEN await vaultAsBob.work( 1, mdexWorker.address, "0", "0", ethers.utils.parseEther("5000000000"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ lpUnderBobPosition.div(2), ethers.utils.parseEther("5000000000"), ethers.utils.parseEther("3.314970984982483322"), ] ), ] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); // After Bob liquidate half of his position which worth // 13.314970984982483322 BTOKEN (price impact+trading fee included) // Bob wish to return 5,000,000,000 BTOKEN (when maxReturn > debt, return all debt) // The following criteria must be stratified: // - Bob should get 13.314970984982483322 - 10 = 3.314970984982483322 BTOKEN back. // - Bob's position debt must be 0 expect( bobBefore.add(ethers.utils.parseEther("3.314970984982483322")), "Expect BTOKEN in Bob's account after close position to increase by ~3.32 BTOKEN" ).to.be.eq(bobAfter); // Check Bob position info const [bobHealth, bobDebtVal] = await vault.positionInfo("1"); // Bob's health after partial close position must be 50% less than before // due to he exit half of lp under his position expect(bobHealth).to.be.lt(bobHealthBefore.div(2)); // Bob's debt should be 0 BTOKEN due he said he wants to return at max 5,000,000,000 BTOKEN (> debt, return all debt) expect(bobDebtVal).to.be.eq("0"); // Check LP deposited by Worker on MasterChef [workerLPAfter] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); // LP tokens + LP tokens from reinvest of worker should be decreased by lpUnderBobPosition/2 // due to Bob execute StrategyClosePartialLiquidate expect(workerLPAfter).to.be.eq( workerLPBefore.add(ethers.utils.parseEther("0.010276168801924356")).sub(lpUnderBobPosition.div(2)) ); }); }); context("when worker factor is not satisfy", async () => { it("should revert bad work factor", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, mdexWorker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Bob think he made enough. He now wants to close position partially. // He liquidate all of his position but not payback the debt. const lpUnderBobPosition = await mdexWorker.shareToBalance(await mdexWorker.shares(1)); // Bob closes position with maxReturn 0 and liquidate all of his position // Expect that Bob will not be able to close his position as he liquidate all underlying assets but not paydebt // which made his position debt ratio higher than allow work factor await expect( vaultAsBob.work( 1, mdexWorker.address, "0", "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [lpUnderBobPosition, "0", "0"] ), ] ) ) ).revertedWith("bad work factor"); }); }); }); }); context("#addCollateral", async () => { const deposit = ethers.utils.parseEther("3"); const borrowedAmount = ethers.utils.parseEther("1"); let snapedTimestampAfterWork: BigNumber = ethers.constants.Zero; beforeEach(async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can borrow 1 BTOKEN + 1 BTOKEN of her to create a new position await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); // Position#1: Alice borrows 1 BTOKEN and supply another 1 BTOKEN // After calling `work()` // 2 BTOKEN needs to swap 0.0732967258967755614 BTOKEN to 0.042234424701074812 FTOKEN // new reserve after swap will be 1.732967258967755614 BTOKEN 0.057765575298925188 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 1.267032741032244386 BTOKEN + 0.042234424701074812 FTOKEN // lp amount from adding liquidity will be (0.042234424701074812 / 0.057765575298925188) * 0.316227766016837933(first total supply) = 0.231205137369691323 LP // new reserve after adding liquidity 2.999999999999999954 BTOKEN + 0.100000000000000000 FTOKEN // ---------------- // BTOKEN-FTOKEN reserve = 2.999999999999999954 BTOKEN + 0.100000000000000000 FTOKEN // BTOKEN-FTOKEN total supply = 0.547432903386529256 BTOKEN-FTOKEN LP // ---------------- await swapHelper.loadReserves(await mdexWorker.getPath()); await vaultAsAlice.work( 0, mdexWorker.address, ethers.utils.parseEther("1"), borrowedAmount, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); snapedTimestampAfterWork = await TimeHelpers.latest(); const [expectedLp] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("1").add(borrowedAmount), await mdexWorker.getPath() ); const expectedHealth = await swapHelper.computeLpHealth(expectedLp, baseToken.address, farmToken.address); expect(await mdexWorker.health(1)).to.be.eq(expectedHealth); expect(await mdexWorker.shares(1)).to.eq(expectedLp); expect(await mdexWorker.shareToBalance(await mdexWorker.shares(1))).to.eq(expectedLp); }); async function successBtokenOnly(lastWorkBlock: BigNumber, goRouge: boolean) { let accumLp = await mdexWorker.shareToBalance(await mdexWorker.shares(1)); const [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); const debris = await baseToken.balanceOf(addStrat.address); const reinvestPath = await mdexWorker.getReinvestPath(); const path = await mdexWorker.getPath(); let reserves = await swapHelper.loadReserves(reinvestPath); reserves.push(...(await swapHelper.loadReserves(path))); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); const targetTestTimeStamp = snapedTimestampAfterWork.add( TimeHelpers.duration.days(ethers.BigNumber.from("1")) ); await TimeHelpers.set(targetTestTimeStamp); await vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const blockAfter = await TimeHelpers.latestBlockNumber(); const blockDiff = blockAfter.sub(lastWorkBlock); const totalRewards = workerLpBefore .mul(MDX_REWARD_PER_BLOCK.mul(blockDiff).mul(1e12).div(workerLpBefore)) .div(1e12); const totalReinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); const reinvestLeft = totalRewards.sub(totalReinvestFees); const reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); const reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debris); const [reinvestLp] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); // Compute add collateral const addCollateralBtoken = ethers.utils.parseEther("1"); const [addCollateralLp] = await swapHelper.computeOneSidedOptimalLp(addCollateralBtoken, path); accumLp = accumLp.add(addCollateralLp); const [health, debt] = await vault.positionInfo("1"); expect(health).to.be.above(ethers.utils.parseEther("3")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(debt.toString(), interest.add(borrowedAmount).toString()); const baseAmount = (await baseToken.balanceOf(vault.address)).toString(); AssertHelpers.assertAlmostEqual(baseAmount, deposit.sub(borrowedAmount).toString()); AssertHelpers.assertAlmostEqual( (await vault.vaultDebtVal()).toString(), interest.add(borrowedAmount).toString() ); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); const vaultReservePool = (await vault.reservePool()).toString(); AssertHelpers.assertAlmostEqual(reservePool.toString(), vaultReservePool); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); const deployerMdxBalance = await mdx.balanceOf(DEPLOYER); expect(await mdexWorker.shares(1), `expect Alice's shares = ${accumLp}`).to.be.eq(accumLp); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Alice's staked LPs = ${accumLp}` ).to.be.eq(accumLp); expect( deployerMdxBalance, `expect Deployer gets ${ethers.utils.formatEther(totalReinvestFees)} MDX` ).to.be.eq(totalReinvestFees); // Check reward // withdraw trading reward to deployer const withDrawTx = await mdexWorker.withdrawTradingRewards(DEPLOYER); const mdxAfter = await mdx.balanceOf(DEPLOYER); // get trading reward of the previos block const pIds = [0, 1]; const totalRewardPrev = await mdexWorker.getMiningRewards(pIds, { blockTag: Number(withDrawTx.blockNumber) - 1, }); const withDrawBlockReward = await swapMining["reward()"]({ blockTag: withDrawTx.blockNumber }); const totalReward = totalRewardPrev.add(withDrawBlockReward); expect(mdxAfter.sub(deployerMdxBalance)).to.eq(totalReward); } async function successTwoSides(lastWorkBlock: BigNumber, goRouge: boolean) { await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); // Random action to trigger interest computation await vault.deposit("0"); // Set intertest rate to 0 for easy testing await simpleVaultConfig.setParams( MIN_DEBT_SIZE, 0, RESERVE_POOL_BPS, KILL_PRIZE_BPS, wbnb.address, wNativeRelayer.address, fairLaunch.address, KILL_TREASURY_BPS, deployerAddress ); let accumLp = await mdexWorker.shareToBalance(await mdexWorker.shares(1)); const [workerLpBefore] = await bscPool.userInfo(POOL_IDX, mdexWorker.address); const debris = await baseToken.balanceOf(addStrat.address); const reinvestPath = await mdexWorker.getReinvestPath(); const path = await mdexWorker.getPath(); let reserves = await swapHelper.loadReserves(reinvestPath); reserves.push(...(await swapHelper.loadReserves(path))); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await farmTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.1")); await vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ twoSidesStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], [ethers.utils.parseEther("0.1"), "0"]), ] ) ); const blockAfter = await TimeHelpers.latestBlockNumber(); const blockDiff = blockAfter.sub(lastWorkBlock); const totalRewards = workerLpBefore .mul(MDX_REWARD_PER_BLOCK.mul(blockDiff).mul(1e12).div(workerLpBefore)) .div(1e12); const totalReinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); const reinvestLeft = totalRewards.sub(totalReinvestFees); const reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); const reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debris); const [reinvestLp] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); // Compute add collateral const addCollateralBtoken = ethers.utils.parseEther("1"); const addCollateralFtoken = ethers.utils.parseEther("0.1"); const [addCollateralLp, debrisBtoken, debrisFtoken] = await swapHelper.computeTwoSidesOptimalLp( addCollateralBtoken, addCollateralFtoken, path ); accumLp = accumLp.add(addCollateralLp); const [health, debt] = await vault.positionInfo("1"); expect(health).to.be.above(ethers.utils.parseEther("3")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(debt.toString(), interest.add(borrowedAmount).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(borrowedAmount).toString() ); AssertHelpers.assertAlmostEqual( (await vault.vaultDebtVal()).toString(), interest.add(borrowedAmount).toString() ); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); expect(await mdexWorker.shares(1), `expect Alice's shares = ${accumLp}`).to.be.eq(accumLp); expect( await mdexWorker.shareToBalance(await mdexWorker.shares(1)), `expect Alice's staked LPs = ${accumLp}` ).to.be.eq(accumLp); expect(await mdx.balanceOf(DEPLOYER), `expect Deployer gets ${totalReinvestFees} MDX`).to.be.eq( totalReinvestFees ); expect( await baseToken.balanceOf(twoSidesStrat.address), `expect TwoSides to have debris ${debrisBtoken} BTOKEN` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(twoSidesStrat.address), `expect TwoSides to have debris ${debrisFtoken} FTOKEN` ).to.be.eq(debrisFtoken); } async function revertNotEnoughCollateral(goRouge: boolean, stratAddress: string) { // Simulate price swing to make position under water await farmToken.approve(mdexRouter.address, ethers.utils.parseEther("888")); await mdexRouter.swapExactTokensForTokens( ethers.utils.parseEther("888"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Add super small collateral that it would still under the water after collateral is getting added await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.000000000000000001")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("0.000000000000000001"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("debtRatio > killFactor margin"); } async function revertUnapprovedStrat(goRouge: boolean, stratAddress: string) { await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("88")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("!approved strat"); } async function revertReserveNotConsistent(goRouge: boolean, stratAddress: string) { await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("88")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("reserve !consistent"); } context("when go rouge is false", async () => { context("when worker is stable", async () => { it("should increase health when add BTOKEN only strat is choosen", async () => { await successBtokenOnly(await TimeHelpers.latestBlockNumber(), false); }); it("should increase health when twosides strat is choosen", async () => { await successTwoSides(await TimeHelpers.latestBlockNumber(), false); }); it("should revert when not enough collateral to pass kill factor", async () => { await revertNotEnoughCollateral(false, addStrat.address); }); it("should revert when using liquidate strat", async () => { await revertUnapprovedStrat(false, liqStrat.address); }); it("should revert when using minimize trading strat", async () => { await revertUnapprovedStrat(false, minimizeStrat.address); }); it("should revert when using partial close liquidate start", async () => { await revertUnapprovedStrat(false, partialCloseStrat.address); }); it("should revert when using partial close minimize start", async () => { await revertUnapprovedStrat(false, partialCloseMinimizeStrat.address); }); }); context("when worker is unstable", async () => { it("should revert", async () => { // Set worker to unstable simpleVaultConfig.setWorker(mdexWorker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, true); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), false, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("worker !stable"); }); }); }); context("when go rouge is true", async () => { context("when worker is unstable", async () => { beforeEach(async () => { // Set worker to unstable await simpleVaultConfig.setWorker(mdexWorker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, true); }); it("should increase health when add BTOKEN only strat is choosen", async () => { await successBtokenOnly((await TimeHelpers.latestBlockNumber()).sub(1), true); }); it("should increase health when twosides strat is choosen", async () => { await successTwoSides((await TimeHelpers.latestBlockNumber()).sub(1), true); }); it("should revert when not enough collateral to pass kill factor", async () => { await revertNotEnoughCollateral(true, addStrat.address); }); it("should revert when using liquidate strat", async () => { await revertUnapprovedStrat(true, liqStrat.address); }); it("should revert when using minimize trading strat", async () => { await revertUnapprovedStrat(true, minimizeStrat.address); }); it("should revert when using partial close liquidate start", async () => { await revertUnapprovedStrat(true, partialCloseStrat.address); }); it("should revert when using partial close minimize start", async () => { await revertUnapprovedStrat(true, partialCloseMinimizeStrat.address); }); }); context("when reserve is inconsistent", async () => { beforeEach(async () => { // Set worker to unstable await simpleVaultConfig.setWorker(mdexWorker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, false); }); it("should revert", async () => { await revertReserveNotConsistent(true, addStrat.address); }); }); }); }); context("#setRewardPath", async () => { beforeEach(async () => { const rewardPath = [mdx.address, wbnb.address, baseToken.address]; // set beneficialVaultConfig await mdexWorkerAsDeployer.setBeneficialVaultConfig(BENEFICIALVAULT_BOUNTY_BPS, vault.address, rewardPath); }); it("should revert", async () => { const rewardPath = [mdx.address, farmToken.address, farmToken.address]; await expect(mdexWorkerAsDeployer.setRewardPath(rewardPath)).to.revertedWith( "MdexWorker02::setRewardPath:: rewardPath must start with MDX and end with beneficialVault token" ); }); it("should be able to set new rewardpath", async () => { const rewardPath = [mdx.address, farmToken.address, baseToken.address]; await expect(mdexWorkerAsDeployer.setRewardPath(rewardPath)) .to.emit(mdexWorker, "SetRewardPath") .withArgs(deployerAddress, rewardPath); }); }); context("#withdrawTradingRewards", async () => { it("should only withdraw mdx tradingReward from swapMining", async () => { // simulate there are some mdx tokens left in workers await mdxTokenAsDeployer.transfer(mdexWorker.address, ethers.utils.parseEther("0.1")); const deployerMdxBalanceBefore = await mdx.balanceOf(DEPLOYER); const workerMdxBalanceBefore = await mdx.balanceOf(mdexWorker.address); // withdraw mdx reward from swapMining and send to deployer const withDrawTx = await mdexWorkerAsDeployer.withdrawTradingRewards(deployerAddress); const deployerMdxBalanceAfter = await mdx.balanceOf(DEPLOYER); const workerMdxBalanceAfter = await mdx.balanceOf(mdexWorker.address); // there should be no change in worker's mdx amount expect(workerMdxBalanceAfter).to.eq(workerMdxBalanceBefore); expect(deployerMdxBalanceAfter.sub(deployerMdxBalanceBefore)).to.eq(0); }); }); }); }); describe("restricted test", async () => { context("When the withdrawTradingRewards caller is not an owner", async () => { it("should be reverted", async () => { await expect(mdexWorkerAsEve.withdrawTradingRewards(await eve.getAddress())).to.reverted; }); }); }); });
the_stack
'use strict'; /* Directive tells jshint that suite and test are globals defined by mocha */ /* global suite */ /* global test */ /* global setup */ /* global teardown */ import * as _ from "underscore"; import * as assert from "assert"; const util = require('./util/util'); const cp = util.commonParameters; const testRequire = util.testRequire; import * as adal from "../lib/adal"; const AuthenticationContext = adal.AuthenticationContext; const SelfSignedJwt = testRequire('self-signed-jwt'); /** * Tests AuthenticationContext.acquireTokenWithClientCredentials */ suite('client-credential', function() { setup(function() { util.resetLogging(); util.clearStaticCache(); }); teardown(function() { util.resetLogging(); util.clearStaticCache(); }); test('happy-path', function(done) { var responseOptions = { noRefresh : true }; var response = util.createResponse(responseOptions); var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(200, response.wireResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(response.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { if (!err) { assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The response did not match what was expected'); tokenRequest.done(); } done(err); }); }); // Tests happy-path followed by an additional call to acquireTokenWithClientCredentials that should // be served from the cache. test('happy-path-cached-token', function(done) { var responseOptions = { noRefresh : true }; var response = util.createResponse(responseOptions); var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(200, response.wireResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(response.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { if (err) { done(err); return; } assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The response did not match what was expected'); tokenRequest.done(); context.acquireTokenWithClientCredentials(response.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { if (!err) { assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The cached response did not match what was expected'); } done(err); }); }); }); // Tests happy path plus a call to the cache only function acquireToken which should find the token from the // previous call to acquireTokenWithClientCredentials. test('happy-path-cached-token2', function(done) { var responseOptions = { noRefresh : true }; var response = util.createResponse(responseOptions); var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(200, response.wireResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(response.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { if (err) { done(err); return; } assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The response did not match what was expected'); tokenRequest.done(); var nullUser = null; var context2 = new AuthenticationContext(cp.authUrl); context2.acquireToken(response.resource, nullUser as any, cp.clientId, function (err, tokenResponse) { if (!err) { assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The cached response did not match what was expected'); } done(err); }); }); }); test('no-callback', function(done) { var context = new AuthenticationContext(cp.authorityTenant); var argumentError; try { context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, cp.clientSecret, null as any); } catch(err) { argumentError = err; } assert(argumentError, 'Did not receive expected error'); assert(argumentError.message.indexOf('callback') >= 0, 'Error does not appear to be specific to callback parameter.'); done(); }); test('no-arguments', function(done) { var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCredentials(null as any, null as any, null as any, function(err) { assert(err, 'Did not receive expected error.'); assert(err.message.indexOf('parameter') >= 0, 'Error was not specific to a parameter.'); done(); }); }); test('no-client-secret', function(done) { var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, null as any, function(err) { assert(err, 'Did not receive expected error.'); assert(err.message.indexOf('parameter') >= 0, 'Error was not specific to a parameter.'); done(); }); }); test('no-client-id', function(done) { var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCredentials(cp.resource, null as any, cp.clientSecret, function(err) { assert(err, 'Did not receive expected error.'); assert(err.message.indexOf('parameter') >= 0, 'Error was not specific to a parameter.'); done(); }); }); test('no-resource', function(done) { var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCredentials(null as any, cp.clientId, cp.clientSecret, function(err) { assert(err, 'Did not receive expected error.'); assert(err.message.indexOf('parameter') >= 0, 'Error was not specific to a parameter.'); done(); }); }); test('http-error', function(done) { var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(403); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { assert(err, 'No error was returned when one was expected.'); assert(!tokenResponse, 'a token response was returned when non was expected.'); tokenRequest.done(); done(); }); }); test('oauth-error', function(done) { var errorResponse = { error : 'invalid_client', error_description : 'This is a test error description', // jshint ignore:line error_uri : 'http://errordescription.com/invalid_client.html' // jshint ignore:line }; var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(400, errorResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, cp.clientSecret, function (err, tokenResponse) { assert(err, 'No error was returned when one was expected.'); assert(_.isEqual(errorResponse, tokenResponse), 'The response did not match what was expected'); tokenRequest.done(); done(); }); }); test('error-with-useless-return', function(done) { var junkResponse = 'This is not properly formated return value.'; var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(400, junkResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, cp.clientSecret, function (err) { assert(err, 'No error was returned when one was expected.'); tokenRequest.done(); done(); }); }); test('success-with-useless-return', function(done) { var junkResponse = 'This is not properly formated return value.'; var tokenRequest = util.setupExpectedClientCredTokenRequestResponse(200, junkResponse); var context = new AuthenticationContext(cp.authUrl); context.acquireTokenWithClientCredentials(cp.resource, cp.clientId, cp.clientSecret, function (err) { assert(err, 'No error was returned when one was expected.'); tokenRequest.done(); done(); }); }); test('no-cached-token-found-error', function(done) { var context = new AuthenticationContext(cp.authUrl); context.acquireToken(cp.resource, 'unknownUser', cp.clientId, function(err) { assert(err, 'Expected an error and non was received.'); assert(-1 !== err.message.indexOf('not found'), 'Returned error did not contain expected message: ' + err.message); done(); }); }); function updateSelfSignedJwtStubs() { var savedProto: any = {}; savedProto._getDateNow = SelfSignedJwt.prototype._getDateNow; savedProto._getNewJwtId = SelfSignedJwt.prototype._getNewJwtId; SelfSignedJwt.prototype._getDateNow = function() { return cp.nowDate; }; SelfSignedJwt.prototype._getNewJwtId = function() { return cp.jwtId; }; return savedProto; } function resetSelfSignedJwtStubs(saveProto: any) { _.extend(SelfSignedJwt.prototype, saveProto); } test('cert-happy-path', function(done) { var saveProto = updateSelfSignedJwtStubs(); var responseOptions = { noRefresh : true }; var response = util.createResponse(responseOptions); var tokenRequest = util.setupExpectedClientAssertionTokenRequestResponse(200, response.wireResponse, cp.authorityTenant); var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCertificate(response.resource, cp.clientId, cp.cert, cp.certHash, function (err, tokenResponse) { resetSelfSignedJwtStubs(saveProto); tokenRequest.done(); if (!err) { assert(util.isMatchTokenResponse(response.cachedResponse, tokenResponse), 'The response did not match what was expected'); tokenRequest.done(); } done(err); }); }); test('cert-bad-cert', function(done) { var cert = 'gobbledy'; var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCertificate(cp.resource, cp.clientId, cert, cp.certHash, function (err) { assert(err, 'Did not receive expected error.'); assert(0 <= err.message.indexOf('Failed to sign JWT'), 'Unexpected error message' + err.message); done(); }); }); test('cert-bad-thumbprint', function(done) { var thumbprint = 'gobbledy'; var context = new AuthenticationContext(cp.authorityTenant); context.acquireTokenWithClientCertificate(cp.resource, cp.clientId, cp.cert, thumbprint, function (err) { assert(err, 'Did not receive expected error.'); assert(0 <= err.message.indexOf('thumbprint does not match a known format'), 'Unexpected error message' + err.message); done(); }); }); });
the_stack
import * as d3 from 'd3-selection'; var tempDiv = document.createElement('div'); import * as utils from './utils'; var scrollbarSizes: WeakMap<Node, {width: number; height: number;}> = new WeakMap(); export function appendTo(el: string | Node, container: Element) { var node: Node; if (el instanceof Node) { node = el; } else { tempDiv.insertAdjacentHTML('afterbegin', el); node = tempDiv.childNodes[0]; } container.appendChild(node); return node; } export function getScrollbarSize(container: HTMLElement) { if (scrollbarSizes.has(container)) { return scrollbarSizes.get(container); } var initialOverflow = container.style.overflow; container.style.overflow = 'scroll'; var size = { width: (container.offsetWidth - container.clientWidth), height: (container.offsetHeight - container.clientHeight) }; container.style.overflow = initialOverflow; scrollbarSizes.set(container, size); return size; } /** * Sets padding as a placeholder for scrollbars. * @param el Target element. * @param [direction=both] Scrollbar direction ("horizontal", "vertical" or "both"). */ export function setScrollPadding(el: HTMLElement, direction?: 'horizontal' | 'vertical' | 'both') { direction = direction || 'both'; var isBottom = direction === 'horizontal' || direction === 'both'; var isRight = direction === 'vertical' || direction === 'both'; var scrollbars = getScrollbarSize(el); var initialPaddingRight = isRight ? `${scrollbars.width}px` : '0'; var initialPaddingBottom = isBottom ? `${scrollbars.height}px` : '0'; el.style.overflow = 'hidden'; el.style.padding = `0 ${initialPaddingRight} ${initialPaddingBottom} 0`; var hasBottomScroll = el.scrollWidth > el.clientWidth; var hasRightScroll = el.scrollHeight > el.clientHeight; var paddingRight = isRight && !hasRightScroll ? `${scrollbars.width}px` : '0'; var paddingBottom = isBottom && !hasBottomScroll ? `${scrollbars.height}px` : '0'; el.style.padding = `0 ${paddingRight} ${paddingBottom} 0`; // NOTE: Manually set scroll due to overflow:auto Chrome 53 bug // https://bugs.chromium.org/p/chromium/issues/detail?id=644450 el.style.overflow = ''; el.style.overflowX = hasBottomScroll ? 'scroll' : 'hidden'; el.style.overflowY = hasRightScroll ? 'scroll' : 'hidden'; return scrollbars; } export function getStyle(el: Element, prop: string) { return window.getComputedStyle(el).getPropertyValue(prop); } export function getStyleAsNum(el: Element, prop: string) { return parseInt(getStyle(el, prop) || '0', 10); } export function getContainerSize(el: HTMLElement) { var pl = getStyleAsNum(el, 'padding-left'); var pr = getStyleAsNum(el, 'padding-right'); var pb = getStyleAsNum(el, 'padding-bottom'); var pt = getStyleAsNum(el, 'padding-top'); var borderWidthT = getStyleAsNum(el, 'border-top-width'); var borderWidthL = getStyleAsNum(el, 'border-left-width'); var borderWidthR = getStyleAsNum(el, 'border-right-width'); var borderWidthB = getStyleAsNum(el, 'border-bottom-width'); var bw = borderWidthT + borderWidthL + borderWidthR + borderWidthB; var rect = el.getBoundingClientRect(); return { width: rect.width - pl - pr - 2 * bw, height: rect.height - pb - pt - 2 * bw }; } export function getAxisTickLabelSize(text: string) { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.visibility = 'hidden'; div.style.width = '100px'; div.style.height = '100px'; div.style.border = '1px solid green'; div.style.top = '0'; document.body.appendChild(div); div.innerHTML = `<svg class="tau-chart__svg"> <g class="tau-chart__cell cell"> <g class="x axis"> <g class="tick"><text></text></g> </g> </g> </svg>`; var textNode = div.querySelector('.x.axis .tick text'); textNode.textContent = text; var size = { width: 0, height: 0 }; // Internet Explorer, Firefox 3+, Google Chrome, Opera 9.5+, Safari 4+ var rect = textNode.getBoundingClientRect(); size.width = rect.right - rect.left; size.height = rect.bottom - rect.top; var avgLetterSize = (text.length !== 0) ? (size.width / text.length) : 0; size.width = size.width + (1.5 * avgLetterSize); document.body.removeChild(div); return size; } export function getLabelSize( lines: string[], {fontSize, fontFamily, fontWeight}: {fontSize?: number, fontFamily?: string, fontWeight?: string} ) { var xFontSize = typeof (fontSize) === 'string' ? fontSize : (`${fontSize}px`); var maxWidthLine = lines .map(function (line) { for (var i = 0, width = 0; i <= line.length - 1; i++) { var s = getCharSize(line.charAt(i), {fontSize: xFontSize, fontFamily, fontWeight}); width += s.width; } return width; }) .sort(function (w1, w2) { return w2 - w1; })[0]; var linesCount = lines.length; var fontSizeNumeric = parseInt(xFontSize); var spaceBetweenLines = (fontSizeNumeric * 0.39) * linesCount; return { width: maxWidthLine, height: fontSizeNumeric * linesCount + spaceBetweenLines }; } export const getCharSize = utils.memoize( (char: string, {fontSize, fontFamily, fontWeight}) => { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.visibility = 'hidden'; div.style.border = '0px'; div.style.top = '0'; div.style.fontSize = fontSize; div.style.fontFamily = fontFamily; div.style.fontWeight = fontWeight; document.body.appendChild(div); div.innerHTML = (char === ' ') ? '&nbsp;' : char; var size = { width: 0, height: 0 }; // Internet Explorer, Firefox 3+, Google Chrome, Opera 9.5+, Safari 4+ var rect = div.getBoundingClientRect(); size.width = rect.right - rect.left; size.height = rect.bottom - rect.top; document.body.removeChild(div); return size; }, (char, props) => `${char}_${JSON.stringify(props)}` ); type d3Selection = d3.Selection<Element, any, Element, any>; /** * Searches for immediate child element by specified selector. * If missing, creates an element that matches the selector. */ export function selectOrAppend(container: Element, selector: string): Element; export function selectOrAppend(container: d3Selection, selector: string): d3Selection; export function selectOrAppend(_container: Element | d3Selection, selector: string) { var delimitersActions = { '.': (text, el) => el.classed(text, true), '#': (text, el) => el.attr('id', text) }; var delimiters = Object.keys(delimitersActions).join(''); if (selector.indexOf(' ') >= 0) { throw new Error('Selector should not contain whitespaces.'); } if (delimiters.indexOf(selector[0]) >= 0) { throw new Error('Selector must have tag at the beginning.'); } var isElement = (_container instanceof Element); var container: d3Selection = isElement ? d3.select(_container as Element) : (_container as d3Selection); var result = (d3El: d3Selection) => (isElement ? d3El.node() : d3El); // Search for existing immediate child var child = container.selectAll(selector) .filter(function (this: Element) { return (this.parentNode === container.node()); }) .filter((d, i) => i === 0) as d3Selection; if (!child.empty()) { return result(child); } // Create new element var element; var lastFoundIndex = -1; var lastFoundDelimiter = null; for (var i = 1, l = selector.length, text; i <= l; i++) { if (i == l || delimiters.indexOf(selector[i]) >= 0) { text = selector.substring(lastFoundIndex + 1, i); if (lastFoundIndex < 0) { element = container.append(text); } else { delimitersActions[lastFoundDelimiter].call(null, text, element); } lastFoundDelimiter = selector[i]; lastFoundIndex = i; } } return result(element); } export function selectImmediate(container: Element, selector: string) { return selectAllImmediate(container, selector)[0] || null; } export function selectAllImmediate(container: Element, selector: string) { var results = []; var matches = ( Element.prototype.matches || Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector ); for ( var child = container.firstElementChild; Boolean(child); child = child.nextElementSibling ) { if (matches.call(child, selector)) { results.push(child); } } return results; } export function sortChildren(parent: Element, sorter: (a: Element, b: Element) => number) { if (parent.childElementCount > 0) { // Note: move DOM elements with // minimal number of iterations // and affected nodes to prevent // unneccessary repaints. // Get from/to index pairs. const unsorted = Array.prototype.filter.call( parent.childNodes, (el) => el.nodeType === Node.ELEMENT_NODE); const sorted = unsorted.slice().sort(sorter); const unsortedIndices = unsorted.reduce((map, el, i) => { map.set(el, i); return map; }, new Map()); // Get groups (sequences of elements with unchanged order) var currGroup; var currDiff; const groups = sorted.reduce((groupsInfo, el, to) => { const from = unsortedIndices.get(el); const diff = (to - from); if (diff !== currDiff) { if (currGroup) { groupsInfo.push(currGroup); } currDiff = diff; currGroup = { from, to, elements: [] }; } currGroup.elements.push(el); if (to === sorted.length - 1) { groupsInfo.push(currGroup); } return groupsInfo; }, []); const unsortedGroups = groups.slice().sort((a, b) => { return (a.from - b.from); }); const unsortedGroupsIndices = unsortedGroups.reduce((map, g, i) => { map.set(g, i); return map; }, new Map()); // Get required iterations const createIterations = (forward) => { const iterations = groups .map((g, i) => { return { elements: g.elements, from: unsortedGroupsIndices.get(g), to: i }; }) .sort(utils.createMultiSorter<{elements, to}>( ((a, b) => a.elements.length - b.elements.length), (forward ? ((a, b) => b.to - a.to) : ((a, b) => a.to - b.to)) )); for (var i = 0, j, g, h; i < iterations.length; i++) { g = iterations[i]; if (g.from > g.to) { for (j = i + 1; j < iterations.length; j++) { h = iterations[j]; if (h.from >= g.to && h.from < g.from) { h.from++; } } } if (g.from < g.to) { for (j = i + 1; j < iterations.length; j++) { h = iterations[j]; if (h.from > g.from && h.from <= g.to) { h.from--; } } } } return iterations.filter((g) => g.from !== g.to); }; const forwardIterations = createIterations(true); const backwardIterations = createIterations(false); const iterations = (forwardIterations.length < backwardIterations.length ? forwardIterations : backwardIterations); // Finally sort DOM nodes const mirror = unsortedGroups.map(g => g.elements); iterations .forEach((g) => { const targetGroup = mirror.splice(g.from, 1)[0]; const groupAfter = mirror[g.to]; const siblingAfter = (groupAfter ? groupAfter[0] : null); var targetNode; if (g.elements.length === 1) { targetNode = targetGroup[0]; } else { targetNode = document.createDocumentFragment(); targetGroup.forEach((el) => { targetNode.appendChild(el); }); } parent.insertBefore(targetNode, siblingAfter); mirror.splice(g.to, 0, targetGroup); }); } } /** * Generates "class" attribute string. */ export function classes(...args: (string | {[cls: string]: boolean})[]) { var classes = []; args.filter((c) => Boolean(c)) .forEach((c) => { if (typeof c === 'string') { classes.push(c); } else if (typeof c === 'object') { classes.push.apply( classes, Object.keys(c) .filter((key) => Boolean(c[key])) ); } }); return ( utils.unique(classes) .join(' ') .trim() .replace(/\s{2,}/g, ' ') ); } export function dispatchMouseEvent(target: Element, eventName: string, ...args) { const event = document.createEvent('MouseEvents'); const defaults = [true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null]; const results = args.concat(defaults.slice(args.length)); (event as any).initMouseEvent(eventName, ...results); target.dispatchEvent(event); }
the_stack
import '@testing-library/jest-dom/extend-expect'; import React, { useState } from 'react'; import { render, cleanup, fireEvent, RenderResult, act, } from '@testing-library/react'; import genericUserEvent from '@testing-library/user-event'; import { BraidTestProvider, MenuItem, MenuItemLink, MenuItemCheckbox, MenuItemDivider, } from '..'; import { MenuRendererProps } from './MenuRenderer'; // The generic `user-event` library currently doesn't have knowledge // of the react lifecycle, e.g. it's methods are not wrapped with // the `act` function. See issue for details: // https://github.com/testing-library/user-event/issues/128 const userEvent = { click: (el: HTMLElement) => act(() => genericUserEvent.click(el)), }; const TAB = 9; const ENTER = 13; const ESCAPE = 27; const SPACE = 32; const ARROW_UP = 38; const ARROW_DOWN = 40; interface MenuTestSuiteParams { name: string; Component: React.FunctionComponent< Pick<MenuRendererProps, 'onOpen' | 'onClose' | 'children'> >; } export const menuTestSuite = ({ name, Component }: MenuTestSuiteParams) => { function renderMenu() { const openHandler = jest.fn(); const closeHandler = jest.fn(); const menuItemHandler = jest.fn(); const parentHandler = jest.fn(); const TestCase = () => { const [checked, setChecked] = useState(false); return ( <BraidTestProvider> <div onClick={parentHandler}> <Component onOpen={openHandler} onClose={closeHandler}> <MenuItem onClick={() => menuItemHandler('MenuItem')}> MenuItem </MenuItem> <MenuItemDivider /> <MenuItemLink href="#" onClick={() => menuItemHandler('MenuItemLink')} > MenuItemLink </MenuItemLink> <MenuItemDivider /> <MenuItemCheckbox checked={checked} onChange={(value) => { setChecked(value); menuItemHandler('MenuItemCheckbox'); }} > MenuItemCheckbox </MenuItemCheckbox> </Component> </div> </BraidTestProvider> ); }; const { getAllByRole } = render(<TestCase />); return { getAllByRole, openHandler, closeHandler, menuItemHandler, parentHandler, }; } function getElements({ getAllByRole, }: { getAllByRole: RenderResult['getAllByRole']; }) { return { menuButton: getAllByRole((_, el) => Boolean(el?.getAttribute('aria-haspopup')), )[0], menu: getAllByRole('menu', { hidden: true })[0], menuItems: getAllByRole(/menuitem|menuitemcheckbox/, { hidden: true }), }; } describe(`Menu: ${name}`, () => { describe('Mouse interactions', () => { afterEach(cleanup); it('should open menu when clicked', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); userEvent.click(menuButton); expect(menu).toBeVisible(); expect(menuButton).toHaveFocus(); expect(openHandler).toHaveBeenCalledTimes(1); expect(closeHandler).not.toHaveBeenCalled(); }); it('should toggle the menu when clicked again', () => { const { getAllByRole, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); userEvent.click(menuButton); userEvent.click(menuButton); expect(menu).not.toBeVisible(); expect(menuButton).toHaveFocus(); expect(closeHandler).toHaveBeenCalledTimes(1); }); it('should set the focused menu item on mouse over', () => { const { getAllByRole } = renderMenu(); const { menuButton, menuItems: initialMenuItems } = getElements({ getAllByRole, }); userEvent.click(menuButton); fireEvent.mouseOver(initialMenuItems[2]); const { menuItems: mouseOverMenuItems } = getElements({ getAllByRole, }); expect(mouseOverMenuItems[2]).toHaveFocus(); }); it('should unfocus all menu items on mouse out', () => { const { getAllByRole } = renderMenu(); const { menu, menuButton, menuItems } = getElements({ getAllByRole, }); userEvent.click(menuButton); fireEvent.mouseOver(menuItems[1]); fireEvent.mouseOut(menu); const { menuItems: mouseOutMenuItems } = getElements({ getAllByRole, }); expect(mouseOutMenuItems[0]).not.toHaveFocus(); expect(mouseOutMenuItems[1]).not.toHaveFocus(); expect(mouseOutMenuItems[2]).not.toHaveFocus(); }); it('should trigger the click handler on a MenuItem', () => { const { getAllByRole, openHandler, closeHandler, menuItemHandler, parentHandler, } = renderMenu(); const { menu, menuButton, menuItems } = getElements({ getAllByRole }); userEvent.click(menuButton); openHandler.mockClear(); // Clear initial open invocation, to allow later negative assertion expect(menu).toBeVisible(); // `userEvent` is clashing with state update from the `onMouseEnter` handler // on menu item. Need to use `fireEvent`. fireEvent.click(menuItems[0]); expect(menu).not.toBeVisible(); expect(openHandler).not.toHaveBeenCalled(); expect(closeHandler).toHaveBeenCalledTimes(1); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItem'); expect(menuButton).toHaveFocus(); // Should not bubble expect(parentHandler).not.toHaveBeenCalled(); }); it('should toggle the state on a MenuItemCheckbox', () => { const { getAllByRole, openHandler, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton, menuItems } = getElements({ getAllByRole }); userEvent.click(menuButton); openHandler.mockClear(); // Clear initial open invocation, to allow later negative assertion expect(menu).toBeVisible(); const menuItemCheckbox = menuItems[2]; expect(menuItemCheckbox.getAttribute('aria-checked')).toBe('false'); userEvent.click(menuItemCheckbox); expect(menuItemCheckbox.getAttribute('aria-checked')).toBe('true'); expect(menu).toBeVisible(); expect(openHandler).not.toHaveBeenCalled(); expect(closeHandler).not.toHaveBeenCalled(); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItemCheckbox'); expect(menuItemCheckbox).toHaveFocus(); }); }); describe('Keyboard interactions', () => { afterEach(cleanup); it('should open the menu with enter key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: ENTER }); const { menuItems } = getElements({ getAllByRole }); expect(menu).toBeVisible(); expect(menuItems[0]).toHaveFocus(); expect(openHandler).toHaveBeenCalledTimes(1); expect(closeHandler).not.toHaveBeenCalled(); }); it('should open the menu with space key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: SPACE }); const { menuItems } = getElements({ getAllByRole }); expect(menu).toBeVisible(); expect(menuItems[0]).toHaveFocus(); expect(openHandler).toHaveBeenCalledTimes(1); expect(closeHandler).not.toHaveBeenCalled(); }); it('should open the menu with down arrow key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: ARROW_DOWN }); const { menuItems } = getElements({ getAllByRole }); expect(menu).toBeVisible(); expect(menuItems[0]).toHaveFocus(); expect(openHandler).toHaveBeenCalledTimes(1); expect(closeHandler).not.toHaveBeenCalled(); }); it('should open the menu with up arrow key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: ARROW_UP }); const { menuItems } = getElements({ getAllByRole }); expect(menu).toBeVisible(); expect(menuItems[2]).toHaveFocus(); expect(openHandler).toHaveBeenCalledTimes(1); expect(closeHandler).not.toHaveBeenCalled(); }); it('should close the menu with escape key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton, menuItems } = getElements({ getAllByRole, }); userEvent.click(menuButton); openHandler.mockClear(); // Clear initial open invocation, to allow later negative assertion fireEvent.keyUp(menuItems[0], { keyCode: ESCAPE }); expect(menu).not.toBeVisible(); expect(menuButton).toHaveFocus(); expect(openHandler).not.toHaveBeenCalled(); expect(closeHandler).toHaveBeenCalledTimes(1); }); it('should close the menu with tab key', () => { const { getAllByRole, openHandler, closeHandler } = renderMenu(); const { menu, menuButton, menuItems } = getElements({ getAllByRole, }); userEvent.click(menuButton); openHandler.mockClear(); // Clear initial open invocation, to allow later negative assertion fireEvent.keyDown(menuItems[0], { keyCode: TAB }); expect(menu).not.toBeVisible(); expect(menuButton).toHaveFocus(); expect(openHandler).not.toHaveBeenCalled(); expect(closeHandler).toHaveBeenCalledTimes(1); }); it('should be able to navigate down the list and back to the start', () => { const { getAllByRole } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: ARROW_DOWN }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; expect(firstMenuItem).toHaveFocus(); fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); const secondDown = getElements({ getAllByRole }); const secondMenuItem = secondDown.menuItems[1]; expect(secondMenuItem).toHaveFocus(); fireEvent.keyUp(secondMenuItem, { keyCode: ARROW_DOWN }); const thirdDown = getElements({ getAllByRole }); const thirdMenuItem = thirdDown.menuItems[2]; expect(thirdMenuItem).toHaveFocus(); fireEvent.keyUp(thirdMenuItem, { keyCode: ARROW_DOWN }); const forthDown = getElements({ getAllByRole }); const firstMenuItemAgain = forthDown.menuItems[0]; expect(firstMenuItemAgain).toHaveFocus(); }); it('should be able to navigate up the list and back to the end', () => { const { getAllByRole } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); expect(menu).not.toBeVisible(); fireEvent.keyUp(menuButton, { keyCode: ARROW_UP }); const firstUp = getElements({ getAllByRole }); const thirdMenuItem = firstUp.menuItems[2]; expect(thirdMenuItem).toHaveFocus(); fireEvent.keyUp(thirdMenuItem, { keyCode: ARROW_UP }); const secondUp = getElements({ getAllByRole }); const secondMenuItem = secondUp.menuItems[1]; expect(secondMenuItem).toHaveFocus(); fireEvent.keyUp(secondMenuItem, { keyCode: ARROW_UP }); const thirdUp = getElements({ getAllByRole }); const firstMenuItem = thirdUp.menuItems[0]; expect(firstMenuItem).toHaveFocus(); fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_UP }); const forthUp = getElements({ getAllByRole }); const lastMenuItemAgain = forthUp.menuItems[2]; expect(lastMenuItemAgain).toHaveFocus(); }); it('should trigger the click handler on MenuItem when selecting it with enter', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Action the item fireEvent.keyUp(firstMenuItem, { keyCode: ENTER }); expect(menu).not.toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(1); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItem'); expect(menuButton).toHaveFocus(); }); it('should trigger the click handler on MenuItem when selecting it with space', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Action the item fireEvent.keyUp(firstMenuItem, { keyCode: SPACE }); expect(menu).not.toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(1); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItem'); expect(menuButton).toHaveFocus(); }); it('should trigger the click handler on MenuItemLink when selecting it with enter', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Navigate down fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); const secondDown = getElements({ getAllByRole }); const secondMenuItem = secondDown.menuItems[1]; // Action the item fireEvent.keyUp(secondMenuItem, { keyCode: ENTER }); expect(menu).not.toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(1); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItemLink'); expect(menuButton).toHaveFocus(); }); it('should trigger the click handler on MenuItemLink when selecting it with space', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Navigate down fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); const secondDown = getElements({ getAllByRole }); const secondMenuItem = secondDown.menuItems[1]; // Action the item fireEvent.keyUp(secondMenuItem, { keyCode: SPACE }); expect(menu).not.toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(1); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItemLink'); expect(menuButton).toHaveFocus(); }); it('should toggle the state on MenuItemCheckbox when selecting it with enter', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Navigate down fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); const thirdDown = getElements({ getAllByRole }); const thirdMenuItem = thirdDown.menuItems[2]; expect(thirdMenuItem.getAttribute('aria-checked')).toBe('false'); // Action the item fireEvent.keyUp(thirdMenuItem, { keyCode: ENTER }); expect(thirdMenuItem.getAttribute('aria-checked')).toBe('true'); expect(menu).toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(0); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItemCheckbox'); }); it('should toggle the state on MenuItemCheckbox when selecting it with space', () => { const { getAllByRole, closeHandler, menuItemHandler } = renderMenu(); const { menu, menuButton } = getElements({ getAllByRole }); // Open menu fireEvent.keyUp(menuButton, { keyCode: ENTER }); const firstDown = getElements({ getAllByRole }); const firstMenuItem = firstDown.menuItems[0]; // Navigate down fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); fireEvent.keyUp(firstMenuItem, { keyCode: ARROW_DOWN }); const thirdDown = getElements({ getAllByRole }); const thirdMenuItem = thirdDown.menuItems[2]; expect(thirdMenuItem.getAttribute('aria-checked')).toBe('false'); // Action the item fireEvent.keyUp(thirdMenuItem, { keyCode: SPACE }); expect(thirdMenuItem.getAttribute('aria-checked')).toBe('true'); expect(menu).toBeVisible(); expect(closeHandler).toHaveBeenCalledTimes(0); expect(menuItemHandler).toHaveBeenNthCalledWith(1, 'MenuItemCheckbox'); }); }); }); };
the_stack
import { Action, BaseResource, exceptions, handlerEvent, HandlerErrorCode, integer, Integer, LoggerProxy, OperationStatus, Optional, ProgressEvent, ResourceHandlerRequest, SessionProxy } from '@amazon-web-services-cloudformation/cloudformation-cli-typescript-lib'; import fetch, { Response } from 'node-fetch'; import { ResourceModel } from './models'; interface CallbackContext extends Record<string, any> {} enum ApiEndpoints { US = 'https://synthetics.newrelic.com/synthetics/api', EU = 'https://synthetics.eu.newrelic.com/synthetics/api', } type EndpointRegions = keyof typeof ApiEndpoints; interface Monitor { readonly id?: string; readonly name?: string; readonly uri?: string; readonly type?: string; readonly frequency?: integer; readonly status?: string; readonly locations?: string[]; readonly slaThreshold?: number; } /** * Resource to be used in AWS CloudFormation to create and manage * New Relic's synthetic monitors of type "ping" (SIMPLE). * See documentation {@link https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api}. */ class Resource extends BaseResource<ResourceModel> { static readonly DEFAULT_HEADERS = { 'Accept': 'application/json', 'Content-Type': 'application/json' }; static readonly DEFAULT_MONITOR_KIND = 'SIMPLE'; static readonly DEFAULT_MONITOR_STATUS = 'MUTED'; static readonly DEFAULT_MONITOR_LOCATIONS = [ 'AWS_EU_CENTRAL_1', 'AWS_US_WEST_1' ]; static readonly DEFAULT_MONITOR_SLA_THRESHOLD = 7.0; private async checkResponse(response: Response, logger: LoggerProxy, uid?: string): Promise<any> { if (response.status === 400) { throw new exceptions.AlreadyExists(this.typeName, uid); } else if (response.status === 401) { throw new exceptions.AccessDenied(response.statusText); } else if (response.status === 404) { throw new exceptions.NotFound(this.typeName, uid); } else if (response.status > 400) { throw new exceptions.InternalFailure( `error ${response.status} ${response.statusText}`, HandlerErrorCode.InternalFailure, ); } const responseData = await response.text() || '{}'; logger.log('HTTP response', responseData); return JSON.parse(responseData); } /** * CloudFormation invokes this handler when the resource is initially created * during stack create operations. * * @param session Current AWS session passed through from caller * @param request The request object for the provisioning request passed to the implementor * @param callbackContext Custom context object to allow the passing through of additional * state or metadata between subsequent retries * @param logger Logger to proxy requests to default publishers */ @handlerEvent(Action.Create) public async create( session: Optional<SessionProxy>, request: ResourceHandlerRequest<ResourceModel>, callbackContext: CallbackContext, logger: LoggerProxy ): Promise<ProgressEvent> { logger.log('request', request); // It is important that we create a new instance of the model, // because the desired state is immutable. const model = new ResourceModel(request.desiredResourceState); const progress = ProgressEvent.progress<ProgressEvent<ResourceModel>>(model); // Id is a read only property, which means that // it cannot be set during creation or update operations. if (model.id) { throw new exceptions.InvalidRequest('Read only property [Id] cannot be provided by the user.'); } try { // Set or fallback to default values model.frequency = model.frequency || Integer(5); model.endpointRegion = model.endpointRegion || 'US'; model.kind = Resource.DEFAULT_MONITOR_KIND; model.status = Resource.DEFAULT_MONITOR_STATUS; model.locations = Resource.DEFAULT_MONITOR_LOCATIONS; model.slaThreshold = Resource.DEFAULT_MONITOR_SLA_THRESHOLD; // Create a new synthetics monitor // https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#create-monitor const apiKey = model.apiKey; const apiEndpoint = ApiEndpoints[model.endpointRegion as EndpointRegions]; const createResponse: Response = await fetch(`${apiEndpoint}/v3/monitors`, { method: 'POST', headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey }, body: JSON.stringify({ name: model.name, uri: model.uri, type: model.kind, frequency: model.frequency, status: model.status, locations: model.locations, slaThreshold: model.slaThreshold } as Monitor) }); await this.checkResponse(createResponse, logger, request.logicalResourceIdentifier); // Use address from location header to read newly created monitor // https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#get-specific-monitor const locationUrl = createResponse.headers.get('location'); if (!locationUrl) { throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier); } const response: Response = await fetch(locationUrl, { method: 'GET', headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey } }); const monitor: Monitor = await this.checkResponse(response, logger, request.logicalResourceIdentifier); model.id = monitor.id; // model.apiKey = null; // Setting Status to success will signal to CloudFormation that the operation is complete progress.status = OperationStatus.Success; } catch(err) { logger.log(err); if (err instanceof exceptions.BaseHandlerException) { throw err; } throw new exceptions.InternalFailure(err.message); } logger.log('progress', progress); return progress; } /** * CloudFormation invokes this handler when the resource is updated * as part of a stack update operation. * * @param session Current AWS session passed through from caller * @param request The request object for the provisioning request passed to the implementor * @param callbackContext Custom context object to allow the passing through of additional * state or metadata between subsequent retries * @param logger Logger to proxy requests to default publishers */ @handlerEvent(Action.Update) public async update( session: Optional<SessionProxy>, request: ResourceHandlerRequest<ResourceModel>, callbackContext: CallbackContext, logger: LoggerProxy ): Promise<ProgressEvent> { logger.log('request', request); const model = new ResourceModel(request.desiredResourceState); const { id, name } = request.previousResourceState; if (!model.id) { throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier); } else if (model.id !== id) { logger.log(this.typeName, `[NEW ${model.id}] [${request.logicalResourceIdentifier}] does not match identifier from saved resource [OLD ${id}].`); throw new exceptions.NotUpdatable('Read only property [Id] cannot be updated.'); } else if (model.name !== name) { // The Name is a create only property, which means that it cannot be updated. logger.log(this.typeName, `[NEW ${model.name}] [${request.logicalResourceIdentifier}] does not match identifier from saved resource [OLD ${name}].`); throw new exceptions.NotUpdatable('Create only property [Name] cannot be updated.'); } try { // Set or fallback to default values model.frequency = model.frequency || Integer(5); model.endpointRegion = model.endpointRegion || 'US'; model.kind = Resource.DEFAULT_MONITOR_KIND; model.status = Resource.DEFAULT_MONITOR_STATUS; model.locations = Resource.DEFAULT_MONITOR_LOCATIONS; model.slaThreshold = Resource.DEFAULT_MONITOR_SLA_THRESHOLD; // Update the synthetics monitor by calling the endpoint with its ID. // https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#update-monitor const apiKey = model.apiKey; const apiEndpoint = ApiEndpoints[model.endpointRegion as EndpointRegions]; const response: Response = await fetch(`${apiEndpoint}/v3/monitors/${id}`, { method: 'PUT', headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': apiKey }, body: JSON.stringify({ name, uri: model.uri, type: model.kind, frequency: model.frequency, status: model.status, locations: model.locations, slaThreshold: model.slaThreshold } as Monitor) }); await this.checkResponse(response, logger, id); // model.apiKey = null; const progress = ProgressEvent.success<ProgressEvent<ResourceModel>>(model); logger.log('progress', progress); return progress; } catch(err) { logger.log(err); if (err instanceof exceptions.BaseHandlerException) { throw err; } return ProgressEvent.failed<ProgressEvent<ResourceModel>>(HandlerErrorCode.InternalFailure, err.message); } } /** * CloudFormation invokes this handler when the resource is deleted, either when * the resource is deleted from the stack as part of a stack update operation, * or the stack itself is deleted. * * @param session Current AWS session passed through from caller * @param request The request object for the provisioning request passed to the implementor * @param callbackContext Custom context object to allow the passing through of additional * state or metadata between subsequent retries * @param logger Logger to proxy requests to default publishers */ @handlerEvent(Action.Delete) public async delete( session: Optional<SessionProxy>, request: ResourceHandlerRequest<ResourceModel>, callbackContext: CallbackContext, logger: LoggerProxy ): Promise<ProgressEvent> { logger.log('request', request); const model = new ResourceModel(request.desiredResourceState); // The Id property, being the primary identifier, cannot be left empty. if (!model.id) { throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier); } // Remove the synthetics monitor by calling the delete endpoint with its ID. // https://docs.newrelic.com/docs/apis/synthetics-rest-api/monitor-examples/manage-synthetics-monitors-rest-api#delete-monitor model.endpointRegion = model.endpointRegion || 'US'; const apiEndpoint = ApiEndpoints[model.endpointRegion as EndpointRegions]; const response: Response = await fetch(`${apiEndpoint}/v3/monitors/${model.id}`, { method: 'DELETE', headers: { ...Resource.DEFAULT_HEADERS, 'Api-Key': model.apiKey } }); await this.checkResponse(response, logger, model.id); const progress = ProgressEvent.success<ProgressEvent<ResourceModel>>(); logger.log('progress', progress); return progress; } /** * CloudFormation invokes this handler as part of a stack update operation when * detailed information about the resource's current state is required. * * @param session Current AWS session passed through from caller * @param request The request object for the provisioning request passed to the implementor * @param callbackContext Custom context object to allow the passing through of additional * state or metadata between subsequent retries * @param logger Logger to proxy requests to default publishers */ @handlerEvent(Action.Read) public async read( session: Optional<SessionProxy>, request: ResourceHandlerRequest<ResourceModel>, callbackContext: CallbackContext, logger: LoggerProxy ): Promise<ProgressEvent> { logger.log('request', request); const model = new ResourceModel(request.desiredResourceState); if (!model.id) { throw new exceptions.NotFound(this.typeName, request.logicalResourceIdentifier); } model.kind = Resource.DEFAULT_MONITOR_KIND; model.status = Resource.DEFAULT_MONITOR_STATUS; model.locations = Resource.DEFAULT_MONITOR_LOCATIONS; model.slaThreshold = Resource.DEFAULT_MONITOR_SLA_THRESHOLD; const progress = ProgressEvent.success<ProgressEvent<ResourceModel>>(model); logger.log('progress', progress); return progress; } } export const resource = new Resource(ResourceModel.TYPE_NAME, ResourceModel); // Entrypoint for production usage after registered in CloudFormation export const entrypoint = resource.entrypoint; // Entrypoint used for local testing purpose export const testEntrypoint = resource.testEntrypoint;
the_stack
* @module Errors */ import { AuthStatus, BentleyError, BentleyStatus, BriefcaseStatus, ChangeSetStatus, GeoServiceStatus, HttpStatus, IModelHubStatus, IModelStatus, RealityDataStatus, RepositoryStatus, RpcInterfaceStatus, } from "./BentleyError"; /* eslint-disable @typescript-eslint/no-shadow */ /** @alpha */ export type StatusCategoryHandler = (error: BentleyError) => StatusCategory | undefined; /** A group of related statuses for aggregate reporting purposes. * @alpha */ export abstract class StatusCategory { public static handlers: Set<StatusCategoryHandler> = new Set(); public static for(error: BentleyError): StatusCategory { for (const handler of this.handlers) { const category = handler(error); if (category) { return category; } } return lookupCategory(error); } public abstract name: string; public abstract code: number; public abstract error: boolean; } /*** * A success status. * @alpha */ export abstract class SuccessCategory extends StatusCategory { public error = false; } /** * An error status. * @alpha */ export abstract class ErrorCategory extends StatusCategory { public error = true; } namespace HTTP { export class OK extends SuccessCategory { public name = "OK"; public code = 200; } export class Accepted extends SuccessCategory { public name = "Accepted"; public code = 202; } export class NoContent extends SuccessCategory { public name = "NoContent"; public code = 204; } export class BadRequest extends ErrorCategory { public name = "BadRequest"; public code = 400; } export class Unauthorized extends ErrorCategory { public name = "Unauthorized"; public code = 401; } export class Forbidden extends ErrorCategory { public name = "Forbidden"; public code = 403; } export class NotFound extends ErrorCategory { public name = "NotFound"; public code = 404; } export class RequestTimeout extends ErrorCategory { public name = "RequestTimeout"; public code = 408; } export class Conflict extends ErrorCategory { public name = "Conflict"; public code = 409; } export class Gone extends ErrorCategory { public name = "Gone"; public code = 410; } export class PreconditionFailed extends ErrorCategory { public name = "PreconditionFailed"; public code = 412; } export class ExpectationFailed extends ErrorCategory { public name = "ExpectationFailed"; public code = 417; } export class MisdirectedRequest extends ErrorCategory { public name = "MisdirectedRequest"; public code = 421; } export class UnprocessableEntity extends ErrorCategory { public name = "UnprocessableEntity"; public code = 422; } export class UpgradeRequired extends ErrorCategory { public name = "UpgradeRequired"; public code = 426; } export class PreconditionRequired extends ErrorCategory { public name = "PreconditionRequired"; public code = 428; } export class TooManyRequests extends ErrorCategory { public name = "TooManyRequests"; public code = 429; } export class InternalServerError extends ErrorCategory { public name = "InternalServerError"; public code = 500; } export class NotImplemented extends ErrorCategory { public name = "NotImplemented"; public code = 501; } } class Success extends HTTP.OK { } class Pending extends HTTP.Accepted { } class NoContent extends HTTP.NoContent { } class NothingToDo extends HTTP.NoContent { } class BadRequest extends HTTP.BadRequest { } class Forbidden extends HTTP.Forbidden { } class PermissionsViolation extends HTTP.Forbidden { } class ReadOnly extends HTTP.Forbidden { } class NotFound extends HTTP.NotFound { } class NotEnabled extends HTTP.UnprocessableEntity { } class NotSupported extends HTTP.UnprocessableEntity { } class ValidationError extends HTTP.BadRequest { } class Timeout extends HTTP.RequestTimeout { } class Conflict extends HTTP.Conflict { } class Cancelled extends HTTP.Gone { } class ConstraintViolation extends HTTP.Forbidden { } class VersioningViolation extends HTTP.Forbidden { } class Corruption extends HTTP.InternalServerError { } class InvalidData extends HTTP.InternalServerError { } class OperationFailed extends HTTP.InternalServerError { } class StateViolation extends HTTP.InternalServerError { } class Locked extends HTTP.Conflict { } class NetworkError extends HTTP.InternalServerError { } class Throttled extends HTTP.TooManyRequests { } class FileSystemError extends HTTP.InternalServerError { } class InternalError extends HTTP.InternalServerError { } class UnknownError extends HTTP.InternalServerError { } class NotImplemented extends HTTP.NotImplemented { } function lookupCategory(error: BentleyError): StatusCategory { switch (error.errorNumber) { case BentleyStatus.SUCCESS: return new Success(); case BentleyStatus.ERROR: return new UnknownError(); case IModelStatus.Success: return new Success(); case IModelStatus.AlreadyLoaded: return new StateViolation(); case IModelStatus.AlreadyOpen: return new StateViolation(); case IModelStatus.BadArg: return new ValidationError(); case IModelStatus.BadElement: return new ValidationError(); case IModelStatus.BadModel: return new ValidationError(); case IModelStatus.BadRequest: return new BadRequest(); case IModelStatus.BadSchema: return new ValidationError(); case IModelStatus.CannotUndo: return new OperationFailed(); case IModelStatus.CodeNotReserved: return new StateViolation(); case IModelStatus.DeletionProhibited: return new Forbidden(); case IModelStatus.DuplicateCode: return new Conflict(); case IModelStatus.DuplicateName: return new Conflict(); case IModelStatus.ElementBlockedChange: return new ConstraintViolation(); case IModelStatus.FileAlreadyExists: return new Conflict(); case IModelStatus.FileNotFound: return new NotFound(); case IModelStatus.FileNotLoaded: return new FileSystemError(); case IModelStatus.ForeignKeyConstraint: return new ConstraintViolation(); case IModelStatus.IdExists: return new Conflict(); case IModelStatus.InDynamicTransaction: return new StateViolation(); case IModelStatus.InvalidCategory: return new ValidationError(); case IModelStatus.InvalidCode: return new ValidationError(); case IModelStatus.InvalidCodeSpec: return new ValidationError(); case IModelStatus.InvalidId: return new ValidationError(); case IModelStatus.InvalidName: return new ValidationError(); case IModelStatus.InvalidParent: return new Conflict(); case IModelStatus.InvalidProfileVersion: return new InvalidData(); case IModelStatus.IsCreatingChangeSet: return new StateViolation(); case IModelStatus.LockNotHeld: return new Forbidden(); case IModelStatus.Mismatch2d3d: return new ValidationError(); case IModelStatus.MismatchGcs: return new ValidationError(); case IModelStatus.MissingDomain: return new ValidationError(); case IModelStatus.MissingHandler: return new ValidationError(); case IModelStatus.MissingId: return new ValidationError(); case IModelStatus.NoGeometry: return new NoContent(); case IModelStatus.NoMultiTxnOperation: return new StateViolation(); case IModelStatus.NotEnabled: return new NotEnabled(); case IModelStatus.NotFound: return new NotFound(); case IModelStatus.NotOpen: return new StateViolation(); case IModelStatus.NotOpenForWrite: return new Forbidden(); case IModelStatus.NotSameUnitBase: return new ValidationError(); case IModelStatus.NothingToRedo: return new NothingToDo(); case IModelStatus.NothingToUndo: return new NothingToDo(); case IModelStatus.ParentBlockedChange: return new Forbidden(); case IModelStatus.ReadError: return new FileSystemError(); case IModelStatus.ReadOnly: return new ReadOnly(); case IModelStatus.ReadOnlyDomain: return new ReadOnly(); case IModelStatus.RepositoryManagerError: return new NetworkError(); case IModelStatus.SQLiteError: return new InternalError(); case IModelStatus.TransactionActive: return new StateViolation(); case IModelStatus.UnitsMissing: return new ValidationError(); case IModelStatus.UnknownFormat: return new InvalidData(); case IModelStatus.UpgradeFailed: return new OperationFailed(); case IModelStatus.ValidationFailed: return new ValidationError(); case IModelStatus.VersionTooNew: return new VersioningViolation(); case IModelStatus.VersionTooOld: return new VersioningViolation(); case IModelStatus.ViewNotFound: return new NotFound(); case IModelStatus.WriteError: return new FileSystemError(); case IModelStatus.WrongClass: return new ValidationError(); case IModelStatus.WrongIModel: return new ValidationError(); case IModelStatus.WrongDomain: return new ValidationError(); case IModelStatus.WrongElement: return new ValidationError(); case IModelStatus.WrongHandler: return new ValidationError(); case IModelStatus.WrongModel: return new ValidationError(); case IModelStatus.ConstraintNotUnique: return new ConstraintViolation(); case IModelStatus.NoGeoLocation: return new ValidationError(); case IModelStatus.ServerTimeout: return new Timeout(); case IModelStatus.NoContent: return new NoContent(); case IModelStatus.NotRegistered: return new NotImplemented(); case IModelStatus.FunctionNotFound: return new NotImplemented(); case IModelStatus.NoActiveCommand: return new StateViolation(); case BriefcaseStatus.CannotAcquire: return new OperationFailed(); case BriefcaseStatus.CannotDownload: return new OperationFailed(); case BriefcaseStatus.CannotUpload: return new OperationFailed(); case BriefcaseStatus.CannotCopy: return new OperationFailed(); case BriefcaseStatus.CannotDelete: return new OperationFailed(); case BriefcaseStatus.VersionNotFound: return new NotFound(); case BriefcaseStatus.CannotApplyChanges: return new OperationFailed(); case BriefcaseStatus.DownloadCancelled: return new Cancelled(); case BriefcaseStatus.ContainsDeletedChangeSets: return new ValidationError(); case RpcInterfaceStatus.Success: return new Success(); case RpcInterfaceStatus.IncompatibleVersion: return new VersioningViolation(); case ChangeSetStatus.Success: return new Success(); case ChangeSetStatus.ApplyError: return new OperationFailed(); case ChangeSetStatus.ChangeTrackingNotEnabled: return new NotEnabled(); case ChangeSetStatus.CorruptedChangeStream: return new Corruption(); case ChangeSetStatus.FileNotFound: return new NotFound(); case ChangeSetStatus.FileWriteError: return new FileSystemError(); case ChangeSetStatus.HasLocalChanges: return new StateViolation(); case ChangeSetStatus.HasUncommittedChanges: return new StateViolation(); case ChangeSetStatus.InvalidId: return new Corruption(); case ChangeSetStatus.InvalidVersion: return new Corruption(); case ChangeSetStatus.InDynamicTransaction: return new StateViolation(); case ChangeSetStatus.IsCreatingChangeSet: return new StateViolation(); case ChangeSetStatus.IsNotCreatingChangeSet: return new StateViolation(); case ChangeSetStatus.MergePropagationError: return new OperationFailed(); case ChangeSetStatus.NothingToMerge: return new NothingToDo(); case ChangeSetStatus.NoTransactions: return new OperationFailed(); case ChangeSetStatus.ParentMismatch: return new ValidationError(); case ChangeSetStatus.SQLiteError: return new InternalError(); case ChangeSetStatus.WrongDgnDb: return new ValidationError(); case ChangeSetStatus.CouldNotOpenDgnDb: return new OperationFailed(); case ChangeSetStatus.MergeSchemaChangesOnOpen: return new BadRequest(); case ChangeSetStatus.ReverseOrReinstateSchemaChanges: return new Conflict(); case ChangeSetStatus.ProcessSchemaChangesOnOpen: return new BadRequest(); case ChangeSetStatus.CannotMergeIntoReadonly: return new ValidationError(); case ChangeSetStatus.CannotMergeIntoMaster: return new ValidationError(); case ChangeSetStatus.CannotMergeIntoReversed: return new ValidationError(); case RepositoryStatus.Success: return new Success(); case RepositoryStatus.ServerUnavailable: return new NetworkError(); case RepositoryStatus.LockAlreadyHeld: return new Conflict(); case RepositoryStatus.SyncError: return new NetworkError(); case RepositoryStatus.InvalidResponse: return new NetworkError(); case RepositoryStatus.PendingTransactions: return new StateViolation(); case RepositoryStatus.LockUsed: return new StateViolation(); case RepositoryStatus.CannotCreateChangeSet: return new InternalError(); case RepositoryStatus.InvalidRequest: return new NetworkError(); case RepositoryStatus.ChangeSetRequired: return new StateViolation(); case RepositoryStatus.CodeUnavailable: return new Conflict(); case RepositoryStatus.CodeNotReserved: return new StateViolation(); case RepositoryStatus.CodeUsed: return new StateViolation(); case RepositoryStatus.LockNotHeld: return new Forbidden(); case RepositoryStatus.RepositoryIsLocked: return new Locked(); case RepositoryStatus.ChannelConstraintViolation: return new ConstraintViolation(); case HttpStatus.Success: return new Success(); case IModelHubStatus.Success: return new Success(); case IModelHubStatus.Unknown: return new UnknownError(); case IModelHubStatus.MissingRequiredProperties: return new ValidationError(); case IModelHubStatus.InvalidPropertiesValues: return new ValidationError(); case IModelHubStatus.UserDoesNotHavePermission: return new PermissionsViolation(); case IModelHubStatus.UserDoesNotHaveAccess: return new PermissionsViolation(); case IModelHubStatus.InvalidBriefcase: return new ValidationError(); case IModelHubStatus.BriefcaseDoesNotExist: return new NotFound(); case IModelHubStatus.BriefcaseDoesNotBelongToUser: return new PermissionsViolation(); case IModelHubStatus.AnotherUserPushing: return new StateViolation(); case IModelHubStatus.ChangeSetAlreadyExists: return new Conflict(); case IModelHubStatus.ChangeSetDoesNotExist: return new NotFound(); case IModelHubStatus.FileIsNotUploaded: return new StateViolation(); case IModelHubStatus.iModelIsNotInitialized: return new StateViolation(); case IModelHubStatus.ChangeSetPointsToBadSeed: return new InvalidData(); case IModelHubStatus.OperationFailed: return new OperationFailed(); case IModelHubStatus.PullIsRequired: return new StateViolation(); case IModelHubStatus.MaximumNumberOfBriefcasesPerUser: return new Throttled(); case IModelHubStatus.MaximumNumberOfBriefcasesPerUserPerMinute: return new Throttled(); case IModelHubStatus.DatabaseTemporarilyLocked: return new Locked(); case IModelHubStatus.iModelIsLocked: return new Locked(); case IModelHubStatus.CodesExist: return new Conflict(); case IModelHubStatus.LocksExist: return new Conflict(); case IModelHubStatus.iModelAlreadyExists: return new Conflict(); case IModelHubStatus.iModelDoesNotExist: return new NotFound(); case IModelHubStatus.FileDoesNotExist: return new NotFound(); case IModelHubStatus.FileAlreadyExists: return new Conflict(); case IModelHubStatus.LockDoesNotExist: return new NotFound(); case IModelHubStatus.LockOwnedByAnotherBriefcase: return new Conflict(); case IModelHubStatus.CodeStateInvalid: return new StateViolation(); case IModelHubStatus.CodeReservedByAnotherBriefcase: return new Conflict(); case IModelHubStatus.CodeDoesNotExist: return new NotFound(); case IModelHubStatus.EventTypeDoesNotExist: return new NotFound(); case IModelHubStatus.EventSubscriptionDoesNotExist: return new NotFound(); case IModelHubStatus.EventSubscriptionAlreadyExists: return new StateViolation(); case IModelHubStatus.ITwinIdIsNotSpecified: return new ValidationError(); case IModelHubStatus.FailedToGetITwinPermissions: return new OperationFailed(); case IModelHubStatus.FailedToGetITwinMembers: return new OperationFailed(); case IModelHubStatus.ChangeSetAlreadyHasVersion: return new Conflict(); case IModelHubStatus.VersionAlreadyExists: return new Conflict(); case IModelHubStatus.JobSchedulingFailed: return new InternalError(); case IModelHubStatus.ConflictsAggregate: return new Conflict(); case IModelHubStatus.FailedToGetITwinById: return new OperationFailed(); case IModelHubStatus.DatabaseOperationFailed: return new OperationFailed(); case IModelHubStatus.SeedFileInitializationFailed: return new OperationFailed(); case IModelHubStatus.FailedToGetAssetPermissions: return new OperationFailed(); case IModelHubStatus.FailedToGetAssetMembers: return new OperationFailed(); case IModelHubStatus.ITwinDoesNotExist: return new NotFound(); case IModelHubStatus.LockChunkDoesNotExist: return new NotFound(); case IModelHubStatus.CheckpointAlreadyExists: return new Conflict(); case IModelHubStatus.CheckpointDoesNotExist: return new NotFound(); case IModelHubStatus.UndefinedArgumentError: return new ValidationError(); case IModelHubStatus.InvalidArgumentError: return new ValidationError(); case IModelHubStatus.MissingDownloadUrlError: return new ValidationError(); case IModelHubStatus.NotSupportedInBrowser: return new NotSupported(); case IModelHubStatus.FileHandlerNotSet: return new NotImplemented(); case IModelHubStatus.FileNotFound: return new NotFound(); case IModelHubStatus.InitializationTimeout: return new Timeout(); case AuthStatus.Success: return new Success(); case AuthStatus.Error: return new UnknownError(); case GeoServiceStatus.Success: return new Success(); case GeoServiceStatus.NoGeoLocation: return new ValidationError(); case GeoServiceStatus.OutOfUsefulRange: return new ValidationError(); case GeoServiceStatus.OutOfMathematicalDomain: return new ValidationError(); case GeoServiceStatus.NoDatumConverter: return new OperationFailed(); case GeoServiceStatus.VerticalDatumConvertError: return new OperationFailed(); case GeoServiceStatus.CSMapError: return new InternalError(); case GeoServiceStatus.Pending: return new Pending(); case RealityDataStatus.Success: return new Success(); case RealityDataStatus.InvalidData: return new InvalidData(); default: return new UnknownError(); } }
the_stack
import { URLExt } from '@jupyterlab/coreutils'; import { ServerConnection } from '@jupyterlab/services'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; import { JSONObject, PromiseDelegate } from '@lumino/coreutils'; import { ISignal, Signal } from '@lumino/signaling'; import { Conda, IEnvironmentManager } from './tokens'; /** * Type of environment that can be created. */ interface IType { [key: string]: string[]; } namespace RESTAPI { /** * Description of the REST API response when loading environments */ export interface IEnvironments { /** * List of available environments. */ environments: Array<Conda.IEnvironment>; } /** * Package properties returned by conda tools */ export interface IRawPackage { /** * Package name */ name: string; /** * Package version */ version: string; /** * Build number */ build_number: number; /** * Build string */ build_string: string; /** * Channel */ channel: string; /** * Platform */ platform: string; } } /** * Cancellable actions */ export interface ICancellableAction { /** * Type of cancellable action */ type: string; /** * Cancellable function */ cancel: () => void; } /** * Conda Environment Manager */ export class CondaEnvironments implements IEnvironmentManager { constructor(settings?: ISettingRegistry.ISettings) { this._environments = new Array<Conda.IEnvironment>(); if (settings) { this._updateSettings(settings); settings.changed.connect(this._updateSettings, this); const clean = new Promise<void>( ((resolve: () => void): void => { this._clean = resolve; }).bind(this) ); clean.then(() => { settings.changed.disconnect(this._updateSettings, this); }); } } get environments(): Promise<Array<Conda.IEnvironment>> { return this.refresh().then(() => { return Promise.resolve(this._environments); }); } get environmentChanged(): ISignal< IEnvironmentManager, Conda.IEnvironmentChange > { return this._environmentChanged; } getPackageManager(name?: string): Conda.IPackageManager { this._packageManager.environment = name; return this._packageManager; } /** * Test whether the manager is disposed. */ get isDisposed(): boolean { return this._isDisposed; } /** * Get the list of packages to install for a given environment type. * * The returned package list is the input type split with " ". * * @param type Environment type * @returns List of packages to create the environment */ getEnvironmentFromType(type: string): string[] { if (type in this._environmentTypes) { return this._environmentTypes[type]; } return type.split(' '); } /** * Get the list of user-defined environment types */ get environmentTypes(): string[] { return Object.keys(this._environmentTypes); } /** * Load user settings * * @param settings User settings */ private _updateSettings(settings: ISettingRegistry.ISettings): void { this._environmentTypes = settings.get('types').composite as IType; this._fromHistory = settings.get('fromHistory').composite as boolean; this._whitelist = settings.get('whitelist').composite as boolean; } /** * Dispose of the resources used by the manager. */ dispose(): void { if (this.isDisposed) { return; } this._isDisposed = true; clearInterval(this._environmentsTimer); this._clean(); this._environments.length = 0; } async getChannels(name: string): Promise<Conda.IChannels> { try { const request = { method: 'GET' }; const { promise } = Private.requestServer( URLExt.join('conda', 'channels'), request ); const response = await promise; if (response.ok) { const data = await response.json(); return data['channels'] as Conda.IChannels; } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `Fail to get the channels for environment ${name}.`; } throw new Error(message); } } async clone(target: string, name: string): Promise<void> { try { const request: RequestInit = { body: JSON.stringify({ name, twin: target }), method: 'POST' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments'), request ); const response = await promise; if (response.ok) { this._environmentChanged.emit({ name: name, source: target, type: 'clone' }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while cloning environment "${target}".`; } throw new Error(message); } } async create(name: string, type?: string): Promise<void> { try { const packages: Array<string> = this.getEnvironmentFromType(type || ''); const request: RequestInit = { body: JSON.stringify({ name, packages }), method: 'POST' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments'), request ); const response = await promise; if (response.ok) { this._environmentChanged.emit({ name: name, source: packages, type: 'create' }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while creating environment "${name}".`; } throw new Error(message); } } export(name: string, fromHistory: boolean | null = null): Promise<Response> { if (fromHistory === null) { fromHistory = this._fromHistory; } try { const request: RequestInit = { method: 'GET' }; const args = URLExt.objectToQueryString({ download: 1, history: fromHistory ? 1 : 0 }); const { promise } = Private.requestServer( URLExt.join('conda', 'environments', name) + args, request ); return promise; } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while exporting environment "${name}".`; } throw new Error(message); } } async import( name: string, fileContent: string, fileName?: string ): Promise<void> { try { const data: JSONObject = { name, file: fileContent }; if (fileName) { data['filename'] = fileName; } const request: RequestInit = { body: JSON.stringify(data), method: 'POST' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments'), request ); const response = await promise; if (response.ok) { this._environmentChanged.emit({ name: name, source: fileContent, type: 'import' }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while importing "${name}".`; } throw new Error(message); } } async refresh(): Promise<Array<Conda.IEnvironment>> { try { const request: RequestInit = { method: 'GET' }; const queryArgs = { whitelist: this._whitelist ? 1 : 0 }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments') + URLExt.objectToQueryString(queryArgs), request ); const response = await promise; const data = (await response.json()) as RESTAPI.IEnvironments; this._environments = data.environments; return data.environments; } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while listing Conda environments.'; } throw new Error(message); } } async remove(name: string): Promise<void> { try { const request: RequestInit = { method: 'DELETE' }; const { promise } = await Private.requestServer( URLExt.join('conda', 'environments', name), request ); const response = await promise; if (response.ok) { this._environmentChanged.emit({ name: name, source: null, type: 'remove' }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while removing "${name}".`; } throw new Error(message); } } async update( name: string, fileContent: string, fileName?: string ): Promise<void> { try { const data: JSONObject = { file: fileContent }; if (fileName) { data['filename'] = fileName; } const request: RequestInit = { body: JSON.stringify(data), method: 'PATCH' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments', name), request ); const response = await promise; if (response.ok) { this._environmentChanged.emit({ name: name, source: fileContent, type: 'update' }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while updating "${name}".`; } throw new Error(message); } } // Resolve promise to disconnect signals at disposal private _clean: () => void = () => { return; }; private _isDisposed = false; private _environmentChanged = new Signal< IEnvironmentManager, Conda.IEnvironmentChange >(this); private _environments: Array<Conda.IEnvironment>; private _environmentsTimer = -1; private _environmentTypes: IType = { python3: ['python=3', 'ipykernel'], r: ['r-base', 'r-essentials'] }; private _fromHistory = false; private _packageManager = new CondaPackage(); private _whitelist = false; } export class CondaPackage implements Conda.IPackageManager { /** * Conda environment of interest */ environment?: string; constructor(environment?: string) { this.environment = environment; } get packageChanged(): ISignal<Conda.IPackageManager, Conda.IPackageChange> { return this._packageChanged; } /** * Refresh the package list. * * @param includeAvailable Include available package list * @param environment Environment name * * @returns The package list */ async refresh( includeAvailable = true, environment?: string ): Promise<Array<Conda.IPackage>> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined) { return Promise.resolve([]); } this._cancelTasks('default'); try { const request: RequestInit = { method: 'GET' }; // Get installed packages const { promise, cancel } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment), request ); const idx = this._cancellableStack.push({ type: 'default', cancel }) - 1; const response = await promise; this._cancellableStack.splice(idx, 1); const data = (await response.json()) as { packages: Array<RESTAPI.IRawPackage>; }; const installedPkgs = data.packages; const allPackages: Array<Conda.IPackage> = []; if (includeAvailable) { // Get all available packages allPackages.push(...(await this._getAvailablePackages())); } // Set installed package status //- packages are sorted by name, we take advantage of this. const finalList = []; let availableIdx = 0; let installedIdx = 0; while ( installedIdx < installedPkgs.length || availableIdx < allPackages.length ) { const installed = installedPkgs[installedIdx]; let pkg = allPackages[availableIdx] || { ...installed, version: [installed.version], build_number: [installed.build_number], build_string: [installed.build_string], summary: '', home: '', keywords: '', tags: '' }; pkg.summary = pkg.summary || ''; // Stringify keywords and tags pkg.keywords = (pkg.keywords || '').toString().toLowerCase(); pkg.tags = (pkg.tags || '').toString().toLowerCase(); pkg.version_installed = ''; pkg.version_selected = 'none'; pkg.updatable = false; if (installed !== undefined) { if (pkg.name > installed.name) { // installed is not in available pkg = { ...installed, version: [installed.version], build_number: [installed.build_number], build_string: [installed.build_string], summary: '', home: '', keywords: '', tags: '' }; availableIdx -= 1; } if (pkg.name === installed.name) { pkg.version_installed = installed.version; pkg.version_selected = installed.version; if (pkg.version.indexOf(installed.version) < 0) { pkg.version.push(installed.version); } installedIdx += 1; } } // Simplify the package channel name const splitUrl = pkg.channel.split('/'); if (splitUrl.length > 2) { let firstNotEmpty = 0; if ( ['http:', 'https:', 'file:'].indexOf(splitUrl[firstNotEmpty]) >= 0 ) { firstNotEmpty = 1; // Skip the scheme http, https or file } while (splitUrl[firstNotEmpty].length === 0) { firstNotEmpty += 1; } pkg.channel = splitUrl[firstNotEmpty]; let pos = splitUrl.length - 1; while ( Conda.PkgSubDirs.indexOf(splitUrl[pos]) > -1 && pos > firstNotEmpty ) { pos -= 1; } if (pos > firstNotEmpty) { pkg.channel += '/...'; } pkg.channel += '/' + splitUrl[pos]; } finalList.push(pkg); availableIdx += 1; } return finalList; } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while retrieving available packages.'; } throw new Error(message); } } async install(packages: Array<string>, environment?: string): Promise<void> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined || packages.length === 0) { return Promise.resolve(); } try { const request: RequestInit = { body: JSON.stringify({ packages }), method: 'POST' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment, 'packages'), request ); const response = await promise; if (response.ok) { this._packageChanged.emit({ environment: theEnvironment, type: 'install', packages }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while installing packages.'; } throw new Error(message); } } async develop(path: string, environment?: string): Promise<void> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined || path.length === 0) { return Promise.resolve(); } try { const request: RequestInit = { body: JSON.stringify({ packages: [path] }), method: 'POST' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment, 'packages') + URLExt.objectToQueryString({ develop: 1 }), request ); const response = await promise; if (response.ok) { this._packageChanged.emit({ environment: theEnvironment, type: 'develop', packages: [path] }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = `An error occurred while installing in development mode package in ${path}.`; } throw new Error(message); } } async check_updates(environment?: string): Promise<Array<string>> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined) { return Promise.resolve([]); } this._cancelTasks('default'); try { const request: RequestInit = { method: 'GET' }; const { promise, cancel } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment) + URLExt.objectToQueryString({ status: 'has_update' }), request ); const idx = this._cancellableStack.push({ type: 'default', cancel }) - 1; const response = await promise; this._cancellableStack.splice(idx, 1); const data = (await response.json()) as { updates: Array<RESTAPI.IRawPackage>; }; return data.updates.map(pkg => pkg.name); } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while checking for package updates.'; } throw new Error(message); } } async update(packages: Array<string>, environment?: string): Promise<void> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined) { return Promise.resolve(); } try { const request: RequestInit = { body: JSON.stringify({ packages }), method: 'PATCH' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment, 'packages'), request ); const response = await promise; if (response.ok) { this._packageChanged.emit({ environment: theEnvironment, type: 'update', packages }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while updating packages.'; } throw new Error(message); } } async remove(packages: Array<string>, environment?: string): Promise<void> { const theEnvironment = environment || this.environment; if (theEnvironment === undefined) { return Promise.resolve(); } try { const request: RequestInit = { body: JSON.stringify({ packages }), method: 'DELETE' }; const { promise } = Private.requestServer( URLExt.join('conda', 'environments', theEnvironment, 'packages'), request ); const response = await promise; if (response.ok) { this._packageChanged.emit({ environment: theEnvironment, type: 'remove', packages }); } } catch (error) { let message: string = error.message || error.toString(); if (message !== 'cancelled') { console.error(message); message = 'An error occurred while removing packages.'; } throw new Error(message); } } async getDependencies( pkg: string, cancellable = true ): Promise<Conda.IPackageDeps> { this._cancelTasks('getDependencies'); const request: RequestInit = { method: 'GET' }; const { promise, cancel } = Private.requestServer( URLExt.join('conda', 'packages') + URLExt.objectToQueryString({ dependencies: 1, query: pkg }), request ); let idx: number; if (cancellable) { idx = this._cancellableStack.push({ type: 'getDependencies', cancel }) - 1; } const response = await promise; if (idx) { this._cancellableStack.splice(idx, 1); } const data = (await response.json()) as Conda.IPackageDeps; return Promise.resolve(data); } async refreshAvailablePackages(cancellable = true): Promise<void> { await this._getAvailablePackages(true, cancellable); } /** * Does the available packages have description? * * @returns description presence */ hasDescription(): boolean { return CondaPackage._hasDescription; } /** * Get the available packages list. * * @param force Force refreshing the available package list * @param cancellable Can this asynchronous action be cancelled? */ private async _getAvailablePackages( force = false, cancellable = true ): Promise<Array<Conda.IPackage>> { this._cancelTasks('default'); if (CondaPackage._availablePackages === null || force) { const request: RequestInit = { method: 'GET' }; const { promise, cancel } = Private.requestServer( URLExt.join('conda', 'packages'), request ); let idx: number; if (cancellable) { idx = this._cancellableStack.push({ type: 'default', cancel }) - 1; } const response = await promise; if (idx) { this._cancellableStack.splice(idx, 1); } const data = (await response.json()) as { packages: Array<Conda.IPackage>; with_description: boolean; }; CondaPackage._availablePackages = data.packages; CondaPackage._hasDescription = data.with_description || false; } return Promise.resolve(CondaPackage._availablePackages); } /** * Cancel optional tasks */ private _cancelTasks(type: string): void { if (this._cancellableStack.length > 0) { const tasks = this._cancellableStack.splice( 0, this._cancellableStack.length ); tasks.forEach(action => { if (action.type === type) { action.cancel(); } }); } } private _packageChanged: Signal< CondaPackage, Conda.IPackageChange > = new Signal<this, Conda.IPackageChange>(this); private _cancellableStack: Array<ICancellableAction> = []; private static _availablePackages: Array<Conda.IPackage> = null; private static _hasDescription = false; } namespace Private { /** * Polling interval for accepted tasks */ const POLLING_INTERVAL = 1000; export interface ICancellablePromise<T> { promise: Promise<T>; cancel: () => void; } /** Helper functions to carry on python notebook server request * * @param {string} url : request url * @param {RequestInit} request : initialization parameters for the request * @returns {ICancellablePromise<Response>} : Cancellable response to the request */ export const requestServer = function ( url: string, request: RequestInit ): ICancellablePromise<Response> { const settings = ServerConnection.makeSettings(); const fullUrl = URLExt.join(settings.baseUrl, url); let answer: ICancellablePromise<Response>; let cancelled = false; const promise = new PromiseDelegate<Response>(); ServerConnection.makeRequest(fullUrl, request, settings) .then(response => { if (!response.ok) { response .json() .then(body => promise.reject( new ServerConnection.ResponseError(response, body.error) ) ) .catch(reason => { console.error( 'Fail to read JSON response for request', request, reason ); }); } else if (response.status === 202) { const redirectUrl = response.headers.get('Location') || url; setTimeout( (url: string, settings: RequestInit) => { if (cancelled) { // If cancelled, tell the backend to delete the task. console.debug(`Request cancelled ${url}.`); settings = { ...settings, method: 'DELETE' }; } answer = requestServer(url, settings); answer.promise .then(response => promise.resolve(response)) .catch(reason => promise.reject(reason)); }, POLLING_INTERVAL, redirectUrl, { method: 'GET' } ); } else { promise.resolve(response); } }) .catch(reason => { promise.reject(new ServerConnection.NetworkError(reason)); }); return { promise: promise.promise, cancel: (): void => { cancelled = true; if (answer) { answer.cancel(); } promise.reject('cancelled'); } }; }; }
the_stack
import { actions } from "common/actions"; import { ITCH_URL_RE } from "common/constants/urls"; import { Space } from "common/helpers/space"; import { Store, TabPage } from "common/types"; import { Watcher } from "common/util/watcher"; import { BrowserWindow, WebContents, webContents } from "electron"; import { mainLogger } from "main/logger"; import { openAppDevTools } from "main/reactors/open-app-devtools"; import { hookWebContentsContextMenu } from "main/reactors/web-contents-context-menu"; import { parseWellKnownUrl } from "main/reactors/web-contents/parse-well-known-url"; import { forgetWebContents, getWebContents, storeWebContents, } from "main/reactors/web-contents/web-contents-state"; import { getNativeWindow } from "main/reactors/winds"; const logger = mainLogger.child(__filename); const SHOW_DEVTOOLS = parseInt(process.env.DEVTOOLS, 10) > 1; export type ExtendedWebContents = Electron.WebContents & { history: string[]; currentIndex: number; pendingIndex: number; inPageIndex: number; }; type WebContentsCallback<T> = (wc: ExtendedWebContents) => T; function withWebContents<T>( store: Store, wind: string, tab: string, cb: WebContentsCallback<T> ): T | null { const wc = getWebContents(wind, tab); if (wc && !wc.isDestroyed()) { return cb(wc as ExtendedWebContents); } return null; } function loadURL(wc: WebContents, url: string) { if (ITCH_URL_RE.test(url)) { return; } wc.loadURL(url); } export default function (watcher: Watcher) { watcher.on(actions.windHtmlFullscreenChanged, async (store, action) => { const { wind, htmlFullscreen } = action.payload; if (htmlFullscreen) { logger.warn(`fullscreen: reimplement`); } }); watcher.on(actions.tabGotWebContents, async (store, action) => { const { wind, tab, webContentsId } = action.payload; const rs = store.getState(); const initialURL = rs.winds[wind].tabInstances[tab].location.url; const wc = webContents.fromId(webContentsId); storeWebContents(wind, tab, wc); logger.debug(`Loading url '${initialURL}'`); await hookWebContents(store, wind, tab, wc as ExtendedWebContents); loadURL(wc, initialURL); }); watcher.on(actions.tabLosingWebContents, async (store, action) => { const { wind, tab } = action.payload; logger.debug(`Tab ${tab} losing web contents!`); forgetWebContents(wind, tab); }); watcher.on(actions.analyzePage, async (store, action) => { const { wind, tab, url } = action.payload; await withWebContents(store, wind, tab, async (wc) => { const onNewPath = (url: string, resource: string) => { if (resource) { logger.debug(`Got resource ${resource}`); store.dispatch( actions.evolveTab({ wind, tab, url, resource, replace: true, onlyIfMatchingURL: true, fromWebContents: true, }) ); } }; const code = `(document.querySelector('meta[name="itch:path"]') || {}).content`; const newPath = await wc.executeJavaScript(code); onNewPath(url, newPath); }); }); watcher.on(actions.tabReloaded, async (store, action) => { const { wind, tab } = action.payload; withWebContents(store, wind, tab, (wc) => { wc.reload(); }); }); watcher.on(actions.commandStop, async (store, action) => { const { wind } = action.payload; const { tab } = store.getState().winds[wind].navigation; withWebContents(store, wind, tab, (wc) => { wc.stop(); }); }); watcher.on(actions.commandLocation, async (store, action) => { const { wind } = action.payload; const { tab } = store.getState().winds[wind].navigation; store.dispatch( actions.focusLocationBar({ wind, tab, }) ); const nw = getNativeWindow(store.getState(), wind); if (nw && nw.webContents) { nw.webContents.focus(); } }); watcher.on(actions.focusSearch, async (store, action) => { const wind = "root"; const nw = getNativeWindow(store.getState(), wind); if (nw && nw.webContents) { nw.webContents.focus(); } }); watcher.on(actions.commandBack, async (store, action) => { const { wind } = action.payload; store.dispatch(actions.blurLocationBar({})); }); watcher.on(actions.openDevTools, async (store, action) => { const { wind, tab } = action.payload; if (tab) { const { tab } = store.getState().winds[wind].navigation; withWebContents(store, wind, tab, (wc) => { wc.openDevTools({ mode: "detach" }); }); } else { openAppDevTools(BrowserWindow.getFocusedWindow()); } }); watcher.on(actions.inspect, async (store, action) => { const { webContentsId, x, y } = action.payload; const wc = webContents.fromId(webContentsId); if (wc && !wc.isDestroyed()) { const dwc = wc.devToolsWebContents; if (dwc) { wc.devToolsWebContents.focus(); } else { wc.openDevTools({ mode: "detach" }); } wc.inspectElement(x, y); } }); watcher.on(actions.tabGoBack, async (store, action) => { const { wind, tab } = action.payload; const rs = store.getState(); const ti = rs.winds[wind].tabInstances[tab]; if (!ti) { return; } store.dispatch( actions.tabGoToIndex({ wind, tab, index: ti.currentIndex - 1, }) ); }); watcher.on(actions.tabGoForward, async (store, action) => { const { wind, tab } = action.payload; const rs = store.getState(); const ti = rs.winds[wind].tabInstances[tab]; if (!ti) { return; } store.dispatch( actions.tabGoToIndex({ wind, tab, index: ti.currentIndex + 1, }) ); }); watcher.on(actions.tabGoToIndex, async (store, action) => { const { wind, tab, index } = action.payload; const rs = store.getState(); const ti = rs.winds[wind].tabInstances[tab]; if (!ti) { return; } if (index < 0 || index >= ti.history.length) { return; } store.dispatch( actions.tabWentToIndex({ wind, tab, index, oldIndex: ti.currentIndex, }) ); }); watcher.on(actions.tabWentToIndex, async (store, action) => { const rs = store.getState(); const { wind, tab, oldIndex, index, fromWebContents } = action.payload; if (fromWebContents) { return; } withWebContents(store, wind, tab, (wc) => { let offset = index - oldIndex; const url = rs.winds[wind].tabInstances[tab].history[index].url; if ( wc.canGoToOffset(offset) && wc.history[wc.currentIndex + offset] === url ) { logger.debug(`\n`); logger.debug(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`); logger.debug( `For index ${oldIndex} => ${index}, applying offset ${offset}` ); logger.debug(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n`); wc.goToOffset(offset); } else { const url = Space.fromState(rs, wind, tab).url(); logger.debug(`\n`); logger.debug(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`); logger.debug( `For index ${oldIndex} => ${index}, clearing history and loading ${url}` ); logger.debug(`(could go to offset? ${wc.canGoToOffset(offset)})`); logger.debug(`(wcl = ${wc.history[wc.currentIndex + offset]})`); logger.debug(`(url = ${url})`); if (offset == 1) { logger.debug( `Wait, no, we're just going forward one, we don't need to clear history` ); } else { wc.clearHistory(); } logger.debug(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n`); loadURL(wc, url); } }); }); watcher.on(actions.evolveTab, async (store, action) => { const { wind, tab, url, replace, fromWebContents } = action.payload; if (replace || fromWebContents) { return; } withWebContents(store, wind, tab, async (wc) => { const webUrl = wc.history[wc.currentIndex]; if (webUrl !== url) { logger.debug( `WebContents has\n--> ${webUrl}\ntab evolved to\n--> ${url}\nlet's load` ); loadURL(wc, url); } else { logger.debug( `WebContents has\n--> ${webUrl}\ntab evolved to\n--> ${url}\nwe're good.` ); } }); }); } async function hookWebContents( store: Store, wind: string, tab: string, wc: ExtendedWebContents ) { let setLoading = (loading: boolean) => { store.dispatch(actions.tabLoadingStateChanged({ wind, tab, loading })); }; let pushPageUpdate = (page: Partial<TabPage>) => { store.dispatch( actions.tabPageUpdate({ wind, tab, page, }) ); }; setLoading(wc.isLoading()); wc.on("certificate-error", (ev, url, error, certificate, cb) => { cb(false); logger.warn( `Certificate error ${error} for ${url}, issued by ${certificate.issuerName} for ${certificate.subjectName}` ); }); wc.on( "did-fail-load", (ev, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { return; } logger.warn( `Did fail load: ${errorCode}, ${errorDescription} for ${validatedURL}` ); } ); wc.once("did-finish-load", () => { logger.debug(`did-finish-load (once)`); hookWebContentsContextMenu(wc, wind, store); if (SHOW_DEVTOOLS) { wc.openDevTools({ mode: "detach" }); } }); wc.on("did-finish-load", () => { store.dispatch( actions.analyzePage({ wind, tab, url: wc.getURL(), }) ); }); wc.on("did-start-loading", () => { setLoading(true); }); wc.on("did-stop-loading", () => { setLoading(false); }); wc.on("page-title-updated" as any, (ev, title: string) => { pushPageUpdate({ label: title, }); }); wc.on("page-favicon-updated", (ev, favicons) => { pushPageUpdate({ favicon: favicons[0], }); }); wc.on( "new-window", (ev, url, frameName, disposition, options, additionalFeatures) => { ev.preventDefault(); logger.debug(`new-window fired for ${url}`); wc.loadURL(url); } ); enum NavMode { Append, Replace, } const didNavigate = (url: string, navMode?: NavMode) => { let resource = null; const result = parseWellKnownUrl(url); if (result) { url = result.url; resource = result.resource; logger.debug(`Parsed well-known url: ${url} => ${resource}`); } store.dispatch( actions.evolveTab({ wind, tab, url, label: wc.getTitle(), resource, replace: navMode === NavMode.Replace, fromWebContents: true, }) ); }; let printWebContentsHistory = (previousIndex: number) => { if (wc.history.length === 0) { logger.debug(`(The webcontents history are empty for some reason)`); } else { logger.debug("WebContents history:"); for (let i = 0; i < wc.history.length; i++) { let prevMark = i === previousIndex ? "<" : " "; let pendMark = i === wc.pendingIndex ? "P" : " "; let currMark = i === wc.currentIndex ? ">" : " "; logger.debug(`W|${prevMark}${pendMark}${currMark} ${wc.history[i]}`); } } }; let printStateHistory = () => { const space = Space.fromStore(store, wind, tab); logger.debug(`---------------------------------`); logger.debug("State history:"); for (let i = 0; i < space.history().length; i++) { const page = space.history()[i]; logger.debug(`S| ${i === space.currentIndex() ? ">" : " "} ${page.url}`); } }; let previousState = { previousIndex: 0, previousHistorySize: 1, }; const commit = ( reason: "will-navigate" | "did-navigate" | "did-navigate-in-page", event: any, url: string, // latest URL inPage: boolean, // in-page navigation (HTML5 pushState/popState/replaceState) replaceEntry: boolean // previous history entry was replaced ) => { if (wc.currentIndex < 0) { // We get those spurious events after a "clear history & loadURL()" // at this point `wc.history.length` is 0 anyway, so it's not like we // can figure out much. They're followed by a meaningful event shortly after. logger.debug(`Ignoring commit with negative currentIndex`); return; } let { previousIndex, previousHistorySize } = previousState; previousState = { previousIndex: wc.currentIndex, previousHistorySize: wc.history.length, }; const space = Space.fromStore(store, wind, tab); const stateHistory = space.history(); const getStateURL = (index: number) => { if (index >= 0 && index < stateHistory.length) { return stateHistory[index].url; } // The index passed to this function is sometimes computed // from the current index + an offset, so it might be out // of bounds. // We always use it to find equal URLs, // so it's okay to just return undefined in these cases return undefined; }; const stateIndex = space.currentIndex(); const stateURL = getStateURL(stateIndex); logger.debug("\n"); logger.debug(`=================================`); logger.debug(`commit ${url}, reason ${reason}`); logger.debug( `currentIndex ${wc.currentIndex} pendingIndex ${wc.pendingIndex} inPageIndex ${wc.inPageIndex} inPage ${inPage}` ); printWebContentsHistory(previousIndex); printStateHistory(); const wcTitle = wc.getTitle(); if ( wcTitle !== url && space.label() !== wc.getTitle() && !/^itch:/i.test(url) ) { // page-title-updated does not always fire, so a navigation (in-page or not) // is a good place to check. // we also check that the webContents' title is not its URL, which happens // while it's currently loading a page. logger.debug(`pushing webContents title ${wcTitle}`); pushPageUpdate({ url, label: wcTitle, }); } let offset = wc.currentIndex - previousIndex; let sizeOffset = wc.history.length - previousHistorySize; if (sizeOffset === 1) { logger.debug(`History grew one, offset is ${offset}`); if (stateURL === url) { logger.debug(`web and state point to same URL, doing nothing`); } if (offset === 0) { logger.debug(`Replacing because offset is 0`); didNavigate(url, NavMode.Replace); printStateHistory(); return; } let currentURL = space.url(); let previousWebURL = wc.history[wc.currentIndex - 1]; if (currentURL && previousWebURL !== currentURL) { logger.debug( `Replacing because previous web url \n${previousWebURL}\n is not current state url \n${currentURL}` ); didNavigate(url, NavMode.Replace); printStateHistory(); return; } logger.debug(`Assuming regular navigation happened`); didNavigate(url, NavMode.Append); printStateHistory(); return; } if (sizeOffset === 0) { logger.debug(`History stayed the same size, offset is ${offset}`); if (offset === 1) { if (stateURL === url) { logger.debug(`web and state point to same URL, doing nothing`); return; } if (getStateURL(stateIndex + offset) === url) { logger.debug(`If we apply the history offset, the URLs match!`); // fallthrough to in-history navigation } else { logger.debug(`Assuming normal navigation happened`); didNavigate(url, NavMode.Append); printStateHistory(); return; } } else if (offset === 0) { if (replaceEntry) { const index = space.currentIndex(); if (inPage) { if (getStateURL(index - 1) === url) { logger.debug( `replaceEntry is true, but inPage & previous is a dupe, ignoring` ); return; } if (getStateURL(index + 1) === url) { logger.debug( `replaceEntry is true, but inPage & next is a dupe, ignoring` ); return; } } logger.debug(`Handling it like a replace`); didNavigate(url, NavMode.Replace); printStateHistory(); return; } else { const index = space.currentIndex(); let prevURL = getStateURL(index - 1); let webURL = wc.history[wc.currentIndex]; logger.debug(`prevURL = ${prevURL}`); logger.debug(` webURL = ${webURL}`); if (prevURL === webURL) { logger.debug( `looks like a forward navigation, but previous is a dupe` ); didNavigate(url, NavMode.Replace); return; } else { logger.debug(`Not a replace, doing nothing.`); return; } } } if (stateURL === url) { logger.debug(`web and state point to same URL, doing nothing`); return; } let oldIndex = stateIndex; let index = oldIndex + offset; if (getStateURL(index) === url) { logger.debug( `Assuming in-history navigation (${oldIndex} => ${index})` ); store.dispatch( actions.tabWentToIndex({ wind, tab, oldIndex, index, fromWebContents: true, }) ); printStateHistory(); return; } else { logger.debug(`We're not sure what happened, doing nothing`); return; } } logger.debug(`History shrunk ; usually means normal navigation.`); if (stateURL === url) { logger.debug(`Except the url is already good, nvm!`); } else { logger.debug(`Assuming normal navigation happened`); didNavigate(url, NavMode.Append); printStateHistory(); } return; }; wc.on("did-navigate", (event, url) => { commit("did-navigate", event, url, false, false); }); wc.on("did-navigate-in-page", (event, url) => { commit("did-navigate-in-page", event, url, true, false); }); }
the_stack
* Hyperledger Cactus Plugin - Connector Iroha * Can perform basic tasks on a Iroha ledger * * The version of the OpenAPI document: 0.0.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { Configuration } from './configuration'; import globalAxios, { AxiosPromise, AxiosInstance } from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; // @ts-ignore import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base'; /** * * @export * @interface InlineResponse501 */ export interface InlineResponse501 { /** * * @type {string} * @memberof InlineResponse501 */ message?: string; } /** * * @export * @interface InvokeContractV1Request */ export interface InvokeContractV1Request { /** * * @type {any} * @memberof InvokeContractV1Request */ contractName?: any | null; } /** * * @export * @interface IrohaBaseConfig */ export interface IrohaBaseConfig { [key: string]: object | any; /** * * @type {string} * @memberof IrohaBaseConfig */ irohaHost?: string; /** * * @type {number} * @memberof IrohaBaseConfig */ irohaPort?: number; /** * * @type {string} * @memberof IrohaBaseConfig */ creatorAccountId?: string; /** * * @type {Array<any>} * @memberof IrohaBaseConfig */ privKey?: Array<any>; /** * * @type {number} * @memberof IrohaBaseConfig */ quorum?: number; /** * * @type {number} * @memberof IrohaBaseConfig */ timeoutLimit?: number; /** * Can only be set to false for an insecure grpc connection. * @type {boolean} * @memberof IrohaBaseConfig */ tls?: boolean; } /** * * @export * @enum {string} */ export enum IrohaCommand { /** * Make entity in the system, capable of sending transactions or queries, storing signatories, personal data and identifiers. */ CreateAccount = 'createAccount', /** * Set key-value information for a given account. */ SetAccountDetail = 'setAccountDetail', /** * Set the number of signatories required to confirm the identity of a user, who creates the transaction. */ SetAccountQuorum = 'setAccountQuorum', /** * Set key-value information for a given account if the old value matches the value passed. */ CompareAndSetAccountDetail = 'compareAndSetAccountDetail', /** * Create a new type of asset, unique in a domain. An asset is a countable representation of a commodity. */ CreateAsset = 'createAsset', /** * Increase the quantity of an asset on account of transaction creator. */ AddAssetQuantity = 'addAssetQuantity', /** * Decrease the number of assets on account of transaction creator. */ SubtractAssetQuantity = 'subtractAssetQuantity', /** * Share assets within the account in peer network: in the way that source account transfers assets to the target account. */ TransferAsset = 'transferAsset', /** * Make new domain in Iroha network, which is a group of accounts. */ CreateDomain = 'createDomain', /** * Create a new role in the system from the set of permissions. */ CreateRole = 'createRole', /** * Detach a role from the set of roles of an account. */ DetachRole = 'detachRole', /** * Promote an account to some created role in the system, where a role is a set of permissions account has to perform an action (command or query). */ AppendRole = 'appendRole', /** * Add an identifier to the account. Such identifier is a public key of another device or a public key of another user. */ AddSignatory = 'addSignatory', /** * Remove a public key, associated with an identity, from an account */ RemoveSignatory = 'removeSignatory', /** * Give another account rights to perform actions on the account of transaction sender (give someone right to do something with my account). */ GrantPermission = 'grantPermission', /** * Revoke or dismiss given granted permission from another account in the network. */ RevokePermission = 'revokePermission', /** * Write into ledger the fact of peer addition into the peer network. */ AddPeer = 'addPeer', /** * Write into ledger the fact of peer removal from the network. */ RemovePeer = 'removePeer', /** * This command is not available for use, it was added for backward compatibility with Iroha. */ SetSettingValue = 'setSettingValue', /** * This command is not availalbe for use because it is related to smart contract. */ CallEngine = 'callEngine' } /** * * @export * @enum {string} */ export enum IrohaQuery { /** * To get the state of an account */ GetAccount = 'getAccount', /** * To get details of the account. */ GetAccountDetail = 'getAccountDetail', /** * To get information on the given asset (as for now - its precision). */ GetAssetInfo = 'getAssetInfo', /** * To get the state of all assets in an account (a balance). */ GetAccountAssets = 'getAccountAssets', /** * To retrieve information about transactions, based on their hashes. */ GetTransactions = 'getTransactions', /** * To retrieve a list of pending (not fully signed) multisignature transactions or batches of transactions issued by account of query creator. */ GetPendingTransactions = 'getPendingTransactions', /** * To retrieve a list of transactions per account. */ GetAccountTransactions = 'getAccountTransactions', /** * To retrieve all transactions associated with given account and asset. */ GetAccountAssetTransactions = 'getAccountAssetTransactions', /** * To get existing roles in the system. */ GetRoles = 'getRoles', /** * To get signatories, which act as an identity of the account. */ GetSignatories = 'getSignatories', /** * To get available permissions per role in the system. */ GetRolePermissions = 'getRolePermissions', /** * To get a specific block, using its height as an identifier. */ GetBlock = 'getBlock', /** * To retrieve a receipt of a CallEngine command. Allows to access the event log created during computations inside the EVM. */ GetEngineReceipts = 'getEngineReceipts', /** * To get new blocks as soon as they are committed, a user can invoke FetchCommits RPC call to Iroha network. */ FetchCommits = 'fetchCommits', /** * A query that returns a list of peers in Iroha network. */ GetPeers = 'getPeers' } /** * * @export * @interface KeyPair */ export interface KeyPair { /** * SHA-3 ed25519 public keys of length 64 are recommended. * @type {string} * @memberof KeyPair */ publicKey: string; /** * SHA-3 ed25519 private keys of length 64 are recommended. * @type {string} * @memberof KeyPair */ privateKey: string; } /** * * @export * @interface RunTransactionRequestV1 */ export interface RunTransactionRequestV1 { /** * * @type {string} * @memberof RunTransactionRequestV1 */ commandName: string; /** * * @type {IrohaBaseConfig} * @memberof RunTransactionRequestV1 */ baseConfig?: IrohaBaseConfig; /** * The list of arguments to pass in to the transaction request. * @type {Array<any>} * @memberof RunTransactionRequestV1 */ params: Array<any>; } /** * * @export * @interface RunTransactionResponse */ export interface RunTransactionResponse { /** * * @type {any} * @memberof RunTransactionResponse */ transactionReceipt: any | null; } /** * DefaultApi - axios parameter creator * @export */ export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) { return { /** * * @summary Get the Prometheus Metrics * @param {*} [options] Override http request option. * @throws {RequiredError} */ getPrometheusMetricsV1: async (options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-iroha/get-prometheus-exporter-metrics`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Invokes a contract on a Iroha ledger * @param {InvokeContractV1Request} [invokeContractV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ invokeContractV1: async (invokeContractV1Request?: InvokeContractV1Request, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-iroha/invoke-contract`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(invokeContractV1Request, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, /** * * @summary Executes a transaction on a Iroha ledger * @param {RunTransactionRequestV1} [runTransactionRequestV1] * @param {*} [options] Override http request option. * @throws {RequiredError} */ runTransactionV1: async (runTransactionRequestV1?: RunTransactionRequestV1, options: any = {}): Promise<RequestArgs> => { const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-ledger-connector-iroha/run-transaction`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; const localVarHeaderParameter = {} as any; const localVarQueryParameter = {} as any; localVarHeaderParameter['Content-Type'] = 'application/json'; setSearchParams(localVarUrlObj, localVarQueryParameter, options.query); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = serializeDataIfNeeded(runTransactionRequestV1, localVarRequestOptions, configuration) return { url: toPathString(localVarUrlObj), options: localVarRequestOptions, }; }, } }; /** * DefaultApi - functional programming interface * @export */ export const DefaultApiFp = function(configuration?: Configuration) { const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration) return { /** * * @summary Get the Prometheus Metrics * @param {*} [options] Override http request option. * @throws {RequiredError} */ async getPrometheusMetricsV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPrometheusMetricsV1(options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Invokes a contract on a Iroha ledger * @param {InvokeContractV1Request} [invokeContractV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async invokeContractV1(invokeContractV1Request?: InvokeContractV1Request, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> { const localVarAxiosArgs = await localVarAxiosParamCreator.invokeContractV1(invokeContractV1Request, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** * * @summary Executes a transaction on a Iroha ledger * @param {RunTransactionRequestV1} [runTransactionRequestV1] * @param {*} [options] Override http request option. * @throws {RequiredError} */ async runTransactionV1(runTransactionRequestV1?: RunTransactionRequestV1, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<RunTransactionResponse>> { const localVarAxiosArgs = await localVarAxiosParamCreator.runTransactionV1(runTransactionRequestV1, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, } }; /** * DefaultApi - factory interface * @export */ export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { const localVarFp = DefaultApiFp(configuration) return { /** * * @summary Get the Prometheus Metrics * @param {*} [options] Override http request option. * @throws {RequiredError} */ getPrometheusMetricsV1(options?: any): AxiosPromise<string> { return localVarFp.getPrometheusMetricsV1(options).then((request) => request(axios, basePath)); }, /** * * @summary Invokes a contract on a Iroha ledger * @param {InvokeContractV1Request} [invokeContractV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} */ invokeContractV1(invokeContractV1Request?: InvokeContractV1Request, options?: any): AxiosPromise<void> { return localVarFp.invokeContractV1(invokeContractV1Request, options).then((request) => request(axios, basePath)); }, /** * * @summary Executes a transaction on a Iroha ledger * @param {RunTransactionRequestV1} [runTransactionRequestV1] * @param {*} [options] Override http request option. * @throws {RequiredError} */ runTransactionV1(runTransactionRequestV1?: RunTransactionRequestV1, options?: any): AxiosPromise<RunTransactionResponse> { return localVarFp.runTransactionV1(runTransactionRequestV1, options).then((request) => request(axios, basePath)); }, }; }; /** * DefaultApi - object-oriented interface * @export * @class DefaultApi * @extends {BaseAPI} */ export class DefaultApi extends BaseAPI { /** * * @summary Get the Prometheus Metrics * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public getPrometheusMetricsV1(options?: any) { return DefaultApiFp(this.configuration).getPrometheusMetricsV1(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Invokes a contract on a Iroha ledger * @param {InvokeContractV1Request} [invokeContractV1Request] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public invokeContractV1(invokeContractV1Request?: InvokeContractV1Request, options?: any) { return DefaultApiFp(this.configuration).invokeContractV1(invokeContractV1Request, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Executes a transaction on a Iroha ledger * @param {RunTransactionRequestV1} [runTransactionRequestV1] * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof DefaultApi */ public runTransactionV1(runTransactionRequestV1?: RunTransactionRequestV1, options?: any) { return DefaultApiFp(this.configuration).runTransactionV1(runTransactionRequestV1, options).then((request) => request(this.axios, this.basePath)); } }
the_stack
import { ComposeHelper, compose_file } from './composer'; import { debug_print, each_exec, fromLineCharToOffset, get_extra_indent, hash, insert_segments, MappedKeys, MappedPosition, MappedRange, Mappings, Position, Range, range_for, reduce_segments, tab_aware_index, underline } from './helpers'; import { GeneratedLine, GeneratedSourceText, Line, parse, ParsedSource, SourceText } from './parser'; /** * * SourceMapping Tests * * - Original range (expected) never changes * - Generated range (actual) "always" changes * * Tested ranges cannot be stored as simple positions, * else they wouldn't map correctly on generated range change * * TestedRange format [number, number, string] * * [0] : index of the tested range in original * [1] : length in original * [2] : generated text for the range * * To find Tested Ranges between changes, * * 1) Reverse lookup the generated position for [0] * 2) Find the closest occurence of [2] * */ type RawTestRange = [ogStart: number, ogLength: number, genText: string]; type SourceMappingTest = { actual: Range; expected: Range; range: MappedRange }; // inject/retrieve info from raw file namespace raw { // test.edit.jsx const EDIT_FILE_START = `/** Surround [[[text]]] with brackets & run tests to add it to this sample's tested ranges */\n`; const EDIT_FILE_END = `\n/** content-hash: $ */`.split('$'); // Hash of own content (used to check if ranges were edited) // test.jsx const TEST_FILE_START = '/** tested-ranges: $ */'.split('$'); // RawTestRange[] (what tests are evaluated from) const TEST_FILE_END = '\n/** origin-hash: $ */'.split('$'); // Hash of input.svelte /** * Return raw ranges and the hash from a test.jsx input string. */ export function fromTestFile(file: string) { if (!file.startsWith(TEST_FILE_START[0]) || !file.includes(TEST_FILE_END[0])) throw new Error('Invalid test file'); const length = TEST_FILE_START[0].length; const ranges = JSON.parse(file.slice(length, file.indexOf(TEST_FILE_START[1], length))); const hash = file.slice( file.lastIndexOf(TEST_FILE_END[0]) + TEST_FILE_END[0].length, -TEST_FILE_END[1].length ); return { ranges: ranges as RawTestRange[], hash }; } /** * Returns a string for a test.jsx file */ export function toTestFile(origin: string, content: string, ranges: RawTestRange[]) { const raw = JSON.stringify(ranges); if (raw.includes(TEST_FILE_START[1])) throw new Error(`Tested range cannot include "${TEST_FILE_START[1]}"`); let header = TEST_FILE_START[0] + raw + TEST_FILE_START[1]; if (ranges.length && /^\s*{\/\*\*/.test(content)) { const width = content.indexOf('{'); content = content.slice(Math.min(width, header.length)); } return header + content + TEST_FILE_END[0] + hash(origin) + TEST_FILE_END[1]; } export function fromEditFile(file: string) { const start = file.lastIndexOf(EDIT_FILE_START); const end = file.lastIndexOf(EDIT_FILE_END[0]); if (start > 0) throw new Error('Test Edit file invalid start'); if (end === -1) throw new Error('Test Edit file is missing its content-hash'); return { content: file.slice(start === -1 ? 0 : EDIT_FILE_START.length, end), hash: file.slice(end + EDIT_FILE_END[0].length, file.indexOf(EDIT_FILE_END[1], end)) }; } export function toEditFile(content: string) { return EDIT_FILE_START + content + EDIT_FILE_END[0] + hash(content) + EDIT_FILE_END[1]; } } namespace print { /** * Return string for mappings.jsx */ export function mappings({ generated }: ParsedSource): string { return compose_file(function* (composer) { for (const line of generated.lines) { if ( line.index < generated.firstMapped || line.index > generated.lastMapped || line.isExact() ) { yield line; } else { yield composer.rule('', '-'); yield line; yield composer.comment(comment_for(line), { indent: 0 }); yield composer.rule('', '-'); } } }); function* comment_for(line: GeneratedLine) { const text_generated = line.print(); for (const { ogLine, text: text_og_subset, index } of line.subsets()) { const mapping_rel_generated = line.getGeneratedMappingResult(ogLine); const mapping_rel_original = line.getOriginalMappingResult(ogLine); const mapping_unordered = line.getOrderBreaking(ogLine); const text_original = ogLine.print(); const show_gen_mapping = mapping_rel_generated !== text_generated && mapping_rel_generated !== text_og_subset && mapping_rel_generated !== mapping_rel_original; let rest = ''; const others = line.source.for(ogLine).filter((l) => l !== line); if (others.length !== 0) { const lines = others.map((line) => line.index + 1).join(', '); rest = `(rest generated at line${others.length === 1 ? '' : 's'} ${lines})`; } const offset = line.toString().match(/^\t*/)[0].length * 3; // prettier-ignore yield* [ index !== 0 && [``, `` ], index === 0 && !line.hasStartOrigin && [line.getUnmappedStart(), `Originless mappings` ], true && [text_generated, `[generated] line ${line.index + 1}` ], !line.isSingleOrigin && [text_og_subset, `[generated] subset` ], show_gen_mapping && [mapping_rel_generated, `` ], !!mapping_unordered && [mapping_unordered, `Order-breaking mappings` ], mapping_rel_original !== text_original && [mapping_rel_original, `` ], true && [text_original, `[original] line ${ogLine.index + 1} ${rest}` ] ].filter(Boolean).map(([map,comment])=>[" ".repeat(offset)+map,comment]) as [string, string][]; } } } /** * Print string for test.jsx */ export function test(test_ranges: RawTestRange[], source: ParsedSource): string { return raw.toTestFile( source.original.text, compose_file(compose_test, { match_first_column_width: true }), test_ranges ); function* compose_test(composer: ComposeHelper) { const ranges = test_ranges.map((range) => tryEvalTestRange(range, source).range); for (let i = 0; i < ranges.length; i++) { yield composer.rule('', '-'); if (is_same_line(ranges[i].start, ranges[i].end)) { const j = i; // print ranges that map from same gen line to same og line together while (i < ranges.length - 1 && can_merge(ranges[i], ranges[i + 1])) i++; const target = ranges.slice(j, i + 1); const is_single = j === i; for (const key of MappedKeys) { const { line } = target[0].start[key]; if (!line) continue; yield line; yield composer.comment([ reduce_segments( target.map((range) => range_for(key, range)), (range, i) => underline( tab_aware_index(line.toString(), range.start.character), tab_aware_index(line.toString(), range.end.character), (is_single ? '#' : i + 1) + '==' ) ).padEnd(line.length + get_extra_indent(line.toString()) - 3), `[${key}] line ${line.index + 1}${ key === 'generated' && !target[0].start.original.line ? ' => No Mappings !' : '' }` ]); } } else { for (const key of MappedKeys) { const p0 = ranges[i].start[key]; const p1 = ranges[i].end[key]; const lines = source[key].lines.slice(p0.line.index, p1.line.index + 1); yield* lines; const length = p1.line.start - p0.line.start + p1.character; const full_underline = underline(p0.character, length, '#=#').toString(); yield composer.comment( (function* (): Generator<[string, string]> { let off = 0; const r = lines.map<Range>((line: Line) => ({ start: { line, character: 0 }, end: { line, character: line.length - 1 } })); const l = r.length - 1; r[0].start.character = p0.character; r[l].end.character = p1.character; for (let i = 0; i < lines.length; i++) { const line = lines[i]; yield [ ' '.repeat(off) + line.print(), `[${key}] line ${line.index + 1}` ]; yield [full_underline.slice(off, off + line.length), '']; off += line.length; } })(), { indent: 2 } ); } } yield composer.rule('---'); } } function can_merge(r1: MappedRange, r2: MappedRange) { return ( is_same_line(r1.start, r2.end) && r2.start.generated.character > r1.end.generated.character && r2.start.original.character > r1.end.original.character ); } function is_same_line(p1: MappedPosition, p2: MappedPosition) { return p1.generated.line === p2.generated.line && p1.original.line === p2.original.line; } } /** * Print string for test.edit.jsx */ export function test_edit(parsed_tests: SourceMappingTest[], source: ParsedSource) { return raw.toEditFile( insert_segments( source.generated.text, (function* () { for (const test of parsed_tests) { const { start, end } = range_for('generated', test.range); yield { start: fromLineCharToOffset(start), text: '[[[' }; yield { start: fromLineCharToOffset(end) + 1, text: ']]]' }; } })() ) ); } } function tryEvalTestRange( tested_range: RawTestRange, source: ParsedSource ): SourceMappingTest | null { const { generated, original } = source; const [ogStart, ogLength, genText] = tested_range; if (generated.text.includes(genText)) { const index = tryFindGenPosition(generated, genText, ogStart); const range = { start: generated.at(index), end: generated.at(index + genText.length - 1) }; return { range, actual: range_for('original', range), expected: { start: original.toLineChar(ogStart), end: original.toLineChar(ogStart + ogLength - 1) } }; } } function tryFindGenPosition( generated: GeneratedSourceText, generated_subset: string, ogStart: number ) { const matches = generated.from(ogStart); const { generated: cue } = matches.length === 1 ? matches[0] : tryPickMatch(matches); const forward = generated.text.indexOf(generated_subset, fromLineCharToOffset(cue)); const backward = generated.text.lastIndexOf(generated_subset, fromLineCharToOffset(cue)); const target = forward === backward || forward === -1 ? backward : forward; return target; function tryPickMatch(matches: MappedPosition[]) { const exact = matches.filter((match) => match.generated.line.source.text .slice(fromLineCharToOffset(match.generated)) .startsWith(generated_subset) ); if (exact.length === 1) return exact[0]; const l = exact.length; const m = matches.length; const m_of_them = l === m ? 'all of them' : l === 0 ? 'none' : `${l} out of ${m}`; throw new Error( `Could not find TestRange: Generated text includes ` + `${m} characters mapping back to origin's ${toString(matches[0].original)} and ` + `${m_of_them} start with the tested text "${generated_subset}"` + `\n Matching : ${matches.map((match) => toString(match.generated)).join(',\n')}` ); } function toString(pos: Position) { return `[${pos.line.index + 1}:${pos.character + 1}]`; } } export function validate_edit_file(text_with_ranges: string) { for (const raw of parse_edit_ranges(text_with_ranges, false)) { if (raw.start === -1 || raw.end === -1) { const missing_start = raw.start === -1; const end = missing_start ? 'start' : 'end'; const start = missing_start ? 'end' : 'start'; const index = missing_start ? raw.end : raw.start; const { line, character } = new SourceText(text_with_ranges).toLineChar(index); throw new Error( `Line ${line.index + 1} ${start}s a range that has no corresponding ${end}\n\n` + `\t${line.print()}\n` + `\t${' '.repeat(character) + '^^^'}\n` ); } } } export function validate_test_file(test: string) { raw.fromTestFile(test); } export function is_edit_changed(edit_file: string) { try { const { content, hash: prev } = raw.fromEditFile(edit_file); return hash(content) !== prev; } catch { return true; } } export function is_test_from_same_input(test: string, input: string) { return hash(input) === raw.fromTestFile(test).hash; } export function is_test_empty(test: string) { return raw.fromTestFile(test).ranges.length === 0; } export function is_edit_from_same_generated(test_edit: string, generated: string) { return raw.fromEditFile(test_edit).content.replace(/\[\[\[|\]\]\]/g, '') === generated; } export function is_edit_empty(test_edit: string) { return !/\[\[\[[^\]]*\]\]\]/.test(raw.fromEditFile(test_edit).content); } export function process_transformed_text( original_text: string, generated_text: string, mappings: Mappings ) { const source = parse(original_text, generated_text, mappings); return { print_mappings: () => print.mappings(source), generate_test_edit(test_file: string = '') { return print.test_edit(parse_test_file(test_file, source), source); }, generate_test(test_edit_file: string = '') { if (test_edit_file) validate_edit_file(test_edit_file); return print.test(parse_edit_file(test_edit_file, source), source); }, each_test_range( test_file: string, assertStrictEqual: (actual: string, expected: string) => void, invalid_file: () => void, invalid_range: (arr: RawTestRange[]) => void ) { const tested_ranges = parse_test_file(test_file, source, invalid_file, invalid_range); for (const { actual, expected, range } of tested_ranges) { const { start, end } = range_for('generated', range); let gen = ''; if (start.line === end.line) { gen += start.line.print() + '\n'; gen += underline(start.character, end.character); } else { gen += source.generated.print_slice( start.line.start, end.line.start + end.line.length ) + '\n'; gen += underline(start.character, end.line.start + end.character); } const og = source.original.print_slice( Math.min(actual.start.line.start, expected.start.line.start), Math.max(actual.end.line.end + 1, expected.start.line.end + 1) ); assertStrictEqual( gen + '\n' + og + '\n' + underline_offset(actual, expected), gen + '\n' + og + '\n' + underline_offset(expected, actual) ); } } }; function underline_offset(r1: Range, r2: Range) { return underline( r1.start.character + (r1.start.line.start - r2.start.line.start), r1.end.character + (r1.end.line.start - r2.end.line.start), '#==' ); } } function parse_test_file( test_file: string, source: ParsedSource, on_invalid_file?: () => void, on_invalid_range?: (ranges: RawTestRange[]) => void ) { const parsed: SourceMappingTest[] = []; const invalid: RawTestRange[] = []; const test_ranges = (function () { try { return raw.fromTestFile(test_file).ranges; } catch { return on_invalid_file?.(), []; } })(); for (const test_range of test_ranges) { const range = tryEvalTestRange(test_range, source); if (range) parsed.push(range); else invalid.push(test_range); } if (invalid.length) on_invalid_range?.(invalid); return parsed; } function parse_edit_file(edit_file: string, { generated }: ParsedSource) { if (!edit_file) return []; return parse_edit_ranges(edit_file, true).map<RawTestRange>(function (raw) { const range = { start: generated.at(raw.start), end: generated.at(raw.end) }; const original = range_for('original', range); const { start, end } = range_for('generated', range); const text = generated.text.slice( fromLineCharToOffset(start), fromLineCharToOffset(end) + 1 ); if ( !original.start.line || !original.end.line || (original.start.line === original.end.line && original.start.character === original.end.character && !start.line.hasExactMappingFor(start.character)) ) { throw new Error( `Failed to generate mapping test, selected range has no mappings.\n\n` + debug_print(start, end) ); } const ogStart = fromLineCharToOffset(original.start); const ogLength = fromLineCharToOffset(original.end) - ogStart + 1; return [ogStart, ogLength, text]; }); } function parse_edit_ranges(text_with_ranges: string, index_relative: boolean) { const ranges: { start: number; end: number }[] = []; const pending: { start: number; end: number }[] = []; const { content } = raw.fromEditFile(text_with_ranges); let offset = 0; for (const { match, index } of each_exec(content, /\[\[\[|\]\]\]/g)) { if (match === '[[[') { const range = { start: index - offset, end: -1 }; pending.push(range); ranges.push(range); } else { if (pending.length === 0) { const range = { start: -1, end: -1 }; // error for later ranges.push(range); pending.push(range); } pending.pop().end = index - offset - 1; } if (index_relative) offset += 3; } return ranges; }
the_stack
import React from 'react' import _ from 'lodash' import { StoreState, MenuPosition, Role, MenuItem } from 'src/types' import { Store } from 'redux'; import { updateMenuItems } from 'src/store/reducers/menu'; import { getBootConfig, currentLang } from 'src/packages/datav-core/src'; import localeData from 'src/core/library/locale'; export let routers = [] export const initRoutes = (store: Store<StoreState>) => { getBootConfig().sidemenu.forEach((item: MenuItem) => { item.showPosition = MenuPosition.Top item.exact = true if (item.children && item.children.length != 0) { item.children.forEach((child) => { child.exact = true child.component = React.lazy(() => import('src/views/dashboard/DashboardPage')) }) } item.component = React.lazy(() => import('src/views/dashboard/DashboardPage')) if (!item.id) { item.component = null item.redirectTo = null } else { item.redirectTo = item.url } }) const dashboardMenumItems = getBootConfig().sidemenu const fixMenuItems: MenuItem[] = [ { id: 'datav-fix-menu-d', url: '/d/:uid', text: 'Dashboard Page', icon: 'home-alt', subTitle: 'Dashboard Page', showPosition: null, exact:false, component: React.lazy(() => import('src/views/dashboard/DashboardPage')) }, { id: 'datav-fix-menu-plugin', url: '/plugin/:pluginID', text: 'Plugin Info', icon: 'home-alt', component: React.lazy(() => import('src/views/cfg/plugins/PluginPage')), subTitle: 'Plugin Info', showPosition: null, parentID: null, exact:false, }, { id: 'datav-fix-menu-newDataSource', url: '/datasources/new', text: 'New Datasource', icon: 'home-alt', component: React.lazy(() => import('src/views/cfg/datasources/NewDataSourcePage')), subTitle: 'New Datasource', showPosition: null, parentID: null, exact: true }, { id: 'datav-fix-menu-editDataSource', url: '/datasources/edit/:datasourceID', text: 'Edit DataSource', icon: 'home-alt', component: React.lazy(() => import('src/views/cfg/datasources/EditDataSourcePage')), subTitle: 'Edit DataSource', showPosition: null, parentID: null, exact:false }, // these two are core menu items, be careful to modify { id: 'datav-fix-menu-new', url: '/new', text: localeData[currentLang]['common.new'], subTitle: localeData[currentLang]['common.addSubTitle'], icon: 'plus', showPosition: MenuPosition.Bottom, redirectTo: null, needRole: Role.Editor, exact: true, children: [ { icon: 'apps', id: 'datav-fix-menu-create-dashboard', url: '/new/dashboard', text: localeData[currentLang]['common.dashboard'], exact: true, component: React.lazy(() => import('src/views/dashboard/DashboardPage')) }, { icon: 'apps', id: 'datav-fix-menu-create-datasource', url: '/datasources/new', text: localeData[currentLang]['common.datasource'], exact: true, component: React.lazy(() => import('src/views/cfg/datasources/NewDataSourcePage')), }, { icon: 'import', id: 'datav-fix-menu-import-dashboard', url: '/new/import', text: localeData[currentLang]['common.import'], exact: true, component: React.lazy(() => import('src/views/dashboard/ImportPage')) }, { icon: 'folder', id: 'datav-fix-menu-new-folder', text: localeData[currentLang]['common.folder'], url: '/new/folder', needRole: Role.Editor, exact: true, component: React.lazy(() => import('src/views/search/components/DashboardListPage')) }, { icon: 'users-alt', id: 'datav-fix-menu-new-team', text: localeData[currentLang]['common.team'], url: '/new/team', needRole: Role.Admin, exact: true, component: React.lazy(() => import('src/views/cfg/teams/TeamsPage')) }, ], }, { id: 'datav-fix-menu-alerting', url: '/alerting', text: localeData[currentLang]['common.alerting'], icon: 'bell', subTitle: localeData[currentLang]['common.alertingSubTitle'], showPosition: MenuPosition.Bottom, redirectTo: '/alerting/rules', exact: true, children: [ { icon: "list-ul", id: "datav-fix-menu-alerting-rules", text: localeData[currentLang]['common.rules'], url: "/alerting/rules", exact: true, component: React.lazy(() => import('src/views/alerting/AlertRulesPage')) }, { icon: "history", id: "datav-fix-menu-alerting-history", text: localeData[currentLang]['common.history'], url: "/alerting/history", exact: true, component: React.lazy(() => import('src/views/alerting/AlertHistoryPage')) }, ] }, { id: 'datav-fix-menu-cfg', url: '/cfg', text: localeData[currentLang]['common.configuration'], icon: 'cog', subTitle: localeData[currentLang]['common.cfgSubTitle'], showPosition: MenuPosition.Bottom, redirectTo: null, exact: true, children: [ { icon: "database", id: "datav-fix-menu-datasources", text: localeData[currentLang]['common.datasource'], url: "/cfg/datasources", needRole: Role.Admin, exact: true, component: React.lazy(() => import('src/views/cfg/datasources/DataSourceListPage')) }, { icon: "plug", id: "datav-fix-menu-plugins", text: localeData[currentLang]['common.plugin'], url: "/cfg/plugins", exact: true, component: React.lazy(() => import('src/views/cfg/plugins/Plugins')) }, { icon: "folder", id: "datav-fix-menu-folders", text: localeData[currentLang]['common.folder'], url: "/cfg/folders", needRole: Role.Editor, exact: true, component: React.lazy(() => import('src/views/search/components/DashboardListPage')) }, { icon: "users-alt", id: "datav-fix-menu-users", text: localeData[currentLang]['common.user'], url: "/cfg/users", exact: true, component: React.lazy(() => import('src/views/cfg/users/UserPage')) }, { icon: "users-alt", id: "datav-fix-menu-teams", text: localeData[currentLang]['common.team'], url: "/cfg/teams", exact: true, component: React.lazy(() => import('src/views/cfg/teams/TeamsPage')) }, { icon: "calculator-alt", id: "datav-fix-menu-globalVariable", text: localeData[currentLang]['common.globalVariable'], url: "/cfg/globalVariable", redirectTo: '/d/-1', exact: true, component: React.lazy(() => import('src/views/cfg/globalVariable/GlobalVariablePage')) }, ] }, { id: 'datav-fix-menu-team-manage', url: null, text: localeData[currentLang]['common.teamManage'], icon: 'users-alt', subTitle: localeData[currentLang]['team.subTitle'], showPosition: null, redirectTo: null, exact: true, children: [ { icon: "users-alt", id: "datav-fix-menu-team-members", text: localeData[currentLang]['common.member'], url: "/team/members/:id", exact: false, component: React.lazy(() => import('src/views/cfg/teams/team/MemberPage')) }, { icon: "list-ul", id: "datav-fix-menu-team-sidemenu", text: localeData[currentLang]['team.sidemenu'], url: "/team/sidemenu/:id", exact: false, component: React.lazy(() => import('src/views/cfg/teams/team/SideMenuPage')) }, { icon: "list-ul", id: "datav-fix-menu-alerting-rules", text: localeData[currentLang]['common.rules'], url: "/team/rules/:id", exact: true, component: React.lazy(() => import('src/views/cfg/teams/team/AlertRulesPage')) }, { icon: "history", id: "datav-fix-menu-alerting-history", text: localeData[currentLang]['common.history'], url: "/team/history/:id", exact: true, component: React.lazy(() => import('src/views/cfg/teams/team/AlertHistoryPage')) }, { icon: "at", id: "datav-fix-menu-alerting-notifications", text: localeData[currentLang]['common.notificationChannel'], url: "/team/notifications/:id", exact: true, component: React.lazy(() => import('src/views/cfg/teams/team/NotificationPage')) }, { icon: "cog", id: "datav-fix-menu-team-setting", text: localeData[currentLang]['common.setting'], url: "/team/setting/:id", exact: false, component: React.lazy(() => import('src/views/cfg/teams/team/SettingPage')) }, ] }, { id: 'datav-fix-menu-manage-folder', url: null, text: 'Folder', icon: 'folder-open', subTitle: localeData[currentLang]['folder.subTitle'], showPosition: null, redirectTo: null, exact: true, children: [ { icon: "th-large", id: "datav-fix-menu-folder-dashboard", text: "Dashboards", url: "/f/:uid/dashboards", exact: false, component: React.lazy(() => import('src/views/search/components/DashboardListPage')) }, { icon: "cog", id: "datav-fix-menu-folder-settings", text: "Settings", url: "/f/:uid/settings", exact: false, component: React.lazy(() => import('src/views/cfg/folders/SettingPage')) }, ] }, { id: 'datav-fix-menu-user', url: '/user', text: localeData[currentLang]['user.currentUser'] + " - " + (store.getState().user.name == '' ? store.getState().user.username : store.getState().user.username + ' / ' + store.getState().user.name), subTitle: localeData[currentLang]['user.subTitle'], icon: 'user', showPosition: MenuPosition.Bottom, redirectTo: '/user/preferences', exact: true, children: [ { icon: "sliders-v-alt", id: "datav-fix-menu-preferences", text: localeData[currentLang]['common.preferences'], url: "/user/preferences", exact: true, component: React.lazy(() => import('src/views/cfg/users/UserPreferencePage')) } ] }, { id: 'datav-fix-menu-help', url: '/help', text: localeData[currentLang]['common.help'], icon: 'question-circle', redirectTo: null, exact: true, showPosition: MenuPosition.Bottom, } ] const menuItems = _.concat(dashboardMenumItems, fixMenuItems) store.dispatch(updateMenuItems(menuItems)) const dashRouters = [] dashboardMenumItems.map((menuItem: any) => { dashRouters.push(menuItem) if (!_.isEmpty(menuItem.children)) { menuItem.children.map(r => { r.url = menuItem.url + r.url r.parentID = menuItem.id // concat route.path and its child's path dashRouters.push(r) }) } }) const fixRouters = [] fixMenuItems.map((menuItem: any) => { if (!_.isEmpty(menuItem.children)) { menuItem.children.map(r => { r.parentID = menuItem.id // concat route.path and its child's path fixRouters.push(r) }) } else { fixRouters.push(menuItem) } }) routers = _.concat(dashRouters,fixRouters) } // urls are reserved in datav, cant be used by users export const reservedUrls = ['/d','/plugin','/datasources','/new','/cfg','/team','/f','/user','/help','/t']
the_stack
import React, { useState, PropsWithChildren } from 'react' import Link from 'next/link' import Button from '../components/Button' import Hero from '../components/Hero' import * as Feature from '../components/Feature' import Footer from '../components/Footer' import Navigation from '../components/Navigation' import Section from '../components/Section' import Tier from '../components/Tier' import Testimonial from '../components/Testimonial' import { NOTION_DOCS_URL, NOTION_SUPPORT_URL } from '../constants' import { scrollToId } from '../lib/scroll' /* Pricing event */ export default function Home() { return ( <> <title>GitHub LabelSync - The best way to sync labels</title> <Title></Title> <Introduction></Introduction> <Features></Features> <DetailedFeatures></DetailedFeatures> <Testimonials></Testimonials> <Pricing></Pricing> <FAQ></FAQ> <Footer></Footer> </> ) } /* Sections */ function Title() { return ( <div className="relative bg-gray-80 overflow-hidden"> <div className="relative pt-6 pb-12 sm:pb-16 md:pb-20 lg:pb-28 xl:pb-32"> <Navigation links={[ { label: 'Documentation', href: NOTION_DOCS_URL, }, { label: 'Install', href: 'https://github.com/apps/labelsync-manager', }, { label: 'Pricing', href: '#', onClick: () => scrollToId('pricing'), }, { label: 'Features', href: '#', onClick: () => scrollToId('features'), }, { label: 'Support', href: NOTION_SUPPORT_URL, }, ]} ></Navigation> {/* Hero */} <Hero></Hero> </div> </div> ) } function Introduction() { return ( <div className="py-10 bg-gray-30 overflow-hidden md:py-14 lg:py-24"> <Testimonial heading="Welcome to LabelSync!" name="Matic Zavadlal" role="Creator of LabelSync" image="/img/testimonial/matic.jpg" content={ <p> &ldquo;While working at Prisma, I discovered that many companies struggle with repository organisation. In particular, companies struggle with managing labels across multiple repositories in their GitHub accounts. That's why I created LabelSync - to help you get to the best parts of labels more quickly. &rdquo; </p> } ></Testimonial> </div> ) } function Features() { return ( <Section id="features" name="features" className="bg-white overflow-hidden"> <div className="container"> <div className="relative max-w-screen-xl mx-auto py-12 px-4 sm:px-6 lg:px-8"> {/* <!-- Side art --> */} <svg className="absolute top-0 left-full transform -translate-x-1/2 -translate-y-3/4 lg:left-auto lg:right-full lg:translate-x-2/3 lg:translate-y-1/4" width="404" height="784" fill="none" viewBox="0 0 404 784" > <defs> <pattern id="8b1b5f72-e944-4457-af67-0c6d15a99f38" x="0" y="0" width="20" height="20" patternUnits="userSpaceOnUse" > <rect x="0" y="0" width="4" height="4" className="text-gray-200" fill="currentColor" /> </pattern> </defs> <rect width="404" height="784" fill="url(#8b1b5f72-e944-4457-af67-0c6d15a99f38)" /> </svg> {/* <!-- Features --> */} <div className="relative lg:grid lg:grid-cols-3 lg:col-gap-8"> <div className="lg:col-span-1"> <h3 className="text-3xl leading-9 font-extrabold tracking-tight text-gray-900 sm:text-4xl sm:leading-10"> <span className="mr-3">🚀</span> <span className="underline-green">It's game changing.</span> </h3> </div> <div className="mt-10 sm:grid sm:grid-cols-2 sm:col-gap-8 sm:row-gap-10 lg:col-span-2 lg:mt-0"> {/* <!-- Features --> */} <div> <div className="flex items-center justify-center h-12 w-12 rounded-md bg-green-500 text-white"> <svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" /> </svg> </div> <div className="mt-5"> <h5 className="text-lg leading-6 font-medium text-gray-900"> Centralised management </h5> <p className="mt-2 text-base leading-6 text-gray-500"> Sync all your repositories from a central management repository using one of the configuration languages. </p> </div> </div> <div className="mt-10 sm:mt-0"> <div className="flex items-center justify-center h-12 w-12 rounded-md bg-green-500 text-white"> <svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" /> </svg> </div> <div className="mt-5"> <h5 className="text-lg leading-6 font-medium text-gray-900"> Flexible configuration </h5> <p className="mt-2 text-base leading-6 text-gray-500"> Restrict unconfigured labels, or create a set of common ones to share between repositories. </p> </div> </div> <div className="mt-10 sm:mt-0"> <div className="flex items-center justify-center h-12 w-12 rounded-md bg-green-500 text-white"> <svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" /> </svg> </div> <div className="mt-5"> <h5 className="text-lg leading-6 font-medium text-gray-900"> Label Aliases </h5> <p className="mt-2 text-base leading-6 text-gray-500"> Align label configurations quickly by <a href="https://github.com/maticzav/label-sync#yaml" className="font-bold mx-1" > aliasing </a> a group of old labels to a new, single label. </p> </div> </div> <div className="mt-10 sm:mt-0"> <div className="flex items-center justify-center h-12 w-12 rounded-md bg-green-500 text-white"> <svg fill="none" className="h-6 w-6" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" > <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"></path> </svg> </div> <div className="mt-5"> <h5 className="text-lg leading-6 font-medium text-gray-900"> Automate your workflow </h5> <p className="mt-2 text-base leading-6 text-gray-500"> Create Label workflows using label <a href="https://github.com/maticzav/label-sync#yaml" className="font-bold ml-1" > siblings </a> . </p> </div> </div> </div> </div> </div> </div> </Section> ) } function DetailedFeatures() { return ( <Section id="detailed-features" name="detailed fetaures" className="relative bg-gray-50 overflow-hidden" > {/* <!-- Leading text --> */} <div className="text-center"> <h2 className="inline-block mt-20 text-4xl tracking-tight leading-10 font-extrabold text-gray-900 sm:leading-none sm:text-6xl lg:text-5xl xl:text-6xl underline-green"> Features </h2> </div> {/* <!-- Features --> */} <div className="relative container mx-auto pt-6 md:px-10 pb-20 md:pb-20 lg:pb-24 xl:pb-32"> {/* <!-- GH Issues --> */} <Feature.Left caption="Automate in Github" title={['bring your', 'workflows to life']} icon={<span className="mr-2">🌈</span>} description={ <> Keep your workflow in GitHub so everyone can see what the priorities are and how far down the chain bug has come. </> } alt="Issues Overview" image="/img/examples/issues.png" ></Feature.Left> {/* PR message */} <Feature.Right caption="Immediate feedback" title={['get feedback', 'instantly']} description={ <> LabelSync manager comments on your pull request so you can predict what changes are going to happen. </> } alt="PullRequest message" image="/img/examples/pr-comment.png" icon={<span className="mr-2">🤖</span>} ></Feature.Right> {/* Yaml */} <Feature.Left caption="Language of flexibility" title={['use the power of', 'yaml for configuration.']} icon={ <span className="inline-block mr-2"> <svg className="w-10 h-10" viewBox="0 0 512 512"> <path d="M235.793457,20.9389935l-91.8156738,137.6740112v87.2750244H87.7020035v-87.2751465L0,20.9389935h63.2502899l55.7678528,88.6458817l56.2244568-88.6458817H235.793457z M330.2944641,195.8635406H228.4328003l-20.7168121,50.0244904h-45.1060944l95.3815918-224.9490356h46.1360474l91.5108948,224.9490356h-48.1963501L330.2944641,195.8635406z M313.3734131,151.1300201l-31.2258606-82.5503616l-34.8368378,82.5503616H313.3734131z M87.7023544,270.5895996v220.471405h47.3023605V338.9823914l49.5055237,102.2188416h37.2337494l51.1964111-105.8118896v155.6254272h45.3786011V270.5895996h-61.959259l-54.977951,99.7063904l-52.3599548-99.7063904H87.7023544z M512,443.201355H395.6384277V270.5895996h-48.1963501v219.5221863L512,490.111969V443.201355z" /> </svg> </span> } description={ <> LabelSync uses YAML as a default configuration language. This allows you to use features such as anchors to organise your configuration more efficiently. </> } image="/img/examples/yaml.png" alt="YAML configuration" ></Feature.Left> {/* TypeScript */} <Feature.Right caption="Prefer TypeScript?" title={['Use TypeScript to', 'configure anything.']} icon={ <span className="mr-3"> <svg className="h-10 w-10 inline-block" viewBox="0 0 128 128"> <path d="M1.5,63.91v62.5h125V1.41H1.5Zm100.73-5a15.56,15.56,0,0,1,7.82,4.5,20.58,20.58,0,0,1,3,4c0,.16-5.4,3.81-8.69,5.85-.12.08-.6-.44-1.13-1.23a7.09,7.09,0,0,0-5.87-3.53c-3.79-.26-6.23,1.73-6.21,5a4.58,4.58,0,0,0,.54,2.34c.83,1.73,2.38,2.76,7.24,4.86,8.95,3.85,12.78,6.39,15.16,10,2.66,4,3.25,10.46,1.45,15.24-2,5.2-6.9,8.73-13.83,9.9a38.32,38.32,0,0,1-9.52-.1,23,23,0,0,1-12.72-6.63c-1.15-1.27-3.39-4.58-3.25-4.82a9.34,9.34,0,0,1,1.15-.73L82,101l3.59-2.08.75,1.11a16.78,16.78,0,0,0,4.74,4.54c4,2.1,9.46,1.81,12.16-.62a5.43,5.43,0,0,0,.69-6.92c-1-1.39-3-2.56-8.59-5-6.45-2.78-9.23-4.5-11.77-7.24a16.48,16.48,0,0,1-3.43-6.25,25,25,0,0,1-.22-8c1.33-6.23,6-10.58,12.82-11.87A31.66,31.66,0,0,1,102.23,58.93ZM72.89,64.15l0,5.12H56.66V115.5H45.15V69.26H28.88v-5A49.19,49.19,0,0,1,29,59.09C29.08,59,39,59,51,59L72.83,59Z"></path> </svg> </span> } description={ <> LabelSync ships with a TypeScript library that lets you use everything that TypeScript offers to automate you configuration. </> } image="/img/examples/typescript.png" alt="Issues overview" ></Feature.Right> {/* Siblings */} <Feature.Left caption="Efficient workflow" title={['connect labels with', "LabelSync's siblings."]} icon={<span className="inline-block mr-2">👨‍👩‍👦</span>} description={ <> Each label in your configuration can reference <span className="underline-green ml-1">mutliple siblings</span>. Whenever you add a label to an issue or pull request, LabelSync will automatically add all the missing siblings as well. </> } image="/img/examples/siblings.png" alt="Siblings example" ></Feature.Left> {/* */} <div className="text-center"> <h2 className="inline-block mt-20 text-4xl tracking-tight leading-10 font-bold text-gray-900 sm:leading-none sm:text-4xl lg:text-3xl xl:text-4xl"> and more... </h2> </div> {/* <!-- --> */} </div> </Section> ) } function Testimonials() { return ( <Section id="prisma-testimonial" name="prisma testimonial" className="py-15 bg-gray-30 overflow-hidden md:py-20 lg:py-24" > <Testimonial heading="What our users say about us?" content={ <> <p className="mb-3"> &ldquo;Label-Sync enables us to have much a more efficient project management process where everything relies on a consistent set of labels. Triage, Prioritization, Estimation, everything can be done with labels now. &rdquo; </p> </> } role="Engineering Manager, Prisma" name="Jan Piotrowski" image="/img/testimonial/jan.png" logo={{ image: '/img/logos/prisma.svg', name: 'Prisma', url: 'https://prisma.io', }} pattern ></Testimonial> </Section> ) } const prices = { ANNUALLY: 8, MONTHLY: 10, } function Pricing() { const [period, setPeriod] = useState<'ANNUALLY' | 'MONTHLY'>('ANNUALLY') function toggle() { switch (period) { case 'MONTHLY': { setPeriod('ANNUALLY') break } case 'ANNUALLY': { setPeriod('MONTHLY') break } } } return ( <Section id="pricing" name="pricing" className="bg-green-500"> <div className="pt-12 container text-center px-10 sm:px-6 sm:pt-16 lg:pt-24"> <h2 className="text-lg leading-6 font-semibold text-gray-300 uppercase tracking-wider"> Pricing </h2> <p className="mt-2 text-3xl leading-9 font-extrabold text-white sm:text-4xl sm:leading-10 lg:text-5xl lg:leading-none"> Ready to get started? </p> <p className="mt-4 md:mt-6 text-xl mx-auto md:max-w-2xl leading-7 text-gray-200"> We are also giving you an option for 14-day free trial to find out how the tool works and a free tier to see how great it is. </p> </div> {/* Launch discount */} {/* <div className="mt-8 text-center sm:mt-8 lg:mt-12"> <p className="text-2xl leading-9 font-bold text-white sm:text-3xl sm:leading-none italic"> 20% Launch Dicount </p> </div> */} {/* Period changer */} <div className="block mx-auto flex justify-center mt-8 lg:mt-12"> <span className="mr-3 text-gray-200 font-semibold align-baseline"> Pay monthly </span> {/* Simple toggle On: "bg-green-500", Off: "bg-gray-200" */} <span onClick={toggle} className={ 'relative inline-block flex-shrink-0 h-6 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:shadow-outline ' + (period === 'ANNUALLY' ? 'bg-green-400' : 'bg-gray-200') } > {/* On: "translate-x-5", Off: "translate-x-0" */} <span className={ 'inline-block h-5 w-5 rounded-full bg-white shadow transform transition ease-in-out duration-200 ' + (period === 'ANNUALLY' ? 'translate-x-5' : 'translate-x-0') } ></span> </span> <span className="align-baseline font-semibold ml-3 text-gray-200"> Pay annualy </span> </div> {/* <!-- Tiers --> */} <div className="mt-8 pb-12 bg-white sm:mt-12 sm:pb-16 lg:mt-12 lg:pb-24"> {/* Container */} <div className="relative"> {/* Background */} <div className="absolute inset-0 h-3/4 lg:h-1/2 bg-green-500"></div> {/* Tiers container */} <div className="relative z-10 container mx-auto px-4 sm:px-6 lg:px-8"> <div className="max-w-md mx-auto lg:max-w-5xl lg:grid lg:grid-cols-2 lg:gap-5"> {/* <!-- Free tier --> */} <div> <Tier name="Free" description="Great for starting out with LabelSync." price={<>$0</>} features={[ { name: 'LabelSync Manager' }, { name: 'Configuration Libraries' }, { name: 'Limited to 5 repositories' }, ]} link={ <Link href={{ pathname: '/subscribe', query: { plan: 'FREE' }, }} > <a> <Button>Install LabelSync</Button> </a> </Link> } ></Tier> </div> {/* <!-- Paid Tier --> */} <div className="mt-10 lg:mt-0"> <Tier name="The Complete solution" description="Best for teams and users with rapid workflows." price={ <> {/* Yearly pricing */} {period === 'ANNUALLY' && ( <> ${prices.ANNUALLY} {/* $12 <span className="ml-1 text-2xl leading-8 font-medium text-gray-500 line-through"> $16 </span> */} </> )} {/* Monthly pricing */} {period === 'MONTHLY' && ( <> ${prices.MONTHLY} {/* $16 <span className="ml-1 text-2xl leading-8 font-medium text-gray-500 line-through"> $20 </span> */} </> )} <span className="ml-1 text-2xl leading-8 font-medium text-gray-500"> /mo </span> </> } features={[ { name: 'LabelSync Manager' }, { name: 'Configuration Libraries' }, { name: 'Siblings and Aliasing' }, { name: 'Unlimited repositories' }, { name: 'Wildcard repository configuration' }, ]} link={ <Link href={{ pathname: '/subscribe', query: { plan: 'PAID', period }, }} > <a> <Button>Sync my labels</Button> </a> </Link> } ></Tier> </div> {/* End of tiers */} </div> </div> {/* <!-- End of tiers container --> */} </div> </div> {/* End of tier container */} </Section> ) } function FAQ() { return ( <div className="bg-white"> <div className="container mx-auto pt-12 pb-16 sm:pt-16 sm:pb-20 px-4 sm:px-6 lg:pt-20 lg:pb-28 lg:px-8"> <h2 className="text-3xl leading-9 font-extrabold text-gray-900"> Frequently asked questions </h2> <div className="mt-6 border-t-2 border-gray-100 pt-10"> <dl className="md:grid md:grid-cols-2 md:gap-8"> {/* <!-- LEFT Questions --> */} <div> <div> <dt className="text-lg leading-6 font-medium text-gray-900"> I have a problem but don't know who to ask. </dt> <dd className="mt-2"> <p className="text-base leading-6 text-gray-500"> Please send us an <a className="mx-1" href="mailto:support@label-sync.com"> email </a> to our support team. We'll try to get back to you as soon as possible. </p> </dd> </div> </div> {/* <!-- RIGHT questions --> */} <div className="mt-12 md:mt-0"> <div> <dt className="text-lg leading-6 font-medium text-gray-900"> I have an idea/problem that LabelSync could solve. </dt> <dd className="mt-2"> <p className="text-base leading-6 text-gray-500"> Please reach out to <a href="mailto:matic@label-sync.com" className=" ml-1"> matic@label-sync.com </a> . I'd be more than happy to chat about LabelSync with you! </p> </dd> </div> </div> </dl> </div> </div> </div> ) }
the_stack
import fs from "fs"; import ts, { factory } from "typescript"; ts.parseIsolatedEntityName; type KeywordTypeName = | "any" | "number" | "object" | "string" | "boolean" | "undefined" | "null"; export const questionToken = factory.createToken(ts.SyntaxKind.QuestionToken); export function createQuestionToken(token?: boolean | ts.QuestionToken) { if (!token) return undefined; if (token === true) return questionToken; return token; } export function createKeywordType(type: KeywordTypeName) { switch (type) { case "any": return factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); case "number": return factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword); case "object": return factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword); case "string": return factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword); case "boolean": return factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword); case "undefined": return factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword); case "null": return factory.createLiteralTypeNode( ts.factory.createToken(ts.SyntaxKind.NullKeyword) ); } } export const keywordType: { [type: string]: ts.KeywordTypeNode | ts.LiteralTypeNode; } = { any: factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword), number: factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword), object: factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword), string: factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), boolean: factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword), undefined: factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword), null: factory.createLiteralTypeNode( ts.factory.createToken(ts.SyntaxKind.NullKeyword) ), }; export const modifier = { async: factory.createModifier(ts.SyntaxKind.AsyncKeyword), export: factory.createModifier(ts.SyntaxKind.ExportKeyword), }; export function createTypeAliasDeclaration({ decorators, modifiers, name, typeParameters, type, }: { decorators?: Array<ts.Decorator>; modifiers?: Array<ts.Modifier>; name: string | ts.Identifier; typeParameters?: Array<ts.TypeParameterDeclaration>; type: ts.TypeNode; }) { return factory.createTypeAliasDeclaration( decorators, modifiers, name, typeParameters, type ); } export function toExpression(ex: ts.Expression | string) { if (typeof ex === "string") return factory.createIdentifier(ex); return ex; } export function createCall( expression: ts.Expression | string, { typeArgs, args, }: { typeArgs?: Array<ts.TypeNode>; args?: Array<ts.Expression>; } = {} ) { return factory.createCallExpression(toExpression(expression), typeArgs, args); } export function createMethodCall( method: string, opts: { typeArgs?: Array<ts.TypeNode>; args?: Array<ts.Expression>; } ) { return createCall( factory.createPropertyAccessExpression(factory.createThis(), method), opts ); } export function createObjectLiteral(props: [string, string | ts.Expression][]) { return factory.createObjectLiteralExpression( props.map(([name, identifier]) => createPropertyAssignment(name, toExpression(identifier)) ), true ); } export function createPropertyAssignment( name: string, expression: ts.Expression ) { if (ts.isIdentifier(expression)) { if (expression.text === name) { return factory.createShorthandPropertyAssignment(name); } } return factory.createPropertyAssignment(propertyName(name), expression); } export function block(...statements: ts.Statement[]) { return factory.createBlock(statements, true); } export function createArrowFunction( parameters: ts.ParameterDeclaration[], body: ts.ConciseBody, { modifiers, typeParameters, type, equalsGreaterThanToken, }: { modifiers?: ts.Modifier[]; typeParameters?: ts.TypeParameterDeclaration[]; type?: ts.TypeNode; equalsGreaterThanToken?: ts.EqualsGreaterThanToken; } = {} ) { return factory.createArrowFunction( modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body ); } export function createFunctionDeclaration( name: string | ts.Identifier | undefined, { decorators, modifiers, asteriskToken, typeParameters, type, }: { decorators?: ts.Decorator[]; modifiers?: ts.Modifier[]; asteriskToken?: ts.AsteriskToken; typeParameters?: ts.TypeParameterDeclaration[]; type?: ts.TypeNode; }, parameters: ts.ParameterDeclaration[], body?: ts.Block ): ts.FunctionDeclaration { return factory.createFunctionDeclaration( decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body ); } export function createClassDeclaration({ decorators, modifiers, name, typeParameters, heritageClauses, members, }: { decorators?: Array<ts.Decorator>; modifiers?: Array<ts.Modifier>; name?: string | ts.Identifier; typeParameters?: Array<ts.TypeParameterDeclaration>; heritageClauses?: Array<ts.HeritageClause>; members: Array<ts.ClassElement>; }) { return factory.createClassDeclaration( decorators, modifiers, name, typeParameters, heritageClauses, members ); } export function createConstructor({ decorators, modifiers, parameters, body, }: { decorators?: Array<ts.Decorator>; modifiers?: Array<ts.Modifier>; parameters: Array<ts.ParameterDeclaration>; body?: ts.Block; }) { return factory.createConstructorDeclaration( decorators, modifiers, parameters, body ); } export function createMethod( name: | string | ts.Identifier | ts.StringLiteral | ts.NumericLiteral | ts.ComputedPropertyName, { decorators, modifiers, asteriskToken, questionToken, typeParameters, type, }: { decorators?: ts.Decorator[]; modifiers?: ts.Modifier[]; asteriskToken?: ts.AsteriskToken; questionToken?: ts.QuestionToken | boolean; typeParameters?: ts.TypeParameterDeclaration[]; type?: ts.TypeNode; } = {}, parameters: ts.ParameterDeclaration[] = [], body?: ts.Block ): ts.MethodDeclaration { return factory.createMethodDeclaration( decorators, modifiers, asteriskToken, name, createQuestionToken(questionToken), typeParameters, parameters, type, body ); } export function createParameter( name: string | ts.BindingName, { decorators, modifiers, dotDotDotToken, questionToken, type, initializer, }: { decorators?: Array<ts.Decorator>; modifiers?: Array<ts.Modifier>; dotDotDotToken?: ts.DotDotDotToken; questionToken?: ts.QuestionToken | boolean; type?: ts.TypeNode; initializer?: ts.Expression; } ): ts.ParameterDeclaration { return factory.createParameterDeclaration( decorators, modifiers, dotDotDotToken, name, createQuestionToken(questionToken), type, initializer ); } function propertyName(name: string | ts.PropertyName): ts.PropertyName { if (typeof name === "string") { return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name); } return name; } export function createPropertySignature({ modifiers, name, questionToken, type, }: { modifiers?: Array<ts.Modifier>; name: ts.PropertyName | string; questionToken?: ts.QuestionToken | boolean; type?: ts.TypeNode; }) { return factory.createPropertySignature( modifiers, propertyName(name), createQuestionToken(questionToken), type ); } export function createIndexSignature( type: ts.TypeNode, { decorators, modifiers, indexName = "key", indexType = keywordType.string, }: { indexName?: string; indexType?: ts.TypeNode; decorators?: Array<ts.Decorator>; modifiers?: Array<ts.Modifier>; } = {} ) { return factory.createIndexSignature( decorators, modifiers, [createParameter(indexName, { type: indexType })], type ); } export function createObjectBinding( elements: Array<{ name: string | ts.BindingName; dotDotDotToken?: ts.DotDotDotToken; propertyName?: string | ts.PropertyName; initializer?: ts.Expression; }> ) { return factory.createObjectBindingPattern( elements.map(({ dotDotDotToken, propertyName, name, initializer }) => factory.createBindingElement( dotDotDotToken, propertyName, name, initializer ) ) ); } export function createTemplateString( head: string, spans: Array<{ literal: string; expression: ts.Expression }> ) { if (!spans.length) return factory.createStringLiteral(head); return factory.createTemplateExpression( factory.createTemplateHead(head), spans.map(({ expression, literal }, i) => factory.createTemplateSpan( expression, i === spans.length - 1 ? factory.createTemplateTail(literal) : factory.createTemplateMiddle(literal) ) ) ); } export function findNode<T extends ts.Node>( nodes: ts.NodeArray<ts.Node>, kind: T extends { kind: infer K } ? K : never, test?: (node: T) => boolean | undefined ): T { const node = nodes.find( (s) => s.kind === kind && (!test || test(s as T)) ) as T; if (!node) throw new Error(`Node not found: ${kind}`); return node; } export function getName(name: ts.Node) { if (ts.isIdentifier(name)) { return name.escapedText; } if (ts.isLiteralExpression(name)) { return name.text; } return ""; } export function getFirstDeclarationName(n: ts.VariableStatement) { const name = ts.getNameOfDeclaration(n.declarationList.declarations[0]); return name ? getName(name) : ""; } export function findFirstVariableDeclaration( nodes: ts.NodeArray<ts.Node>, name: string ) { const statement = findNode<ts.VariableStatement>( nodes, ts.SyntaxKind.VariableStatement, (n) => getFirstDeclarationName(n) === name ); const [first] = statement.declarationList.declarations; if (!first) throw new Error("Missing declaration"); return first; } export function changePropertyValue( o: ts.ObjectLiteralExpression, property: string, value: ts.Expression ) { const p = o.properties.find( (p) => ts.isPropertyAssignment(p) && getName(p.name) === property ); if (p && ts.isPropertyAssignment(p)) { // p.initializer is readonly, this might break in a future TS version, but works fine for now. Object.assign(p, { initializer: value }); } else { throw new Error(`No such property: ${property}`); } } export function appendNodes<T extends ts.Node>( array: ts.NodeArray<T>, ...nodes: T[] ) { return factory.createNodeArray([...array, ...nodes]); } export function addComment<T extends ts.Node>(node: T, comment?: string) { if (!comment) return node; return ts.addSyntheticLeadingComment( node, ts.SyntaxKind.MultiLineCommentTrivia, `*\n * ${comment.replace(/\n/g, "\n * ")}\n `, true ); } export function parseFile(file: string) { return ts.createSourceFile( file, fs.readFileSync(file, "utf8"), ts.ScriptTarget.Latest, /*setParentNodes*/ false, ts.ScriptKind.TS ); } const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed, }); export function printNode(node: ts.Node) { const file = ts.createSourceFile( "someFileName.ts", "", ts.ScriptTarget.Latest, /*setParentNodes*/ false, ts.ScriptKind.TS ); return printer.printNode(ts.EmitHint.Unspecified, node, file); } export function printNodes(nodes: ts.Node[]) { const file = ts.createSourceFile( "someFileName.ts", "", ts.ScriptTarget.Latest, /*setParentNodes*/ false, ts.ScriptKind.TS ); return nodes .map((node) => printer.printNode(ts.EmitHint.Unspecified, node, file)) .join("\n"); } export function printFile(sourceFile: ts.SourceFile) { return printer.printFile(sourceFile); } export function isValidIdentifier(str: string) { if (!str.length || str.trim() !== str) return false; const node = ts.parseIsolatedEntityName(str, ts.ScriptTarget.Latest); return ( !!node && node.kind === ts.SyntaxKind.Identifier && node.originalKeywordKind === undefined ); }
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623784563652, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Usage of disk space across all nodes\n\n**Capacity**: Maximum store size across all nodes. This value may be explicitly set per node using [--store](https://www.cockroachlabs.com/docs/v21.1/cockroach-start.html#store). If a store size has not been set, this metric displays the actual disk capacity.\n\n**Available**: Free disk space available to CockroachDB data across all nodes.\n\n**Used**: Disk space in use by CockroachDB data across all nodes. This excludes the Cockroach binary, operating system, and other system files.\n\n[How are these metrics calculated?](https://www.cockroachlabs.com/docs/v21.1/ui-storage-dashboard.html#capacity-metrics)", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sum(capacity{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Max", refId: "B" }, { expr: `sum(sum(capacity_available{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", legendFormat: "Available", refId: "C" }, { expr: `sum(sum(capacity{integration_id="${integrationId}",instance=~"$node"}) by (instance)) - sum(sum(capacity_available{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Used", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Capacity", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:99", format: "bytes", label: "capacity", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:100", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Amount of data that can be read by applications and CockroachDB.\n\n**Live**: Number of logical bytes stored in live [key-value pairs](https://www.cockroachlabs.com/docs/v21.1/architecture/distribution-layer.html#table-data) across all nodes. Live data excludes historical and deleted data.\n\n**System**: Number of physical bytes stored in [system key-value pairs](https://www.cockroachlabs.com/docs/v21.1/architecture/distribution-layer.html#table-data).", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(sum(livebytes{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Live", refId: "A" }, { expr: `sum(sum(sysbytes{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "System", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Live Bytes", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:323", format: "bytes", label: "live bytes", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:324", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 99th %ile latency for commits to the Raft Log. This measures essentially an fdatasync to the storage engine's write-ahead log.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99,rate(raft_process_logcommit_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Log Commit Latency: 99th Percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:474", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:475", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 50th %ile latency for commits to the Raft Log. This measures essentially an fdatasync to the storage engine's write-ahead log.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 6, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.50,rate(raft_process_logcommit_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Log Commit Latency: 50th Percentile", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:550", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:551", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 99th %ile latency for commits of Raft commands. This measures applying a batch to the storage engine (including writes to the write-ahead log), but no fsync.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 30 }, hiddenSeries: false, id: 10, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.99,rate(raft_process_commandcommit_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Command Commit Latency: 99th Percentile ", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:774", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:775", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The 50th %ile latency for commits of Raft commands. This measures applying a batch to the storage engine (including writes to the write-ahead log), but no fsync.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 38 }, hiddenSeries: false, id: 12, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `histogram_quantile(0.50,rate(raft_process_commandcommit_latency_bucket{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Command Commit Latency: 50th percentile ", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:850", format: "ns", label: "latency", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:851", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The average number of real read operations executed per logical read operation.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 46 }, hiddenSeries: false, id: 20, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `avg(avg(rocksdb_read_amplification{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", legendFormat: "Read Amplification", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Read Amplification", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:926", format: "short", label: "factor", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:927", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of SSTables in use.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 54 }, hiddenSeries: false, id: 16, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rocksdb_num_sstables{integration_id="${integrationId}",instance=~"$node"})`, interval: "", legendFormat: "SSTables", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "SSTables", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1002", format: "short", label: "sstables", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1003", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of open file descriptors, compared with the file descriptor limit.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 62 }, hiddenSeries: false, id: 14, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(sum(sys_fd_open{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Open", refId: "A" }, { expr: `sum(sum(sys_fd_softlimit{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Limit", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "File Descriptors", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1226", format: "short", label: "descriptors", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:1227", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of compactions and memtable flushes per second.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 70 }, hiddenSeries: false, id: 18, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(rocksdb_compactions{integration_id="${integrationId}"}[5m]))`, interval: "", legendFormat: "Compactions", refId: "A" }, { expr: `sum(rate(rocksdb_flushes{integration_id="${integrationId}"}[5m]))`, interval: "", legendFormat: "Flushes", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Compactions/Flushes", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1376", format: "short", label: "count", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1377", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of successfully written time series samples, and number of errors attempting to write time series, per second.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 78 }, hiddenSeries: false, id: 24, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(timeseries_write_samples{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Samples Written", refId: "A" }, { exemplar: true, expr: `sum(rate(timeseries_write_errors{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Errors", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Time Series Writes", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1452", format: "short", label: "count", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1453", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: 'The number of bytes written by the time series system per second. \nNote that this does not reflect the rate at which disk space is consumed by time series; the data is highly compressed on disk. This rate is instead intended to indicate the amount of network traffic and disk activity generated by time series writes.\nSee the "databases" tab to find the current disk usage for time series data.', fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 86 }, hiddenSeries: false, id: 22, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(rate(timeseries_write_bytes{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", legendFormat: "Bytes Written", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Time Series Bytes Written", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1528", format: "bytes", label: "bytes", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1529", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } } ], schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: false, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheus-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 1, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "utc", title: "CRDB Console: Storage", uid: `sto-${integrationId}`, version: 6 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import 'mocha' import * as C from '../../../src/constants' import { expect } from 'chai' import RecordHandler from './record-handler' import * as M from './test-messages' import * as testHelper from '../../test/helper/test-helper' import { getTestMocks } from '../../test/helper/test-mocks' describe('record handler handles messages', () => { let testMocks let recordHandler let client let config let services beforeEach(() => { testMocks = getTestMocks() client = testMocks.getSocketWrapper('someUser') const options = testHelper.getDeepstreamOptions() config = options.config services = options.services recordHandler = new RecordHandler( config, services, testMocks.subscriptionRegistry, testMocks.listenerRegistry ) }) afterEach(() => { client.socketWrapperMock.verify() testMocks.subscriptionRegistryMock.verify() }) it('creates a non existing record', () => { client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(M.readResponseMessage) recordHandler.handle(client.socketWrapper, M.subscribeCreateAndReadMessage) expect(services.cache.lastSetKey).to.equal('some-record') expect(services.cache.lastSetVersion).to.equal(0) expect(services.cache.lastSetValue).to.deep.equal({}) expect(services.storage.lastSetKey).to.equal('some-record') expect(services.storage.lastSetVersion).to.equal(0) expect(services.storage.lastSetValue).to.deep.equal({}) }) it('tries to create a non existing record, but receives an error from the cache', () => { services.cache.failNextSet = true client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.RECORD_CREATE_ERROR, originalAction: C.RECORD_ACTION.SUBSCRIBECREATEANDREAD, name: M.subscribeCreateAndReadMessage.names[0] }) recordHandler.handle(client.socketWrapper, M.subscribeCreateAndReadMessage) // expect(options.logger.lastLogMessage).to.equal('storage:storageError') }) it('does not store new record when excluded', () => { config.record.storageExclusionPrefixes = ['some-record'] recordHandler.handle(client.socketWrapper, M.subscribeCreateAndReadMessage) expect(services.storage.lastSetKey).to.equal(null) expect(services.storage.lastSetVersion).to.equal(null) expect(services.storage.lastSetValue).to.equal(null) }) it('returns an existing record', () => { services.cache.set('some-record', M.recordVersion, M.recordData, () => {}) client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.READ_RESPONSE, name: 'some-record', version: M.recordVersion, parsedData: M.recordData }) recordHandler.handle(client.socketWrapper, M.subscribeCreateAndReadMessage) }) it('returns a snapshot of the data that exists with version number and data', () => { services.cache.set('some-record', M.recordVersion, M.recordData, () => {}) client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.READ_RESPONSE, name: 'some-record', parsedData: M.recordData, version: M.recordVersion }) recordHandler.handle(client.socketWrapper, M.recordSnapshotMessage) }) it('returns an error for a snapshot of data that doesn\'t exists', () => { client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.RECORD_NOT_FOUND, originalAction: M.recordSnapshotMessage.action, name: M.recordSnapshotMessage.name, isError: true }) recordHandler.handle(client.socketWrapper, M.recordSnapshotMessage) }) it('returns an error for a snapshot if message error occurs with record retrieval', () => { services.cache.nextOperationWillBeSuccessful = false client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.RECORD_LOAD_ERROR, originalAction: M.recordSnapshotMessage.action, name: M.recordSnapshotMessage.name, isError: true }) recordHandler.handle(client.socketWrapper, M.recordSnapshotMessage) }) it('returns a version of the data that exists with version number', () => { ['record/1', 'record/2', 'record/3'].forEach((name) => { const version = Math.floor(Math.random() * 100) const data = { firstname: 'Wolfram' } services.cache.set(name, version, data, () => {}) client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(Object.assign({}, M.recordHeadResponseMessage, { name, version })) recordHandler.handle(client.socketWrapper, Object.assign({}, M.recordHeadMessage, { name })) }) }) it('returns an version of -1 for head request of data that doesn\'t exist', () => { ['record/1', 'record/2', 'record/3'].forEach((name) => { client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(Object.assign({}, { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.HEAD_RESPONSE, name: M.recordHeadMessage.name, version: -1 }, { name })) recordHandler.handle(client.socketWrapper, Object.assign({}, M.recordHeadMessage, { name })) }) }) it('returns an error for a version if message error occurs with record retrieval', () => { services.cache.nextOperationWillBeSuccessful = false client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.RECORD_LOAD_ERROR, originalAction: M.recordHeadMessage.action, name: M.recordHeadMessage.name, isError: true }) recordHandler.handle(client.socketWrapper, M.recordHeadMessage) }) it('patches a record', () => { const recordPatch = Object.assign({}, M.recordPatch) services.cache.set('some-record', M.recordVersion, Object.assign({}, M.recordData), () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordPatch.name, recordPatch, false, client.socketWrapper) recordHandler.handle(client.socketWrapper, recordPatch) services.cache.get('some-record', (error, version, record) => { expect(version).to.equal(version) expect(record).to.deep.equal({ name: 'Kowalski', lastname: 'Egon' }) }) }) it('updates a record', () => { services.cache.set('some-record', M.recordVersion, M.recordData, () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordUpdate.name, M.recordUpdate, false, client.socketWrapper) recordHandler.handle(client.socketWrapper, M.recordUpdate) services.cache.get('some-record', (error, version, result) => { expect(version).to.equal(6) expect(result).to.deep.equal({ name: 'Kowalski' }) }) }) it('rejects updates for existing versions', () => { services.cache.set(M.recordUpdate.name, M.recordVersion, M.recordData, () => {}) const ExistingVersion = Object.assign({}, M.recordUpdate, { version: M.recordVersion }) client.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.VERSION_EXISTS, originalAction: ExistingVersion.action, name: ExistingVersion.name, version: ExistingVersion.version, parsedData: M.recordData, isWriteAck: false, correlationId: undefined }) recordHandler.handle(client.socketWrapper, ExistingVersion) expect(services.logger.lastLogMessage).to.equal('someUser tried to update record some-record to version 5 but it already was 5') }) describe('notifies when db/cache remotely changed', () => { beforeEach(() => { services.storage.nextGetWillBeSynchronous = true services.cache.nextGetWillBeSynchronous = true }) it ('notifies users when record changes', () => { M.notify.names.forEach(name => { services.storage.set(name, 123, { name }, () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(name, { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.UPDATE, name, parsedData: { name }, version: 123 }, true, null) }) recordHandler.handle(client.socketWrapper, M.notify) }) it('notifies users when records deleted', () => { M.notify.names.forEach(name => { testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(name, { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.DELETED, name }, true, null) }) recordHandler.handle(client.socketWrapper, M.notify) }) it('notifies users when records updated and deleted combined', () => { services.storage.set(M.notify.names[0], 1, { name: M.notify.names[0] }, () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.notify.names[0], { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.UPDATE, name: M.notify.names[0], parsedData: { name: M.notify.names[0] }, version: 1 }, true, null) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.notify.names[1], { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.DELETED, name: M.notify.names[1] }, true, null) recordHandler.handle(client.socketWrapper, M.notify) }) }) describe('subscription registry', () => { it('handles unsubscribe messages', () => { testMocks.subscriptionRegistryMock .expects('unsubscribeBulk') .once() .withExactArgs(M.unsubscribeMessage, client.socketWrapper) recordHandler.handle(client.socketWrapper, M.unsubscribeMessage) }) }) it('updates a record via same client to the same version', (done) => { config.record.cacheRetrievalTimeout = 50 services.cache.nextGetWillBeSynchronous = false services.cache.set(M.recordUpdate.name, M.recordVersion, M.recordData, () => {}) client.socketWrapperMock .expects('sendMessage') .twice() .withExactArgs({ topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.VERSION_EXISTS, originalAction: C.RECORD_ACTION.UPDATE, version: M.recordVersion, parsedData: M.recordData, name: M.recordUpdate.name, isWriteAck: false, correlationId: undefined }) recordHandler.handle(client.socketWrapper, M.recordUpdate) recordHandler.handle(client.socketWrapper, M.recordUpdate) recordHandler.handle(client.socketWrapper, M.recordUpdate) setTimeout(() => { /** * Important to note this is a race condition since version exists errors are sent as soon as record is retrieved, * which means it hasn't yet been written to cache. */ done() }, 50) }) it('handles deletion messages', () => { services.cache.nextGetWillBeSynchronous = false services.cache.set(M.recordDelete.name, 1, {}, () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordDelete.name, { topic: C.TOPIC.RECORD, action: C.RECORD_ACTION.DELETED, name: M.recordDelete.name }, true, client.socketWrapper) testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .once() .returns(new Set()) recordHandler.handle(client.socketWrapper, M.recordDelete) services.cache.get(M.recordDelete.name, (error, version, data) => { expect(version).to.deep.equal(-1) expect(data).to.equal(null) }) }) it('updates a record with a -1 version number', () => { services.cache.set(M.recordUpdate.name, 5, Object.assign({}, M.recordData), () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordUpdate.name, Object.assign({}, M.recordUpdate, { version: 6 }), false, client.socketWrapper) recordHandler.handle(client.socketWrapper, Object.assign({}, M.recordUpdate, { version: -1 })) services.cache.get(M.recordUpdate.name, (error, version, data) => { expect(data).to.deep.equal(M.recordUpdate.parsedData) expect(version).to.equal(6) }) }) it('updates multiple updates with an -1 version number', () => { const data = Object.assign({}, M.recordData) services.cache.set(M.recordUpdate.name, 5, data, () => {}) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordUpdate.name, Object.assign({}, M.recordUpdate, { version: 6 }), false, client.socketWrapper) testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs(M.recordUpdate.name, Object.assign({}, M.recordUpdate, { version: 7 }), false, client.socketWrapper) recordHandler.handle(client.socketWrapper, Object.assign({}, M.recordUpdate, { version: -1 })) recordHandler.handle(client.socketWrapper, Object.assign({}, M.recordUpdate, { version: -1 })) services.cache.get(M.recordUpdate.name, (error, version, result) => { expect(result).to.deep.equal(M.recordUpdate.parsedData) }) }) it.skip('creates records when using CREATEANDUPDATE', () => { testMocks.subscriptionRegistryMock .expects('sendToSubscribers') .once() .withExactArgs( M.createAndUpdate.name, Object.assign({}, M.createAndUpdate, { action: C.RECORD_ACTION.UPDATE, version: 1 }), false, client.socketWrapper ) recordHandler.handle(client.socketWrapper, M.createAndUpdate) services.cache.get(M.createAndUpdate.name, (error, version, data) => { expect(version).to.deep.equal(1) expect(data).to.deep.equal(M.recordData) }) }) it('registers a listener', () => { testMocks.listenerRegistryMock .expects('handle') .once() .withExactArgs(client.socketWrapper, M.listenMessage) recordHandler.handle(client.socketWrapper, M.listenMessage) }) it('removes listeners', () => { testMocks.listenerRegistryMock .expects('handle') .once() .withExactArgs(client.socketWrapper, M.unlistenMessage) recordHandler.handle(client.socketWrapper, M.unlistenMessage) }) it('processes listen accepts', () => { testMocks.listenerRegistryMock .expects('handle') .once() .withExactArgs(client.socketWrapper, M.listenAcceptMessage) recordHandler.handle(client.socketWrapper, M.listenAcceptMessage) }) it('processes listen rejects', () => { testMocks.listenerRegistryMock .expects('handle') .once() .withExactArgs(client.socketWrapper, M.listenRejectMessage) recordHandler.handle(client.socketWrapper, M.listenRejectMessage) }) })
the_stack
* Adapted from React TypeScript definition * @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts * https://github.com/DefinitelyTyped/DefinitelyTyped/commit/e6491e0d87a72a566c0f6ce61fca2b57199aa172 */ import type * as CSS from "csstype" export * from "./extra" export { styled } from "./styled" type Booleanish = boolean | "true" | "false" export function className(value: ClassNames): string export { createElement as h, jsx as jsxs } export interface ClassList { (value: Element): void readonly size: number readonly value: string add(...tokens: string[]): void remove(...tokens: string[]): void toggle(token: string, force?: boolean): void contains(token: string): boolean } /** @internal */ declare const __defaultExport: { createElement: typeof createElement Fragment: typeof Fragment Component: typeof Component } export default __defaultExport type Key = string | number type ClassName = string | { [key: string]: boolean } | false | null | undefined | ClassName[] export type ClassNames = ClassName | ClassList export interface RefObject<T> { readonly current: T | null } export type RefCallback<T> = (instance: T) => void export type Ref<T> = RefCallback<T> | RefObject<T> | null /** * @internal You shouldn't need to use this type since you never see these attributes * inside your component or have to validate them. */ interface Attributes { key?: Key | null | undefined } interface AttrWithRef<T> extends Attributes { ref?: Ref<T> | undefined } type ReactElement = HTMLElement | SVGElement type DOMFactory<P extends DOMAttributes<T>, T extends Element> = ( props?: (AttrWithRef<T> & P) | null, ...children: ReactNode[] ) => T type HTMLFactory<T extends HTMLElement> = DetailedHTMLFactory<AllHTMLAttributes<T>, T> interface DetailedHTMLFactory<P extends HTMLAttributes<T>, T extends HTMLElement> extends DOMFactory<P, T> { (props?: (AttrWithRef<T> & P) | null, ...children: ReactNode[]): T (...children: ReactNode[]): T } interface SVGFactory extends DOMFactory<SVGAttributes<SVGElement>, SVGElement> { ( props?: (AttrWithRef<SVGElement> & SVGAttributes<SVGElement>) | null, ...children: ReactNode[] ): SVGElement (...children: ReactNode[]): SVGElement } // // React Nodes // http://facebook.github.io/react/docs/glossary.html // ---------------------------------------------------------------------- type ReactText = string | number type ReactChild = Node | ReactText type ReactChildren = ReactNodeArray | NodeList | HTMLCollection interface ReactNodeArray extends Array<ReactNode> {} export type ReactNode = | ReactChild | ReactChildren | DocumentFragment | Text | Comment | boolean | null | undefined // // Top Level API // ---------------------------------------------------------------------- export type HTMLElementTagNames = keyof HTMLElementTagNameMap export type SVGElementTagNames = keyof ReactSVG // DOM Elements export function createFactory<K extends HTMLElementTagNames>(type: K): HTMLFactory<ReactHTML[K]> export function createFactory(type: SVGElementTagNames): SVGFactory export function createFactory<T extends Element>(type: string): T // DOM Elements export function createElement<K extends HTMLElementTagNames, T extends HTMLElementTagNameMap[K]>( type: K, props?: (HTMLAttributes<T> & AttrWithRef<T>) | null, ...children: ReactNode[] ): T export function createElement<K extends SVGElementTagNames, T extends ReactSVG[K]>( type: K, props?: (SVGAttributes<T> & AttrWithRef<T>) | null, ...children: ReactNode[] ): SVGElement export function createElement<T extends Element>( type: string, props?: (AttrWithRef<T> & DOMAttributes<T>) | null, ...children: ReactNode[] ): T // Custom components export function createElement<P extends {}, T extends Element>( type: ComponentType<P, T>, props?: (Attributes & P) | null, ...children: ReactNode[] ): T export function createElement<T extends Element>( type: string, props?: Attributes | null, ...children: ReactNode[] ): T // DOM Elements export function jsx<K extends HTMLElementTagNames, T extends HTMLElementTagNameMap[K]>( type: K, props?: PropsWithChildren<HTMLAttributes<T> & AttrWithRef<T>> | null, key?: string ): T export function jsx<K extends SVGElementTagNames, T extends ReactSVG[K]>( type: K, props?: PropsWithChildren<SVGAttributes<T> & AttrWithRef<T>> | null, key?: string ): SVGElement export function jsx<T extends Element>( type: string, props?: PropsWithChildren<AttrWithRef<T> & DOMAttributes<T>> | null, key?: string ): T // Custom components export function jsx<P extends {}, T extends Element>( type: ComponentType<P, T>, props?: PropsWithChildren<Attributes & P> | null, key?: string ): T export function jsx<T extends Element>( type: string, props?: PropsWithChildren<Attributes> | null, key?: string ): T export function Fragment(props: { children?: ReactNode | undefined }): any // DocumentFragment export function StrictMode(props: { children?: ReactNode | undefined }): any // DocumentFragment export interface FunctionComponent<P = {}, T extends Element = JSX.Element> { (props: PropsWithChildren<P>, context?: any): T | null defaultProps?: Partial<P> displayName?: string } export { FunctionComponent as FC } export interface ComponentClass<P = {}, T extends Element = JSX.Element> { new (props: P, context?: any): Component<P, T> defaultProps?: Partial<P> | undefined displayName?: string | undefined } export class Component<P = {}, T extends Element = JSX.Element> { constructor(props: PropsWithChildren<P>) readonly props: PropsWithChildren<P> render(): T | null } export { Component as PureComponent } type PropsWithChildren<P> = P & { children?: ReactNode | undefined } export type ComponentType<P = {}, T extends Element = JSX.Element> = | ComponentClass<P, T> | FunctionComponent<P, T> // // React Hooks // ---------------------------------------------------------------------- // based on the code in https://github.com/facebook/react/pull/13968 // TODO (TypeScript 3.0): ReadonlyArray<unknown> type DependencyList = ReadonlyArray<any> export interface MutableRefObject<T> { current: T } export function createRef<T = any>(): RefObject<T> /** * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument * (`initialValue`). The returned object will persist for the full lifetime of the component. * * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable * value around similar to how you’d use instance fields in classes. * * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#useref */ export function useRef<T extends unknown>(initialValue: T): MutableRefObject<T> // convenience overload for refs given as a ref prop as they typically start with a null value /** * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument * (`initialValue`). The returned object will persist for the full lifetime of the component. * * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable * value around similar to how you’d use instance fields in classes. * * Usage note: if you need the result of useRef to be directly mutable, include `| null` in the type * of the generic argument. * * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#useref */ export function useRef<T extends unknown>(initialValue: T | null): RefObject<T> // convenience overload for potentially undefined initialValue / call with 0 arguments // has a default to stop it from defaulting to {} instead /** * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument * (`initialValue`). The returned object will persist for the full lifetime of the component. * * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable * value around similar to how you’d use instance fields in classes. * * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#useref */ export function useRef<T = unknown>(): MutableRefObject<T | undefined> // I made 'inputs' required here and in useMemo as there's no point to memoizing without the memoization key // useCallback(X) is identical to just using X, useMemo(() => Y) is identical to just using Y. /** * `useCallback` will return a memoized version of the callback that only changes if one of the `inputs` * has changed. * * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usecallback */ export function useCallback<T extends (...args: never[]) => any>( callback: T, deps: DependencyList ): T /** * `useMemo` will only recompute the memoized value when one of the `deps` has changed. * * Usage note: if calling `useMemo` with a referentially stable function, also give it as the input in * the second argument. * * ```ts * function expensive () { ... } * * function Component () { * const expensiveResult = useMemo(expensive, [expensive]) * return ... * } * ``` * * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usememo */ // allow undefined, but don't make it optional as that is very likely a mistake export function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T interface CurrentTarget<T> { currentTarget: EventTarget & T } type FormEvent = Event type ChangeEvent = Event // // Event Handler Types // ---------------------------------------------------------------------- type EventHandler<E extends Event, T> = (this: T, event: E & CurrentTarget<T>) => void export type ReactEventHandler<T = Element> = EventHandler<Event, T> export type ClipboardEventHandler<T = Element> = EventHandler<ClipboardEvent, T> export type CompositionEventHandler<T = Element> = EventHandler<CompositionEvent, T> export type DragEventHandler<T = Element> = EventHandler<DragEvent, T> export type FocusEventHandler<T = Element> = EventHandler<FocusEvent, T> export type FormEventHandler<T = Element> = EventHandler<FormEvent, T> export type ChangeEventHandler<T = Element> = EventHandler<ChangeEvent, T> export type KeyboardEventHandler<T = Element> = EventHandler<KeyboardEvent, T> export type MouseEventHandler<T = Element> = EventHandler<MouseEvent, T> export type TouchEventHandler<T = Element> = EventHandler<TouchEvent, T> export type PointerEventHandler<T = Element> = EventHandler<PointerEvent, T> export type UIEventHandler<T = Element> = EventHandler<UIEvent, T> export type WheelEventHandler<T = Element> = EventHandler<WheelEvent, T> export type AnimationEventHandler<T = Element> = EventHandler<AnimationEvent, T> export type TransitionEventHandler<T = Element> = EventHandler<TransitionEvent, T> export type DetailedHTMLProps<E extends HTMLAttributes<T>, T> = AttrWithRef<T> & E export interface SVGProps<T> extends SVGAttributes<T>, AttrWithRef<T> {} export interface DOMAttributes<T> { children?: ReactNode | undefined dangerouslySetInnerHTML?: { __html: string } | undefined // Clipboard Events onCopy?: ClipboardEventHandler<T> | undefined onCopyCapture?: ClipboardEventHandler<T> | undefined onCut?: ClipboardEventHandler<T> | undefined onCutCapture?: ClipboardEventHandler<T> | undefined onPaste?: ClipboardEventHandler<T> | undefined onPasteCapture?: ClipboardEventHandler<T> | undefined // Composition Events onCompositionEnd?: CompositionEventHandler<T> | undefined onCompositionEndCapture?: CompositionEventHandler<T> | undefined onCompositionStart?: CompositionEventHandler<T> | undefined onCompositionStartCapture?: CompositionEventHandler<T> | undefined onCompositionUpdate?: CompositionEventHandler<T> | undefined onCompositionUpdateCapture?: CompositionEventHandler<T> | undefined // Focus Events onFocus?: FocusEventHandler<T> | undefined onFocusCapture?: FocusEventHandler<T> | undefined onBlur?: FocusEventHandler<T> | undefined onBlurCapture?: FocusEventHandler<T> | undefined // Form Events onChange?: FormEventHandler<T> | undefined onChangeCapture?: FormEventHandler<T> | undefined onBeforeInput?: FormEventHandler<T> | undefined onBeforeInputCapture?: FormEventHandler<T> | undefined onInput?: FormEventHandler<T> | undefined onInputCapture?: FormEventHandler<T> | undefined onReset?: FormEventHandler<T> | undefined onResetCapture?: FormEventHandler<T> | undefined onSubmit?: FormEventHandler<T> | undefined onSubmitCapture?: FormEventHandler<T> | undefined onInvalid?: FormEventHandler<T> | undefined onInvalidCapture?: FormEventHandler<T> | undefined // Image Events onLoad?: ReactEventHandler<T> | undefined onLoadCapture?: ReactEventHandler<T> | undefined onError?: ReactEventHandler<T> | undefined // also a Media Event onErrorCapture?: ReactEventHandler<T> | undefined // also a Media Event // Keyboard Events onKeyDown?: KeyboardEventHandler<T> | undefined onKeyDownCapture?: KeyboardEventHandler<T> | undefined onKeyPress?: KeyboardEventHandler<T> | undefined onKeyPressCapture?: KeyboardEventHandler<T> | undefined onKeyUp?: KeyboardEventHandler<T> | undefined onKeyUpCapture?: KeyboardEventHandler<T> | undefined // Media Events onAbort?: ReactEventHandler<T> | undefined onAbortCapture?: ReactEventHandler<T> | undefined onCanPlay?: ReactEventHandler<T> | undefined onCanPlayCapture?: ReactEventHandler<T> | undefined onCanPlayThrough?: ReactEventHandler<T> | undefined onCanPlayThroughCapture?: ReactEventHandler<T> | undefined onDurationChange?: ReactEventHandler<T> | undefined onDurationChangeCapture?: ReactEventHandler<T> | undefined onEmptied?: ReactEventHandler<T> | undefined onEmptiedCapture?: ReactEventHandler<T> | undefined onEncrypted?: ReactEventHandler<T> | undefined onEncryptedCapture?: ReactEventHandler<T> | undefined onEnded?: ReactEventHandler<T> | undefined onEndedCapture?: ReactEventHandler<T> | undefined onLoadedData?: ReactEventHandler<T> | undefined onLoadedDataCapture?: ReactEventHandler<T> | undefined onLoadedMetadata?: ReactEventHandler<T> | undefined onLoadedMetadataCapture?: ReactEventHandler<T> | undefined onLoadStart?: ReactEventHandler<T> | undefined onLoadStartCapture?: ReactEventHandler<T> | undefined onPause?: ReactEventHandler<T> | undefined onPauseCapture?: ReactEventHandler<T> | undefined onPlay?: ReactEventHandler<T> | undefined onPlayCapture?: ReactEventHandler<T> | undefined onPlaying?: ReactEventHandler<T> | undefined onPlayingCapture?: ReactEventHandler<T> | undefined onProgress?: ReactEventHandler<T> | undefined onProgressCapture?: ReactEventHandler<T> | undefined onRateChange?: ReactEventHandler<T> | undefined onRateChangeCapture?: ReactEventHandler<T> | undefined onSeeked?: ReactEventHandler<T> | undefined onSeekedCapture?: ReactEventHandler<T> | undefined onSeeking?: ReactEventHandler<T> | undefined onSeekingCapture?: ReactEventHandler<T> | undefined onStalled?: ReactEventHandler<T> | undefined onStalledCapture?: ReactEventHandler<T> | undefined onSuspend?: ReactEventHandler<T> | undefined onSuspendCapture?: ReactEventHandler<T> | undefined onTimeUpdate?: ReactEventHandler<T> | undefined onTimeUpdateCapture?: ReactEventHandler<T> | undefined onVolumeChange?: ReactEventHandler<T> | undefined onVolumeChangeCapture?: ReactEventHandler<T> | undefined onWaiting?: ReactEventHandler<T> | undefined onWaitingCapture?: ReactEventHandler<T> | undefined // MouseEvents onAuxClick?: MouseEventHandler<T> | undefined onAuxClickCapture?: MouseEventHandler<T> | undefined onClick?: MouseEventHandler<T> | undefined onClickCapture?: MouseEventHandler<T> | undefined onContextMenu?: MouseEventHandler<T> | undefined onContextMenuCapture?: MouseEventHandler<T> | undefined onDoubleClick?: MouseEventHandler<T> | undefined onDoubleClickCapture?: MouseEventHandler<T> | undefined onDrag?: DragEventHandler<T> | undefined onDragCapture?: DragEventHandler<T> | undefined onDragEnd?: DragEventHandler<T> | undefined onDragEndCapture?: DragEventHandler<T> | undefined onDragEnter?: DragEventHandler<T> | undefined onDragEnterCapture?: DragEventHandler<T> | undefined onDragExit?: DragEventHandler<T> | undefined onDragExitCapture?: DragEventHandler<T> | undefined onDragLeave?: DragEventHandler<T> | undefined onDragLeaveCapture?: DragEventHandler<T> | undefined onDragOver?: DragEventHandler<T> | undefined onDragOverCapture?: DragEventHandler<T> | undefined onDragStart?: DragEventHandler<T> | undefined onDragStartCapture?: DragEventHandler<T> | undefined onDrop?: DragEventHandler<T> | undefined onDropCapture?: DragEventHandler<T> | undefined onMouseDown?: MouseEventHandler<T> | undefined onMouseDownCapture?: MouseEventHandler<T> | undefined onMouseEnter?: MouseEventHandler<T> | undefined onMouseLeave?: MouseEventHandler<T> | undefined onMouseMove?: MouseEventHandler<T> | undefined onMouseMoveCapture?: MouseEventHandler<T> | undefined onMouseOut?: MouseEventHandler<T> | undefined onMouseOutCapture?: MouseEventHandler<T> | undefined onMouseOver?: MouseEventHandler<T> | undefined onMouseOverCapture?: MouseEventHandler<T> | undefined onMouseUp?: MouseEventHandler<T> | undefined onMouseUpCapture?: MouseEventHandler<T> | undefined // Selection Events onSelect?: ReactEventHandler<T> | undefined onSelectCapture?: ReactEventHandler<T> | undefined // Touch Events onTouchCancel?: TouchEventHandler<T> | undefined onTouchCancelCapture?: TouchEventHandler<T> | undefined onTouchEnd?: TouchEventHandler<T> | undefined onTouchEndCapture?: TouchEventHandler<T> | undefined onTouchMove?: TouchEventHandler<T> | undefined onTouchMoveCapture?: TouchEventHandler<T> | undefined onTouchStart?: TouchEventHandler<T> | undefined onTouchStartCapture?: TouchEventHandler<T> | undefined // Pointer Events onPointerDown?: PointerEventHandler<T> | undefined onPointerDownCapture?: PointerEventHandler<T> | undefined onPointerMove?: PointerEventHandler<T> | undefined onPointerMoveCapture?: PointerEventHandler<T> | undefined onPointerUp?: PointerEventHandler<T> | undefined onPointerUpCapture?: PointerEventHandler<T> | undefined onPointerCancel?: PointerEventHandler<T> | undefined onPointerCancelCapture?: PointerEventHandler<T> | undefined onPointerEnter?: PointerEventHandler<T> | undefined onPointerEnterCapture?: PointerEventHandler<T> | undefined onPointerLeave?: PointerEventHandler<T> | undefined onPointerLeaveCapture?: PointerEventHandler<T> | undefined onPointerOver?: PointerEventHandler<T> | undefined onPointerOverCapture?: PointerEventHandler<T> | undefined onPointerOut?: PointerEventHandler<T> | undefined onPointerOutCapture?: PointerEventHandler<T> | undefined onGotPointerCapture?: PointerEventHandler<T> | undefined onGotPointerCaptureCapture?: PointerEventHandler<T> | undefined onLostPointerCapture?: PointerEventHandler<T> | undefined onLostPointerCaptureCapture?: PointerEventHandler<T> | undefined // UI Events onScroll?: UIEventHandler<T> | undefined onScrollCapture?: UIEventHandler<T> | undefined // Wheel Events onWheel?: WheelEventHandler<T> | undefined onWheelCapture?: WheelEventHandler<T> | undefined // Animation Events onAnimationStart?: AnimationEventHandler<T> | undefined onAnimationStartCapture?: AnimationEventHandler<T> | undefined onAnimationEnd?: AnimationEventHandler<T> | undefined onAnimationEndCapture?: AnimationEventHandler<T> | undefined onAnimationIteration?: AnimationEventHandler<T> | undefined onAnimationIterationCapture?: AnimationEventHandler<T> | undefined // Transition Events onTransitionEnd?: TransitionEventHandler<T> | undefined onTransitionEndCapture?: TransitionEventHandler<T> | undefined } export interface CSSProperties extends CSS.Properties<string | number> { /** * The index signature was removed to enable closed typing for style * using CSSType. You're able to use type assertion or module augmentation * to add properties or an index signature of your own. * * For examples and more information, visit: * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors */ } // All the WAI-ARIA 1.1 attributes from https://www.w3.org/TR/wai-aria-1.1/ export interface AriaAttributes { /** Identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application. */ "aria-activedescendant"?: string | undefined /** Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute. */ "aria-atomic"?: Booleanish | undefined /** * Indicates whether inputting text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be * presented if they are made. */ "aria-autocomplete"?: "none" | "inline" | "list" | "both" | undefined /** Indicates an element is being modified and that assistive technologies MAY want to wait until the modifications are complete before exposing them to the user. */ "aria-busy"?: Booleanish | undefined /** * Indicates the current "checked" state of checkboxes, radio buttons, and other widgets. * @see aria-pressed @see aria-selected. */ "aria-checked"?: boolean | "false" | "mixed" | "true" | undefined /** * Defines the total number of columns in a table, grid, or treegrid. * @see aria-colindex. */ "aria-colcount"?: number | undefined /** * Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid. * @see aria-colcount @see aria-colspan. */ "aria-colindex"?: number | undefined /** * Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-colindex @see aria-rowspan. */ "aria-colspan"?: number | undefined /** * Identifies the element (or elements) whose contents or presence are controlled by the current element. * @see aria-owns. */ "aria-controls"?: string | undefined /** Indicates the element that represents the current item within a container or set of related elements. */ "aria-current"?: Booleanish | "page" | "step" | "location" | "date" | "time" | undefined /** * Identifies the element (or elements) that describes the object. * @see aria-labelledby */ "aria-describedby"?: string | undefined /** * Identifies the element that provides a detailed, extended description for the object. * @see aria-describedby. */ "aria-details"?: string | undefined /** * Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable. * @see aria-hidden @see aria-readonly. */ "aria-disabled"?: Booleanish | undefined /** * Indicates what functions can be performed when a dragged object is released on the drop target. * @deprecated in ARIA 1.1 */ "aria-dropeffect"?: "none" | "copy" | "execute" | "link" | "move" | "popup" | undefined /** * Identifies the element that provides an error message for the object. * @see aria-invalid @see aria-describedby. */ "aria-errormessage"?: string | undefined /** Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed. */ "aria-expanded"?: Booleanish | undefined /** * Identifies the next element (or elements) in an alternate reading order of content which, at the user's discretion, * allows assistive technology to override the general default of reading in document source order. */ "aria-flowto"?: string | undefined /** * Indicates an element's "grabbed" state in a drag-and-drop operation. * @deprecated in ARIA 1.1 */ "aria-grabbed"?: Booleanish | undefined /** Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element. */ "aria-haspopup"?: Booleanish | "menu" | "listbox" | "tree" | "grid" | "dialog" | undefined /** * Indicates whether the element is exposed to an accessibility API. * @see aria-disabled. */ "aria-hidden"?: Booleanish | undefined /** * Indicates the entered value does not conform to the format expected by the application. * @see aria-errormessage. */ "aria-invalid"?: Booleanish | "grammar" | "spelling" | undefined /** Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element. */ "aria-keyshortcuts"?: string | undefined /** * Defines a string value that labels the current element. * @see aria-labelledby. */ "aria-label"?: string | undefined /** * Identifies the element (or elements) that labels the current element. * @see aria-describedby. */ "aria-labelledby"?: string | undefined /** Defines the hierarchical level of an element within a structure. */ "aria-level"?: number | undefined /** Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region. */ "aria-live"?: "off" | "assertive" | "polite" | undefined /** Indicates whether an element is modal when displayed. */ "aria-modal"?: Booleanish | undefined /** Indicates whether a text box accepts multiple lines of input or only a single line. */ "aria-multiline"?: Booleanish | undefined /** Indicates that the user may select more than one item from the current selectable descendants. */ "aria-multiselectable"?: Booleanish | undefined /** Indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous. */ "aria-orientation"?: "horizontal" | "vertical" | undefined /** * Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship * between DOM elements where the DOM hierarchy cannot be used to represent the relationship. * @see aria-controls. */ "aria-owns"?: string | undefined /** * Defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. * A hint could be a sample value or a brief description of the expected format. */ "aria-placeholder"?: string | undefined /** * Defines an element's number or position in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-setsize. */ "aria-posinset"?: number | undefined /** * Indicates the current "pressed" state of toggle buttons. * @see aria-checked @see aria-selected. */ "aria-pressed"?: boolean | "false" | "mixed" | "true" | undefined /** * Indicates that the element is not editable, but is otherwise operable. * @see aria-disabled. */ "aria-readonly"?: Booleanish | undefined /** * Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. * @see aria-atomic. */ "aria-relevant"?: | "additions" | "additions removals" | "additions text" | "all" | "removals" | "removals additions" | "removals text" | "text" | "text additions" | "text removals" | undefined /** Indicates that user input is required on the element before a form may be submitted. */ "aria-required"?: Booleanish | undefined /** Defines a human-readable, author-localized description for the role of an element. */ "aria-roledescription"?: string | undefined /** * Defines the total number of rows in a table, grid, or treegrid. * @see aria-rowindex. */ "aria-rowcount"?: number | undefined /** * Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid. * @see aria-rowcount @see aria-rowspan. */ "aria-rowindex"?: number | undefined /** * Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid. * @see aria-rowindex @see aria-colspan. */ "aria-rowspan"?: number | undefined /** * Indicates the current "selected" state of various widgets. * @see aria-checked @see aria-pressed. */ "aria-selected"?: Booleanish | undefined /** * Defines the number of items in the current set of listitems or treeitems. Not required if all elements in the set are present in the DOM. * @see aria-posinset. */ "aria-setsize"?: number | undefined /** Indicates if items in a table or grid are sorted in ascending or descending order. */ "aria-sort"?: "none" | "ascending" | "descending" | "other" | undefined /** Defines the maximum allowed value for a range widget. */ "aria-valuemax"?: number | undefined /** Defines the minimum allowed value for a range widget. */ "aria-valuemin"?: number | undefined /** * Defines the current value for a range widget. * @see aria-valuetext. */ "aria-valuenow"?: number | undefined /** Defines the human readable text alternative of aria-valuenow for a range widget. */ "aria-valuetext"?: string | undefined } // All the WAI-ARIA 1.1 role attribute values from https://www.w3.org/TR/wai-aria-1.1/#role_definitions type AriaRole = | "alert" | "alertdialog" | "application" | "article" | "banner" | "button" | "cell" | "checkbox" | "columnheader" | "combobox" | "complementary" | "contentinfo" | "definition" | "dialog" | "directory" | "document" | "feed" | "figure" | "form" | "grid" | "gridcell" | "group" | "heading" | "img" | "link" | "list" | "listbox" | "listitem" | "log" | "main" | "marquee" | "math" | "menu" | "menubar" | "menuitem" | "menuitemcheckbox" | "menuitemradio" | "navigation" | "none" | "note" | "option" | "presentation" | "progressbar" | "radio" | "radiogroup" | "region" | "row" | "rowgroup" | "rowheader" | "scrollbar" | "search" | "searchbox" | "separator" | "slider" | "spinbutton" | "status" | "switch" | "tab" | "table" | "tablist" | "tabpanel" | "term" | "textbox" | "timer" | "toolbar" | "tooltip" | "tree" | "treegrid" | "treeitem" | (string & {}) export type StyleInput = string | CSSProperties | (string | CSSProperties)[] export interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> { // Extension namespaceURI?: string | undefined class?: ClassNames | undefined innerHTML?: string | undefined innerText?: string | undefined textContent?: string | undefined dataset?: { [key: string]: string } | undefined // Standard HTML Attributes accessKey?: string | undefined className?: ClassNames | undefined contentEditable?: Booleanish | "inherit" | undefined contextMenu?: string | undefined dir?: string | undefined draggable?: Booleanish | undefined hidden?: boolean | undefined id?: string | undefined lang?: string | undefined placeholder?: string | undefined slot?: string | undefined spellCheck?: Booleanish | undefined style?: StyleInput | undefined tabIndex?: number | undefined title?: string | undefined translate?: "yes" | "no" | undefined // Unknown radioGroup?: string | undefined // <command>, <menuitem> // WAI-ARIA role?: AriaRole | undefined // RDFa Attributes about?: string | undefined datatype?: string | undefined inlist?: any | undefined prefix?: string | undefined property?: string | undefined resource?: string | undefined typeof?: string | undefined vocab?: string | undefined // Non-standard Attributes autoCapitalize?: string | undefined autoCorrect?: string | undefined autoSave?: string | undefined color?: string | undefined itemProp?: string | undefined itemScope?: boolean | undefined itemType?: string | undefined itemID?: string | undefined itemRef?: string | undefined results?: number | undefined security?: string | undefined unselectable?: "on" | "off" | undefined // Living Standard /** * Hints at the type of data that might be entered by the user while editing the element or its contents * @see https://html.spec.whatwg.org/multipage/interaction.html#input-modalities:-the-inputmode-attribute */ inputMode?: | "none" | "text" | "tel" | "url" | "email" | "numeric" | "decimal" | "search" | undefined /** * Specify that a standard HTML element should behave like a defined custom built-in element * @see https://html.spec.whatwg.org/multipage/custom-elements.html#attr-is */ is?: string | undefined } export interface AllHTMLAttributes<T> extends HTMLAttributes<T> { // Standard HTML Attributes accept?: string | undefined acceptCharset?: string | undefined action?: string | undefined allowFullScreen?: boolean | undefined allowTransparency?: boolean | undefined alt?: string | undefined as?: string | undefined async?: boolean | undefined autoComplete?: string | undefined autoFocus?: boolean | undefined autoPlay?: boolean | undefined capture?: boolean | string | undefined cellPadding?: number | string | undefined cellSpacing?: number | string | undefined charSet?: string | undefined challenge?: string | undefined checked?: boolean | undefined cite?: string | undefined classID?: string | undefined cols?: number | undefined colSpan?: number | undefined content?: string | undefined controls?: boolean | undefined coords?: string | undefined crossOrigin?: string | undefined data?: string | undefined dateTime?: string | undefined default?: boolean | undefined defer?: boolean | undefined disabled?: boolean | undefined download?: any encType?: string | undefined form?: string | undefined formAction?: string | undefined formEncType?: string | undefined formMethod?: string | undefined formNoValidate?: boolean | undefined formTarget?: string | undefined frameBorder?: number | string | undefined headers?: string | undefined height?: number | string | undefined high?: number | undefined href?: string | undefined hrefLang?: string | undefined htmlFor?: string | undefined httpEquiv?: string | undefined integrity?: string | undefined keyParams?: string | undefined keyType?: string | undefined kind?: string | undefined label?: string | undefined list?: string | undefined loop?: boolean | undefined low?: number | undefined manifest?: string | undefined marginHeight?: number | undefined marginWidth?: number | undefined max?: number | string | undefined maxLength?: number | undefined media?: string | undefined mediaGroup?: string | undefined method?: string | undefined min?: number | string | undefined minLength?: number | undefined multiple?: boolean | undefined muted?: boolean | undefined name?: string | undefined nonce?: string | undefined noValidate?: boolean | undefined open?: boolean | undefined optimum?: number | undefined pattern?: string | undefined placeholder?: string | undefined playsInline?: boolean | undefined poster?: string | undefined preload?: string | undefined readOnly?: boolean | undefined rel?: string | undefined required?: boolean | undefined reversed?: boolean | undefined rows?: number | undefined rowSpan?: number | undefined sandbox?: string | undefined scope?: string | undefined scoped?: boolean | undefined scrolling?: string | undefined seamless?: boolean | undefined selected?: boolean | undefined shape?: string | undefined size?: number | undefined sizes?: string | undefined span?: number | undefined src?: string | undefined srcDoc?: string | undefined srcLang?: string | undefined srcSet?: string | undefined start?: number | undefined step?: number | string | undefined summary?: string | undefined target?: string | undefined type?: string | undefined useMap?: string | undefined value?: string | readonly string[] | number | undefined width?: number | string | undefined wmode?: string | undefined wrap?: string | undefined } export type HTMLAttributeReferrerPolicy = | "" | "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url" export type HTMLAttributeAnchorTarget = "_self" | "_blank" | "_parent" | "_top" | (string & {}) interface AnchorHTMLAttributes<T> extends HTMLAttributes<T> { download?: any | undefined href?: string | undefined hrefLang?: string | undefined media?: string | undefined ping?: string | undefined rel?: string | undefined target?: HTMLAttributeAnchorTarget | undefined type?: string | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined } interface AudioHTMLAttributes<T> extends MediaHTMLAttributes<T> {} interface AreaHTMLAttributes<T> extends HTMLAttributes<T> { alt?: string | undefined coords?: string | undefined download?: any | undefined href?: string | undefined hrefLang?: string | undefined media?: string | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined rel?: string | undefined shape?: string | undefined target?: string | undefined } interface BaseHTMLAttributes<T> extends HTMLAttributes<T> { href?: string | undefined target?: string | undefined } interface BlockquoteHTMLAttributes<T> extends HTMLAttributes<T> { cite?: string | undefined } interface ButtonHTMLAttributes<T> extends HTMLAttributes<T> { autoFocus?: boolean | undefined disabled?: boolean | undefined form?: string | undefined formAction?: string | undefined formEncType?: string | undefined formMethod?: string | undefined formNoValidate?: boolean | undefined formTarget?: string | undefined name?: string | undefined type?: "submit" | "reset" | "button" | undefined value?: string | readonly string[] | number | undefined } interface CanvasHTMLAttributes<T> extends HTMLAttributes<T> { height?: number | string | undefined width?: number | string | undefined } interface ColHTMLAttributes<T> extends HTMLAttributes<T> { span?: number | undefined width?: number | string | undefined } interface ColgroupHTMLAttributes<T> extends HTMLAttributes<T> { span?: number | undefined } interface DataHTMLAttributes<T> extends HTMLAttributes<T> { value?: string | readonly string[] | number | undefined } interface DetailsHTMLAttributes<T> extends HTMLAttributes<T> { open?: boolean | undefined onToggle?: ReactEventHandler<T> | undefined } interface DelHTMLAttributes<T> extends HTMLAttributes<T> { cite?: string | undefined dateTime?: string | undefined } interface DialogHTMLAttributes<T> extends HTMLAttributes<T> { open?: boolean | undefined } interface EmbedHTMLAttributes<T> extends HTMLAttributes<T> { height?: number | string | undefined src?: string | undefined type?: string | undefined width?: number | string | undefined } interface FieldsetHTMLAttributes<T> extends HTMLAttributes<T> { disabled?: boolean | undefined form?: string | undefined name?: string | undefined } interface FormHTMLAttributes<T> extends HTMLAttributes<T> { acceptCharset?: string | undefined action?: string | undefined autoComplete?: string | undefined encType?: string | undefined method?: string | undefined name?: string | undefined noValidate?: boolean | undefined target?: string | undefined } interface HtmlHTMLAttributes<T> extends HTMLAttributes<T> { manifest?: string | undefined } interface IframeHTMLAttributes<T> extends HTMLAttributes<T> { allow?: string | undefined allowFullScreen?: boolean | undefined allowTransparency?: boolean | undefined /** @deprecated */ frameBorder?: number | string | undefined height?: number | string | undefined loading?: "eager" | "lazy" | undefined /** @deprecated */ marginHeight?: number | undefined /** @deprecated */ marginWidth?: number | undefined name?: string | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined sandbox?: string | undefined /** @deprecated */ scrolling?: string | undefined seamless?: boolean | undefined src?: string | undefined srcDoc?: string | undefined width?: number | string | undefined } interface ImgHTMLAttributes<T> extends HTMLAttributes<T> { alt?: string | undefined crossOrigin?: "anonymous" | "use-credentials" | "" | undefined decoding?: "async" | "auto" | "sync" | undefined height?: number | string | undefined loading?: "eager" | "lazy" | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined sizes?: string | undefined src?: string | undefined srcSet?: string | undefined useMap?: string | undefined width?: number | string | undefined } interface InsHTMLAttributes<T> extends HTMLAttributes<T> { cite?: string | undefined dateTime?: string | undefined } interface InputHTMLAttributes<T> extends HTMLAttributes<T> { accept?: string | undefined alt?: string | undefined autoComplete?: string | undefined autoFocus?: boolean | undefined capture?: boolean | string | undefined // https://www.w3.org/TR/html-media-capture/#the-capture-attribute checked?: boolean | undefined crossOrigin?: string | undefined disabled?: boolean | undefined enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send" | undefined form?: string | undefined formAction?: string | undefined formEncType?: string | undefined formMethod?: string | undefined formNoValidate?: boolean | undefined formTarget?: string | undefined height?: number | string | undefined list?: string | undefined max?: number | string | undefined maxLength?: number | undefined min?: number | string | undefined minLength?: number | undefined multiple?: boolean | undefined name?: string | undefined pattern?: string | undefined placeholder?: string | undefined readOnly?: boolean | undefined required?: boolean | undefined size?: number | undefined src?: string | undefined step?: number | string | undefined type?: string | undefined value?: string | readonly string[] | number | undefined width?: number | string | undefined onChange?: ChangeEventHandler<T> | undefined } interface KeygenHTMLAttributes<T> extends HTMLAttributes<T> { autoFocus?: boolean | undefined challenge?: string | undefined disabled?: boolean | undefined form?: string | undefined keyType?: string | undefined keyParams?: string | undefined name?: string | undefined } interface LabelHTMLAttributes<T> extends HTMLAttributes<T> { form?: string | undefined htmlFor?: string | undefined } interface LiHTMLAttributes<T> extends HTMLAttributes<T> { value?: string | readonly string[] | number | undefined } interface LinkHTMLAttributes<T> extends HTMLAttributes<T> { as?: string | undefined crossOrigin?: string | undefined href?: string | undefined hrefLang?: string | undefined integrity?: string | undefined media?: string | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined rel?: string | undefined sizes?: string | undefined type?: string | undefined charSet?: string | undefined } interface MapHTMLAttributes<T> extends HTMLAttributes<T> { name?: string | undefined } interface MenuHTMLAttributes<T> extends HTMLAttributes<T> { type?: string | undefined } interface MediaHTMLAttributes<T> extends HTMLAttributes<T> { autoPlay?: boolean | undefined controls?: boolean | undefined controlsList?: string | undefined crossOrigin?: string | undefined loop?: boolean | undefined mediaGroup?: string | undefined muted?: boolean | undefined playsInline?: boolean | undefined preload?: string | undefined src?: string | undefined } interface MetaHTMLAttributes<T> extends HTMLAttributes<T> { charSet?: string | undefined content?: string | undefined httpEquiv?: string | undefined name?: string | undefined media?: string | undefined } interface MeterHTMLAttributes<T> extends HTMLAttributes<T> { form?: string | undefined high?: number | undefined low?: number | undefined max?: number | string | undefined min?: number | string | undefined optimum?: number | undefined value?: string | readonly string[] | number | undefined } interface QuoteHTMLAttributes<T> extends HTMLAttributes<T> { cite?: string | undefined } interface ObjectHTMLAttributes<T> extends HTMLAttributes<T> { classID?: string | undefined data?: string | undefined form?: string | undefined height?: number | string | undefined name?: string | undefined type?: string | undefined useMap?: string | undefined width?: number | string | undefined wmode?: string | undefined } interface OlHTMLAttributes<T> extends HTMLAttributes<T> { reversed?: boolean | undefined start?: number | undefined type?: "1" | "a" | "A" | "i" | "I" | undefined } interface OptgroupHTMLAttributes<T> extends HTMLAttributes<T> { disabled?: boolean | undefined label?: string | undefined } interface OptionHTMLAttributes<T> extends HTMLAttributes<T> { disabled?: boolean | undefined label?: string | undefined selected?: boolean | undefined value?: string | readonly string[] | number | undefined } interface OutputHTMLAttributes<T> extends HTMLAttributes<T> { form?: string | undefined htmlFor?: string | undefined name?: string | undefined } interface ParamHTMLAttributes<T> extends HTMLAttributes<T> { name?: string | undefined value?: string | readonly string[] | number | undefined } interface ProgressHTMLAttributes<T> extends HTMLAttributes<T> { max?: number | string | undefined value?: string | readonly string[] | number | undefined } interface ScriptHTMLAttributes<T> extends HTMLAttributes<T> { async?: boolean | undefined /** @deprecated */ charSet?: string | undefined crossOrigin?: string | undefined defer?: boolean | undefined integrity?: string | undefined noModule?: boolean | undefined nonce?: string | undefined referrerPolicy?: HTMLAttributeReferrerPolicy | undefined src?: string | undefined type?: string | undefined } interface SelectHTMLAttributes<T> extends HTMLAttributes<T> { autoComplete?: string | undefined autoFocus?: boolean | undefined disabled?: boolean | undefined form?: string | undefined multiple?: boolean | undefined name?: string | undefined required?: boolean | undefined size?: number | undefined value?: string | readonly string[] | number | undefined onChange?: ChangeEventHandler<T> | undefined } interface SlotHTMLAttributes<T> extends HTMLAttributes<T> { name?: string | undefined } interface SourceHTMLAttributes<T> extends HTMLAttributes<T> { height?: number | string | undefined media?: string | undefined sizes?: string | undefined src?: string | undefined srcSet?: string | undefined type?: string | undefined width?: number | string | undefined } interface StyleHTMLAttributes<T> extends HTMLAttributes<T> { media?: string | undefined nonce?: string | undefined scoped?: boolean | undefined type?: string | undefined } interface TableHTMLAttributes<T> extends HTMLAttributes<T> { cellPadding?: number | string | undefined cellSpacing?: number | string | undefined summary?: string | undefined width?: number | string | undefined } interface TextareaHTMLAttributes<T> extends HTMLAttributes<T> { autoComplete?: string | undefined autoFocus?: boolean | undefined cols?: number | undefined dirName?: string | undefined disabled?: boolean | undefined form?: string | undefined maxLength?: number | undefined minLength?: number | undefined name?: string | undefined placeholder?: string | undefined readOnly?: boolean | undefined required?: boolean | undefined rows?: number | undefined value?: string | readonly string[] | number | undefined wrap?: string | undefined onChange?: ChangeEventHandler<T> | undefined } interface TdHTMLAttributes<T> extends HTMLAttributes<T> { align?: "left" | "center" | "right" | "justify" | "char" | undefined colSpan?: number | undefined headers?: string | undefined rowSpan?: number | undefined scope?: string | undefined abbr?: string | undefined height?: number | string | undefined width?: number | string | undefined valign?: "top" | "middle" | "bottom" | "baseline" | undefined } interface ThHTMLAttributes<T> extends HTMLAttributes<T> { align?: "left" | "center" | "right" | "justify" | "char" | undefined colSpan?: number | undefined headers?: string | undefined rowSpan?: number | undefined scope?: string | undefined abbr?: string | undefined } interface TimeHTMLAttributes<T> extends HTMLAttributes<T> { dateTime?: string | undefined } interface TrackHTMLAttributes<T> extends HTMLAttributes<T> { default?: boolean | undefined kind?: string | undefined label?: string | undefined src?: string | undefined srcLang?: string | undefined } interface VideoHTMLAttributes<T> extends MediaHTMLAttributes<T> { height?: number | string | undefined playsInline?: boolean | undefined poster?: string | undefined width?: number | string | undefined disablePictureInPicture?: boolean | undefined disableRemotePlayback?: boolean | undefined } // this list is "complete" in that it contains every SVG attribute // that React supports, but the types can be improved. // Full list here: https://facebook.github.io/react/docs/dom-elements.html // // The three broad type categories are (in order of restrictiveness): // - "number | string" // - "string" // - union of string literals export interface SVGAttributes<T> extends AriaAttributes, DOMAttributes<T> { // Attributes which also defined in HTMLAttributes // See comment in SVGDOMPropertyConfig.js class?: ClassNames | undefined className?: ClassNames | undefined color?: string | undefined height?: number | string | undefined id?: string | undefined lang?: string | undefined max?: number | string | undefined media?: string | undefined method?: string | undefined min?: number | string | undefined name?: string | undefined style?: string | CSSProperties | undefined target?: string | undefined type?: string | undefined width?: number | string | undefined // Other HTML properties supported by SVG elements in browsers role?: AriaRole | undefined tabIndex?: number | undefined crossOrigin?: "anonymous" | "use-credentials" | "" | undefined // SVG Specific attributes accentHeight?: number | string | undefined accumulate?: "none" | "sum" | undefined additive?: "replace" | "sum" | undefined alignmentBaseline?: | "auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit" | undefined allowReorder?: "no" | "yes" | undefined alphabetic?: number | string | undefined amplitude?: number | string | undefined arabicForm?: "initial" | "medial" | "terminal" | "isolated" | undefined ascent?: number | string | undefined attributeName?: string | undefined attributeType?: string | undefined autoReverse?: Booleanish | undefined azimuth?: number | string | undefined baseFrequency?: number | string | undefined baselineShift?: number | string | undefined baseProfile?: number | string | undefined bbox?: number | string | undefined begin?: number | string | undefined bias?: number | string | undefined by?: number | string | undefined calcMode?: number | string | undefined capHeight?: number | string | undefined clip?: number | string | undefined clipPath?: string | undefined clipPathUnits?: number | string | undefined clipRule?: number | string | undefined colorInterpolation?: number | string | undefined colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit" | undefined colorProfile?: number | string | undefined colorRendering?: number | string | undefined contentScriptType?: number | string | undefined contentStyleType?: number | string | undefined cursor?: number | string | undefined cx?: number | string | undefined cy?: number | string | undefined d?: string | undefined decelerate?: number | string | undefined descent?: number | string | undefined diffuseConstant?: number | string | undefined direction?: number | string | undefined display?: number | string | undefined divisor?: number | string | undefined dominantBaseline?: number | string | undefined dur?: number | string | undefined dx?: number | string | undefined dy?: number | string | undefined edgeMode?: number | string | undefined elevation?: number | string | undefined enableBackground?: number | string | undefined end?: number | string | undefined exponent?: number | string | undefined externalResourcesRequired?: Booleanish | undefined fill?: string | undefined fillOpacity?: number | string | undefined fillRule?: "nonzero" | "evenodd" | "inherit" | undefined filter?: string | undefined filterRes?: number | string | undefined filterUnits?: number | string | undefined floodColor?: number | string | undefined floodOpacity?: number | string | undefined focusable?: Booleanish | "auto" | undefined fontFamily?: string | undefined fontSize?: number | string | undefined fontSizeAdjust?: number | string | undefined fontStretch?: number | string | undefined fontStyle?: number | string | undefined fontVariant?: number | string | undefined fontWeight?: number | string | undefined format?: number | string | undefined from?: number | string | undefined fx?: number | string | undefined fy?: number | string | undefined g1?: number | string | undefined g2?: number | string | undefined glyphName?: number | string | undefined glyphOrientationHorizontal?: number | string | undefined glyphOrientationVertical?: number | string | undefined glyphRef?: number | string | undefined gradientTransform?: string | undefined gradientUnits?: string | undefined hanging?: number | string | undefined horizAdvX?: number | string | undefined horizOriginX?: number | string | undefined href?: string | undefined ideographic?: number | string | undefined imageRendering?: number | string | undefined in2?: number | string | undefined in?: string | undefined intercept?: number | string | undefined k1?: number | string | undefined k2?: number | string | undefined k3?: number | string | undefined k4?: number | string | undefined k?: number | string | undefined kernelMatrix?: number | string | undefined kernelUnitLength?: number | string | undefined kerning?: number | string | undefined keyPoints?: number | string | undefined keySplines?: number | string | undefined keyTimes?: number | string | undefined lengthAdjust?: number | string | undefined letterSpacing?: number | string | undefined lightingColor?: number | string | undefined limitingConeAngle?: number | string | undefined local?: number | string | undefined markerEnd?: string | undefined markerHeight?: number | string | undefined markerMid?: string | undefined markerStart?: string | undefined markerUnits?: number | string | undefined markerWidth?: number | string | undefined mask?: string | undefined maskContentUnits?: number | string | undefined maskUnits?: number | string | undefined mathematical?: number | string | undefined mode?: number | string | undefined numOctaves?: number | string | undefined offset?: number | string | undefined opacity?: number | string | undefined operator?: number | string | undefined order?: number | string | undefined orient?: number | string | undefined orientation?: number | string | undefined origin?: number | string | undefined overflow?: number | string | undefined overlinePosition?: number | string | undefined overlineThickness?: number | string | undefined paintOrder?: number | string | undefined panose1?: number | string | undefined path?: string | undefined pathLength?: number | string | undefined patternContentUnits?: string | undefined patternTransform?: number | string | undefined patternUnits?: string | undefined pointerEvents?: number | string | undefined points?: string | undefined pointsAtX?: number | string | undefined pointsAtY?: number | string | undefined pointsAtZ?: number | string | undefined preserveAlpha?: Booleanish | undefined preserveAspectRatio?: string | undefined primitiveUnits?: number | string | undefined r?: number | string | undefined radius?: number | string | undefined refX?: number | string | undefined refY?: number | string | undefined renderingIntent?: number | string | undefined repeatCount?: number | string | undefined repeatDur?: number | string | undefined requiredExtensions?: number | string | undefined requiredFeatures?: number | string | undefined restart?: number | string | undefined result?: string | undefined rotate?: number | string | undefined rx?: number | string | undefined ry?: number | string | undefined scale?: number | string | undefined seed?: number | string | undefined shapeRendering?: number | string | undefined slope?: number | string | undefined spacing?: number | string | undefined specularConstant?: number | string | undefined specularExponent?: number | string | undefined speed?: number | string | undefined spreadMethod?: string | undefined startOffset?: number | string | undefined stdDeviation?: number | string | undefined stemh?: number | string | undefined stemv?: number | string | undefined stitchTiles?: number | string | undefined stopColor?: string | undefined stopOpacity?: number | string | undefined strikethroughPosition?: number | string | undefined strikethroughThickness?: number | string | undefined string?: number | string | undefined stroke?: string | undefined strokeDasharray?: string | number | undefined strokeDashoffset?: string | number | undefined strokeLinecap?: "butt" | "round" | "square" | "inherit" | undefined strokeLinejoin?: "miter" | "round" | "bevel" | "inherit" | undefined strokeMiterlimit?: number | string | undefined strokeOpacity?: number | string | undefined strokeWidth?: number | string | undefined surfaceScale?: number | string | undefined systemLanguage?: number | string | undefined tableValues?: number | string | undefined targetX?: number | string | undefined targetY?: number | string | undefined textAnchor?: string | undefined textDecoration?: number | string | undefined textLength?: number | string | undefined textRendering?: number | string | undefined to?: number | string | undefined transform?: string | undefined u1?: number | string | undefined u2?: number | string | undefined underlinePosition?: number | string | undefined underlineThickness?: number | string | undefined unicode?: number | string | undefined unicodeBidi?: number | string | undefined unicodeRange?: number | string | undefined unitsPerEm?: number | string | undefined vAlphabetic?: number | string | undefined values?: string | undefined vectorEffect?: number | string | undefined version?: string | undefined vertAdvY?: number | string | undefined vertOriginX?: number | string | undefined vertOriginY?: number | string | undefined vHanging?: number | string | undefined vIdeographic?: number | string | undefined viewBox?: string | undefined viewTarget?: number | string | undefined visibility?: number | string | undefined vMathematical?: number | string | undefined widths?: number | string | undefined wordSpacing?: number | string | undefined writingMode?: number | string | undefined x1?: number | string | undefined x2?: number | string | undefined x?: number | string | undefined xChannelSelector?: string | undefined xHeight?: number | string | undefined xlinkActuate?: string | undefined xlinkArcrole?: string | undefined xlinkHref?: string | undefined xlinkRole?: string | undefined xlinkShow?: string | undefined xlinkTitle?: string | undefined xlinkType?: string | undefined xmlBase?: string | undefined xmlLang?: string | undefined xmlns?: string | undefined xmlnsXlink?: string | undefined xmlSpace?: string | undefined y1?: number | string | undefined y2?: number | string | undefined y?: number | string | undefined yChannelSelector?: string | undefined z?: number | string | undefined zoomAndPan?: string | undefined } interface WebViewHTMLAttributes<T> extends HTMLAttributes<T> { allowFullScreen?: boolean | undefined allowpopups?: boolean | undefined autoFocus?: boolean | undefined autosize?: boolean | undefined blinkfeatures?: string | undefined disableblinkfeatures?: string | undefined disableguestresize?: boolean | undefined disablewebsecurity?: boolean | undefined guestinstance?: string | undefined httpreferrer?: string | undefined nodeintegration?: boolean | undefined partition?: string | undefined plugins?: boolean | undefined preload?: string | undefined src?: string | undefined useragent?: string | undefined webpreferences?: string | undefined } // // DOM // ---------------------------------------------------------------------- type ReactHTML = HTMLElementTagNameMap type HTMLWebViewElement = HTMLElement interface ReactSVG { animate: SVGFactory circle: SVGFactory clipPath: SVGFactory defs: SVGFactory desc: SVGFactory ellipse: SVGFactory feBlend: SVGFactory feColorMatrix: SVGFactory feComponentTransfer: SVGFactory feComposite: SVGFactory feConvolveMatrix: SVGFactory feDiffuseLighting: SVGFactory feDisplacementMap: SVGFactory feDistantLight: SVGFactory feDropShadow: SVGFactory feFlood: SVGFactory feFuncA: SVGFactory feFuncB: SVGFactory feFuncG: SVGFactory feFuncR: SVGFactory feGaussianBlur: SVGFactory feImage: SVGFactory feMerge: SVGFactory feMergeNode: SVGFactory feMorphology: SVGFactory feOffset: SVGFactory fePointLight: SVGFactory feSpecularLighting: SVGFactory feSpotLight: SVGFactory feTile: SVGFactory feTurbulence: SVGFactory filter: SVGFactory foreignObject: SVGFactory g: SVGFactory image: SVGFactory line: SVGFactory linearGradient: SVGFactory marker: SVGFactory mask: SVGFactory metadata: SVGFactory path: SVGFactory pattern: SVGFactory polygon: SVGFactory polyline: SVGFactory radialGradient: SVGFactory rect: SVGFactory stop: SVGFactory svg: SVGFactory switch: SVGFactory symbol: SVGFactory text: SVGFactory textPath: SVGFactory tspan: SVGFactory use: SVGFactory view: SVGFactory } export namespace JSX { type Element = ReactElement interface ElementAttributesProperty { props: {} } interface ElementChildrenAttribute { children: {} } interface IntrinsicAttributes extends Attributes {} interface IntrinsicClassAttributes<T> extends AttrWithRef<T> {} interface IntrinsicElements { // HTML a: DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> abbr: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> address: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> area: DetailedHTMLProps<AreaHTMLAttributes<HTMLAreaElement>, HTMLAreaElement> article: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> aside: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> audio: DetailedHTMLProps<AudioHTMLAttributes<HTMLAudioElement>, HTMLAudioElement> b: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> base: DetailedHTMLProps<BaseHTMLAttributes<HTMLBaseElement>, HTMLBaseElement> bdi: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> bdo: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> big: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> blockquote: DetailedHTMLProps<BlockquoteHTMLAttributes<HTMLElement>, HTMLElement> body: DetailedHTMLProps<HTMLAttributes<HTMLBodyElement>, HTMLBodyElement> br: DetailedHTMLProps<HTMLAttributes<HTMLBRElement>, HTMLBRElement> button: DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> canvas: DetailedHTMLProps<CanvasHTMLAttributes<HTMLCanvasElement>, HTMLCanvasElement> caption: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> cite: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> code: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> col: DetailedHTMLProps<ColHTMLAttributes<HTMLTableColElement>, HTMLTableColElement> colgroup: DetailedHTMLProps<ColgroupHTMLAttributes<HTMLTableColElement>, HTMLTableColElement> data: DetailedHTMLProps<DataHTMLAttributes<HTMLDataElement>, HTMLDataElement> datalist: DetailedHTMLProps<HTMLAttributes<HTMLDataListElement>, HTMLDataListElement> dd: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> del: DetailedHTMLProps<DelHTMLAttributes<HTMLElement>, HTMLElement> details: DetailedHTMLProps<DetailsHTMLAttributes<HTMLElement>, HTMLElement> dfn: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> dialog: DetailedHTMLProps<DialogHTMLAttributes<HTMLDialogElement>, HTMLDialogElement> div: DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> dl: DetailedHTMLProps<HTMLAttributes<HTMLDListElement>, HTMLDListElement> dt: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> em: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> embed: DetailedHTMLProps<EmbedHTMLAttributes<HTMLEmbedElement>, HTMLEmbedElement> fieldset: DetailedHTMLProps<FieldsetHTMLAttributes<HTMLFieldSetElement>, HTMLFieldSetElement> figcaption: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> figure: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> footer: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> form: DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement> h1: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> h2: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> h3: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> h4: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> h5: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> h6: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> head: DetailedHTMLProps<HTMLAttributes<HTMLHeadElement>, HTMLHeadElement> header: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> hgroup: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> hr: DetailedHTMLProps<HTMLAttributes<HTMLHRElement>, HTMLHRElement> html: DetailedHTMLProps<HtmlHTMLAttributes<HTMLHtmlElement>, HTMLHtmlElement> i: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> iframe: DetailedHTMLProps<IframeHTMLAttributes<HTMLIFrameElement>, HTMLIFrameElement> img: DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> input: DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> ins: DetailedHTMLProps<InsHTMLAttributes<HTMLModElement>, HTMLModElement> kbd: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> keygen: DetailedHTMLProps<KeygenHTMLAttributes<HTMLElement>, HTMLElement> label: DetailedHTMLProps<LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement> legend: DetailedHTMLProps<HTMLAttributes<HTMLLegendElement>, HTMLLegendElement> li: DetailedHTMLProps<LiHTMLAttributes<HTMLLIElement>, HTMLLIElement> link: DetailedHTMLProps<LinkHTMLAttributes<HTMLLinkElement>, HTMLLinkElement> main: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> map: DetailedHTMLProps<MapHTMLAttributes<HTMLMapElement>, HTMLMapElement> mark: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> menu: DetailedHTMLProps<MenuHTMLAttributes<HTMLElement>, HTMLElement> menuitem: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> meta: DetailedHTMLProps<MetaHTMLAttributes<HTMLMetaElement>, HTMLMetaElement> meter: DetailedHTMLProps<MeterHTMLAttributes<HTMLElement>, HTMLElement> nav: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> noindex: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> noscript: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> object: DetailedHTMLProps<ObjectHTMLAttributes<HTMLObjectElement>, HTMLObjectElement> ol: DetailedHTMLProps<OlHTMLAttributes<HTMLOListElement>, HTMLOListElement> optgroup: DetailedHTMLProps<OptgroupHTMLAttributes<HTMLOptGroupElement>, HTMLOptGroupElement> option: DetailedHTMLProps<OptionHTMLAttributes<HTMLOptionElement>, HTMLOptionElement> output: DetailedHTMLProps<OutputHTMLAttributes<HTMLElement>, HTMLElement> p: DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement> param: DetailedHTMLProps<ParamHTMLAttributes<HTMLParamElement>, HTMLParamElement> picture: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> pre: DetailedHTMLProps<HTMLAttributes<HTMLPreElement>, HTMLPreElement> progress: DetailedHTMLProps<ProgressHTMLAttributes<HTMLProgressElement>, HTMLProgressElement> q: DetailedHTMLProps<QuoteHTMLAttributes<HTMLQuoteElement>, HTMLQuoteElement> rp: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> rt: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> ruby: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> s: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> samp: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> script: DetailedHTMLProps<ScriptHTMLAttributes<HTMLScriptElement>, HTMLScriptElement> section: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> select: DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement> slot: DetailedHTMLProps<SlotHTMLAttributes<HTMLElement>, HTMLSlotElement> small: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> source: DetailedHTMLProps<SourceHTMLAttributes<HTMLSourceElement>, HTMLSourceElement> span: DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement> strong: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> style: DetailedHTMLProps<StyleHTMLAttributes<HTMLStyleElement>, HTMLStyleElement> sub: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> summary: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> sup: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> table: DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, HTMLTableElement> template: DetailedHTMLProps<HTMLAttributes<HTMLTemplateElement>, HTMLTemplateElement> tbody: DetailedHTMLProps<HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement> td: DetailedHTMLProps<TdHTMLAttributes<HTMLTableDataCellElement>, HTMLTableDataCellElement> textarea: DetailedHTMLProps<TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement> tfoot: DetailedHTMLProps<HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement> th: DetailedHTMLProps<ThHTMLAttributes<HTMLTableHeaderCellElement>, HTMLTableHeaderCellElement> thead: DetailedHTMLProps<HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement> time: DetailedHTMLProps<TimeHTMLAttributes<HTMLElement>, HTMLElement> title: DetailedHTMLProps<HTMLAttributes<HTMLTitleElement>, HTMLTitleElement> tr: DetailedHTMLProps<HTMLAttributes<HTMLTableRowElement>, HTMLTableRowElement> track: DetailedHTMLProps<TrackHTMLAttributes<HTMLTrackElement>, HTMLTrackElement> u: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> ul: DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement> var: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> video: DetailedHTMLProps<VideoHTMLAttributes<HTMLVideoElement>, HTMLVideoElement> wbr: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> webview: DetailedHTMLProps<WebViewHTMLAttributes<HTMLWebViewElement>, HTMLWebViewElement> // SVG svg: SVGProps<SVGSVGElement> animate: SVGProps<SVGElement> // TODO: It is SVGAnimateElement but is not in TypeScript's lib.dom.d.ts for now. animateMotion: SVGProps<SVGElement> animateTransform: SVGProps<SVGElement> // TODO: It is SVGAnimateTransformElement but is not in TypeScript's lib.dom.d.ts for now. circle: SVGProps<SVGCircleElement> clipPath: SVGProps<SVGClipPathElement> defs: SVGProps<SVGDefsElement> desc: SVGProps<SVGDescElement> ellipse: SVGProps<SVGEllipseElement> feBlend: SVGProps<SVGFEBlendElement> feColorMatrix: SVGProps<SVGFEColorMatrixElement> feComponentTransfer: SVGProps<SVGFEComponentTransferElement> feComposite: SVGProps<SVGFECompositeElement> feConvolveMatrix: SVGProps<SVGFEConvolveMatrixElement> feDiffuseLighting: SVGProps<SVGFEDiffuseLightingElement> feDisplacementMap: SVGProps<SVGFEDisplacementMapElement> feDistantLight: SVGProps<SVGFEDistantLightElement> feDropShadow: SVGProps<SVGFEDropShadowElement> feFlood: SVGProps<SVGFEFloodElement> feFuncA: SVGProps<SVGFEFuncAElement> feFuncB: SVGProps<SVGFEFuncBElement> feFuncG: SVGProps<SVGFEFuncGElement> feFuncR: SVGProps<SVGFEFuncRElement> feGaussianBlur: SVGProps<SVGFEGaussianBlurElement> feImage: SVGProps<SVGFEImageElement> feMerge: SVGProps<SVGFEMergeElement> feMergeNode: SVGProps<SVGFEMergeNodeElement> feMorphology: SVGProps<SVGFEMorphologyElement> feOffset: SVGProps<SVGFEOffsetElement> fePointLight: SVGProps<SVGFEPointLightElement> feSpecularLighting: SVGProps<SVGFESpecularLightingElement> feSpotLight: SVGProps<SVGFESpotLightElement> feTile: SVGProps<SVGFETileElement> feTurbulence: SVGProps<SVGFETurbulenceElement> filter: SVGProps<SVGFilterElement> foreignObject: SVGProps<SVGForeignObjectElement> g: SVGProps<SVGGElement> image: SVGProps<SVGImageElement> line: SVGProps<SVGLineElement> linearGradient: SVGProps<SVGLinearGradientElement> marker: SVGProps<SVGMarkerElement> mask: SVGProps<SVGMaskElement> metadata: SVGProps<SVGMetadataElement> mpath: SVGProps<SVGElement> path: SVGProps<SVGPathElement> pattern: SVGProps<SVGPatternElement> polygon: SVGProps<SVGPolygonElement> polyline: SVGProps<SVGPolylineElement> radialGradient: SVGProps<SVGRadialGradientElement> rect: SVGProps<SVGRectElement> stop: SVGProps<SVGStopElement> switch: SVGProps<SVGSwitchElement> symbol: SVGProps<SVGSymbolElement> text: SVGProps<SVGTextElement> textPath: SVGProps<SVGTextPathElement> tspan: SVGProps<SVGTSpanElement> use: SVGProps<SVGUseElement> view: SVGProps<SVGViewElement> } }
the_stack
import Decimal from "decimal.js-light"; import { SeedName, SEEDS } from "../types/crops"; import { InventoryItemName } from "../types/game"; import { Section } from "lib/utils/hooks/useScrollIntoView"; import { Flag, FLAGS } from "./flags"; import { marketRate } from "../lib/halvening"; import { KNOWN_IDS, KNOWN_ITEMS, LimitedItemType } from "."; import { OnChainLimitedItems } from "../lib/goblinMachine"; import { isArray } from "lodash"; export { FLAGS }; export type CraftAction = { type: "item.crafted"; item: InventoryItemName; amount: number; }; export type CraftableName = | LimitedItemName | Tool | SeedName | Food | Animal | Flag; export interface Craftable { name: CraftableName; description: string; price?: Decimal; ingredients: Ingredient[]; limit?: number; supply?: number; disabled?: boolean; requires?: InventoryItemName; section?: Section; } // NEW =========== export type Ingredient = { id?: number; item: InventoryItemName; amount: Decimal; }; export interface CraftableItem { id?: number; name: CraftableName; description: string; tokenAmount?: Decimal; ingredients?: Ingredient[]; disabled?: boolean; requires?: InventoryItemName; } export interface LimitedItem extends CraftableItem { maxSupply?: number; section?: Section; cooldownSeconds?: number; mintedAt?: number; type?: LimitedItemType; } export type BlacksmithItem = | "Sunflower Statue" | "Potato Statue" | "Christmas Tree" | "Gnome" | "Sunflower Tombstone" | "Sunflower Rock" | "Goblin Crown" | "Fountain" | "Woody the Beaver" | "Apprentice Beaver" | "Foreman Beaver" | "Nyon Statue" | "Homeless Tent" | "Egg Basket" | "Farmer Bath"; export type BarnItem = | "Farm Cat" | "Farm Dog" | "Chicken Coop" | "Gold Egg" | "Easter Bunny"; export type MarketItem = | "Nancy" | "Scarecrow" | "Kuebiko" | "Golden Cauliflower" | "Mysterious Parsnip" | "Carrot Sword"; export type LimitedItemName = BlacksmithItem | BarnItem | MarketItem | Flag; export type Tool = | "Axe" | "Pickaxe" | "Stone Pickaxe" | "Iron Pickaxe" | "Hammer" | "Rod"; export type Food = | "Pumpkin Soup" | "Roasted Cauliflower" | "Sauerkraut" | "Radish Pie"; export type Animal = "Chicken" | "Cow" | "Pig" | "Sheep"; export const FOODS: () => Record<Food, CraftableItem> = () => ({ "Pumpkin Soup": { name: "Pumpkin Soup", description: "A creamy soup that goblins love", tokenAmount: marketRate(3), ingredients: [ { item: "Pumpkin", amount: new Decimal(5), }, ], limit: 1, }, Sauerkraut: { name: "Sauerkraut", description: "Fermented cabbage", tokenAmount: marketRate(25), ingredients: [ { item: "Cabbage", amount: new Decimal(10), }, ], }, "Roasted Cauliflower": { name: "Roasted Cauliflower", description: "A Goblin's favourite", tokenAmount: marketRate(150), ingredients: [ { item: "Cauliflower", amount: new Decimal(30), }, ], }, "Radish Pie": { name: "Radish Pie", description: "Despised by humans, loved by goblins", tokenAmount: marketRate(300), ingredients: [ { item: "Radish", amount: new Decimal(60), }, ], }, }); export const TOOLS: Record<Tool, CraftableItem> = { Axe: { name: "Axe", description: "Used to collect wood", tokenAmount: new Decimal(1), ingredients: [], }, Pickaxe: { name: "Pickaxe", description: "Used to collect stone", tokenAmount: new Decimal(1), ingredients: [ { item: "Wood", amount: new Decimal(2), }, ], }, "Stone Pickaxe": { name: "Stone Pickaxe", description: "Used to collect iron", tokenAmount: new Decimal(2), ingredients: [ { item: "Wood", amount: new Decimal(3), }, { item: "Stone", amount: new Decimal(3), }, ], }, "Iron Pickaxe": { name: "Iron Pickaxe", description: "Used to collect gold", tokenAmount: new Decimal(5), ingredients: [ { item: "Wood", amount: new Decimal(5), }, { item: "Iron", amount: new Decimal(3), }, ], }, Hammer: { name: "Hammer", description: "Used to construct buildings", tokenAmount: new Decimal(5), ingredients: [ { item: "Wood", amount: new Decimal(5), }, { item: "Stone", amount: new Decimal(5), }, ], disabled: true, }, Rod: { name: "Rod", description: "Used to fish trout", tokenAmount: new Decimal(5), ingredients: [ { item: "Wood", amount: new Decimal(5), }, ], disabled: true, }, }; export const BLACKSMITH_ITEMS: Record<BlacksmithItem, LimitedItem> = { "Sunflower Statue": { name: "Sunflower Statue", description: "A symbol of the holy token", section: Section["Sunflower Statue"], type: LimitedItemType.BlacksmithItem, }, "Potato Statue": { name: "Potato Statue", description: "The OG potato hustler flex", section: Section["Potato Statue"], type: LimitedItemType.BlacksmithItem, }, "Christmas Tree": { name: "Christmas Tree", description: "Receive a Santa Airdrop on Christmas day", section: Section["Christmas Tree"], type: LimitedItemType.BlacksmithItem, }, Gnome: { name: "Gnome", description: "A lucky gnome", section: Section.Gnome, type: LimitedItemType.BlacksmithItem, }, "Homeless Tent": { name: "Homeless Tent", description: "A nice and cozy tent", section: Section.Tent, type: LimitedItemType.BlacksmithItem, }, "Sunflower Tombstone": { name: "Sunflower Tombstone", description: "In memory of Sunflower Farmers", section: Section["Sunflower Tombstone"], type: LimitedItemType.BlacksmithItem, }, "Sunflower Rock": { name: "Sunflower Rock", description: "The game that broke Polygon", section: Section["Sunflower Rock"], type: LimitedItemType.BlacksmithItem, }, "Goblin Crown": { name: "Goblin Crown", description: "Summon the leader of the Goblins", section: Section["Goblin Crown"], type: LimitedItemType.BlacksmithItem, }, Fountain: { name: "Fountain", description: "A relaxing fountain for your farm", section: Section.Fountain, type: LimitedItemType.BlacksmithItem, }, "Nyon Statue": { name: "Nyon Statue", description: "In memory of Nyon Lann", // TODO: Add section type: LimitedItemType.BlacksmithItem, }, "Farmer Bath": { name: "Farmer Bath", description: "A beetroot scented bath for the farmers", section: Section["Bath"], type: LimitedItemType.BlacksmithItem, }, "Woody the Beaver": { name: "Woody the Beaver", description: "Increase wood drops by 20%", section: Section.Beaver, type: LimitedItemType.BlacksmithItem, }, "Apprentice Beaver": { name: "Apprentice Beaver", description: "Trees recover 50% faster", section: Section.Beaver, type: LimitedItemType.BlacksmithItem, }, "Foreman Beaver": { name: "Foreman Beaver", description: "Cut trees without axes", section: Section.Beaver, type: LimitedItemType.BlacksmithItem, }, "Egg Basket": { name: "Egg Basket", description: "Gives access to the Easter Egg Hunt", type: LimitedItemType.BlacksmithItem, }, }; export const MARKET_ITEMS: Record<MarketItem, LimitedItem> = { Nancy: { name: "Nancy", description: "Keeps a few crows away. Crops grow 15% faster", section: Section.Scarecrow, type: LimitedItemType.MarketItem, }, Scarecrow: { name: "Scarecrow", description: "A goblin scarecrow. Yield 20% more crops", section: Section.Scarecrow, type: LimitedItemType.MarketItem, }, Kuebiko: { name: "Kuebiko", description: "Even the shopkeeper is scared of this scarecrow. Seeds are free", section: Section.Scarecrow, type: LimitedItemType.MarketItem, }, "Golden Cauliflower": { name: "Golden Cauliflower", description: "Double the rewards from cauliflowers", type: LimitedItemType.MarketItem, }, "Mysterious Parsnip": { name: "Mysterious Parsnip", description: "Parsnips grow 50% faster", type: LimitedItemType.MarketItem, }, "Carrot Sword": { name: "Carrot Sword", description: "Increase chance of a mutant crop appearing", type: LimitedItemType.MarketItem, }, }; export const BARN_ITEMS: Record<BarnItem, LimitedItem> = { "Chicken Coop": { name: "Chicken Coop", description: "Collect 3x the amount of eggs", section: Section["Chicken Coop"], type: LimitedItemType.BarnItem, }, "Farm Cat": { name: "Farm Cat", description: "Keep the rats away", section: Section["Farm Cat"], type: LimitedItemType.BarnItem, }, "Farm Dog": { name: "Farm Dog", description: "Herd sheep 4x faster", section: Section["Farm Dog"], type: LimitedItemType.BarnItem, }, "Gold Egg": { name: "Gold Egg", description: "A rare egg, what lays inside?", type: LimitedItemType.BarnItem, }, "Easter Bunny": { name: "Easter Bunny", description: "Earn 20% more Carrots", section: Section["Easter Bunny"], type: LimitedItemType.BarnItem, }, }; export const ANIMALS: Record<Animal, CraftableItem> = { Chicken: { name: "Chicken", description: "Produces eggs. Requires wheat for feeding", tokenAmount: new Decimal(5), ingredients: [], disabled: true, }, Cow: { name: "Cow", description: "Produces milk. Requires wheat for feeding", tokenAmount: new Decimal(50), ingredients: [], disabled: true, }, Pig: { name: "Pig", description: "Produces manure. Requires wheat for feeding", tokenAmount: new Decimal(20), ingredients: [], disabled: true, }, Sheep: { name: "Sheep", description: "Produces wool. Requires wheat for feeding", tokenAmount: new Decimal(20), ingredients: [], disabled: true, }, }; type Craftables = Record<CraftableName, CraftableItem>; export const CRAFTABLES: () => Craftables = () => ({ ...TOOLS, ...BLACKSMITH_ITEMS, ...BARN_ITEMS, ...MARKET_ITEMS, ...SEEDS(), ...FOODS(), ...ANIMALS, ...FLAGS, }); /** * getKeys is a ref to Object.keys, but the return is typed literally. */ export const getKeys = Object.keys as <T extends object>( obj: T ) => Array<keyof T>; export const LIMITED_ITEMS = { ...BLACKSMITH_ITEMS, ...BARN_ITEMS, ...MARKET_ITEMS, ...FLAGS, }; export const LIMITED_ITEM_NAMES = getKeys(LIMITED_ITEMS); export const makeLimitedItemsByName = ( items: Record<LimitedItemName, LimitedItem>, onChainItems: OnChainLimitedItems ) => { return getKeys(items).reduce((limitedItems, itemName) => { const name = itemName as LimitedItemName; // Get id form limited item name const id = KNOWN_IDS[name]; // Get onchain item based on id const onChainItem = onChainItems[id]; if (onChainItem) { const { tokenAmount, ingredientAmounts, ingredientIds, cooldownSeconds, maxSupply, mintedAt, enabled, } = onChainItem; // Build ingredients const ingredients = ingredientIds.map((id, index) => ({ id, item: KNOWN_ITEMS[id], amount: new Decimal(ingredientAmounts[index]), })); limitedItems[name] = { id: onChainItem.mintId, name, description: items[name].description, tokenAmount: new Decimal(tokenAmount), maxSupply, cooldownSeconds, ingredients, mintedAt, type: items[name].type, disabled: !enabled, }; } return limitedItems; // TODO: FIX TYPE }, {} as Record<CraftableName, LimitedItem>); }; export const filterLimitedItemsByType = ( type: LimitedItemType | LimitedItemType[], limitedItems: Record<LimitedItemName, LimitedItem> ) => { // Convert `obj` to a key/value array // `[['name', 'Luke Skywalker'], ['title', 'Jedi Knight'], ...]` const asArray = Object.entries(limitedItems); const filtered = asArray.filter(([_, value]) => { if (value.type && isArray(type)) { return type.includes(value.type); } return value.type === type; }); // Convert the key/value array back to an object: // `{ name: 'Luke Skywalker', title: 'Jedi Knight' }` return Object.fromEntries(filtered); }; export const isLimitedItem = (itemName: any) => { return !!getKeys(LIMITED_ITEMS).find( (limitedItemName) => limitedItemName === itemName ); };
the_stack
import { Mutable, Class, Arrays, Comparator, FromAny, Dictionary, MutableDictionary, Creatable, InitType, Initable, ConsumerType, Consumable, Consumer, } from "@swim/util"; import { Fastener, Property, Provider, ComponentFlags, ComponentInit, Component, } from "@swim/component"; import {WarpRef, WarpService, WarpProvider, DownlinkFastener} from "@swim/client"; import {RefreshService} from "../refresh/RefreshService"; import {RefreshProvider} from "../refresh/RefreshProvider"; import {SelectionService} from "../selection/SelectionService"; import {SelectionProvider} from "../selection/SelectionProvider"; import {ModelContext} from "./ModelContext"; import type {ModelObserver} from "./ModelObserver"; import {ModelRelation} from "./"; // forward import import {AnyTrait, TraitCreator, Trait} from "../"; // forward import import {TraitRelation} from "../"; // forward import /** @public */ export type ModelContextType<M extends Model> = M extends {readonly contextType?: Class<infer T>} ? T : never; /** @public */ export type ModelFlags = ComponentFlags; /** @public */ export type AnyModel<M extends Model = Model> = M | ModelFactory<M> | InitType<M>; /** @public */ export interface ModelInit extends ComponentInit { type?: Creatable<Model>; key?: string; traits?: AnyTrait[]; children?: AnyModel[]; } /** @public */ export interface ModelFactory<M extends Model = Model, U = AnyModel<M>> extends Creatable<M>, FromAny<M, U> { fromInit(init: InitType<M>): M; } /** @public */ export interface ModelClass<M extends Model = Model, U = AnyModel<M>> extends Function, ModelFactory<M, U> { readonly prototype: M; } /** @public */ export interface ModelConstructor<M extends Model = Model, U = AnyModel<M>> extends ModelClass<M, U> { new(): M; } /** @public */ export type ModelCreator<F extends (abstract new (...args: any) => M) & Creatable<InstanceType<F>>, M extends Model = Model> = (abstract new (...args: any) => InstanceType<F>) & Creatable<InstanceType<F>>; /** @public */ export class Model extends Component<Model> implements Initable<ModelInit>, Consumable { constructor() { super(); this.consumers = Arrays.empty; this.firstTrait = null; this.lastTrait = null; this.traitMap = null; } override get componentType(): Class<Model> { return Model; } override readonly observerType?: Class<ModelObserver>; /** @override */ readonly consumerType?: Class<Consumer>; readonly contextType?: Class<ModelContext>; protected override willAttachParent(parent: Model): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillAttachParent !== void 0) { observer.modelWillAttachParent(parent, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willAttachParent(parent); trait = next !== null && next.model === this ? next : null; } } protected override onAttachParent(parent: Model): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onAttachParent(parent); trait = next !== null && next.model === this ? next : null; } } protected override didAttachParent(parent: Model): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didAttachParent(parent); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidAttachParent !== void 0) { observer.modelDidAttachParent(parent, this); } } } protected override willDetachParent(parent: Model): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillDetachParent !== void 0) { observer.modelWillDetachParent(parent, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willDetachParent(parent); trait = next !== null && next.model === this ? next : null; } } protected override onDetachParent(parent: Model): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onDetachParent(parent); trait = next !== null && next.model === this ? next : null; } } protected override didDetachParent(parent: Model): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didDetachParent(parent); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidDetachParent !== void 0) { observer.modelDidDetachParent(parent, this); } } } override setChild<M extends Model>(key: string, newChild: M): Model | null; override setChild<F extends ModelCreator<F>>(key: string, factory: F): Model | null; override setChild(key: string, newChild: AnyModel | null): Model | null; override setChild(key: string, newChild: AnyModel | null): Model | null { if (newChild !== null) { newChild = Model.fromAny(newChild); } return super.setChild(key, newChild) as Model | null; } override appendChild<M extends Model>(child: M, key?: string): M; override appendChild<F extends ModelCreator<F>>(factory: F, key?: string): InstanceType<F>; override appendChild(child: AnyModel, key?: string): Model; override appendChild(child: AnyModel, key?: string): Model { child = Model.fromAny(child); return super.appendChild(child, key); } override prependChild<M extends Model>(child: M, key?: string): M; override prependChild<F extends ModelCreator<F>>(factory: F, key?: string): InstanceType<F>; override prependChild(child: AnyModel, key?: string): Model; override prependChild(child: AnyModel, key?: string): Model { child = Model.fromAny(child); return super.prependChild(child, key); } override insertChild<M extends Model>(child: M, target: Model | null, key?: string): M; override insertChild<F extends ModelCreator<F>>(factory: F, target: Model | null, key?: string): InstanceType<F>; override insertChild(child: AnyModel, target: Model | null, key?: string): Model; override insertChild(child: AnyModel, target: Model | null, key?: string): Model { child = Model.fromAny(child); return super.insertChild(child, target, key); } override replaceChild<M extends Model>(newChild: Model, oldChild: M): M; override replaceChild<M extends Model>(newChild: AnyModel, oldChild: M): M; override replaceChild(newChild: AnyModel, oldChild: Model): Model { newChild = Model.fromAny(newChild); return super.replaceChild(newChild, oldChild); } protected override willInsertChild(child: Model, target: Model | null): void { super.willInsertChild(child, target); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillInsertChild !== void 0) { observer.modelWillInsertChild(child, target, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willInsertChild(child, target); trait = next !== null && next.model === this ? next : null; } } protected override onInsertChild(child: Model, target: Model | null): void { super.onInsertChild(child, target); let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onInsertChild(child, target); trait = next !== null && next.model === this ? next : null; } } protected override didInsertChild(child: Model, target: Model | null): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didInsertChild(child, target); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidInsertChild !== void 0) { observer.modelDidInsertChild(child, target, this); } } super.didInsertChild(child, target); } /** @internal */ override cascadeInsert(updateFlags?: ModelFlags, modelContext?: ModelContext): void { if ((this.flags & Model.MountedFlag) !== 0) { if (updateFlags === void 0) { updateFlags = 0; } updateFlags |= this.flags & Model.UpdateMask; if ((updateFlags & Model.AnalyzeMask) !== 0) { if (modelContext === void 0) { modelContext = this.superModelContext; } this.cascadeAnalyze(updateFlags, modelContext); } } } protected override willRemoveChild(child: Model): void { super.willRemoveChild(child); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillRemoveChild !== void 0) { observer.modelWillRemoveChild(child, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willRemoveChild(child); trait = next !== null && next.model === this ? next : null; } } protected override onRemoveChild(child: Model): void { super.onRemoveChild(child); let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onRemoveChild(child); trait = next !== null && next.model === this ? next : null; } } protected override didRemoveChild(child: Model): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didRemoveChild(child); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidRemoveChild !== void 0) { observer.modelDidRemoveChild(child, this); } } super.didRemoveChild(child); } /** @internal */ override cascadeMount(): void { if ((this.flags & Model.MountedFlag) === 0) { this.willMount(); this.setFlags(this.flags | Model.MountedFlag); this.onMount(); this.mountTraits(); this.mountChildren(); this.didMount(); } else { throw new Error("already mounted"); } } protected override willMount(): void { super.willMount(); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillMount !== void 0) { observer.modelWillMount(this); } } } protected override onMount(): void { // subsume super this.requestUpdate(this, this.flags & Model.UpdateMask, false); this.requireUpdate(this.mountFlags); if (this.decoherent !== null && this.decoherent.length !== 0) { this.requireUpdate(Model.NeedsMutate); } this.mountFasteners(); if (this.consumers.length !== 0) { this.startConsuming(); } } protected override didMount(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidMount !== void 0) { observer.modelDidMount(this); } } super.didMount(); } /** @internal */ override cascadeUnmount(): void { if ((this.flags & Model.MountedFlag) !== 0) { this.willUnmount(); this.setFlags(this.flags & ~Model.MountedFlag); this.unmountChildren(); this.unmountTraits(); this.onUnmount(); this.didUnmount(); } else { throw new Error("already unmounted"); } } protected override willUnmount(): void { super.willUnmount(); const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillUnmount !== void 0) { observer.modelWillUnmount(this); } } } protected override onUnmount(): void { this.stopConsuming(); super.onUnmount(); } protected override didUnmount(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidUnmount !== void 0) { observer.modelDidUnmount(this); } } super.didUnmount(); } override requireUpdate(updateFlags: ModelFlags, immediate: boolean = false): void { const flags = this.flags; const deltaUpdateFlags = updateFlags & ~flags & Model.UpdateMask; if (deltaUpdateFlags !== 0) { this.setFlags(flags | deltaUpdateFlags); this.requestUpdate(this, deltaUpdateFlags, immediate); } } protected needsUpdate(updateFlags: ModelFlags, immediate: boolean): ModelFlags { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; updateFlags = trait.needsUpdate(updateFlags, immediate); trait = next !== null && next.model === this ? next : null; } return updateFlags; } requestUpdate(target: Model, updateFlags: ModelFlags, immediate: boolean): void { updateFlags = this.needsUpdate(updateFlags, immediate); let deltaUpdateFlags = this.flags & ~updateFlags & Model.UpdateMask; if ((updateFlags & Model.AnalyzeMask) !== 0) { deltaUpdateFlags |= Model.NeedsAnalyze; } if ((updateFlags & Model.RefreshMask) !== 0) { deltaUpdateFlags |= Model.NeedsRefresh; } if (deltaUpdateFlags !== 0 || immediate) { this.setFlags(this.flags | deltaUpdateFlags); const parent = this.parent; if (parent !== null) { parent.requestUpdate(target, updateFlags, immediate); } else if (this.mounted) { const refreshProvider = this.refreshProvider.service; if (refreshProvider !== void 0 && refreshProvider !== null) { refreshProvider.requestUpdate(target, updateFlags, immediate); } } } } get updating(): boolean { return (this.flags & Model.UpdatingMask) !== 0; } get analyzing(): boolean { return (this.flags & Model.AnalyzingFlag) !== 0; } protected needsAnalyze(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>): ModelFlags { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; analyzeFlags = trait.needsAnalyze(analyzeFlags, modelContext); trait = next !== null && next.model === this ? next : null; } return analyzeFlags; } cascadeAnalyze(analyzeFlags: ModelFlags, baesModelContext: ModelContext): void { const modelContext = this.extendModelContext(baesModelContext); const outerModelContext = ModelContext.current; try { ModelContext.current = modelContext; analyzeFlags &= ~Model.NeedsAnalyze; analyzeFlags |= this.flags & Model.UpdateMask; analyzeFlags = this.needsAnalyze(analyzeFlags, modelContext); if ((analyzeFlags & Model.AnalyzeMask) !== 0) { let cascadeFlags = analyzeFlags; this.setFlags(this.flags & ~Model.NeedsAnalyze | (Model.AnalyzingFlag | Model.ContextualFlag)); this.willAnalyze(cascadeFlags, modelContext); if (((this.flags | analyzeFlags) & Model.NeedsMutate) !== 0) { cascadeFlags |= Model.NeedsMutate; this.setFlags(this.flags & ~Model.NeedsMutate); this.willMutate(modelContext); } if (((this.flags | analyzeFlags) & Model.NeedsAggregate) !== 0) { cascadeFlags |= Model.NeedsAggregate; this.setFlags(this.flags & ~Model.NeedsAggregate); this.willAggregate(modelContext); } if (((this.flags | analyzeFlags) & Model.NeedsCorrelate) !== 0) { cascadeFlags |= Model.NeedsCorrelate; this.setFlags(this.flags & ~Model.NeedsCorrelate); this.willCorrelate(modelContext); } this.onAnalyze(cascadeFlags, modelContext); if ((cascadeFlags & Model.NeedsMutate) !== 0) { this.onMutate(modelContext); } if ((cascadeFlags & Model.NeedsAggregate) !== 0) { this.onAggregate(modelContext); } if ((cascadeFlags & Model.NeedsCorrelate) !== 0) { this.onCorrelate(modelContext); } if ((cascadeFlags & Model.AnalyzeMask) !== 0) { this.setFlags(this.flags & ~Model.ContextualFlag); this.analyzeChildren(cascadeFlags, modelContext, this.analyzeChild); this.setFlags(this.flags | Model.ContextualFlag); } if ((cascadeFlags & Model.NeedsCorrelate) !== 0) { this.didCorrelate(modelContext); } if ((cascadeFlags & Model.NeedsAggregate) !== 0) { this.didAggregate(modelContext); } if ((cascadeFlags & Model.NeedsMutate) !== 0) { this.didMutate(modelContext); } this.didAnalyze(cascadeFlags, modelContext); } } finally { this.setFlags(this.flags & ~(Model.AnalyzingFlag | Model.ContextualFlag)); ModelContext.current = outerModelContext; } } protected willAnalyze(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willAnalyze(analyzeFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected onAnalyze(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onAnalyze(analyzeFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected didAnalyze(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didAnalyze(analyzeFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected willMutate(modelContext: ModelContextType<this>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillMutate !== void 0) { observer.modelWillMutate(modelContext, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willMutate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected onMutate(modelContext: ModelContextType<this>): void { this.recohereFasteners(modelContext.updateTime); let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onMutate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected didMutate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didMutate(modelContext); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidMutate !== void 0) { observer.modelDidMutate(modelContext, this); } } } protected willAggregate(modelContext: ModelContextType<this>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillAggregate !== void 0) { observer.modelWillAggregate(modelContext, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willAggregate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected onAggregate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onAggregate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected didAggregate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didAggregate(modelContext); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidAggregate !== void 0) { observer.modelDidAggregate(modelContext, this); } } } protected willCorrelate(modelContext: ModelContextType<this>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillCorrelate !== void 0) { observer.modelWillCorrelate(modelContext, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willCorrelate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected onCorrelate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onCorrelate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected didCorrelate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didCorrelate(modelContext); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidCorrelate !== void 0) { observer.modelDidCorrelate(modelContext, this); } } } protected analyzeChildren(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>, analyzeChild: (this: this, child: Model, analyzeFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { const trait = this.firstTrait; if (trait !== null) { this.analyzeTraitChildren(trait, analyzeFlags, modelContext, analyzeChild); } else { this.analyzeOwnChildren(analyzeFlags, modelContext, analyzeChild); } } protected analyzeTraitChildren(trait: Trait, analyzeFlags: ModelFlags, modelContext: ModelContextType<this>, analyzeChild: (this: this, child: Model, analyzeFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { const next = trait.nextTrait; if (next !== null) { trait.analyzeChildren(analyzeFlags, modelContext, analyzeChild as any, this.analyzeTraitChildren.bind(this, next) as any); } else { trait.analyzeChildren(analyzeFlags, modelContext, analyzeChild as any, this.analyzeOwnChildren as any); } } protected analyzeOwnChildren(analyzeFlags: ModelFlags, modelContext: ModelContextType<this>, analyzeChild: (this: this, child: Model, analyzeFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; analyzeChild.call(this, child, analyzeFlags, modelContext); if (next !== null && next.parent !== this) { throw new Error("inconsistent analyze pass"); } child = next; } } protected analyzeChild(child: Model, analyzeFlags: ModelFlags, modelContext: ModelContextType<this>): void { child.cascadeAnalyze(analyzeFlags, modelContext); } get refreshing(): boolean { return (this.flags & Model.RefreshingFlag) !== 0; } protected needsRefresh(refreshFlags: ModelFlags, modelContext: ModelContextType<this>): ModelFlags { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; refreshFlags = trait.needsRefresh(refreshFlags, modelContext); trait = next !== null && next.model === this ? next : null; } return refreshFlags; } cascadeRefresh(refreshFlags: ModelFlags, baseModelContext: ModelContext): void { const modelContext = this.extendModelContext(baseModelContext); const outerModelContext = ModelContext.current; try { ModelContext.current = modelContext; refreshFlags &= ~Model.NeedsRefresh; refreshFlags |= this.flags & Model.UpdateMask; refreshFlags = this.needsRefresh(refreshFlags, modelContext); if ((refreshFlags & Model.RefreshMask) !== 0) { let cascadeFlags = refreshFlags; this.setFlags(this.flags & ~Model.NeedsRefresh | (Model.RefreshingFlag | Model.ContextualFlag)); this.willRefresh(cascadeFlags, modelContext); if (((this.flags | refreshFlags) & Model.NeedsValidate) !== 0) { cascadeFlags |= Model.NeedsValidate; this.setFlags(this.flags & ~Model.NeedsValidate); this.willValidate(modelContext); } if (((this.flags | refreshFlags) & Model.NeedsReconcile) !== 0) { cascadeFlags |= Model.NeedsReconcile; this.setFlags(this.flags & ~Model.NeedsReconcile); this.willReconcile(modelContext); } this.onRefresh(cascadeFlags, modelContext); if ((cascadeFlags & Model.NeedsValidate) !== 0) { this.onValidate(modelContext); } if ((cascadeFlags & Model.NeedsReconcile) !== 0) { this.onReconcile(modelContext); } if ((cascadeFlags & Model.RefreshMask)) { this.setFlags(this.flags & ~Model.ContextualFlag); this.refreshChildren(cascadeFlags, modelContext, this.refreshChild); this.setFlags(this.flags | Model.ContextualFlag); } if ((cascadeFlags & Model.NeedsReconcile) !== 0) { this.didReconcile(modelContext); } if ((cascadeFlags & Model.NeedsValidate) !== 0) { this.didValidate(modelContext); } this.didRefresh(cascadeFlags, modelContext); } } finally { this.setFlags(this.flags & ~(Model.RefreshingFlag | Model.ContextualFlag)); ModelContext.current = outerModelContext; } } protected willRefresh(refreshFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willRefresh(refreshFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected onRefresh(refreshFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onRefresh(refreshFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected didRefresh(refreshFlags: ModelFlags, modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didRefresh(refreshFlags, modelContext); trait = next !== null && next.model === this ? next : null; } } protected willValidate(modelContext: ModelContextType<this>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillValidate !== void 0) { observer.modelWillValidate(modelContext, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willValidate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected onValidate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onValidate(modelContext); trait = next !== null && next.model === this ? next : null; } } protected didValidate(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didValidate(modelContext); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidValidate !== void 0) { observer.modelDidValidate(modelContext, this); } } } protected willReconcile(modelContext: ModelContextType<this>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillReconcile !== void 0) { observer.modelWillReconcile(modelContext, this); } } let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.willReconcile(modelContext); trait = next !== null && next.model === this ? next : null; } } protected onReconcile(modelContext: ModelContextType<this>): void { this.recohereDownlinks(modelContext.updateTime); let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.onReconcile(modelContext); trait = next !== null && next.model === this ? next : null; } } protected didReconcile(modelContext: ModelContextType<this>): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.didReconcile(modelContext); trait = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidReconcile !== void 0) { observer.modelDidReconcile(modelContext, this); } } } protected refreshChildren(refreshFlags: ModelFlags, modelContext: ModelContextType<this>, refreshChild: (this: this, child: Model, refreshFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { const trait = this.firstTrait; if (trait !== null) { this.refreshTraitChildren(trait, refreshFlags, modelContext, refreshChild); } else { this.refreshOwnChildren(refreshFlags, modelContext, refreshChild); } } protected refreshTraitChildren(trait: Trait, refreshFlags: ModelFlags, modelContext: ModelContextType<this>, refreshChild: (this: this, child: Model, refreshFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { const next = trait.nextTrait; if (next !== null) { trait.refreshChildren(refreshFlags, modelContext, refreshChild as any, this.refreshTraitChildren.bind(this, next) as any); } else { trait.refreshChildren(refreshFlags, modelContext, refreshChild as any, this.refreshOwnChildren as any); } } protected refreshOwnChildren(refreshFlags: ModelFlags, modelContext: ModelContextType<this>, refreshChild: (this: this, child: Model, refreshFlags: ModelFlags, modelContext: ModelContextType<this>) => void): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; refreshChild.call(this, child, refreshFlags, modelContext); if (next !== null && next.parent !== this) { throw new Error("inconsistent refresh pass"); } child = next; } } protected refreshChild(child: Model, refreshFlags: ModelFlags, modelContext: ModelContextType<this>): void { child.cascadeRefresh(refreshFlags, modelContext); } readonly firstTrait: Trait | null; /** @internal */ setFirstTrait(firstTrait: Trait | null): void { (this as Mutable<this>).firstTrait = firstTrait; } readonly lastTrait: Trait | null; /** @internal */ setLastTrait(lastTrait: Trait | null): void { (this as Mutable<this>).lastTrait = lastTrait; } forEachTrait<T>(callback: (trait: Trait) => T | void): T | undefined; forEachTrait<T, S>(callback: (this: S, trait: Trait) => T | void, thisArg: S): T | undefined; forEachTrait<T, S>(callback: (this: S | undefined, trait: Trait) => T | void, thisArg?: S): T | undefined { let result: T | undefined; let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; const result = callback.call(thisArg, trait); if (result !== void 0) { break; } trait = next !== null && next.model === this ? next : null; } return result; } /** @internal */ readonly traitMap: Dictionary<Trait> | null; /** @internal */ protected insertTraitMap(trait: Trait): void { const key = trait.key; if (key !== void 0) { let traitMap = this.traitMap as MutableDictionary<Trait>; if (traitMap === null) { traitMap = {}; (this as Mutable<this>).traitMap = traitMap; } traitMap[key] = trait; } } /** @internal */ protected removeTraitMap(trait: Trait): void { const key = trait.key; if (key !== void 0) { const traitMap = this.traitMap as MutableDictionary<Trait>; if (traitMap !== null) { delete traitMap[key]; } } } getTrait<F extends abstract new (...args: any) => Trait>(key: string, traitBound: F): InstanceType<F> | null; getTrait(key: string, traitBound?: abstract new (...args: any) => Trait): Trait | null; getTrait<F extends abstract new (...args: any) => Trait>(traitBound: F): InstanceType<F> | null; getTrait(key: string | (abstract new (...args: any) => Trait), traitBound?: abstract new (...args: any) => Trait): Trait | null { if (typeof key === "string") { const traitMap = this.traitMap; if (traitMap !== null) { const trait = traitMap[key]; if (trait !== void 0 && (traitBound === void 0 || trait instanceof traitBound)) { return trait; } } } else { let trait = this.firstTrait; while (trait !== null) { if (trait instanceof key) { return trait; } trait = (trait as Trait).nextTrait; } } return null; } setTrait<T extends Trait>(key: string, newTrait: T): Trait | null; setTrait<F extends TraitCreator<F>>(key: string, factory: F): Trait | null; setTrait(key: string, newTrait: AnyTrait | null): Trait | null; setTrait(key: string, newTrait: AnyTrait | null): Trait | null { if (newTrait !== null) { newTrait = Trait.fromAny(newTrait); } const oldTrait = this.getTrait(key); let target: Trait | null; if (oldTrait !== null && newTrait !== null && oldTrait !== newTrait) { // replace newTrait.remove(); target = oldTrait.nextTrait; this.willRemoveTrait(oldTrait); oldTrait.detachModel(this); this.removeTraitMap(oldTrait); this.onRemoveTrait(oldTrait); this.didRemoveTrait(oldTrait); oldTrait.setKey(void 0); newTrait.setKey(oldTrait.key); this.willInsertTrait(newTrait, target); this.insertTraitMap(newTrait); newTrait.attachModel(this, target); this.onInsertTrait(newTrait, target); this.didInsertTrait(newTrait, target); } else if (newTrait !== oldTrait || newTrait !== null && newTrait.key !== key) { if (oldTrait !== null) { // remove target = oldTrait.nextTrait; this.willRemoveTrait(oldTrait); oldTrait.detachModel(this); this.removeTraitMap(oldTrait); this.onRemoveTrait(oldTrait); this.didRemoveTrait(oldTrait); oldTrait.setKey(void 0); } else { target = null; } if (newTrait !== null) { // insert newTrait.remove(); newTrait.setKey(key); this.willInsertTrait(newTrait, target); this.insertTraitMap(newTrait); newTrait.attachModel(this, target); this.onInsertTrait(newTrait, target); this.didInsertTrait(newTrait, target); } } return oldTrait; } appendTrait<T extends Trait>(trait: T, key?: string): T; appendTrait<F extends TraitCreator<F>>(factory: F, key?: string): InstanceType<F>; appendTrait(trait: AnyTrait, key?: string): Trait; appendTrait(trait: AnyTrait, key?: string): Trait { trait = Trait.fromAny(trait); trait.remove(); if (key !== void 0) { this.removeChild(key); } trait.setKey(key); this.willInsertTrait(trait, null); this.insertTraitMap(trait); trait.attachModel(this, null); this.onInsertTrait(trait, null); this.didInsertTrait(trait, null); return trait; } prependTrait<T extends Trait>(trait: T, key?: string): T; prependTrait<F extends TraitCreator<F>>(factory: F, key?: string): InstanceType<F>; prependTrait(trait: AnyTrait, key?: string): Trait; prependTrait(trait: AnyTrait, key?: string): Trait { trait = Trait.fromAny(trait); trait.remove(); if (key !== void 0) { this.removeChild(key); } const target = this.firstTrait; trait.setKey(key); this.willInsertTrait(trait, target); this.insertTraitMap(trait); trait.attachModel(this, target); this.onInsertTrait(trait, target); this.didInsertTrait(trait, target); return trait; } insertTrait<T extends Trait>(trait: T, target: Trait | null, key?: string): T; insertTrait<F extends TraitCreator<F>>(factory: F, target: Trait | null, key?: string): InstanceType<F>; insertTrait(trait: AnyTrait, target: Trait | null, key?: string): Trait; insertTrait(trait: AnyTrait, target: Trait | null, key?: string): Trait { if (target !== null && target.model !== this) { throw new Error("insert target is not a member trait"); } trait = Trait.fromAny(trait); trait.remove(); if (key !== void 0) { this.removeChild(key); } trait.setKey(key); this.willInsertTrait(trait, target); this.insertTraitMap(trait); trait.attachModel(this, target); this.onInsertTrait(trait, target); this.didInsertTrait(trait, target); return trait; } replaceTrait<T extends Trait>(newTrait: Trait, oldTrait: T): T; replaceTrait<T extends Trait>(newTrait: AnyTrait, oldTrait: T): T; replaceTrait(newTrait: AnyTrait, oldTrait: Trait): Trait { if (oldTrait.model !== this) { throw new Error("replacement target is not a member trait"); } newTrait = Trait.fromAny(newTrait); if (newTrait !== oldTrait) { newTrait.remove(); const target = oldTrait.nextTrait; this.willRemoveTrait(oldTrait); oldTrait.detachModel(this); this.removeTraitMap(oldTrait); this.onRemoveTrait(oldTrait); this.didRemoveTrait(oldTrait); oldTrait.setKey(void 0); newTrait.setKey(oldTrait.key); this.willInsertTrait(newTrait, target); this.insertTraitMap(newTrait); newTrait.attachModel(this, target); this.onInsertTrait(newTrait, target); this.didInsertTrait(newTrait, target); } return oldTrait; } get insertTraitFlags(): ModelFlags { return (this.constructor as typeof Model).InsertTraitFlags; } protected willInsertTrait(trait: Trait, target: Trait | null): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillInsertTrait !== void 0) { observer.modelWillInsertTrait(trait, target, this); } } let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.willInsertTrait(trait, target); } prev = next !== null && next.model === this ? next : null; } } protected onInsertTrait(trait: Trait, target: Trait | null): void { this.requireUpdate(this.insertTraitFlags); this.bindTraitFasteners(trait, target); let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.onInsertTrait(trait, target); } prev = next !== null && next.model === this ? next : null; } } protected didInsertTrait(trait: Trait, target: Trait | null): void { let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.didInsertTrait(trait, target); } prev = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidInsertTrait !== void 0) { observer.modelDidInsertTrait(trait, target, this); } } } removeTrait<T extends Trait>(trait: T): T; removeTrait(key: string | Trait): Trait | null; removeTrait(key: string | Trait): Trait | null { let trait: Trait | null; if (typeof key === "string") { trait = this.getTrait(key); if (trait === null) { return null; } } else { trait = key; if (trait.model !== this) { throw new Error("not a member trait"); } } this.willRemoveTrait(trait); trait.detachModel(this); this.removeTraitMap(trait); this.onRemoveTrait(trait); this.didRemoveTrait(trait); trait.setKey(void 0); return trait; } get removeTraitFlags(): ModelFlags { return (this.constructor as typeof Model).RemoveTraitFlags; } protected willRemoveTrait(trait: Trait): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillRemoveTrait !== void 0) { observer.modelWillRemoveTrait(trait, this); } } let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.willRemoveTrait(trait); } prev = next !== null && next.model === this ? next : null; } } protected onRemoveTrait(trait: Trait): void { this.requireUpdate(this.removeTraitFlags); let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.onRemoveTrait(trait); } prev = next !== null && next.model === this ? next : null; } this.unbindTraitFasteners(trait); } protected didRemoveTrait(trait: Trait): void { let prev = this.firstTrait; while (prev !== null) { const next = prev.nextTrait; if (prev !== trait) { prev.didRemoveTrait(trait); } prev = next !== null && next.model === this ? next : null; } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidRemoveTrait !== void 0) { observer.modelDidRemoveTrait(trait, this); } } } sortTraits(comparator: Comparator<Trait>): void { let trait = this.firstTrait; if (trait !== null) { const traits: Trait[] = []; do { traits.push(trait); trait = trait.nextTrait; } while (trait !== null); traits.sort(comparator); trait = traits[0]!; this.setFirstTrait(trait); trait.setPreviousTrait(null); for (let i = 1; i < traits.length; i += 1) { const next = traits[i]!; trait.setNextTrait(next); next.setPreviousTrait(trait); trait = next; } trait.setNextTrait(null); this.setLastTrait(trait); } } /** @internal */ protected mountTraits(): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.mountTrait(); if (next !== null && next.model !== this) { throw new Error("inconsistent mount"); } trait = next; } } /** @internal */ protected unmountTraits(): void { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; trait.unmountTrait(); if (next !== null && next.model !== this) { throw new Error("inconsistent unmount"); } trait = next; } } getSuperTrait<F extends abstract new (...args: any) => Trait>(superBound: F): InstanceType<F> | null { const parent = this.parent; if (parent === null) { return null; } else { const trait = parent.getTrait(superBound); if (trait !== null) { return trait; } else { return parent.getSuperTrait(superBound); } } } getBaseTrait<F extends abstract new (...args: any) => Trait>(baseBound: F): InstanceType<F> | null { const parent = this.parent; if (parent === null) { return null; } else { const baseTrait = parent.getBaseTrait(baseBound); if (baseTrait !== null) { return baseTrait; } else { return parent.getTrait(baseBound); } } } protected override bindFastener(fastener: Fastener): void { super.bindFastener(fastener); if (fastener instanceof TraitRelation && fastener.binds) { let trait = this.firstTrait; while (trait !== null) { const next = trait.nextTrait; fastener.bindTrait(trait, next); trait = next !== null && next.model === this ? next : null; } } if (fastener instanceof DownlinkFastener && fastener.consumed === true && this.consuming) { fastener.consume(this); } } /** @internal */ protected override bindChildFastener(fastener: Fastener, child: Model, target: Model | null): void { super.bindChildFastener(fastener, child, target); if (fastener instanceof ModelRelation || fastener instanceof TraitRelation) { fastener.bindModel(child, target); } } /** @internal */ protected override unbindChildFastener(fastener: Fastener, child: Model): void { if (fastener instanceof ModelRelation || fastener instanceof TraitRelation) { fastener.unbindModel(child); } super.unbindChildFastener(fastener, child); } /** @internal */ protected bindTraitFasteners(trait: Trait, target: Trait | null): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; this.bindTraitFastener(fastener, trait, target); } } /** @internal */ protected bindTraitFastener(fastener: Fastener, trait: Trait, target: Trait | null): void { if (fastener instanceof TraitRelation) { fastener.bindTrait(trait, target); } } /** @internal */ protected unbindTraitFasteners(trait: Trait): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; this.unbindTraitFastener(fastener, trait); } } /** @internal */ protected unbindTraitFastener(fastener: Fastener, trait: Trait): void { if (fastener instanceof TraitRelation) { fastener.unbindTrait(trait); } } /** @internal @override */ override decohereFastener(fastener: Fastener): void { super.decohereFastener(fastener); if (fastener instanceof DownlinkFastener) { this.requireUpdate(Model.NeedsReconcile); } else { this.requireUpdate(Model.NeedsMutate); } } /** @internal */ override recohereFasteners(t?: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { if (t === void 0) { t = performance.now(); } (this as Mutable<this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; if (!(fastener instanceof DownlinkFastener)) { fastener.recohere(t); } else { this.decohereFastener(fastener); } } } } } /** @internal */ recohereDownlinks(t: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { (this as Mutable<this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; if (fastener instanceof DownlinkFastener) { fastener.recohere(t); } else { this.decohereFastener(fastener); } } } } } /** @internal */ readonly consumers: ReadonlyArray<ConsumerType<this>>; /** @override */ consume(consumer: ConsumerType<this>): void { const oldConsumers = this.consumers; const newConsumers = Arrays.inserted(consumer, oldConsumers); if (oldConsumers !== newConsumers) { this.willConsume(consumer); (this as Mutable<this>).consumers = newConsumers; this.onConsume(consumer); this.didConsume(consumer); if (oldConsumers.length === 0 && this.mounted) { this.startConsuming(); } } } protected willConsume(consumer: ConsumerType<this>): void { // hook } protected onConsume(consumer: ConsumerType<this>): void { // hook } protected didConsume(consumer: ConsumerType<this>): void { // hook } /** @override */ unconsume(consumer: ConsumerType<this>): void { const oldConsumers = this.consumers; const newConsumers = Arrays.removed(consumer, oldConsumers); if (oldConsumers !== newConsumers) { this.willUnconsume(consumer); (this as Mutable<this>).consumers = newConsumers; this.onUnconsume(consumer); this.didUnconsume(consumer); if (newConsumers.length === 0) { this.stopConsuming(); } } } protected willUnconsume(consumer: ConsumerType<this>): void { // hook } protected onUnconsume(consumer: ConsumerType<this>): void { // hook } protected didUnconsume(consumer: ConsumerType<this>): void { // hook } get consuming(): boolean { return (this.flags & Model.ConsumingFlag) !== 0; } get startConsumingFlags(): ModelFlags { return (this.constructor as typeof Model).StartConsumingFlags; } protected startConsuming(): void { if ((this.flags & Model.ConsumingFlag) === 0) { this.willStartConsuming(); this.setFlags(this.flags | Model.ConsumingFlag); this.onStartConsuming(); this.didStartConsuming(); } } protected willStartConsuming(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillStartConsuming !== void 0) { observer.modelWillStartConsuming(this); } } } protected onStartConsuming(): void { this.requireUpdate(this.startConsumingFlags); this.startConsumingFasteners(); } protected didStartConsuming(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidStartConsuming !== void 0) { observer.modelDidStartConsuming(this); } } } get stopConsumingFlags(): ModelFlags { return (this.constructor as typeof Model).StopConsumingFlags; } protected stopConsuming(): void { if ((this.flags & Model.ConsumingFlag) !== 0) { this.willStopConsuming(); this.setFlags(this.flags & ~Model.ConsumingFlag); this.onStopConsuming(); this.didStopConsuming(); } } protected willStopConsuming(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelWillStopConsuming !== void 0) { observer.modelWillStopConsuming(this); } } } protected onStopConsuming(): void { this.requireUpdate(this.stopConsumingFlags); this.stopConsumingFasteners(); } protected didStopConsuming(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.modelDidStopConsuming !== void 0) { observer.modelDidStopConsuming(this); } } } /** @internal */ protected startConsumingFasteners(): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; if (fastener instanceof DownlinkFastener && fastener.consumed === true) { fastener.consume(this); } } } /** @internal */ protected stopConsumingFasteners(): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; if (fastener instanceof DownlinkFastener && fastener.consumed === true) { fastener.unconsume(this); } } } @Provider({ extends: RefreshProvider, type: RefreshService, observes: false, service: RefreshService.global(), }) readonly refreshProvider!: RefreshProvider<this>; @Provider({ extends: SelectionProvider, type: SelectionService, observes: false, service: SelectionService.global(), }) readonly selectionProvider!: SelectionProvider<this>; @Provider({ extends: WarpProvider, type: WarpService, observes: false, service: WarpService.global(), }) readonly warpProvider!: WarpProvider<this>; @Property({type: Object, inherits: true, value: null, updateFlags: Model.NeedsReconcile}) readonly warpRef!: Property<this, WarpRef | null>; /** @internal */ get superModelContext(): ModelContext { const parent = this.parent; if (parent !== null) { return parent.modelContext; } else { return this.refreshProvider.updatedModelContext(); } } /** @internal */ extendModelContext(modelContext: ModelContext): ModelContextType<this> { return modelContext as ModelContextType<this>; } get modelContext(): ModelContextType<this> { if ((this.flags & Model.ContextualFlag) !== 0) { return ModelContext.current as ModelContextType<this>; } else { return this.extendModelContext(this.superModelContext); } } /** @override */ override init(init: ModelInit): void { // hook } static override create<S extends new () => InstanceType<S>>(this: S): InstanceType<S> { return new this(); } static override fromInit<S extends abstract new (...args: any) => InstanceType<S>>(this: S, init: InitType<InstanceType<S>>): InstanceType<S> { let type: Creatable<Model>; if ((typeof init === "object" && init !== null || typeof init === "function") && Creatable.is((init as ModelInit).type)) { type = (init as ModelInit).type!; } else { type = this as unknown as Creatable<Model>; } const view = type.create(); view.init(init as ModelInit); return view as InstanceType<S>; } static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyModel<InstanceType<S>>): InstanceType<S> { if (value === void 0 || value === null) { return value as InstanceType<S>; } else if (value instanceof Model) { if (value instanceof this) { return value; } else { throw new TypeError(value + " not an instance of " + this); } } else if (Creatable.is(value)) { return (value as Creatable<InstanceType<S>>).create(); } else { return (this as unknown as ModelFactory<InstanceType<S>>).fromInit(value); } } /** @internal */ static override uid: () => number = (function () { let nextId = 1; return function uid(): number { const id = ~~nextId; nextId += 1; return id; } })(); /** @internal */ static override readonly MountedFlag: ModelFlags = Component.MountedFlag; /** @internal */ static override readonly RemovingFlag: ModelFlags = Component.RemovingFlag; /** @internal */ static readonly AnalyzingFlag: ModelFlags = 1 << (Component.FlagShift + 0); /** @internal */ static readonly RefreshingFlag: ModelFlags = 1 << (Component.FlagShift + 1); /** @internal */ static readonly ContextualFlag: ModelFlags = 1 << (Component.FlagShift + 2); /** @internal */ static readonly ConsumingFlag: ModelFlags = 1 << (Component.FlagShift + 3); /** @internal */ static readonly UpdatingMask: ModelFlags = Model.AnalyzingFlag | Model.RefreshingFlag; /** @internal */ static readonly StatusMask: ModelFlags = Model.MountedFlag | Model.RemovingFlag | Model.AnalyzingFlag | Model.RefreshingFlag | Model.ContextualFlag | Model.ConsumingFlag; static readonly NeedsAnalyze: ModelFlags = 1 << (Component.FlagShift + 4); static readonly NeedsMutate: ModelFlags = 1 << (Component.FlagShift + 5); static readonly NeedsAggregate: ModelFlags = 1 << (Component.FlagShift + 6); static readonly NeedsCorrelate: ModelFlags = 1 << (Component.FlagShift + 7); /** @internal */ static readonly AnalyzeMask: ModelFlags = Model.NeedsAnalyze | Model.NeedsMutate | Model.NeedsAggregate | Model.NeedsCorrelate; static readonly NeedsRefresh: ModelFlags = 1 << (Component.FlagShift + 8); static readonly NeedsValidate: ModelFlags = 1 << (Component.FlagShift + 9); static readonly NeedsReconcile: ModelFlags = 1 << (Component.FlagShift + 10); /** @internal */ static readonly RefreshMask: ModelFlags = Model.NeedsRefresh | Model.NeedsValidate | Model.NeedsReconcile; /** @internal */ static readonly UpdateMask: ModelFlags = Model.AnalyzeMask | Model.RefreshMask; /** @internal */ static override readonly FlagShift: number = Component.FlagShift + 11; /** @internal */ static override readonly FlagMask: ModelFlags = (1 << Model.FlagShift) - 1; static override readonly MountFlags: ModelFlags = 0; static override readonly InsertChildFlags: ModelFlags = 0; static override readonly RemoveChildFlags: ModelFlags = 0; static readonly InsertTraitFlags: ModelFlags = 0; static readonly RemoveTraitFlags: ModelFlags = 0; static readonly StartConsumingFlags: ModelFlags = 0; static readonly StopConsumingFlags: ModelFlags = 0; }
the_stack
import { Constants, Message, OldMessage, TextChannel } from 'eris'; import { Inject, Subscribe } from '@augu/lilith'; import { LoggingEvents } from '../entities/LoggingEntity'; import { EmbedBuilder } from '../structures'; import CommandService from '../services/CommandService'; import AutomodService from '../services/AutomodService'; import { Color } from '../util/Constants'; import Database from '../components/Database'; import Discord from '../components/Discord'; const HTTP_REGEX = /^https?:\/\/(.*)/; export default class MessageListener { @Inject private readonly commands!: CommandService; @Inject private readonly automod!: AutomodService; @Inject private readonly database!: Database; @Inject private readonly discord!: Discord; @Subscribe('messageCreate', { emitter: 'discord' }) onMessageCreate(msg: Message<TextChannel>) { return this.commands.handleCommand(msg); } @Subscribe('messageDelete', { emitter: 'discord' }) async onMessageDelete(msg: Message<TextChannel>) { if (!msg.author || ![0, 5].includes(msg.channel.type)) return; const settings = await this.database.logging.get(msg.guildID); if (!settings.enabled || !settings.events.includes(LoggingEvents.MessageDeleted)) return; if (settings.ignoreChannels.length > 0 && settings.ignoreChannels.includes(msg.channel.id)) return; if (settings.ignoreUsers.length > 0 && settings.ignoreUsers.includes(msg.author.id)) return; if ( settings.channelID !== undefined && (!msg.channel.guild.channels.has(settings.channelID) || !msg.channel.guild.channels .get<TextChannel>(settings.channelID) ?.permissionsOf(this.discord.client.user.id) .has('sendMessages')) ) return; if (msg.content.indexOf('pinned a message') !== -1) return; if (msg.author.id === this.discord.client.user.id) return; if (msg.author.system) return; // It's in a closure so we don't have to use `return;` on the outer scope const auditLog = await (async () => { if (!msg.channel.guild.members.get(this.discord.client.user.id)?.permissions.has('viewAuditLogs')) return undefined; const audits = await msg.channel.guild.getAuditLog({ limit: 3, actionType: Constants.AuditLogActions.MESSAGE_DELETE, }); return audits.entries.find( (entry) => entry.targetID === msg.author.id && entry.user.id !== msg.author.id && entry.user.id !== this.discord.client.user.id ); })(); const channel = msg.channel.guild.channels.get<TextChannel>(settings.channelID!); const author = msg.author.system ? 'System' : `${msg.author.username}#${msg.author.discriminator}`; const embed = new EmbedBuilder().setColor(Color); if (auditLog !== undefined) embed.setFooter( `Message was actually deleted by ${auditLog.user.username}#${auditLog.user.discriminator} (${auditLog.user.id})` ); if (msg.embeds.length > 0) { const em = msg.embeds[0]; if (em.author) embed.setAuthor(em.author.name, em.author.url, em.author.icon_url); if (em.description) embed.setDescription(em.description.length > 2000 ? `${em.description.slice(0, 1993)}...` : em.description); if (em.fields && em.fields.length > 0) { for (const field of em.fields) embed.addField(field.name, field.value, field.inline || false); } if (em.footer) { const footer = embed.footer; embed.setFooter( footer !== undefined ? `${em.footer.text} (${footer.text})` : em.footer.text, em.footer.icon_url ); } if (em.title) embed.setTitle(em.title); if (em.url) embed.setURL(em.url); } else { embed.setDescription( msg.content.length > 1997 ? `${msg.content.slice(0, 1995)}...` : msg.content || 'Nothing was provided (probably attachments)' ); } return channel.createMessage({ content: `**[** A message was deleted by **${author}** (⁄ ⁄•⁄ω⁄•⁄ ⁄) in <#${msg.channel.id}> **]**`, embed: embed.build(), }); } @Subscribe('messageUpdate', { emitter: 'discord' }) async onMessageUpdate(msg: Message<TextChannel>, old: OldMessage | null) { await this.automod.run('message', msg); if (old === null) return; if (old.content === msg.content) return; // discord is shit send help please if (old.pinned && !msg.pinned) return; if (msg.content !== old.content) await this.commands.handleCommand(msg); const result = await this.automod.run('message', msg); if (result) return; const settings = await this.database.logging.get(msg.channel.guild.id); if (!settings.enabled || !settings.events.includes(LoggingEvents.MessageUpdated)) return; if (settings.ignoreChannels.length > 0 && settings.ignoreChannels.includes(msg.channel.id)) return; if (settings.ignoreUsers.length > 0 && settings.ignoreUsers.includes(msg.author.id)) return; if ( settings.channelID !== undefined && (!msg.channel.guild.channels.has(settings.channelID) || !msg.channel.guild.channels .get<TextChannel>(settings.channelID) ?.permissionsOf(this.discord.client.user.id) .has('sendMessages')) ) return; if (msg.content.indexOf('pinned a message') !== -1) return; if (msg.author.id === this.discord.client.user.id) return; // discord being shit part 2 if (HTTP_REGEX.test(old.content)) return; const channel = msg.channel.guild.channels.get<TextChannel>(settings.channelID!); const author = msg.author.system ? 'System' : `${msg.author.username}#${msg.author.discriminator}`; const jumpUrl = `https://discord.com/channels/${msg.guildID}/${msg.channel.id}/${msg.id}`; const embed = new EmbedBuilder() .setColor(Color) .setDescription(`**[[Jump Here]](${jumpUrl})**`) .addFields([ { name: '❯ Old Message Content', value: old.content || 'Nothing was provided (probably attachments?)', inline: false, }, { name: '❯ Message Content', value: msg.content || 'Nothing was provided?', }, ]); return channel.createMessage({ content: `**[** A message was updated by **${author}** (⁄ ⁄•⁄ω⁄•⁄ ⁄) in <#${msg.channel.id}> **]**`, embed: embed.build(), }); } @Subscribe('messageDeleteBulk', { emitter: 'discord' }) async onMessageDeleteBulk(messages: Message<TextChannel>[]) { const allMsgs = messages .filter((msg) => msg.guildID !== undefined) .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()); const msg = allMsgs[0]; const settings = await this.database.logging.get(msg.channel.guild.id); if (!settings.enabled || !settings.events.includes(LoggingEvents.MessageUpdated)) return; if (!settings.channelID) return; if (!msg.channel.guild) return; if ( !msg.channel.guild.channels.has(settings.channelID) || !msg.channel.guild.channels .get<TextChannel>(settings.channelID) ?.permissionsOf(this.discord.client.user.id) .has('sendMessages') ) return; const buffers: Buffer[] = []; for (let i = 0; i < allMsgs.length; i++) { const msg = allMsgs[i]; // skip all that don't have an author if (!msg.author) continue; const contents = [ `♥*♡∞:。.。 [ Message #${i + 1} / ${allMsgs.length} ] 。.。:∞♡*♥`, `❯ Created At: ${new Date(msg.createdAt).toUTCString()}`, `❯ Author : ${msg.author.username}#${msg.author.discriminator}`, `❯ Channel : #${msg.channel.name} (${msg.channel.id})`, '', ]; if (msg.embeds.length > 0) { contents.push(msg.content); contents.push('\n'); for (let j = 0; j < msg.embeds.length; j++) { const embed = msg.embeds[j]; let content = `[ Embed ${j + 1}/${msg.embeds.length} ]\n`; if (embed.author !== undefined) content += `❯ ${embed.author.name}${embed.author.url !== undefined ? ` (${embed.author.url})` : ''}\n`; if (embed.title !== undefined) content += `❯ ${embed.title}${embed.url !== undefined ? ` (${embed.url})` : ''}\n`; if (embed.description !== undefined) content += `${embed.description}\n\n`; if (embed.fields !== undefined) content += embed.fields.map((field) => `• ${field.name}: ${field.value}`).join('\n') + '\n'; if (embed.footer !== undefined) content += `${embed.footer.text}${ embed.timestamp !== undefined ? ` (${(embed.timestamp instanceof Date ? embed.timestamp : new Date(embed.timestamp)).toUTCString()})` : '' }`; contents.push(content, '\n'); } } else { contents.push(msg.content, '\n'); } buffers.push(Buffer.from(contents.join('\n'))); } // Don't do anything if we can't create a message if (buffers.length > 0) return; const buffer = Buffer.concat(buffers); const channel = msg.channel.guild.channels.get<TextChannel>(settings.channelID!); const users: string[] = [...new Set(allMsgs.map((m) => `${m.author.username}#${m.author.discriminator}`))]; const embed = new EmbedBuilder() .setColor(Color) .setDescription([ `${allMsgs.length} messages were deleted in ${msg.channel.mention}, view the file below to read all messages`, '', '```apache', `❯ Messages Deleted ~> ${allMsgs.length}/${messages.length} (${( (allMsgs.length / messages.length) * 100 ).toFixed(1)}% cached)`, `❯ Affected Users ~> ${users.join(', ')}`, '```', ]); await Promise.all([ channel.createMessage({ embed: embed.build() }), channel.createMessage('', { file: buffer, name: `trace_${Date.now()}.txt`, }), ]); } }
the_stack
import * as React from 'react'; import { IPropertyFieldMaskedInputPropsInternal } from './PropertyFieldMaskedInput'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import 'office-ui-fabric-react/lib/components/TextField/TextField.scss'; /** * @interface * PropertyFieldMaskedInputHost properties interface * */ export interface IPropertyFieldMaskedInputHostProps extends IPropertyFieldMaskedInputPropsInternal { } /** * @interface * Defines the masked input properties * */ interface IMaskedInputProps { type?: string; id?: string; placeholder?: string; className?: string; pattern?: string; maxLength?: string; title?: string; label?: string; dataCharset?: string; required?: boolean; value?: string; initialValue?: string; onChange?(newValue?: string): void; disabled?: boolean; onGetErrorMessage?: (value: string) => string | Promise<string>; deferredValidationTime?: number; } /** * @interface * Defines the state of masked input control * */ interface IMaskedInputState { firstLoading?: boolean; value?: string; errorMessage: string; } /** * @interface * MaskedInput control. * This control is a fork of the input masking component available on GitHub * https://github.com/estelle/input-masking * by Estelle Weyl. & Alex Schmitz (c) * */ class MaskedInput extends React.Component<IMaskedInputProps, IMaskedInputState> { private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; constructor(props: IPropertyFieldMaskedInputHostProps) { super(props); //Binds events this.handleChange = this.handleChange.bind(this); this.handleFocus = this.handleFocus.bind(this); this.handleBlur = this.handleBlur.bind(this); //Inits default value this.state = { firstLoading: true, errorMessage: '', value: this.props.initialValue != null ? this.props.initialValue : '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } public componentDidMount(): void { var e = this.refs['inputShell']; var event = { target: e }; this.handleChange(event); } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } private handleChange(e): void { var previousValue = this.state.value; e.target.value = this.handleCurrentValue(e); this.state.value = e.target.value; if (this.state.firstLoading === true && previousValue == '') this.state.value = ''; this.state.firstLoading = false; this.setState(this.state); this.delayedValidate(e.target.value); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(newValue: string) { if (this.props.onChange != null) this.props.onChange(newValue); } private handleCurrentValue(e): string { var isCharsetPresent = e.target.getAttribute('data-charset'), maskedNumber = 'XMDY', maskedLetter = '_', placeholder = isCharsetPresent || e.target.getAttribute('data-placeholder'), value = e.target.value, l = placeholder.length, newValue = '', i, j, isInt, isLetter, strippedValue, matchesNumber, matchesLetter; // strip special characters strippedValue = isCharsetPresent ? value.replace(/\W/g, "") : value.replace(/\D/g, ""); for (i = 0, j = 0; i < l; i++) { isInt = !isNaN(parseInt(strippedValue[j])); isLetter = strippedValue[j] ? strippedValue[j].match(/[A-Z]/i) : false; matchesNumber = (maskedNumber.indexOf(placeholder[i]) >= 0); matchesLetter = (maskedLetter.indexOf(placeholder[i]) >= 0); if ((matchesNumber && isInt) || (isCharsetPresent && matchesLetter && isLetter)) { newValue += strippedValue[j++]; } else if ((!isCharsetPresent && !isInt && matchesNumber) || (isCharsetPresent && ((matchesLetter && !isLetter) || (matchesNumber && !isInt)))) { //this.options.onError( e ); // write your own error handling function return newValue; } else { newValue += placeholder[i]; } // break if no characters left and the pattern is non-special character if (strippedValue[j] == undefined) { break; } } if (this.props['data-valid-example']) { return this.validateProgress(e, newValue); } return newValue; }; private validateProgress(e, value): string { var validExample = this.props['data-valid-example'], pattern = new RegExp(this.props.pattern), placeholder = e.target.getAttribute('data-placeholder'), l = value.length, testValue = '', i; //convert to months if ((l == 1) && (placeholder.toUpperCase().substr(0,2) == 'MM')) { if(value > 1 && value < 10) { value = '0' + value; } return value; } for ( i = l; i >= 0; i--) { testValue = value + validExample.substr(value.length); if (pattern.test(testValue)) { return value; } else { value = value.substr(0, value.length-1); } } return value; }; private handleBlur(e): void { var currValue = e.target.value, pattern; // if value is empty, remove label parent class if(currValue.length == 0) { if(e.target.required) { this.updateLabelClass(e, "required", true); this.handleError(e, 'required'); } } else { pattern = new RegExp('^' + this.props.pattern + '$'); if(pattern.test(currValue)) { this.updateLabelClass(e, "good", true); } else { this.updateLabelClass(e, "error", true); this.handleError(e, 'invalidValue'); } } }; private handleFocus(e): void { this.updateLabelClass(e, 'focus', false); }; private updateLabelClass(e, className, replaceExistingClass): void { var parentLI = e.target.parentNode.parentNode, pastClasses = ['error', 'required', 'focus', 'good'], i; if (replaceExistingClass) { for(i = 0; i < pastClasses.length; i++) { parentLI.classList.remove(pastClasses[i]); } } parentLI.classList.add(className); }; private handleError(e, errorMsg): boolean { return true; }; public render(): JSX.Element { var props = { type: (this.props && this.props.type) || '' , id: this.props.id, placeholder: this.props.placeholder, className: "masked " + (this.props.className || ''), pattern: this.props.pattern, maxLength: this.props.pattern.length, title: this.props.title, label: this.props.label, dataCharset: this.props['data-charset'], required: this.props.required, initialValue: this.props.initialValue, disabled: this.props.disabled }; var shellStyle = { position: 'relative', lineHeight: '1', }; var shellStyleSpan = { position: 'absolute', left: '12px', top: '3px', color: '#ccc', pointerEvents: 'none', fontSize: '16px', fontFamily: 'monospace', paddingRight: '10px', backgroundColor: 'transparent', textTransform: 'uppercase' }; var shellStyleSpanI = { fontStyle: 'normal', color: 'transparent', //opacity: '0', visibility: 'hidden' }; var inputShell = { fontSize: '16px', fontFamily: 'monospace', paddingRight: '10px', backgroundColor: 'transparent', textTransform: 'uppercase', boxSizing: 'border-box', margin: '0', boxShadow: 'none', border: '1px solid #c8c8c8', borderRadius: '0', fontWeight: 400, color: '#333333', height: '32px', padding: '0 12px 0 12px', width: '100%', outline: '0', textOverflow: 'ellipsis' }; var placeHolderContent = props.placeholder.substr(this.state.value.length); return ( <div> <span style={shellStyle}> <span style={shellStyleSpan} aria-hidden="true" ref="spanMask" id={props.id + 'Mask'}><i style={shellStyleSpanI}>{this.state.value}</i>{placeHolderContent}</span> <input style={inputShell} id={props.id} ref="inputShell" disabled={props.disabled} onChange={this.handleChange} onFocus={this.handleFocus} onBlur={this.handleBlur} name={props.id} //type={props.type} className={props.className} data-placeholder={props.placeholder} data-pattern={props.pattern} aria-required={props.required} data-charset={props.dataCharset} required={props.required} value={this.state.value} title={props.title}/> </span> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); }; } /** * @class * Renders the controls for PropertyFieldMaskedInput component */ export default class PropertyFieldMaskedInputHost extends React.Component<IPropertyFieldMaskedInputHostProps, {}> { /** * @function * Constructor */ constructor(props: IPropertyFieldMaskedInputHostProps) { super(props); //Bind the current object to the external called onSelectDate method this.onValueChanged = this.onValueChanged.bind(this); } /** * @function * Function called when the the text changed */ private onValueChanged(element: string): void { //Checks if there is a method to called if (this.props.onPropertyChange && element != null) { this.props.properties[this.props.targetProperty] = element; this.props.onPropertyChange(this.props.targetProperty, this.props.initialValue, element); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Renders the controls */ public render(): JSX.Element { //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <MaskedInput id="tel" type="tel" disabled={this.props.disabled} placeholder={this.props.placeholder} pattern={this.props.pattern} className="ms-TextField-field" maxLength={this.props.maxLength} onChange={this.onValueChanged} initialValue={this.props.initialValue} onGetErrorMessage={this.props.onGetErrorMessage} deferredValidationTime={this.props.deferredValidationTime} /> </div> ); } }
the_stack
import {Component, OnInit, Input, Output, EventEmitter, OnChanges, SimpleChanges, ViewChildren} from '@angular/core'; import * as _ from 'lodash'; import {LoggerService} from '../services/logger.service'; import {animate, group, query, style, transition, trigger} from '@angular/animations'; import { RefactorFieldsService } from '../../shared/services/refactor-fields.service'; @Component({ selector: 'app-data-table', templateUrl: './data-table.component.html', styleUrls: ['./data-table.component.css'], animations: [ trigger('tableCarousel', [ transition('* => right', [ group([ query('[currentTable]', [ style({ transform: 'translateX(100%)', }), animate('.35s ease-in-out', style({ transform: 'translateX(0%)', })) ], {optional: true}), query('[previousTable]', [ style({ transform: 'translateX(0%)', }), animate('.35s ease-in-out', style({ transform: 'translateX(-100%)', })) ], {optional: true}) ]) ]), transition('* => left', [ group([ query('[currentTable]', [ style({ transform: 'translateX(-100%)', position: 'absolute' }), animate('.35s ease-in-out', style({ transform: 'translateX(0%)', })) ], {optional: true}), query('[previousTable]', [ style({ transform: 'translateX(0%)', }), animate('.35s ease-in-out', style({ transform: 'translateX(100%)', })) ], {optional: true}) ]) ]), ]) ] }) export class DataTableComponent implements OnInit, OnChanges { constructor( private refactorFieldsService: RefactorFieldsService, private logger: LoggerService) { } @ViewChildren('filteredArray') filteredItems = null; @Input() dataHead; @Input() searchableHeader; @Input() heightValue; @Input() outerArr: any = []; @Input() showingArr: any = []; @Input() allColumns: any = []; @Input() totalRows: any; @Input() firstPaginator: number; @Input() lastPaginator: number; @Input() currentPointer: number; @Input() headerColName = ''; @Input() direction = 0; @Input() paginatorAbsent = false; @Input() tabFilterProperty; @Input() cbModel; @Input() checkBox; @Input() columnWhiteList; @Input() buttonsArr; @Input() searchTextValues = ''; @Input() popRows: any; @Input() parentName: any; @Input() buttonColumn; @Input() errorValue: any; @Input() showGenericMessage: any; @Input() tableIdAppend: any; @Input() searchPassed = ''; @Input() checkedList = []; @Output() selectedRow = new EventEmitter<any>(); @Output() menuClick = new EventEmitter<any>(); @Output() searchRowTxt = new EventEmitter<any>(); @Output() noScrollDetected = new EventEmitter<any>(); @Output() searchTriggerred = new EventEmitter<any>(); @Output() previousPageCalled = new EventEmitter<any>(); @Output() tabSelected = new EventEmitter<any>(); @Output() nextPageCalled = new EventEmitter<any>(); @Output() cbClicked = new EventEmitter<any>(); @Output() rowClickText = new EventEmitter<string>(); errorMessage = 'apiResponseError'; indexSelected: number; sortArr: any = []; rowDetails: any = []; rowIndex = -1; noMinHeight = false; rowObj: any = {}; searchVal = ''; loaded = false; seekdata = false; showError = false; scrollEnabled = false; private rowAccessProperty = 'text'; private allTableData; private tabsData; public filteredColumns = []; public animationState; public previousTableData = []; public currentTableData = []; ngOnInit() { this.noMinHeight = false; this.seekdata = false; if ((this.outerArr !== undefined) && (this.outerArr.length !== 0)) { this.currentTableData = this.outerArr; this.allTableData = this.outerArr; if (this.tabFilterProperty) { this.tabsData = _(this.allTableData) .map((row: any) => { return row[this.tabFilterProperty]; }) .filter((row) => { return !!row[this.rowAccessProperty]; }) .uniqBy((row) => { return row[this.rowAccessProperty]; }) .value(); for (let index = 0; index < this.tabsData.length; index++ ) { this.tabsData[index]['displayName'] = this.refactorFieldsService.getDisplayNameForAKey(this.tabsData[index]['text'].toLowerCase()) || this.tabsData[index]['text']; } } this.restrictShownColumns(this.columnWhiteList); for (let column_index = 0; column_index < this.allColumns.length; column_index++) { this.sortArr[column_index] = { 'showUp': undefined, 'direction': 0 }; } this.loaded = true; } else { this.seekdata = true; this.showError = true; if (this.showGenericMessage === true) { this.errorMessage = 'apiResponseError'; } else { if (this.searchTextValues === '') { this.errorMessage = this.parentName; } else { this.errorMessage = 'dataTableMessage'; } } } } ngOnChanges(changes: SimpleChanges) { const graphDataChange = changes['allColumns']; const dataChange = changes['outerArr']; const errorChange = changes['showGenericMessage']; const errorMsg = changes['parentName']; const errorValueChange = changes['errorValue']; const searchTextChnage = changes['searchTextValues']; if (dataChange) { const cur = JSON.stringify(dataChange.currentValue); const prev = JSON.stringify(dataChange.previousValue); if ((cur !== prev) && (this.allColumns)) { this.ngOnInit(); } } if (graphDataChange) { const cur = JSON.stringify(graphDataChange.currentValue); const prev = JSON.stringify(graphDataChange.previousValue); if ((cur !== prev) && (this.allColumns)) { this.ngOnInit(); } } if (errorChange) { const cur = JSON.stringify(errorChange.currentValue); const prev = JSON.stringify(errorChange.previousValue); if ((cur !== prev)) { this.ngOnInit(); } } if (searchTextChnage) { const cur = JSON.stringify(searchTextChnage.currentValue); const prev = JSON.stringify(searchTextChnage.previousValue); if ((cur !== prev)) { this.ngOnInit(); } } if (errorMsg) { const cur = errorMsg.currentValue; this.errorMessage = cur; } if (errorValueChange) { if (errorValueChange && (errorValueChange.currentValue === 0 || this.errorValue.currentValue === -1)) { this.currentTableData = []; } } this.isSeeMore(); } changeTabSelection(event) { const tab = event.tab; this.tabSelected.emit(tab); if (event.direction === 'right') { this.animationState = event.direction; } this.previousTableData = this.currentTableData; if (tab) { const list = _.filter(this.allTableData, (row) => { return tab[this.rowAccessProperty] === row[this.tabFilterProperty][this.rowAccessProperty]; }); this.currentTableData = list; } else { this.currentTableData = this.allTableData; } this.scrollEnabled = true; setTimeout(() => { this.animationState = null; }, 400); } headerClicked(index, header) { this.rowIndex = -1; for (let i = 0; i < this.sortArr.length; i++) { if (i !== index) { this.sortArr[i].showUp = undefined; this.sortArr[i].direction = 0; } else { if (this.sortArr[i].direction === 0) { this.sortArr[i].direction = 1; } else { this.sortArr[i].direction = this.sortArr[i].direction * -1; } this.direction = this.sortArr[i].direction; } } this.indexSelected = index; this.headerColName = header; } tableRowClicked(rowDetails, index) { this.rowDetails = []; this.rowObj = {}; this.rowObj = rowDetails; this.rowDetails = Object.keys(this.rowObj); this.rowIndex = index; } goToDetails(thisRow, thisCol) { const details = { row: '', col: '' }; details.row = thisRow; details.col = thisCol; this.selectedRow.emit(details); } searchCalled(searchQuery) { this.searchRowTxt.emit(searchQuery); this.searchVal = searchQuery; } callCheckbox(i, row) { const data = {}; data['index'] = i; data['data'] = row; this.cbClicked.emit(data); } triggerSearch() { this.noMinHeight = false; this.searchTriggerred.emit(); } prevPage() { if (this.currentPointer > 0) { this.previousPageCalled.emit(); } } nextPage() { if (this.lastPaginator < this.totalRows) { this.nextPageCalled.emit(); } } isSeeMore() { try { setTimeout(() => { const a = document.getElementsByClassName('data-table-inner-content data-table-current'); const b = document.getElementsByClassName('data-table-inner-wrap relative'); if (a[0] && b[0]) { if (a[0].clientHeight && b[0].clientHeight) { if (a[0].clientHeight > b[0].clientHeight) { this.scrollEnabled = false; } else { this.scrollEnabled = true; if (this.currentTableData.length) { this.noMinHeight = true; this.noScrollDetected.emit(this.noMinHeight); } } } } }, 20); } catch (e) { this.logger.log('error', 'js error - ' + e); } } restrictShownColumns(columnNames) { if (columnNames) { const list = _.filter(columnNames, (whiteListedColumn) => { return _.find(this.allColumns, (column) => { return whiteListedColumn.toLowerCase() === column.toLowerCase(); }); }); this.filteredColumns = list; } else { this.filteredColumns = this.allColumns; } } emitRowText(rowClickText) { this.rowClickText.emit(rowClickText); } menuClicked(row, menu) { const obj = {}; obj['data'] = row; obj['type'] = menu; this.menuClick.emit(obj); row.dropDownShown = false; } }
the_stack
import { switchMode, getIsMarkdown, getMenu, clearEditor, hasClass, editorSelector, isElementVisible, elementExists, typeText, } from "../e2e-helpers"; const boldMenuButtonSelector = ".js-bold-btn"; const insertLinkMenuItemSelector = ".js-insert-link-btn"; const linkViewTooltipSelector = ".js-link-tooltip"; const removeLinkSelector = ".js-link-tooltip-remove"; const getMarkdownContent = async () => { const wasMarkdownModeActive = await getIsMarkdown(); await switchMode(true); const text = await page.innerText(editorSelector); if (!wasMarkdownModeActive) { await switchMode(false); } return text; }; const enterTextAsMarkdown = async (text: string) => { await clearEditor(); await switchMode(true); await typeText(text); await switchMode(false); }; describe("rich-text mode", () => { beforeAll(async () => { await switchMode(false); }); it("should show toggle switch", async () => { const isMarkdown = await getIsMarkdown(); expect(isMarkdown).toBeFalsy(); }); it("should render menu bar", async () => { const menu = await getMenu(); expect(menu).not.toBeNull(); }); it("should highlight bold menu button after click", async () => { await clearEditor(); expect(await hasClass(boldMenuButtonSelector, "is-selected")).toBe( false ); await page.click(boldMenuButtonSelector); expect(await hasClass(boldMenuButtonSelector, "is-selected")).toBe( true ); }); describe("input rules", () => { it.each([`"`, "...", "--"])( "should not transform special characters", async (input) => { await typeText(input); const text = await page.innerText(editorSelector); expect(text).toBe(input); } ); it.each([ // valid rules ["1. ", "ordered_list"], ["2) ", "ordered_list"], ["- ", "bullet_list"], ["+ ", "bullet_list"], ["* ", "bullet_list"], ["> ", "blockquote"], [">! ", "spoiler"], ["# ", "heading"], ["## ", "heading"], ["### ", "heading"], ["```", "code_block"], // invalid rules ["10. ", "paragraph"], ["#### ", "paragraph"], ])( "should create a node on input '%s'", async (input, expectedNodeType) => { await clearEditor(); await typeText(input); // TODO HACK don't use the debugging instance on window since it is unique to our specific view // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const doc = await page.evaluate(() => // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any (<any>window).editorInstance.editorView.state.doc.toJSON() ); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(doc.content[0].type).toBe(expectedNodeType); } ); it.each([ // valid inline mark rules ["**bold** ", "strong"], ["*emphasis* ", "em"], ["__bold__ ", "strong"], ["_emphasis_ ", "em"], ["`code` ", "code"], ["[a link](https://example.com)", "link"], ])( "should create a mark on input '%s'", async (input, expectedMarkType) => { await clearEditor(); const simulateTyping = true; await typeText(input, simulateTyping); // TODO HACK don't use the debugging instance on window since it is unique to our specific view // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const doc = await page.evaluate(() => // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any (<any>window).editorInstance.editorView.state.doc.toJSON() ); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(doc.content[0].content[0].marks[0].type).toContain( expectedMarkType ); } ); it.each([ // invalid followed by valid ["__nope_ _match_", 1], ["**nope* *match*", 1], // invalid, folled by valid, but duplicate text ["__test_ _test_", 1], ["**test* *test*", 1], // no match ["**test*", -1], ["__test_", -1], ])( "should handle strong vs weak emphasis marks (%s)", async (input, matchIndex) => { await clearEditor(); await typeText(input, true); // TODO HACK don't use the debugging instance on window since it is unique to our specific view // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const doc = await page.evaluate(() => // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any (<any>window).editorInstance.editorView.state.doc.toJSON() ); // consider a matchIndex of -1 to mean "should not match" let mark = "em"; if (matchIndex === -1) { mark = undefined; } // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(doc.content[0].content[matchIndex]?.marks[0].type).toBe( mark ); } ); it("should validate links for link input rule", async () => { await clearEditor(); const simulateTyping = true; await typeText("[invalid link](example)", simulateTyping); // TODO HACK don't use the debugging instance on window since it is unique to our specific view // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const doc = await page.evaluate(() => // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-explicit-any (<any>window).editorInstance.editorView.state.doc.toJSON() ); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access expect(doc.content[0].content[0].marks).toBeUndefined(); }); }); describe("editing images", () => { const imagePopoverSelector = ".js-img-popover"; it("should show image popover when selecting an image", async () => { await enterTextAsMarkdown( "![an image](https://localhost/some-image)" ); expect( await page.$eval(imagePopoverSelector, (el) => el.classList.contains("is-visible") ) ).toBe(false); await page.click(".js-editor img"); expect( await page.$eval(imagePopoverSelector, (el) => el.classList.contains("is-visible") ) ).toBe(true); }); it("should hide image popover when deselecting an image", async () => { await enterTextAsMarkdown( "![an image](https://localhost/some-image)" ); await page.click(".js-editor img"); // select image await page.click(boldMenuButtonSelector); // deselect image expect( await page.$eval(imagePopoverSelector, (el) => el.classList.contains("is-visible") ) ).toBe(false); }); }); describe("editing links", () => { it("should insert a link for selected text when clicking menu item", async () => { await clearEditor(); expect(await elementExists(linkViewTooltipSelector)).toBe(false); await typeText("some link here"); // select some text await page.keyboard.down("Shift"); await page.press(editorSelector, "ArrowLeft"); await page.press(editorSelector, "ArrowLeft"); await page.press(editorSelector, "ArrowLeft"); await page.keyboard.up("Shift"); await page.click(insertLinkMenuItemSelector); expect(await isElementVisible(linkViewTooltipSelector)).toBe(true); }); it("should show link popover when selecting a link", async () => { // enter a link in markdown mode and switch back to rich text mode await enterTextAsMarkdown("[a link](https://example.com/a-link)"); expect(await elementExists(linkViewTooltipSelector)).toBe(false); await page.press(editorSelector, "ArrowRight"); expect(await isElementVisible(linkViewTooltipSelector)).toBe(true); expect(await page.innerText(linkViewTooltipSelector)).toEqual( "https://example.com/a-link" ); }); it("should hide link popover when deselecting a link", async () => { await enterTextAsMarkdown("[a link](https://example.com/a-link)"); await page.press(editorSelector, "ArrowRight"); // select link await page.press(editorSelector, "ArrowLeft"); // and deselect again expect(await elementExists(linkViewTooltipSelector)).toBe(false); }); it("should remove link mark when clicking popover action", async () => { await enterTextAsMarkdown("[a link](https://example.com/a-link)"); expect(await getMarkdownContent()).toEqual( "[a link](https://example.com/a-link)" ); await page.press(editorSelector, "ArrowRight"); // select link await page.click(removeLinkSelector); expect(await getMarkdownContent()).toEqual("a link"); }); }); });
the_stack
import * as ts from "typescript"; import * as lua from "../../../LuaAST"; import { cast } from "../../../utils"; import { TransformationContext } from "../../context"; import { validateAssignment } from "../../utils/assignment-validation"; import { createExportedIdentifier, getDependenciesOfSymbol, isSymbolExported } from "../../utils/export"; import { createUnpackCall, wrapInTable } from "../../utils/lua-ast"; import { LuaLibFeature, transformLuaLibFunction } from "../../utils/lualib"; import { isArrayType, isDestructuringAssignment } from "../../utils/typescript"; import { isArrayLength, transformDestructuringAssignment } from "./destructuring-assignments"; import { isMultiReturnCall } from "../language-extensions/multi"; import { notAllowedOptionalAssignment } from "../../utils/diagnostics"; import { transformElementAccessArgument } from "../access"; import { moveToPrecedingTemp, transformExpressionList } from "../expression-list"; import { transformInPrecedingStatementScope } from "../../utils/preceding-statements"; export function transformAssignmentLeftHandSideExpression( context: TransformationContext, node: ts.Expression, rightHasPrecedingStatements?: boolean ): lua.AssignmentLeftHandSideExpression { // Access expressions need the components of the left side cached in temps before the right side's preceding statements if (rightHasPrecedingStatements && (ts.isElementAccessExpression(node) || ts.isPropertyAccessExpression(node))) { let table = context.transformExpression(node.expression); table = moveToPrecedingTemp(context, table, node.expression); let index: lua.Expression; if (ts.isElementAccessExpression(node)) { index = transformElementAccessArgument(context, node); index = moveToPrecedingTemp(context, index, node.argumentExpression); } else { index = lua.createStringLiteral(node.name.text, node.name); } return lua.createTableIndexExpression(table, index, node); } const symbol = context.checker.getSymbolAtLocation(node); const left = context.transformExpression(node); return lua.isIdentifier(left) && symbol && isSymbolExported(context, symbol) ? createExportedIdentifier(context, left) : cast(left, lua.isAssignmentLeftHandSideExpression); } export function transformAssignment( context: TransformationContext, // TODO: Change type to ts.LeftHandSideExpression? lhs: ts.Expression, right: lua.Expression, rightHasPrecedingStatements?: boolean, parent?: ts.Expression ): lua.Statement[] { if (ts.isOptionalChain(lhs)) { context.diagnostics.push(notAllowedOptionalAssignment(lhs)); return []; } if (isArrayLength(context, lhs)) { const arrayLengthAssignment = lua.createExpressionStatement( transformLuaLibFunction( context, LuaLibFeature.ArraySetLength, parent, context.transformExpression(lhs.expression), right ) ); return [arrayLengthAssignment]; } const symbol = lhs.parent && ts.isShorthandPropertyAssignment(lhs.parent) ? context.checker.getShorthandAssignmentValueSymbol(lhs.parent) : context.checker.getSymbolAtLocation(lhs); const dependentSymbols = symbol ? getDependenciesOfSymbol(context, symbol) : []; const left = transformAssignmentLeftHandSideExpression(context, lhs, rightHasPrecedingStatements); const rootAssignment = lua.createAssignmentStatement(left, right, lhs.parent); return [ rootAssignment, ...dependentSymbols.map(symbol => { const [left] = rootAssignment.left; const identifierToAssign = createExportedIdentifier(context, lua.createIdentifier(symbol.name)); return lua.createAssignmentStatement(identifierToAssign, left); }), ]; } export function transformAssignmentWithRightPrecedingStatements( context: TransformationContext, lhs: ts.Expression, right: lua.Expression, rightPrecedingStatements: lua.Statement[], parent?: ts.Expression ): lua.Statement[] { return [ ...rightPrecedingStatements, ...transformAssignment(context, lhs, right, rightPrecedingStatements.length > 0, parent), ]; } function transformDestructuredAssignmentExpression( context: TransformationContext, expression: ts.DestructuringAssignment ) { const rootIdentifier = context.createTempNameForNode(expression.right); let [rightPrecedingStatements, right] = transformInPrecedingStatementScope(context, () => context.transformExpression(expression.right) ); context.addPrecedingStatements(rightPrecedingStatements); if (isMultiReturnCall(context, expression.right)) { right = wrapInTable(right); } const statements = [ lua.createVariableDeclarationStatement(rootIdentifier, right), ...transformDestructuringAssignment(context, expression, rootIdentifier, rightPrecedingStatements.length > 0), ]; return { statements, result: rootIdentifier }; } export function transformAssignmentExpression( context: TransformationContext, expression: ts.AssignmentExpression<ts.EqualsToken> ): lua.Expression { // Validate assignment const rightType = context.checker.getTypeAtLocation(expression.right); const leftType = context.checker.getTypeAtLocation(expression.left); validateAssignment(context, expression.right, rightType, leftType); if (isArrayLength(context, expression.left)) { // array.length = x return transformLuaLibFunction( context, LuaLibFeature.ArraySetLength, expression, context.transformExpression(expression.left.expression), context.transformExpression(expression.right) ); } if (isDestructuringAssignment(expression)) { const { statements, result } = transformDestructuredAssignmentExpression(context, expression); context.addPrecedingStatements(statements); return result; } if (ts.isPropertyAccessExpression(expression.left) || ts.isElementAccessExpression(expression.left)) { const tempVar = context.createTempNameForNode(expression.right); const [precedingStatements, right] = transformInPrecedingStatementScope(context, () => context.transformExpression(expression.right) ); const left = transformAssignmentLeftHandSideExpression( context, expression.left, precedingStatements.length > 0 ); context.addPrecedingStatements([ ...precedingStatements, lua.createVariableDeclarationStatement(tempVar, right, expression.right), lua.createAssignmentStatement(left, lua.cloneIdentifier(tempVar), expression.left), ]); return lua.cloneIdentifier(tempVar); } else { // Simple assignment // ${left} = ${right}; return ${left} const left = context.transformExpression(expression.left); const right = context.transformExpression(expression.right); context.addPrecedingStatements(transformAssignment(context, expression.left, right)); return left; } } const canBeTransformedToLuaAssignmentStatement = ( context: TransformationContext, node: ts.DestructuringAssignment ): node is ts.ArrayDestructuringAssignment => ts.isArrayLiteralExpression(node.left) && node.left.elements.every(element => { if (isArrayLength(context, element)) { return false; } if (ts.isPropertyAccessExpression(element) || ts.isElementAccessExpression(element)) { // Lua's execution order for multi-assignments is not the same as JS's, so we should always // break these down when the left side may have side effects. return false; } if (ts.isIdentifier(element)) { const symbol = context.checker.getSymbolAtLocation(element); if (symbol) { const aliases = getDependenciesOfSymbol(context, symbol); return aliases.length === 0; } } }); export function transformAssignmentStatement( context: TransformationContext, expression: ts.AssignmentExpression<ts.EqualsToken> ): lua.Statement[] { // Validate assignment const rightType = context.checker.getTypeAtLocation(expression.right); const leftType = context.checker.getTypeAtLocation(expression.left); validateAssignment(context, expression.right, rightType, leftType); if (isDestructuringAssignment(expression)) { if (canBeTransformedToLuaAssignmentStatement(context, expression)) { const rightType = context.checker.getTypeAtLocation(expression.right); let right: lua.Expression | lua.Expression[]; if (ts.isArrayLiteralExpression(expression.right)) { right = transformExpressionList(context, expression.right.elements); } else { right = context.transformExpression(expression.right); if (!isMultiReturnCall(context, expression.right) && isArrayType(context, rightType)) { right = createUnpackCall(context, right, expression.right); } } const left = expression.left.elements.map(e => transformAssignmentLeftHandSideExpression(context, e)); return [lua.createAssignmentStatement(left, right, expression)]; } let [rightPrecedingStatements, right] = transformInPrecedingStatementScope(context, () => context.transformExpression(expression.right) ); context.addPrecedingStatements(rightPrecedingStatements); if (isMultiReturnCall(context, expression.right)) { right = wrapInTable(right); } const rootIdentifier = context.createTempNameForNode(expression.left); return [ lua.createVariableDeclarationStatement(rootIdentifier, right), ...transformDestructuringAssignment( context, expression, rootIdentifier, rightPrecedingStatements.length > 0 ), ]; } else { const [precedingStatements, right] = transformInPrecedingStatementScope(context, () => context.transformExpression(expression.right) ); return transformAssignmentWithRightPrecedingStatements(context, expression.left, right, precedingStatements); } }
the_stack
'use strict'; import * as assert from 'assert'; import { Promise, TPromise } from 'vs/base/common/winjs.base'; import Async = require('vs/base/common/async'); suite('Async', () => { test('Throttler - non async', function(done) { var count = 0; var factory = () => { return TPromise.as(++count); }; var throttler = new Async.Throttler(); Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 3); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 5); }) ]).done(() => done()); }); test('Throttler', function(done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; var throttler = new Async.Throttler(); Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }) ]).done(() => { Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 3); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }), throttler.queue(factory).then((result) => { assert.equal(result, 4); }) ]).done(() => done()); }); }); test('Throttler - cancel should not cancel other promises', function(done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; var throttler = new Async.Throttler(); var p1: Promise; Promise.join([ p1 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 1'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 2'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 3'); }), throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p1.cancel(); }); test('Throttler - cancel the first queued promise should not cancel other promises', function(done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; var throttler = new Async.Throttler(); var p2: Promise; Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 1'); }), p2 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 2'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 3'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p2.cancel(); }); test('Throttler - cancel in the middle should not cancel other promises', function(done) { var count = 0; var factory = () => { return TPromise.timeout(0).then(() => { return ++count; }); }; var throttler = new Async.Throttler(); var p3: Promise; Promise.join([ throttler.queue(factory).then((result) => { assert.equal(result, 1); }, () => { assert(false, 'should not be here, 1'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 2'); }), p3 = throttler.queue(factory).then((result) => { assert(false, 'should not be here, 3'); }, () => { assert(true, 'yes, it was cancelled'); }), throttler.queue(factory).then((result) => { assert.equal(result, 2); }, () => { assert(false, 'should not be here, 4'); }) ]).done(() => done()); p3.cancel(); }); test('Throttler - last factory should be the one getting called', function(done) { var factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; var throttler = new Async.Throttler(); var promises: Promise[] = []; promises.push(throttler.queue(factoryFactory(1)).then((n) => { assert.equal(n, 1); })); promises.push(throttler.queue(factoryFactory(2)).then((n) => { assert.equal(n, 3); })); promises.push(throttler.queue(factoryFactory(3)).then((n) => { assert.equal(n, 3); })); Promise.join(promises).done(() => done()); }); test('Throttler - progress should work', function(done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); var throttler = new Async.Throttler(); var promises: Promise[] = []; var progresses: any[][] = [[], [], []]; promises.push(throttler.queue(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(throttler.queue(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(throttler.queue(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('Delayer', function(done) { var count = 0; var factory = () => { return TPromise.as(++count); }; var delayer = new Async.Delayer(0); var promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); Promise.join(promises).done(() => { assert(!delayer.isTriggered()); done(); }); }); test('Delayer - simple cancel', function(done) { var count = 0; var factory = () => { return TPromise.as(++count); }; var delayer = new Async.Delayer(0); assert(!delayer.isTriggered()); delayer.trigger(factory).then(() => { assert(false); }, () => { assert(true, 'yes, it was cancelled'); }).done(() => done()); assert(delayer.isTriggered()); delayer.cancel(); assert(!delayer.isTriggered()); }); test('Delayer - cancel should cancel all calls to trigger', function(done) { var count = 0; var factory = () => { return TPromise.as(++count); }; var delayer = new Async.Delayer(0); var promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); delayer.cancel(); Promise.join(promises).done(() => { assert(!delayer.isTriggered()); done(); }); }); test('Delayer - trigger, cancel, then trigger again', function(done) { var count = 0; var factory = () => { return TPromise.as(++count); }; var delayer = new Async.Delayer(0); var promises: Promise[] = []; assert(!delayer.isTriggered()); delayer.trigger(factory).then((result) => { assert.equal(result, 1); assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(null, () => { assert(true, 'yes, it was cancelled'); })); assert(delayer.isTriggered()); delayer.cancel(); Promise.join(promises).then(() => { promises = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); promises.push(delayer.trigger(factory).then(() => { assert.equal(result, 1); assert(!delayer.isTriggered()); })); assert(delayer.isTriggered()); Promise.join(promises).then(() => { assert(!delayer.isTriggered()); done(); }); assert(delayer.isTriggered()); }); assert(delayer.isTriggered()); }); assert(delayer.isTriggered()); }); test('Delayer - last task should be the one getting called', function(done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; var delayer = new Async.Delayer(0); var promises: Promise[] = []; assert(!delayer.isTriggered()); promises.push(delayer.trigger(factoryFactory(1)).then((n) => { assert.equal(n, 3); })); promises.push(delayer.trigger(factoryFactory(2)).then((n) => { assert.equal(n, 3); })); promises.push(delayer.trigger(factoryFactory(3)).then((n) => { assert.equal(n, 3); })); Promise.join(promises).then(() => { assert(!delayer.isTriggered()); done(); }); assert(delayer.isTriggered()); }); test('Delayer - progress should work', function(done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); var delayer = new Async.Delayer(0); var promises: Promise[] = []; var progresses: any[][] = [[], [], []]; promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('ThrottledDelayer - progress should work', function(done) { var order = 0; var factory = () => new Promise((c, e, p) => { TPromise.timeout(0).done(() => { p(order++); c(true); }); }); var delayer = new Async.ThrottledDelayer(0); var promises: Promise[] = []; var progresses: any[][] = [[], [], []]; promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[0].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[1].push(p))); promises.push(delayer.trigger(factory).then(null, null, (p) => progresses[2].push(p))); Promise.join(promises).done(() => { assert.deepEqual(progresses[0], [0]); assert.deepEqual(progresses[1], [0]); assert.deepEqual(progresses[2], [0]); done(); }); }); test('Sequence', function(done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; Async.sequence([ factoryFactory(1), factoryFactory(2), factoryFactory(3), factoryFactory(4), factoryFactory(5), ]).then((result)=>{ assert.equal(5, result.length); assert.equal(1, result[0]); assert.equal(2, result[1]); assert.equal(3, result[2]); assert.equal(4, result[3]); assert.equal(5, result[4]); done(); }); }); test('Limiter - sync', function(done) { var factoryFactory = (n: number) => () => { return TPromise.as(n); }; var limiter = new Async.Limiter(1); var promises:Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); limiter = new Async.Limiter(100); promises = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); return Promise.join(promises).then((res) => { assert.equal(10, res.length); }); }).done(() => done()); }); test('Limiter - async', function(done) { var factoryFactory = (n: number) => () => { return TPromise.timeout(0).then(() => n); }; var limiter = new Async.Limiter(1); var promises:Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); limiter = new Async.Limiter(100); promises = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); }); }).done(() => done()); }); test('Limiter - assert degree of paralellism', function(done) { var activePromises = 0; var factoryFactory = (n: number) => () => { activePromises++; assert(activePromises < 6); return TPromise.timeout(0).then(() => { activePromises--; return n; }); }; var limiter = new Async.Limiter(5); var promises:Promise[] = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(n => promises.push(limiter.queue(factoryFactory(n)))); Promise.join(promises).then((res) => { assert.equal(10, res.length); assert.deepEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], res); done(); }); }); });
the_stack
import { Component, OnInit, Input } from '@angular/core'; import { ApiService } from '../api.service'; import { NzMessageService } from 'ng-zorro-antd/message'; import { EJSON, ObjectId } from 'bson'; import { NzNotificationService, NzTreeHigherOrderServiceToken, } from 'ng-zorro-antd'; import * as _ from 'lodash'; const Papa = require('papaparse'); interface simpleSearch { key: any; value: any; type: string; } @Component({ selector: 'app-collection', templateUrl: './collection.component.html', styleUrls: ['./collection.component.css'], }) export class CollectionComponent implements OnInit { @Input() database: any; @Input() collection: any; data: any; filter = ''; ejsonFilter: any; loading = false; pageIndex = 1; showEditor = false; documentEditorMode = 'create'; documentBeingEdited: any; searchMode = 'simple'; searchObj: simpleSearch = { key: '', value: '', type: 'String', }; showAdvancedSearchForm = false; error: { status: boolean; desc: string } = { status: false, desc: '' }; constructor( private API: ApiService, private message: NzMessageService, private notification: NzNotificationService ) { } editorOptions = { theme: 'vs', language: 'json', suggest: { showIcons: false, }, contextmenu: false, codeLens: false, renderLineHighlight: 'none', }; code: string = '{}'; importButton = false; importError: any; file = ''; rowData: any; importing = false; attributes = []; isImportVisible = false; ignore = false; isExportVisible = false; exportButton = true; exporting = false; exportAs = 'json'; exportData: any; exportError: any; count = 0; ngOnInit() { this.query(); } query() { // console.log(this.code, '#####'); this.loading = true; this.API.filterDocumentsByQuery( this.database, this.collection, this.ejsonFilter || EJSON.serialize({}), this.pageIndex ) .subscribe((documents: any) => { this.data = EJSON.deserialize(documents); this.count = this.data.count; if (this.searchMode === 'advanced') this.closeAdvancedSearchForm(); }) .add(() => { this.loading = false; }); } getQuery() { if (this.searchMode === 'simple') { if (!this.searchObj.key) return '{}'; let key = this.searchObj.key; let value = this.searchObj.value; if (this.searchObj.type === 'ObjectId' && ObjectId.isValid(value)) value = { $oid: value }; if (this.searchObj.type === 'Date') value = { $date: value }; if (this.searchObj.type === 'Number') value = { $numberInt: value }; if (this.searchObj.type === 'Boolean') { if (value === 'true') value = true; else { value = false; this.searchObj.value = 'false'; } } return JSON.stringify({ [key]: value }); } else return this.filter; } uiQuery() { this.pageIndex = 1; this.filter = this.getQuery(); try { this.ejsonFilter = EJSON.serialize(JSON.parse(this.filter)); } catch (err) { alert('Invalid query'); } this.query(); } clearFilter() { this.filter = ''; this.ejsonFilter = EJSON.serialize({}); this.searchObj = { key: '', value: '', type: 'String', }; this.query(); } deleteDocument(doc) { this.API.deleteDocumentById( this.database, this.collection, EJSON.serialize(_.pick(doc, '_id')) ).subscribe(() => { try { this.API.getDocumentCount( this.database, this.collection, this.filter ? JSON.parse(this.filter) : {} ).subscribe((res: any) => { this.message.info('Deleted!'); this.data = EJSON.deserialize(res); if (this.pageIndex * 10 >= this.data.count) this.pageIndex = Math.ceil(this.data.count / 10); if (this.data.count === 0) this.pageIndex = 1; this.query(); }); } catch (err) { alert('Invalid JSON query!!'); this.loading = false; } }); } updateDocument() { try { this.error.status = false; this.error.desc = ''; const originalDocument = EJSON.serialize( JSON.parse(this.documentBeingEdited) ); // const method = this.documentEditorMode === 'create' ? this.API.createDocument : this.API.updateDocument this.API.createDocuments( this.database, this.collection, originalDocument ).subscribe((response) => { try { if (!response['nUpserted']) { this.closeEditor(); this.message.success('Success!'); this.query(); return; } this.API.getDocumentCount( this.database, this.collection, this.filter ? JSON.parse(this.filter) : {} ).subscribe((res: any) => { this.closeEditor(); this.message.success('Success!'); this.data = EJSON.deserialize(res); this.pageIndex = Math.ceil(this.data.count / 10); if (this.data.count === 0) this.pageIndex = 1; this.query(); }); } catch (err) { alert('Invalid JSON query!!'); this.loading = false; } }); } catch (err) { this.error.status = true; this.error.desc = err; } } openEditor(doc, mode): void { this.documentEditorMode = mode || 'create'; this.showEditor = true; this.documentBeingEdited = JSON.stringify( EJSON.serialize(doc), undefined, 4 ); } closeEditor(): void { this.showEditor = false; this.documentBeingEdited = ''; } openAdvancedSearchForm() { this.showAdvancedSearchForm = true; } closeAdvancedSearchForm() { this.showAdvancedSearchForm = false; } copyToClipboard(text: any, type: string) { text = JSON.stringify((type === 'BSON') ? EJSON.serialize(text) : text); const txtArea = document.createElement('textarea'); txtArea.style.position = 'fixed'; txtArea.style.top = '0'; txtArea.style.left = '0'; txtArea.style.opacity = '0'; txtArea.value = text; document.body.appendChild(txtArea); txtArea.select(); try { const result = document.execCommand('copy'); if (result) { this.message.success('Copied!'); } } catch (err) { } document.body.removeChild(txtArea); } beforeUpload = (file: any): boolean => { this.importError = ''; this.attributes = []; this.rowData = []; this.importButton = false; if (file.type !== 'text/csv' && file.type !== 'application/json') { this.message.error('You can only upload either JSON or CSV files!'); this.importing = false; this.file = ''; return false; } this.file = file.name; try { if (file.type === 'text/csv') { Papa.parse(file, { header: true, skipEmptyLines: true, complete: (result) => { if (!result.errors[0]) { const keys = _.take(_.keys(result.data[0]), 1500); this.attributes = _.map(keys, (key) => ({ include: true, label: key, type: 'String', })); this.rowData = result.data; this.importButton = true; } else { this.importError = result.errors[0].message; this.rowData = []; this.importButton = false; } }, }); } else { let reader = new FileReader(); reader.readAsText(file); reader.onload = (e) => { this.rowData = reader.result; this.importButton = true; }; reader.onerror = (e) => { this.importError = reader.error; this.rowData = []; this.importButton = false; }; } } catch (err) { this.importError = err.message; this.rowData = []; this.importButton = false; } return false; }; showImportModal(): void { this.isImportVisible = true; this.file = ''; this.rowData = []; this.importError = ''; this.importButton = false; this.importing = false; } importRecords(): void { let records: any = []; try { if (this.attributes[0]) { this.importError = ''; this.importing = true; this.importButton = false; for (let row of this.rowData) { let record = {}; for (let attribute of this.attributes) { if (attribute.include) { if (_.get(row, attribute.label)) { switch (attribute.type) { case 'ObjectId': row[attribute.label] = new ObjectId(row[attribute.label]); break; case 'Boolean': row[attribute.label] = Boolean(row[attribute.label]); break; case 'Date': row[attribute.label] = { $date: row[attribute.label] }; break; case 'Number': row[attribute.label] = { $numberInt: row[attribute.label] }; break; default: row[attribute.label] = String(row[attribute.label]); break; } _.set(record, attribute.label, row[attribute.label]); } } } if (this.importing) { records.push(record); this.importError = ''; } else { records = []; break; } } } else { records = this.rowData; this.importError = ''; this.importing = true; this.importButton = false; } if (!this.importError) { const originalDocument = EJSON.serialize( typeof records === 'string' ? JSON.parse(records) : records ); this.API.createDocuments( this.database, this.collection, originalDocument ).subscribe((response) => { this.importing = false; this.importButton = false; if (!response['nUpserted']) { this.message.success('Success!'); this.query(); this.closeImportModal(); return; } this.API.getDocumentCount( this.database, this.collection, this.filter ? JSON.parse(this.filter) : {} ).subscribe((res: any) => { this.message.success('Success!'); this.closeImportModal(); this.data = EJSON.deserialize(res); this.pageIndex = Math.ceil(this.data.count / 10); this.query(); }, (error) => { this.importError = error; this.importButton = true; this.importing = false; }); }, (error) => { this.importError = error; this.importButton = true; this.importing = false; }); } } catch (err) { this.importError = err.message; this.importButton = true; this.importing = false; } } closeImportModal(): void { this.isImportVisible = false; this.importing = false; } getExportAttributes(): void { this.attributes = []; this.API.aggregate( this.database, this.collection, [ { $match: this.ejsonFilter || EJSON.serialize({}) }, { $project: { arrayofkeyvalue: { $objectToArray: '$$ROOT' } } }, { $unwind: '$arrayofkeyvalue' }, { $group: { _id: null, allkeys: { $addToSet: '$arrayofkeyvalue.k' } } } ] ).subscribe((documents: any) => { const keys = new Set(documents[0].allkeys.sort()); for (const key of keys) { this.attributes.push({ include: true, label: key, }); } }); } showExportModal(): void { this.isExportVisible = true; this.exporting = false; this.exportAs = 'json'; this.exportButton = true; this.getExportAttributes(); } closeExportModal(): void { this.isExportVisible = false; this.exporting = false; this.attributes = []; this.exportAs = 'json'; this.exportButton = true; } exportCollection(): void { this.exporting = true; this.exportButton = false; let excludedAttributes = [], includedAttributes = []; for (let attribute of this.attributes) { if (!attribute.include) excludedAttributes.push(attribute.label); else includedAttributes.push(attribute.label) } const query = [ { $match: this.ejsonFilter || EJSON.serialize({}) }, { $unset: excludedAttributes } ]; if (!excludedAttributes[0] || this.exportAs !== 'csv') query.pop(); this.API.aggregate( this.database, this.collection, query ) .subscribe((documents: any) => { documents = EJSON.parse(JSON.stringify(documents)); if (this.exportAs === 'csv') { for (let row of documents) { for (let attribute of includedAttributes) { let rowLabel = _.get(row, attribute); if (typeof rowLabel === 'object') _.set(row, attribute, JSON.stringify(rowLabel)); } } if (includedAttributes[0]) documents = Papa.unparse(documents, { columns: includedAttributes }); else documents = Papa.unparse(documents); } else documents = JSON.stringify(documents, null, 2); var blob = new Blob([documents], { type: 'application/octet-stream' }); var url = window.URL.createObjectURL(blob); var anchor = document.createElement('a'); anchor.download = `${this.collection}.${this.exportAs}`; anchor.href = url; anchor.click(); this.exportButton = true; this.exporting = false; }); } }
the_stack
// clang-format off import 'chrome://settings/lazy_load.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {SecureDnsInputElement, SettingsSecureDnsElement} from 'chrome://settings/lazy_load.js'; import {PrivacyPageBrowserProxyImpl, ResolverOption, SecureDnsMode, SecureDnsUiManagementMode} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/test_util.js'; import {TestPrivacyPageBrowserProxy} from './test_privacy_page_browser_proxy.js'; // clang-format on function focused(inputElement: HTMLElement): boolean { return inputElement.shadowRoot!.querySelector('#input')!.hasAttribute( 'focused_'); } suite('SettingsSecureDnsInputInteractive', function() { let testElement: SecureDnsInputElement; setup(function() { assertTrue(document.hasFocus()); document.body.innerHTML = ''; testElement = document.createElement('secure-dns-input'); document.body.appendChild(testElement); flush(); }); teardown(function() { testElement.remove(); }); test('SecureDnsInputFocus', function() { assertFalse(focused(testElement)); testElement.focus(); assertTrue(focused(testElement)); testElement.blur(); assertFalse(focused(testElement)); }); }); suite('SettingsSecureDnsInteractive', function() { let testBrowserProxy: TestPrivacyPageBrowserProxy; let testElement: SettingsSecureDnsElement; const resolverList: ResolverOption[] = [ {name: 'Custom', value: '', policy: ''}, { name: 'resolver1', value: 'resolver1_template', policy: 'https://resolver1_policy.com/' }, { name: 'resolver2', value: 'resolver2_template', policy: 'https://resolver2_policy.com/' }, { name: 'resolver3', value: 'resolver3_template', policy: 'https://resolver3_policy.com/' }, ]; const invalidEntry = 'invalid_template'; const validEntry = 'https://example.doh.server/dns-query'; suiteSetup(function() { loadTimeData.overrideValues({showSecureDnsSetting: true}); }); setup(async function() { assertTrue(document.hasFocus()); testBrowserProxy = new TestPrivacyPageBrowserProxy(); testBrowserProxy.setResolverList(resolverList); PrivacyPageBrowserProxyImpl.setInstance(testBrowserProxy); document.body.innerHTML = ''; testElement = document.createElement('settings-secure-dns'); testElement.prefs = { dns_over_https: {mode: {value: SecureDnsMode.AUTOMATIC}, templates: {value: ''}}, }; document.body.appendChild(testElement); await testBrowserProxy.whenCalled('getSecureDnsSetting'); await flushTasks(); }); teardown(function() { testElement.remove(); }); test('SecureDnsModeChange', async function() { // Start in automatic mode. webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); // Click on the secure dns toggle to disable secure dns. testElement.$.secureDnsToggle.click(); assertEquals( SecureDnsMode.OFF, testElement.prefs.dns_over_https.mode.value); // Click on the secure dns toggle to go back to automatic mode. testElement.$.secureDnsToggle.click(); assertEquals( SecureDnsMode.AUTOMATIC, testElement.prefs.dns_over_https.mode.value); assertFalse(focused(testElement.$.secureDnsInput)); // Change the radio button to secure mode. The focus should be on the // custom text field and the mode pref should still be 'automatic'. testElement.$.secureDnsRadioGroup.querySelectorAll( 'cr-radio-button')[1]!.click(); assertTrue(testElement.$.secureDnsInput.matches(':focus-within')); assertEquals( SecureDnsMode.AUTOMATIC, testElement.prefs.dns_over_https.mode.value); assertTrue(focused(testElement.$.secureDnsInput)); // Enter a correctly formatted template in the custom text field and // click outside the text field. The mode pref should be updated to // 'secure'. testElement.$.secureDnsInput.value = validEntry; testBrowserProxy.setParsedEntry([validEntry]); testBrowserProxy.setProbeResults({[validEntry]: true}); testElement.$.secureDnsInput.blur(); await Promise.all([ testBrowserProxy.whenCalled('parseCustomDnsEntry'), testBrowserProxy.whenCalled('probeCustomDnsTemplate') ]); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); // Click on the secure dns toggle to disable secure dns. testElement.$.secureDnsToggle.click(); assertEquals( SecureDnsMode.OFF, testElement.prefs.dns_over_https.mode.value); assertFalse(focused(testElement.$.secureDnsInput)); // Click on the secure dns toggle. Focus should be on the custom text field // and the mode pref should remain 'off' until the text field is blurred. testElement.$.secureDnsToggle.click(); assertTrue(focused(testElement.$.secureDnsInput)); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertTrue(testElement.$.secureDnsInput.matches(':focus-within')); assertEquals(validEntry, testElement.$.secureDnsInput.value); assertEquals( SecureDnsMode.OFF, testElement.prefs.dns_over_https.mode.value); testElement.$.secureDnsInput.blur(); await Promise.all([ testBrowserProxy.whenCalled('parseCustomDnsEntry'), testBrowserProxy.whenCalled('probeCustomDnsTemplate') ]); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); }); test('SecureDnsDropdown', function() { const options = testElement.$.secureResolverSelect.querySelectorAll('option'); assertEquals(4, options.length); for (let i = 0; i < options.length; i++) { assertEquals(resolverList[i]!.name, options[i]!.text); assertEquals(resolverList[i]!.value, options[i]!.value); } }); test('SecureDnsDropdownCustom', function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: [''], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals(0, testElement.$.secureResolverSelect.selectedIndex); assertEquals('none', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( 'block', getComputedStyle(testElement.$.secureDnsInput).display); assertEquals('', testElement.$.secureDnsInput.value); }); test('SecureDnsDropdownChangeInSecureMode', async function() { webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: [resolverList[1]!.value], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); const dropdownMenu = testElement.$.secureResolverSelect; const privacyPolicyLine = testElement.$.privacyPolicy; assertEquals(1, dropdownMenu.selectedIndex); assertEquals( 'block', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( resolverList[1]!.policy, privacyPolicyLine.querySelector('a')!.href); // Change to resolver2 dropdownMenu.value = resolverList[2]!.value; dropdownMenu.dispatchEvent(new Event('change')); let args = await testBrowserProxy.whenCalled('recordUserDropdownInteraction'); assertEquals(resolverList[1]!.value, args[0]); assertEquals(resolverList[2]!.value, args[1]); assertEquals(2, dropdownMenu.selectedIndex); assertEquals( 'block', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( resolverList[2]!.policy, privacyPolicyLine.querySelector('a')!.href); assertEquals( resolverList[2]!.value, testElement.prefs.dns_over_https.templates.value); // Change to custom testBrowserProxy.reset(); dropdownMenu.value = ''; dropdownMenu.dispatchEvent(new Event('change')); args = await testBrowserProxy.whenCalled('recordUserDropdownInteraction'); assertEquals(resolverList[2]!.value, args[0]); assertEquals('', args[1]); assertEquals(0, dropdownMenu.selectedIndex); assertEquals('none', getComputedStyle(testElement.$.privacyPolicy).display); assertTrue(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals( resolverList[2]!.value, testElement.prefs.dns_over_https.templates.value); // Input a custom template and make sure it is still there after // manipulating the dropdown. testBrowserProxy.reset(); testElement.$.secureDnsInput.value = 'some_input'; dropdownMenu.value = resolverList[1]!.value; dropdownMenu.dispatchEvent(new Event('change')); args = await testBrowserProxy.whenCalled('recordUserDropdownInteraction'); assertEquals('', args[0]); assertEquals(resolverList[1]!.value, args[1]); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals( resolverList[1]!.value, testElement.prefs.dns_over_https.templates.value); testBrowserProxy.reset(); dropdownMenu.value = ''; dropdownMenu.dispatchEvent(new Event('change')); args = await testBrowserProxy.whenCalled('recordUserDropdownInteraction'); assertEquals(resolverList[1]!.value, args[0]); assertEquals('', args[1]); assertEquals('some_input', testElement.$.secureDnsInput.value); }); test('SecureDnsDropdownChangeInAutomaticMode', async function() { testElement.prefs.dns_over_https.templates.value = 'resolver1_template'; webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [resolverList[1]!.value], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( SecureDnsMode.AUTOMATIC, testElement.$.secureDnsRadioGroup.selected); const dropdownMenu = testElement.$.secureResolverSelect; const privacyPolicyLine = testElement.$.privacyPolicy; // Select resolver3. This change should not be reflected in prefs. assertNotEquals(3, dropdownMenu.selectedIndex); dropdownMenu.value = resolverList[3]!.value; dropdownMenu.dispatchEvent(new Event('change')); const args = await testBrowserProxy.whenCalled('recordUserDropdownInteraction'); assertNotEquals(resolverList[3]!.value, args[0]); assertEquals(resolverList[3]!.value, args[1]); assertEquals(3, dropdownMenu.selectedIndex); assertEquals( 'block', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( resolverList[3]!.policy, privacyPolicyLine.querySelector('a')!.href); assertEquals( 'resolver1_template', testElement.prefs.dns_over_https.templates.value); // Click on the secure dns toggle to disable secure dns. testElement.$.secureDnsToggle.click(); assertTrue(testElement.$.secureDnsRadioGroup.hidden); assertEquals( SecureDnsMode.OFF, testElement.prefs.dns_over_https.mode.value); assertEquals('', testElement.prefs.dns_over_https.templates.value); // Get another event enabling automatic mode. webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [resolverList[1]!.value], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertFalse(testElement.$.secureDnsRadioGroup.hidden); assertEquals(3, dropdownMenu.selectedIndex); assertEquals( 'block', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( resolverList[3]!.policy, privacyPolicyLine.querySelector('a')!.href); // Click on secure mode radio button. testElement.$.secureDnsRadioGroup.querySelectorAll( 'cr-radio-button')[1]!.click(); assertFalse(testElement.$.secureDnsRadioGroup.hidden); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals(3, dropdownMenu.selectedIndex); assertEquals( 'block', getComputedStyle(testElement.$.privacyPolicy).display); assertEquals( resolverList[3]!.policy, privacyPolicyLine.querySelector('a')!.href); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals( 'resolver3_template', testElement.prefs.dns_over_https.templates.value); }); test('SecureDnsInputChange', async function() { // Start in secure mode with a custom valid template testElement.prefs = { dns_over_https: {mode: {value: SecureDnsMode.SECURE}, templates: {value: validEntry}}, }; webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: [validEntry], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( 'block', getComputedStyle(testElement.$.secureDnsInput).display); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals(validEntry, testElement.$.secureDnsInput.value); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); // Make the template invalid and check that the mode pref doesn't change. testElement.$.secureDnsInput.focus(); assertTrue(focused(testElement.$.secureDnsInput)); testElement.$.secureDnsInput.value = invalidEntry; testBrowserProxy.setParsedEntry([]); testElement.$.secureDnsInput.blur(); await testBrowserProxy.whenCalled('parseCustomDnsEntry'); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertTrue(testElement.$.secureDnsInput.isInvalid()); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals(validEntry, testElement.prefs.dns_over_https.templates.value); // Receive a pref update and make sure the custom input field is not // cleared. webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.AUTOMATIC, templates: [], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( 'block', getComputedStyle(testElement.$.secureDnsInput).display); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertTrue(testElement.$.secureDnsInput.isInvalid()); assertEquals(invalidEntry, testElement.$.secureDnsInput.value); assertEquals( SecureDnsMode.AUTOMATIC, testElement.$.secureDnsRadioGroup.selected); // Switching to automatic should remove focus from the input. assertFalse(focused(testElement.$.secureDnsInput)); // Make the template valid, but don't change the radio button yet. testElement.$.secureDnsInput.focus(); assertTrue(focused(testElement.$.secureDnsInput)); const otherEntry = 'https://dns.ex.another/dns-query'; testElement.$.secureDnsInput.value = `${validEntry} ${otherEntry}`; testBrowserProxy.setParsedEntry([validEntry, otherEntry]); testBrowserProxy.setProbeResults({[validEntry]: true}); testElement.$.secureDnsInput.blur(); await Promise.all([ testBrowserProxy.whenCalled('parseCustomDnsEntry'), testBrowserProxy.whenCalled('probeCustomDnsTemplate') ]); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals( SecureDnsMode.AUTOMATIC, testElement.$.secureDnsRadioGroup.selected); // Select the secure radio button and blur the input field. testElement.$.secureDnsRadioGroup.querySelectorAll( 'cr-radio-button')[1]!.click(); assertTrue(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals( SecureDnsMode.AUTOMATIC, testElement.prefs.dns_over_https.mode.value); assertEquals('', testElement.prefs.dns_over_https.templates.value); testElement.$.secureDnsInput.blur(); await Promise.all([ testBrowserProxy.whenCalled('parseCustomDnsEntry'), testBrowserProxy.whenCalled('probeCustomDnsTemplate') ]); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals( `${validEntry} ${otherEntry}`, testElement.prefs.dns_over_https.templates.value); // Make sure the input field updates with a change in the underlying // templates pref in secure mode. webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: [ 'https://manage.ex/dns-query', 'https://manage.ex.another/dns-query{?dns}' ], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); assertEquals( 'block', getComputedStyle(testElement.$.secureDnsInput).display); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertFalse(testElement.$.secureDnsInput.isInvalid()); assertEquals( 'https://manage.ex/dns-query https://manage.ex.another/dns-query{?dns}', testElement.$.secureDnsInput.value); assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); }); test('SecureDnsProbeFailure', async function() { // Start in secure mode with a valid template. webUIListenerCallback('secure-dns-setting-changed', { mode: SecureDnsMode.SECURE, templates: ['https://dns.example/dns-query'], managementMode: SecureDnsUiManagementMode.NO_OVERRIDE, }); flush(); // The input should not be focused automatically. assertFalse(focused(testElement.$.secureDnsInput)); // Enter two valid templates that are both unreachable. testElement.$.secureDnsInput.focus(); assertTrue(focused(testElement.$.secureDnsInput)); const otherEntry = 'https://dns.ex.another/dns-query'; testElement.$.secureDnsInput.value = `${validEntry} ${otherEntry}`; const parsed = [validEntry, otherEntry]; testBrowserProxy.setParsedEntry(parsed); testBrowserProxy.setProbeResults({ [validEntry]: false, [otherEntry]: false, }); testElement.$.secureDnsInput.blur(); assertEquals( testElement.$.secureDnsInput.value, await testBrowserProxy.whenCalled('parseCustomDnsEntry')); await flushTasks(); assertEquals(2, testBrowserProxy.getCallCount('probeCustomDnsTemplate')); assertFalse(testElement.$.secureDnsInput.matches(':focus-within')); assertTrue(testElement.$.secureDnsInput.isInvalid()); // Unreachable templates are accepted and committed anyway. assertEquals( SecureDnsMode.SECURE, testElement.$.secureDnsRadioGroup.selected); assertEquals( SecureDnsMode.SECURE, testElement.prefs.dns_over_https.mode.value); assertEquals( `${validEntry} ${otherEntry}`, testElement.prefs.dns_over_https.templates.value); }); });
the_stack
import colors, { Color } from "chalk"; import { Ora } from "ora"; import { SetRequired } from "type-fest"; declare type ColorType = typeof Color; interface Options { logLevel?: number; mock?: boolean; } declare class Logger { options: Required<Options>; lines: string[]; constructor(options?: Options); setOptions(options: Options): void; log(...args: any[]): void; debug(...args: any[]): void; warn(...args: any[]): void; error(...args: any[]): void; success(...args: any[]): void; tip(...args: any[]): void; info(...args: any[]): void; status(color: ColorType, label: string, ...args: any[]): void; fileAction(color: ColorType, type: string, fp: string): void; fileMoveAction(from: string, to: string): void; } /** * The state of current running prompt */ interface PromptState { /** * Prompt answers */ answers: { [k: string]: any; }; } interface BasePromptOptions { /** * Used as the key for the answer on the returned values (answers) object. */ name: string; /** * The message to display when the prompt is rendered in the terminal. */ message: string; /** Skip the prompt when returns `true` */ skip?: (state: PromptState, value: any) => boolean; /** * Function to validate the submitted value before it's returned. * This function may return a boolean or a string. * If a string is returned it will be used as the validation error message. */ validate?: (value: string, state: PromptState) => boolean | string; /** * Function to format the final submitted value before it's returned. */ result?: (value: string, state: PromptState) => any; /** * Function to format user input in the terminal. */ format?: (value: string, state: PromptState) => Promise<string> | string; /** * Store the prompt answer in order to reuse it as default value the next time * Defaults to `false` */ store?: boolean; } declare type WithPromptState<T> = T | ((state: PromptState) => T); interface Choice { name: string; message?: string; value?: string; hint?: string; disabled?: boolean | string; } interface ArrayPromptOptions extends BasePromptOptions { type: | "autocomplete" | "editable" | "form" | "multiselect" | "select" | "survey" | "list" | "scale"; choices: WithPromptState<string[] | Choice[]>; /** Maxium number of options to select */ maxChoices?: number; /** Allow to select multiple options */ muliple?: boolean; /** Default value for the prompt */ default?: WithPromptState<string>; delay?: number; separator?: boolean; sort?: boolean; linebreak?: boolean; edgeLength?: number; align?: "left" | "right"; /** Make the options scrollable via arrow keys */ scroll?: boolean; } interface BooleanPromptOptions extends BasePromptOptions { type: "confirm"; /** Default value for the prompt */ default?: WithPromptState<boolean>; } interface StringPromptOptions extends BasePromptOptions { type: "input" | "invisible" | "list" | "password" | "text"; /** Default value for the prompt */ default?: WithPromptState<string>; /** Allow the input to be multiple lines */ multiline?: boolean; } declare type PromptOptions = | ArrayPromptOptions | BooleanPromptOptions | StringPromptOptions; interface AddAction { type: "add"; templateDir?: string; files: string[] | string; filters?: { [k: string]: string | boolean | null | undefined; }; /** Transform the template with ejs */ transform?: boolean; /** * Only transform files matching given minimatch patterns */ transformInclude?: string[]; /** * Don't transform files matching given minimatch patterns */ transformExclude?: string; /** * Custom data to use in template transformation */ data?: DataFunction | object; } declare type DataFunction = (this: SAO, context: SAO) => object; interface MoveAction { type: "move"; templateDir?: string; patterns: { [k: string]: string; }; } interface ModifyAction { type: "modify"; files: string | string[]; handler: (data: any, filepath: string) => any; } interface RemoveAction { type: "remove"; files: | string | string[] | { [k: string]: string | boolean; }; when: boolean | string; } declare type Action = AddAction | MoveAction | ModifyAction | RemoveAction; interface GeneratorConfig { /** * Generator description * Used in CLI output */ description?: string; /** * Check updates for npm generators * Defaults to `true` */ updateCheck?: boolean; /** * Transform template content with `ejs` * Defaults to `true` */ transform?: boolean; /** * Extra data to use in template transformation */ data?: DataFunction; /** * Use prompts to ask questions before generating project */ prompts?: | PromptOptions[] | ((this: SAO, ctx: SAO) => PromptOptions[] | Promise<PromptOptions[]>); /** * Use actions to control how files are generated */ actions?: | Action[] | ((this: SAO, ctx: SAO) => Action[] | Promise<Action[]>); /** * Directory to template folder * Defaults to `./template` in your generator folder */ templateDir?: string; /** * Sub generator */ subGenerators?: Array<{ name: string; generator: string; }>; /** * Run some operations before starting */ prepare?: (this: SAO, ctx: SAO) => Promise<void> | void; /** * Run some operations when completed * e.g. log some success message */ completed?: (this: SAO, ctx: SAO) => Promise<void> | void; } declare class SAOError extends Error { sao: boolean; cmdOutput?: string; constructor(message: string); } declare function handleError(error: Error | SAOError): void; interface LocalGenerator { type: "local"; path: string; hash: string; subGenerator?: string; } interface NpmGenerator { type: "npm"; name: string; version: string; slug: string; subGenerator?: string; hash: string; path: string; } interface RepoGenerator { type: "repo"; prefix: GeneratorPrefix; user: string; repo: string; version: string; subGenerator?: string; hash: string; path: string; } declare type ParsedGenerator = LocalGenerator | NpmGenerator | RepoGenerator; declare type GeneratorPrefix = "npm" | "github" | "gitlab" | "bitbucket"; declare class Store { data: { [k: string]: any; }; constructor(); read(): { [k: string]: any; }; set(key: string, value: any): void; get(key: string): any; } declare const store: Store; interface GitUser { name: string; username: string; email: string; } declare type NPM_CLIENT = "npm" | "yarn" | "pnpm"; interface InstallOptions { cwd: string; npmClient?: NPM_CLIENT; installArgs?: string[]; packages?: string[]; saveDev?: boolean; registry?: string; } declare type GroupedGenerators = Map< string, Array<NpmGenerator | RepoGenerator> >; declare class GeneratorList { store: ParsedGenerator[]; constructor(); add(generator: ParsedGenerator): void; findGenerators(generator: ParsedGenerator): ParsedGenerator[]; /** * Group generators by name */ get groupedGenerators(): GroupedGenerators; } declare const generatorList: GeneratorList; declare function runCLI(): Promise<void>; interface IPaths { sourcePath: string; templateDir: string; } interface IExtras { debug: boolean; paths: IPaths; projectType: string; } interface Options$1 { appName?: string; extras: IExtras; outDir?: string; logLevel?: number; debug?: boolean; quiet?: boolean; generator: string; /** Update cached generator before running */ update?: boolean; /** Use `git clone` to download repo */ clone?: boolean; /** Use a custom npm registry */ registry?: string; /** Check for sao/generator updates */ updateCheck?: boolean; /** Mock git info, prompts etc */ mock?: boolean; /** * User-supplied answers * `true` means using default answers for prompts */ answers?: | boolean | { [k: string]: any; }; } declare class SAO { opts: SetRequired<Options$1, "outDir" | "logLevel">; spinner: Ora; colors: colors.Chalk & colors.ChalkFunction & { supportsColor: false | colors.ColorSupport; /** * Create an SAO Error so we can pretty print the error message instead of showing full error stack */ Level: colors.Level; Color: | "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | "gray" | "grey" | "blackBright" | "redBright" | "greenBright" | "yellowBright" | "blueBright" | "magentaBright" | "cyanBright" | "whiteBright" | "bgBlack" | "bgRed" | "bgGreen" | "bgYellow" | "bgBlue" | "bgMagenta" | "bgCyan" | "bgWhite" | "bgGray" | "bgGrey" | "bgBlackBright" | "bgRedBright" | "bgGreenBright" | "bgYellowBright" | "bgBlueBright" | "bgMagentaBright" | "bgCyanBright" | "bgWhiteBright"; ForegroundColor: | "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | "gray" | "grey" | "blackBright" | "redBright" | "greenBright" | "yellowBright" | "blueBright" | "magentaBright" | "cyanBright" | "whiteBright"; BackgroundColor: | "bgBlack" | "bgRed" | "bgGreen" | "bgYellow" | "bgBlue" | "bgMagenta" | "bgCyan" | "bgWhite" | "bgGray" | "bgGrey" | "bgBlackBright" | "bgRedBright" | "bgGreenBright" | "bgYellowBright" | "bgBlueBright" | "bgMagentaBright" | "bgCyanBright" | "bgWhiteBright"; Modifiers: | "reset" | "bold" | "dim" | "italic" | "underline" | "inverse" | "hidden" | "strikethrough" | "visible"; stderr: colors.Chalk & { supportsColor: false | colors.ColorSupport; /** * Get file list of output directory */ }; }; logger: Logger; private _answers; private _data; parsedGenerator: ParsedGenerator; generatorList: GeneratorList; constructor(opts: Options$1); /** * Get the help message for current generator * * Used by SAO CLI, in general you don't want to touch this */ getGeneratorHelp(): Promise<string>; /** * Get actual generator to run and its config * Download it if not yet cached */ getGenerator( generator?: ParsedGenerator, hasParent?: boolean, ): Promise<{ generator: ParsedGenerator; config: GeneratorConfig; }>; runGenerator( generator: ParsedGenerator, config: GeneratorConfig, ): Promise<void>; run(): Promise<void>; /** * Retrive the answers * * You can't access this in `prompts` function */ get answers(): { [k: string]: any; }; set answers(value: { [k: string]: any }); get data(): any; /** * Read package.json from output directory * * Returns an empty object when it doesn't exist */ get pkg(): any; /** * Get the information of system git user */ get gitUser(): GitUser; /** * The basename of output directory */ get outDirName(): string; /** * The absolute path to output directory */ get outDir(): string; /** * The npm client */ get npmClient(): NPM_CLIENT; /** * Run `git init` in output directly * * It will fail silently when `git` is not available */ gitInit(): void; /** * Run `npm install` in output directory */ npmInstall( opts?: Omit<InstallOptions, "cwd" | "registry">, ): Promise<{ code: number; }>; /** * Display a success message */ showProjectTips(): void; /** * Create an SAO Error so we can pretty print the error message instead of showing full error stack */ createError(message: string): SAOError; /** * Get file list of output directory */ getOutputFiles(): Promise<string[]>; /** * Check if a file exists in output directory */ hasOutputFile(file: string): Promise<boolean>; /** * Read a file in output directory * @param file file path */ readOutputFile(file: string): Promise<string>; } export { GeneratorConfig, Options$1 as Options, SAO, generatorList, handleError, runCLI, store, Action, };
the_stack
import { CONSTANTS } from '@/util/common' import AppTbs from '@/components/appTbs' import PageTitle from '@/components/PageTitle' import applicationModels from '@/models/application/model' import applicationService from '@/models/application/service' import { connect } from '@/util/store' import '@/style/masonry.less' import DataSet from '@antv/data-set/lib/data-set' import { Col, Layout, Row } from 'antd' import * as d3 from 'd3' import _ from 'lodash' import moment from 'moment' import React from 'react' import { RouteComponentProps, withRouter } from 'react-router' import { CSSTransition, TransitionGroup } from 'react-transition-group' import { Axis, Chart, Legend, Line, Point, Tooltip } from 'viser-react' const { Content } = Layout const THREAD_CHART_WIDTH = CONSTANTS.CHART_CONTENT_WIDTH const THREAD_DUMP_DATA_UPDATE_INTERVAL = 1000 * 5 const HEIGHT_PER_LINE = 40 const TICK_COUNT = 16 const LEGEND_WIDTH = 250.0 const THREAD_STATE_COLOR_MAP = { RUNNABLE: CONSTANTS.CHART_COLOR.GREEN, WAITING: CONSTANTS.CHART_COLOR.YELLOW, TIMED_WAITING: CONSTANTS.CHART_COLOR.SEA_GREEN, } as any const THREAD_STATE_SHORT_MAP = { RUNNABLE: 'R', WAITING: 'W', TIMED_WAITING: 'T', } as any interface IThreadState { threadStateDatas: any[] timestamps: any[] yAxisData: any[] domain: any[] } class Thread extends React.Component<RouteComponentProps<{ id: string }>, IThreadState> { public state: IThreadState = { threadStateDatas: [], timestamps: [], yAxisData: [], domain: [], } private timer: any private dataSource: any[] = [] private lineChartDataSource: any[] = [] private svg: any private domain: any[] = [] public componentDidMount() { const { match } = this.props this.fetchDumpInfo(match.params.id, true) this.timer = setInterval(() => { this.fetchDumpInfo(match.params.id, false) }, THREAD_DUMP_DATA_UPDATE_INTERVAL) } public componentWillUnmount() { clearInterval(this.timer) } public render() { return ( <> <Row> <Col span={24}> <AppTbs MenuData={this.props} /> </Col> </Row> <Layout className="page"> <Row> <Col span={24}> <PageTitle name="查看线程" info="查看当前实例的线程情况" // titleExtra={<Button type="primary" ghost={true} size="small" icon="download"> Heap Dump </Button>} /> </Col> </Row> <Content style={{ background: '#fff', }}> {this.renderLineChart()} {this.renderBarChart()} </Content> </Layout> </> ) } private fetchDumpInfo(id: string, firstRequest: boolean) { // 定时循环获取最新 dump 数据 this.fetchThreadInfo(id, firstRequest).then((dumps: any) => { // dumps.splice(0, dumps.length - 20) const timestamp = moment().valueOf() const newDump = { timestamp, dumps } const lineNewState = this.prepareLineChartData(newDump) const barNewState = this.prepareBarCharData(newDump, firstRequest) this.setState({ ...lineNewState, ...barNewState }) }) } private renderLineChart() { const { threadStateDatas, timestamps } = this.state const dv = new DataSet.View().source(threadStateDatas) dv.transform({ type: 'fold', fields: ['blockedCount', 'waitedCount'], key: 'threadStateType', value: 'count', }) const threadStateByCountScale = [ { dataKey: 'count', type: 'log', base: '10', }, { dataKey: 'timestamp', type: 'cat', values: timestamps, }, ] const threadStateChartOpts = { height: 256, width: THREAD_CHART_WIDTH, padding: [30, 30, 50, LEGEND_WIDTH], data: dv.rows, scale: threadStateByCountScale, } const threadStateSeriesOpts = { color: ['threadStateType', [CONSTANTS.CHART_COLOR.YELLOW, CONSTANTS.CHART_COLOR.RED]], position: 'timestamp*count', } const threadStateLegendOpts = { position: 'left-center', offsetX: -30, textStyle: { textAlign: 'left', fontSize: '12', fontWeight: 'bold', }, } const threadStatePointOpts = { position: 'timestamp*count', color: ['threadStateType', [CONSTANTS.CHART_COLOR.YELLOW, CONSTANTS.CHART_COLOR.RED]], size: 4, shape: 'hollowCircle', } return ( <Row style={{ marginBottom: '-55px' }}> <Chart {...threadStateChartOpts}> <Tooltip /> <Axis dataKey="count" /> {/* // @ts-ignore */} <Axis dataKey="timestamp" label={null} line={null} tickLine={null} /> <Line {...threadStateSeriesOpts} /> <Legend {...threadStateLegendOpts} /> <Point {...threadStatePointOpts} /> </Chart> </Row> ) } private prepareLineChartData(newDump: any) { this.lineChartDataSource.push({ timestamp: moment(newDump.timestamp).format('HH:mm:ss'), dumps: newDump.dumps, }) // 折线图 const timestamps: any = [] const threadStateDatas = this.lineChartDataSource.reduce((accumulator: any, dump: any) => { timestamps.push(dump.timestamp) const threadState = { waitedCount: 0, blockedCount: 0, timestamp: dump.timestamp, paddingData: dump.paddingData, } dump.dumps = dump.dumps.map((d: any) => { d.timestamp = dump.timestamp threadState.waitedCount += d.waitedCount threadState.blockedCount += d.blockedCount return d }) accumulator.push(threadState) return accumulator }, []) // 保证 data === TICK_COUNT, 这样条形图和折线图可以共用一个坐标轴 ~ while (timestamps.length !== TICK_COUNT) { if (timestamps.length > TICK_COUNT) { timestamps.splice(0, 1) } else { let t = timestamps[timestamps.length - 1] t = moment(t, 'HH:mm:ss') .add(THREAD_DUMP_DATA_UPDATE_INTERVAL / 1000, 'second') .format('HH:mm:ss') timestamps.push(t) } } return { threadStateDatas, timestamps } } private prepareBarCharData(newDump: any, firstRequest: boolean) { this.dataSource.push(newDump) if (firstRequest) { const svg = d3 .select('#d3-thread-state') .append('svg') .attr('width', THREAD_CHART_WIDTH - LEGEND_WIDTH) this.svg = svg this.domain = new Array(TICK_COUNT).fill(0).map((__, i) => { return newDump.timestamp + i * THREAD_DUMP_DATA_UPDATE_INTERVAL }) } while (this.dataSource.length > TICK_COUNT) { // remove old data this.dataSource.splice(0, 1) this.domain.splice(0, 1) this.domain = this.domain.concat( this.domain[this.domain.length - 1] + THREAD_DUMP_DATA_UPDATE_INTERVAL ) } const chartColumnWidth = Math.round((THREAD_CHART_WIDTH - LEGEND_WIDTH) / TICK_COUNT) const maxLine = this.dataSource.reduce( (accumulator: any, current: any, index: number) => { if (current.dumps.length > accumulator.maxLineCount) { accumulator.maxLineIndex = index } accumulator.maxLineCount = d3.max([current.dumps.length, accumulator.maxLineCount]) return accumulator }, { maxLineCount: 0, maxLineIndex: 0 } ) const chartHeight = maxLine.maxLineCount * HEIGHT_PER_LINE + 40 const newFrameTransition = d3 .transition() .duration(this.dataSource.length > TICK_COUNT ? 0 : 275) .ease(d3.easeCubicInOut) as any let yAxisData = this.dataSource[maxLine.maxLineIndex].dumps yAxisData = yAxisData.map((d: any) => { const axisData = _.pick(d, ['threadState', 'threadId', 'threadName']) const latestDumpData = newDump.dumps.find((dump: any) => { return dump.threadId === axisData.threadId }) if (latestDumpData) { axisData.threadState = latestDumpData.threadState } return axisData }) this.svg.attr('height', chartHeight) const dumpClass = `dump_${newDump.timestamp}` const chartColumns = this.svg .selectAll('.chart-column') .data(this.dataSource, (d: any) => d.timestamp) // key to diff, d3 enter exit update pattern chartColumns .exit() .transition( d3 .transition() .duration(275) .ease(d3.easeCubicInOut) ) .attr('width', 0) .remove() chartColumns .enter() .append('g') .classed('chart-column', true) .classed(dumpClass, true) .attr('height', chartHeight) .attr('fill', '#ff00ff') .attr('transform', (_d: any, index: number) => { if (index === TICK_COUNT - 1) { return `translate(${(index + 1) * chartColumnWidth} ,${HEIGHT_PER_LINE} )` } return `translate(${index * chartColumnWidth} ,${HEIGHT_PER_LINE} )` }) .merge(chartColumns) .transition( d3 .transition() .duration(275) .ease(d3.easeCubicInOut) ) .attr( 'transform', (__: any, index: number) => `translate(${index * chartColumnWidth} ,${HEIGHT_PER_LINE} )` ) const newFrames = d3 .select(`.${dumpClass}`) .selectAll('dump-frame') .data(newDump.dumps) newFrames.exit().remove() newFrames .enter() .append('rect') .classed('dump-frame', true) .attr('y', (__: any, index: number) => index * HEIGHT_PER_LINE) .attr('height', '30px') .attr('fill', (d: any) => THREAD_STATE_COLOR_MAP[d.threadState]) .attr('stroke', (d: any) => THREAD_STATE_COLOR_MAP[d.threadState]) .attr('width', 0) .transition(newFrameTransition) .attr('width', chartColumnWidth + 1) return { domain: this.domain, yAxisData } } private renderBarChart() { const { yAxisData, domain } = this.state return ( <Row className="thread-state-chart-container"> <div className="y-axis html-legend"> {yAxisData.map((d: any) => { const state = d.threadState const styles = { background: THREAD_STATE_COLOR_MAP[state], } return ( <div className="legend" style={{ height: '30px' }} key={d.threadId}> <TransitionGroup> <CSSTransition timeout={175} key={THREAD_STATE_SHORT_MAP[state]} classNames="fade" exit={false}> <span className="stateTag" style={styles}> {THREAD_STATE_SHORT_MAP[state]} </span> </CSSTransition> </TransitionGroup> <p className="name">{d.threadName}</p> </div> ) })} </div> <div className="x-axis" style={{ width: (THREAD_CHART_WIDTH - LEGEND_WIDTH) / 0.8 }}> {' '} {/* CSS transform 0.8 for font-size */} {domain && domain.map(d => { return ( <p className="x-axis-item" key={d}> {moment(d).format('HH:mm:ss')} </p> ) })} </div> <Row id="d3-thread-state" /> </Row> ) } private fetchThreadInfo(id: string, initialized: boolean) { return applicationService.fetchApplicationThread(id, initialized) } } export default connect({ ThreadModel: applicationModels.Thread })(withRouter(Thread))
the_stack
import assert from "assert"; import { Storage, StorageListOptions, StorageListResult, StoredKey, StoredKeyMeta, StoredValue, StoredValueMeta, millisToSeconds, viewToArray, } from "@miniflare/shared"; import { listFilterMatch, listPaginate } from "@miniflare/storage-memory"; import { Commands, Pipeline } from "ioredis"; /** @internal */ export function _bufferFromArray(value: Uint8Array): Buffer { return Buffer.from(value.buffer, value.byteOffset, value.byteLength); } export class RedisStorage extends Storage { readonly #redis: Commands; constructor(redis: Commands, protected readonly namespace: string) { super(); this.#redis = redis; } // Store keys and metadata with different prefixes so scanning for keys only // returns one, and we can fetch metadata separately for listing readonly #key = (key: string): string => `${this.namespace}:value:${key}`; readonly #metaKey = (key: string): string => `${this.namespace}:meta:${key}`; // Throws any errors from the result of a pipeline // noinspection JSMethodCanBeStatic protected throwPipelineErrors(pipelineRes: [Error | null, unknown][]): void { for (const [error] of pipelineRes) if (error) throw error; } async has(key: string): Promise<boolean> { return (await this.#redis.exists(this.#key(key))) > 0; } async hasMany(keys: string[]): Promise<number> { if (keys.length === 0) return 0; return await this.#redis.exists(...keys.map(this.#key)); } get<Meta = unknown>( key: string, skipMetadata?: false ): Promise<StoredValueMeta<Meta> | undefined>; get(key: string, skipMetadata: true): Promise<StoredValue | undefined>; async get<Meta>( key: string, skipMetadata?: boolean ): Promise<StoredValueMeta<Meta> | undefined> { if (skipMetadata) { // If we don't need metadata, just get the value, Redis handles expiry const value = await this.#redis.getBuffer(this.#key(key)); return value === null ? undefined : { value: viewToArray(value) }; } // If we do, pipeline get the value, metadata and expiration TTL. Ideally, // we'd use EXPIRETIME here but it was only added in Redis 7 so support // wouldn't be great: https://redis.io/commands/expiretime const pipelineRes = await this.#redis .pipeline() .getBuffer(this.#key(key)) .get(this.#metaKey(key)) .pttl(this.#key(key)) .exec(); // Assert pipeline returned expected number of results successfully assert.strictEqual(pipelineRes.length, 3); this.throwPipelineErrors(pipelineRes); // Extract pipeline results const value: Buffer | null = pipelineRes[0][1]; const meta: string | null = pipelineRes[1][1]; const ttl: number = pipelineRes[2][1]; // Return result if (value === null) return undefined; return { value: viewToArray(value), metadata: meta ? JSON.parse(meta) : undefined, // Used PTTL so ttl is in milliseconds, negative TTL means key didn't // exist or no expiration expiration: ttl >= 0 ? millisToSeconds(Date.now() + ttl) : undefined, }; } getMany<Meta = unknown>( keys: string[], skipMetadata?: false ): Promise<(StoredValueMeta<Meta> | undefined)[]>; getMany( keys: string[], skipMetadata: true ): Promise<(StoredValue | undefined)[]>; async getMany<Meta = unknown>( keys: string[], skipMetadata?: boolean ): Promise<(StoredValueMeta<Meta> | undefined)[]> { if (keys.length === 0) return []; if (skipMetadata) { // If we don't need metadata, we can just get all the values, Redis will // handle expiry // @ts-expect-error mgetBuffer exists, it's just not in type definitions const values: (Buffer | null)[] = await this.#redis.mgetBuffer( ...keys.map(this.#key) ); return values.map((value) => value === null ? undefined : { value: viewToArray(value) } ); } // If we do, pipeline getting the value, then getting metadata, then // getting all expiration TTLs. Note there's no MPTTL command. Again, // ideally we'd use EXPIRETIME here. const redisKeys = keys.map(this.#key); const redisMetaKeys = keys.map(this.#metaKey); let pipeline: Pipeline = this.#redis .pipeline() // @ts-expect-error mgetBuffer exists, it's just not in type definitions .mgetBuffer(...redisKeys) .mget(...redisMetaKeys); for (const redisKey of redisKeys) pipeline = pipeline.pttl(redisKey); const pipelineRes = await pipeline.exec(); // Assert pipeline returned expected number of results successfully: // 2 (mgetBuffer + mget) + |keys| (pttl) assert.strictEqual(pipelineRes.length, 2 + keys.length); this.throwPipelineErrors(pipelineRes); // Extract pipeline results const values = pipelineRes[0][1]; const metas = pipelineRes[1][1]; // Should have value and meta for each key, even if null assert.strictEqual(values.length, keys.length); assert.strictEqual(metas.length, keys.length); // Return result const now = Date.now(); const res: (StoredValueMeta<Meta> | undefined)[] = new Array(keys.length); for (let i = 0; i < keys.length; i++) { // Extract pipeline results // (`2 +` for ttl is for getting past mgetBuffer + mget) const value: Buffer | null = values[i]; const meta: string | null = metas[i]; const ttl: number = pipelineRes[2 + i][1]; if (value === null) { res[i] = undefined; } else { res[i] = { value: viewToArray(value), metadata: meta ? JSON.parse(meta) : undefined, // Used PTTL so ttl is in milliseconds, negative TTL means key // didn't exist or no expiration expiration: ttl >= 0 ? millisToSeconds(now + ttl) : undefined, }; } } return res; } async put<Meta = unknown>( key: string, value: StoredValueMeta<Meta> ): Promise<void> { // May as well pipeline put as may need to set metadata too and reduces // code duplication await this.putMany([[key, value]]); } async putMany<Meta = unknown>( data: [key: string, value: StoredValueMeta<Meta>][] ): Promise<void> { let pipeline = this.#redis.pipeline(); // PX expiry mode is millisecond TTL. Ideally, we'd use EXAT as the mode // here instead, but it was added in Redis 6.2 so support wouldn't be great: // https://redis.io/commands/set#history const now = Date.now(); for (const [key, { value, expiration, metadata }] of data) { const redisKey = this.#key(key); const buffer = _bufferFromArray(value); // Work out millisecond TTL if defined (there are probably some rounding // errors here, but we'll only be off by a second so it's hopefully ok) const ttl = expiration === undefined ? undefined : expiration * 1000 - now; if (ttl === undefined) { pipeline = pipeline.set(redisKey, buffer); } else { pipeline = pipeline.set(redisKey, buffer, "PX", ttl); } if (metadata) { // Only store metadata if defined const redisMetaKey = this.#metaKey(key); const json = JSON.stringify(metadata); if (ttl === undefined) { pipeline = pipeline.set(redisMetaKey, json); } else { pipeline = pipeline.set(redisMetaKey, json, "PX", ttl); } } } // Assert pipeline completed successfully const pipelineRes = await pipeline.exec(); this.throwPipelineErrors(pipelineRes); } async delete(key: string): Promise<boolean> { // Delete the key and associated metadata const deleted = await this.#redis.del(this.#key(key), this.#metaKey(key)); // If we managed to delete a key, return true (we shouldn't ever be able // to delete just the metadata) return deleted > 0; } async deleteMany(keys: string[]): Promise<number> { if (keys.length === 0) return 0; // Delete the keys and their associated metadata. Do this separately so we // can work out the number of actual keys we deleted, as not all keys will // have metadata. const pipeline = this.#redis .pipeline() .del(...keys.map(this.#key)) .del(...keys.map(this.#metaKey)); const pipelineRes = await pipeline.exec(); // Assert pipeline returned expected number of results successfully assert.strictEqual(pipelineRes.length, 2); this.throwPipelineErrors(pipelineRes); // Return number of real keys deleted return pipelineRes[0][1]; } list<Meta = unknown>( options?: StorageListOptions, skipMetadata?: false ): Promise<StorageListResult<StoredKeyMeta<Meta>>>; list( options: StorageListOptions, skipMetadata: true ): Promise<StorageListResult<StoredKey>>; async list<Meta>( options?: StorageListOptions, skipMetadata?: boolean ): Promise<StorageListResult<StoredKeyMeta<Meta>>> { // Get the `NAMESPACE:value:` Redis key prefix so we can remove it const redisKeyPrefix = this.#key(""); // Scan all keys matching the prefix. This is quite inefficient but it would // be difficult to encode all list options in a Redis scan. // TODO (someday): could maybe use a sorted set and ZRANGEBYLEX: https://redis.io/commands/zrangebylex const keys = await new Promise<StoredKeyMeta<Meta>[]>((resolve) => { const keys: StoredKeyMeta<Meta>[] = []; const stream = this.#redis.scanStream({ // Always match the Redis key prefix, optionally match a user-specified // one too match: `${redisKeyPrefix}${options?.prefix ?? ""}*`, // TODO (someday): consider increasing page size a bit }); stream.on("data", (page: string[]) => { for (const key of page) { // Remove the Redis key prefix from each scanned key const name = key.substring(redisKeyPrefix.length); // Apply start and end filter if (listFilterMatch(options, name)) keys.push({ name }); } }); // Resolve the promise once we've fetched all matching keys stream.on("end", () => resolve(keys)); }); // Apply sort, cursor, and limit const res = listPaginate(options, keys); // If we don't need metadata, return now and save fetching it all if (skipMetadata || res.keys.length === 0) return res; // Fetch the metadata for the remaining keys. Note that we're not fetching // metadata for all keys originally matching the prefix, just the ones we're // going to return from the list after the filter. const redisMetaKeys = res.keys.map(({ name }) => this.#metaKey(name)); // Pipeline getting metadata and all expiration TTLs. Again, note there's no // MPTTL command and ideally we'd use EXPIRETIME here. let pipeline: Pipeline = this.#redis.pipeline().mget(...redisMetaKeys); for (const key of res.keys) pipeline = pipeline.pttl(this.#key(key.name)); const pipelineRes = await pipeline.exec(); // Assert pipeline returned expected number of results successfully: // 1 (mget) + |keys| (pttl) assert.strictEqual(pipelineRes.length, 1 + res.keys.length); this.throwPipelineErrors(pipelineRes); // Extract pipeline results const metas = pipelineRes[0][1]; assert.strictEqual(metas.length, res.keys.length); // Populate keys with metadata and expiration const now = Date.now(); for (let i = 0; i < res.keys.length; i++) { // Extract pipeline results (`1 +` for ttl is for getting past mget) const meta: string | null = metas[i]; const ttl: number = pipelineRes[1 + i][1]; res.keys[i].metadata = meta ? JSON.parse(meta) : undefined; // Used PTTL so ttl is in milliseconds, negative TTL means key // didn't exist or no expiration res.keys[i].expiration = ttl >= 0 ? millisToSeconds(now + ttl) : undefined; } return res; } }
the_stack
//prettier-ignore export const nonAsciiIdentifierMap: readonly number[] = [ 0xa0, 0x377, 0x37a, 0x37f, 0x384, 0x38a, 0x38c, 0x38c, 0x38e, 0x3a1, 0x3a3, 0x52f, 0x531, 0x556, 0x559, 0x58a, 0x58d, 0x58f, 0x591, 0x5c7, 0x5d0, 0x5ea, 0x5ef, 0x5f4, 0x600, 0x61c, 0x61e, 0x70d, 0x70f, 0x74a, 0x74d, 0x7b1, 0x7c0, 0x7fa, 0x7fd, 0x82d, 0x830, 0x83e, 0x840, 0x85b, 0x85e, 0x85e, 0x860, 0x86a, 0x8a0, 0x8b4, 0x8b6, 0x8c7, 0x8d3, 0x983, 0x985, 0x98c, 0x98f, 0x990, 0x993, 0x9a8, 0x9aa, 0x9b0, 0x9b2, 0x9b2, 0x9b6, 0x9b9, 0x9bc, 0x9c4, 0x9c7, 0x9c8, 0x9cb, 0x9ce, 0x9d7, 0x9d7, 0x9dc, 0x9dd, 0x9df, 0x9e3, 0x9e6, 0x9fe, 0xa01, 0xa03, 0xa05, 0xa0a, 0xa0f, 0xa10, 0xa13, 0xa28, 0xa2a, 0xa30, 0xa32, 0xa33, 0xa35, 0xa36, 0xa38, 0xa39, 0xa3c, 0xa3c, 0xa3e, 0xa42, 0xa47, 0xa48, 0xa4b, 0xa4d, 0xa51, 0xa51, 0xa59, 0xa5c, 0xa5e, 0xa5e, 0xa66, 0xa76, 0xa81, 0xa83, 0xa85, 0xa8d, 0xa8f, 0xa91, 0xa93, 0xaa8, 0xaaa, 0xab0, 0xab2, 0xab3, 0xab5, 0xab9, 0xabc, 0xac5, 0xac7, 0xac9, 0xacb, 0xacd, 0xad0, 0xad0, 0xae0, 0xae3, 0xae6, 0xaf1, 0xaf9, 0xaff, 0xb01, 0xb03, 0xb05, 0xb0c, 0xb0f, 0xb10, 0xb13, 0xb28, 0xb2a, 0xb30, 0xb32, 0xb33, 0xb35, 0xb39, 0xb3c, 0xb44, 0xb47, 0xb48, 0xb4b, 0xb4d, 0xb55, 0xb57, 0xb5c, 0xb5d, 0xb5f, 0xb63, 0xb66, 0xb77, 0xb82, 0xb83, 0xb85, 0xb8a, 0xb8e, 0xb90, 0xb92, 0xb95, 0xb99, 0xb9a, 0xb9c, 0xb9c, 0xb9e, 0xb9f, 0xba3, 0xba4, 0xba8, 0xbaa, 0xbae, 0xbb9, 0xbbe, 0xbc2, 0xbc6, 0xbc8, 0xbca, 0xbcd, 0xbd0, 0xbd0, 0xbd7, 0xbd7, 0xbe6, 0xbfa, 0xc00, 0xc0c, 0xc0e, 0xc10, 0xc12, 0xc28, 0xc2a, 0xc39, 0xc3d, 0xc44, 0xc46, 0xc48, 0xc4a, 0xc4d, 0xc55, 0xc56, 0xc58, 0xc5a, 0xc60, 0xc63, 0xc66, 0xc6f, 0xc77, 0xc8c, 0xc8e, 0xc90, 0xc92, 0xca8, 0xcaa, 0xcb3, 0xcb5, 0xcb9, 0xcbc, 0xcc4, 0xcc6, 0xcc8, 0xcca, 0xccd, 0xcd5, 0xcd6, 0xcde, 0xcde, 0xce0, 0xce3, 0xce6, 0xcef, 0xcf1, 0xcf2, 0xd00, 0xd0c, 0xd0e, 0xd10, 0xd12, 0xd44, 0xd46, 0xd48, 0xd4a, 0xd4f, 0xd54, 0xd63, 0xd66, 0xd7f, 0xd81, 0xd83, 0xd85, 0xd96, 0xd9a, 0xdb1, 0xdb3, 0xdbb, 0xdbd, 0xdbd, 0xdc0, 0xdc6, 0xdca, 0xdca, 0xdcf, 0xdd4, 0xdd6, 0xdd6, 0xdd8, 0xddf, 0xde6, 0xdef, 0xdf2, 0xdf4, 0xe01, 0xe3a, 0xe3f, 0xe5b, 0xe81, 0xe82, 0xe84, 0xe84, 0xe86, 0xe8a, 0xe8c, 0xea3, 0xea5, 0xea5, 0xea7, 0xebd, 0xec0, 0xec4, 0xec6, 0xec6, 0xec8, 0xecd, 0xed0, 0xed9, 0xedc, 0xedf, 0xf00, 0xf47, 0xf49, 0xf6c, 0xf71, 0xf97, 0xf99, 0xfbc, 0xfbe, 0xfcc, 0xfce, 0xfda, 0x1000, 0x10c5, 0x10c7, 0x10c7, 0x10cd, 0x10cd, 0x10d0, 0x1248, 0x124a, 0x124d, 0x1250, 0x1256, 0x1258, 0x1258, 0x125a, 0x125d, 0x1260, 0x1288, 0x128a, 0x128d, 0x1290, 0x12b0, 0x12b2, 0x12b5, 0x12b8, 0x12be, 0x12c0, 0x12c0, 0x12c2, 0x12c5, 0x12c8, 0x12d6, 0x12d8, 0x1310, 0x1312, 0x1315, 0x1318, 0x135a, 0x135d, 0x137c, 0x1380, 0x1399, 0x13a0, 0x13f5, 0x13f8, 0x13fd, 0x1400, 0x169c, 0x16a0, 0x16f8, 0x1700, 0x170c, 0x170e, 0x1714, 0x1720, 0x1736, 0x1740, 0x1753, 0x1760, 0x176c, 0x176e, 0x1770, 0x1772, 0x1773, 0x1780, 0x17dd, 0x17e0, 0x17e9, 0x17f0, 0x17f9, 0x1800, 0x180e, 0x1810, 0x1819, 0x1820, 0x1878, 0x1880, 0x18aa, 0x18b0, 0x18f5, 0x1900, 0x191e, 0x1920, 0x192b, 0x1930, 0x193b, 0x1940, 0x1940, 0x1944, 0x196d, 0x1970, 0x1974, 0x1980, 0x19ab, 0x19b0, 0x19c9, 0x19d0, 0x19da, 0x19de, 0x1a1b, 0x1a1e, 0x1a5e, 0x1a60, 0x1a7c, 0x1a7f, 0x1a89, 0x1a90, 0x1a99, 0x1aa0, 0x1aad, 0x1ab0, 0x1ac0, 0x1b00, 0x1b4b, 0x1b50, 0x1b7c, 0x1b80, 0x1bf3, 0x1bfc, 0x1c37, 0x1c3b, 0x1c49, 0x1c4d, 0x1c88, 0x1c90, 0x1cba, 0x1cbd, 0x1cc7, 0x1cd0, 0x1cfa, 0x1d00, 0x1df9, 0x1dfb, 0x1f15, 0x1f18, 0x1f1d, 0x1f20, 0x1f45, 0x1f48, 0x1f4d, 0x1f50, 0x1f57, 0x1f59, 0x1f59, 0x1f5b, 0x1f5b, 0x1f5d, 0x1f5d, 0x1f5f, 0x1f7d, 0x1f80, 0x1fb4, 0x1fb6, 0x1fc4, 0x1fc6, 0x1fd3, 0x1fd6, 0x1fdb, 0x1fdd, 0x1fef, 0x1ff2, 0x1ff4, 0x1ff6, 0x1ffe, 0x2000, 0x200d, 0x2010, 0x2027, 0x202a, 0x2064, 0x2066, 0x2071, 0x2074, 0x208e, 0x2090, 0x209c, 0x20a0, 0x20bf, 0x20d0, 0x20f0, 0x2100, 0x218b, 0x2190, 0x2426, 0x2440, 0x244a, 0x2460, 0x2b73, 0x2b76, 0x2b95, 0x2b97, 0x2c2e, 0x2c30, 0x2c5e, 0x2c60, 0x2cf3, 0x2cf9, 0x2d25, 0x2d27, 0x2d27, 0x2d2d, 0x2d2d, 0x2d30, 0x2d67, 0x2d6f, 0x2d70, 0x2d7f, 0x2d96, 0x2da0, 0x2da6, 0x2da8, 0x2dae, 0x2db0, 0x2db6, 0x2db8, 0x2dbe, 0x2dc0, 0x2dc6, 0x2dc8, 0x2dce, 0x2dd0, 0x2dd6, 0x2dd8, 0x2dde, 0x2de0, 0x2e52, 0x2e80, 0x2e99, 0x2e9b, 0x2ef3, 0x2f00, 0x2fd5, 0x2ff0, 0x2ffb, 0x3000, 0x303f, 0x3041, 0x3096, 0x3099, 0x30ff, 0x3105, 0x312f, 0x3131, 0x318e, 0x3190, 0x31e3, 0x31f0, 0x321e, 0x3220, 0x9ffc, 0xa000, 0xa48c, 0xa490, 0xa4c6, 0xa4d0, 0xa62b, 0xa640, 0xa6f7, 0xa700, 0xa7bf, 0xa7c2, 0xa7ca, 0xa7f5, 0xa82c, 0xa830, 0xa839, 0xa840, 0xa877, 0xa880, 0xa8c5, 0xa8ce, 0xa8d9, 0xa8e0, 0xa953, 0xa95f, 0xa97c, 0xa980, 0xa9cd, 0xa9cf, 0xa9d9, 0xa9de, 0xa9fe, 0xaa00, 0xaa36, 0xaa40, 0xaa4d, 0xaa50, 0xaa59, 0xaa5c, 0xaac2, 0xaadb, 0xaaf6, 0xab01, 0xab06, 0xab09, 0xab0e, 0xab11, 0xab16, 0xab20, 0xab26, 0xab28, 0xab2e, 0xab30, 0xab6b, 0xab70, 0xabed, 0xabf0, 0xabf9, 0xac00, 0xd7a3, 0xd7b0, 0xd7c6, 0xd7cb, 0xd7fb, 0xf900, 0xfa6d, 0xfa70, 0xfad9, 0xfb00, 0xfb06, 0xfb13, 0xfb17, 0xfb1d, 0xfb36, 0xfb38, 0xfb3c, 0xfb3e, 0xfb3e, 0xfb40, 0xfb41, 0xfb43, 0xfb44, 0xfb46, 0xfbc1, 0xfbd3, 0xfd3f, 0xfd50, 0xfd8f, 0xfd92, 0xfdc7, 0xfdf0, 0xfdfd, 0xfe00, 0xfe19, 0xfe20, 0xfe52, 0xfe54, 0xfe66, 0xfe68, 0xfe6b, 0xfe70, 0xfe74, 0xfe76, 0xfefc, 0xfeff, 0xfeff, 0xff01, 0xffbe, 0xffc2, 0xffc7, 0xffca, 0xffcf, 0xffd2, 0xffd7, 0xffda, 0xffdc, 0xffe0, 0xffe6, 0xffe8, 0xffee, 0xfff9, 0xfffd, 0x10000, 0x1000b, 0x1000d, 0x10026, 0x10028, 0x1003a, 0x1003c, 0x1003d, 0x1003f, 0x1004d, 0x10050, 0x1005d, 0x10080, 0x100fa, 0x10100, 0x10102, 0x10107, 0x10133, 0x10137, 0x1018e, 0x10190, 0x1019c, 0x101a0, 0x101a0, 0x101d0, 0x101fd, 0x10280, 0x1029c, 0x102a0, 0x102d0, 0x102e0, 0x102fb, 0x10300, 0x10323, 0x1032d, 0x1034a, 0x10350, 0x1037a, 0x10380, 0x1039d, 0x1039f, 0x103c3, 0x103c8, 0x103d5, 0x10400, 0x1049d, 0x104a0, 0x104a9, 0x104b0, 0x104d3, 0x104d8, 0x104fb, 0x10500, 0x10527, 0x10530, 0x10563, 0x1056f, 0x1056f, 0x10600, 0x10736, 0x10740, 0x10755, 0x10760, 0x10767, 0x10800, 0x10805, 0x10808, 0x10808, 0x1080a, 0x10835, 0x10837, 0x10838, 0x1083c, 0x1083c, 0x1083f, 0x10855, 0x10857, 0x1089e, 0x108a7, 0x108af, 0x108e0, 0x108f2, 0x108f4, 0x108f5, 0x108fb, 0x1091b, 0x1091f, 0x10939, 0x1093f, 0x1093f, 0x10980, 0x109b7, 0x109bc, 0x109cf, 0x109d2, 0x10a03, 0x10a05, 0x10a06, 0x10a0c, 0x10a13, 0x10a15, 0x10a17, 0x10a19, 0x10a35, 0x10a38, 0x10a3a, 0x10a3f, 0x10a48, 0x10a50, 0x10a58, 0x10a60, 0x10a9f, 0x10ac0, 0x10ae6, 0x10aeb, 0x10af6, 0x10b00, 0x10b35, 0x10b39, 0x10b55, 0x10b58, 0x10b72, 0x10b78, 0x10b91, 0x10b99, 0x10b9c, 0x10ba9, 0x10baf, 0x10c00, 0x10c48, 0x10c80, 0x10cb2, 0x10cc0, 0x10cf2, 0x10cfa, 0x10d27, 0x10d30, 0x10d39, 0x10e60, 0x10e7e, 0x10e80, 0x10ea9, 0x10eab, 0x10ead, 0x10eb0, 0x10eb1, 0x10f00, 0x10f27, 0x10f30, 0x10f59, 0x10fb0, 0x10fcb, 0x10fe0, 0x10ff6, 0x11000, 0x1104d, 0x11052, 0x1106f, 0x1107f, 0x110c1, 0x110cd, 0x110cd, 0x110d0, 0x110e8, 0x110f0, 0x110f9, 0x11100, 0x11134, 0x11136, 0x11147, 0x11150, 0x11176, 0x11180, 0x111df, 0x111e1, 0x111f4, 0x11200, 0x11211, 0x11213, 0x1123e, 0x11280, 0x11286, 0x11288, 0x11288, 0x1128a, 0x1128d, 0x1128f, 0x1129d, 0x1129f, 0x112a9, 0x112b0, 0x112ea, 0x112f0, 0x112f9, 0x11300, 0x11303, 0x11305, 0x1130c, 0x1130f, 0x11310, 0x11313, 0x11328, 0x1132a, 0x11330, 0x11332, 0x11333, 0x11335, 0x11339, 0x1133b, 0x11344, 0x11347, 0x11348, 0x1134b, 0x1134d, 0x11350, 0x11350, 0x11357, 0x11357, 0x1135d, 0x11363, 0x11366, 0x1136c, 0x11370, 0x11374, 0x11400, 0x1145b, 0x1145d, 0x11461, 0x11480, 0x114c7, 0x114d0, 0x114d9, 0x11580, 0x115b5, 0x115b8, 0x115dd, 0x11600, 0x11644, 0x11650, 0x11659, 0x11660, 0x1166c, 0x11680, 0x116b8, 0x116c0, 0x116c9, 0x11700, 0x1171a, 0x1171d, 0x1172b, 0x11730, 0x1173f, 0x11800, 0x1183b, 0x118a0, 0x118f2, 0x118ff, 0x11906, 0x11909, 0x11909, 0x1190c, 0x11913, 0x11915, 0x11916, 0x11918, 0x11935, 0x11937, 0x11938, 0x1193b, 0x11946, 0x11950, 0x11959, 0x119a0, 0x119a7, 0x119aa, 0x119d7, 0x119da, 0x119e4, 0x11a00, 0x11a47, 0x11a50, 0x11aa2, 0x11ac0, 0x11af8, 0x11c00, 0x11c08, 0x11c0a, 0x11c36, 0x11c38, 0x11c45, 0x11c50, 0x11c6c, 0x11c70, 0x11c8f, 0x11c92, 0x11ca7, 0x11ca9, 0x11cb6, 0x11d00, 0x11d06, 0x11d08, 0x11d09, 0x11d0b, 0x11d36, 0x11d3a, 0x11d3a, 0x11d3c, 0x11d3d, 0x11d3f, 0x11d47, 0x11d50, 0x11d59, 0x11d60, 0x11d65, 0x11d67, 0x11d68, 0x11d6a, 0x11d8e, 0x11d90, 0x11d91, 0x11d93, 0x11d98, 0x11da0, 0x11da9, 0x11ee0, 0x11ef8, 0x11fb0, 0x11fb0, 0x11fc0, 0x11ff1, 0x11fff, 0x12399, 0x12400, 0x1246e, 0x12470, 0x12474, 0x12480, 0x12543, 0x13000, 0x1342e, 0x13430, 0x13438, 0x14400, 0x14646, 0x16800, 0x16a38, 0x16a40, 0x16a5e, 0x16a60, 0x16a69, 0x16a6e, 0x16a6f, 0x16ad0, 0x16aed, 0x16af0, 0x16af5, 0x16b00, 0x16b45, 0x16b50, 0x16b59, 0x16b5b, 0x16b61, 0x16b63, 0x16b77, 0x16b7d, 0x16b8f, 0x16e40, 0x16e9a, 0x16f00, 0x16f4a, 0x16f4f, 0x16f87, 0x16f8f, 0x16f9f, 0x16fe0, 0x16fe4, 0x16ff0, 0x16ff1, 0x17000, 0x187f7, 0x18800, 0x18cd5, 0x18d00, 0x18d08, 0x1b000, 0x1b11e, 0x1b150, 0x1b152, 0x1b164, 0x1b167, 0x1b170, 0x1b2fb, 0x1bc00, 0x1bc6a, 0x1bc70, 0x1bc7c, 0x1bc80, 0x1bc88, 0x1bc90, 0x1bc99, 0x1bc9c, 0x1bca3, 0x1d000, 0x1d0f5, 0x1d100, 0x1d126, 0x1d129, 0x1d1e8, 0x1d200, 0x1d245, 0x1d2e0, 0x1d2f3, 0x1d300, 0x1d356, 0x1d360, 0x1d378, 0x1d400, 0x1d454, 0x1d456, 0x1d49c, 0x1d49e, 0x1d49f, 0x1d4a2, 0x1d4a2, 0x1d4a5, 0x1d4a6, 0x1d4a9, 0x1d4ac, 0x1d4ae, 0x1d4b9, 0x1d4bb, 0x1d4bb, 0x1d4bd, 0x1d4c3, 0x1d4c5, 0x1d505, 0x1d507, 0x1d50a, 0x1d50d, 0x1d514, 0x1d516, 0x1d51c, 0x1d51e, 0x1d539, 0x1d53b, 0x1d53e, 0x1d540, 0x1d544, 0x1d546, 0x1d546, 0x1d54a, 0x1d550, 0x1d552, 0x1d6a5, 0x1d6a8, 0x1d7cb, 0x1d7ce, 0x1da8b, 0x1da9b, 0x1da9f, 0x1daa1, 0x1daaf, 0x1e000, 0x1e006, 0x1e008, 0x1e018, 0x1e01b, 0x1e021, 0x1e023, 0x1e024, 0x1e026, 0x1e02a, 0x1e100, 0x1e12c, 0x1e130, 0x1e13d, 0x1e140, 0x1e149, 0x1e14e, 0x1e14f, 0x1e2c0, 0x1e2f9, 0x1e2ff, 0x1e2ff, 0x1e800, 0x1e8c4, 0x1e8c7, 0x1e8d6, 0x1e900, 0x1e94b, 0x1e950, 0x1e959, 0x1e95e, 0x1e95f, 0x1ec71, 0x1ecb4, 0x1ed01, 0x1ed3d, 0x1ee00, 0x1ee03, 0x1ee05, 0x1ee1f, 0x1ee21, 0x1ee22, 0x1ee24, 0x1ee24, 0x1ee27, 0x1ee27, 0x1ee29, 0x1ee32, 0x1ee34, 0x1ee37, 0x1ee39, 0x1ee39, 0x1ee3b, 0x1ee3b, 0x1ee42, 0x1ee42, 0x1ee47, 0x1ee47, 0x1ee49, 0x1ee49, 0x1ee4b, 0x1ee4b, 0x1ee4d, 0x1ee4f, 0x1ee51, 0x1ee52, 0x1ee54, 0x1ee54, 0x1ee57, 0x1ee57, 0x1ee59, 0x1ee59, 0x1ee5b, 0x1ee5b, 0x1ee5d, 0x1ee5d, 0x1ee5f, 0x1ee5f, 0x1ee61, 0x1ee62, 0x1ee64, 0x1ee64, 0x1ee67, 0x1ee6a, 0x1ee6c, 0x1ee72, 0x1ee74, 0x1ee77, 0x1ee79, 0x1ee7c, 0x1ee7e, 0x1ee7e, 0x1ee80, 0x1ee89, 0x1ee8b, 0x1ee9b, 0x1eea1, 0x1eea3, 0x1eea5, 0x1eea9, 0x1eeab, 0x1eebb, 0x1eef0, 0x1eef1, 0x1f000, 0x1f02b, 0x1f030, 0x1f093, 0x1f0a0, 0x1f0ae, 0x1f0b1, 0x1f0bf, 0x1f0c1, 0x1f0cf, 0x1f0d1, 0x1f0f5, 0x1f100, 0x1f1ad, 0x1f1e6, 0x1f202, 0x1f210, 0x1f23b, 0x1f240, 0x1f248, 0x1f250, 0x1f251, 0x1f260, 0x1f265, 0x1f300, 0x1f6d7, 0x1f6e0, 0x1f6ec, 0x1f6f0, 0x1f6fc, 0x1f700, 0x1f773, 0x1f780, 0x1f7d8, 0x1f7e0, 0x1f7eb, 0x1f800, 0x1f80b, 0x1f810, 0x1f847, 0x1f850, 0x1f859, 0x1f860, 0x1f887, 0x1f890, 0x1f8ad, 0x1f8b0, 0x1f8b1, 0x1f900, 0x1f978, 0x1f97a, 0x1f9cb, 0x1f9cd, 0x1fa53, 0x1fa60, 0x1fa6d, 0x1fa70, 0x1fa74, 0x1fa78, 0x1fa7a, 0x1fa80, 0x1fa86, 0x1fa90, 0x1faa8, 0x1fab0, 0x1fab6, 0x1fac0, 0x1fac2, 0x1fad0, 0x1fad6, 0x1fb00, 0x1fb92, 0x1fb94, 0x1fbca, 0x1fbf0, 0x1fbf9, 0x20000, 0x2a6dd, 0x2a700, 0x2b734, 0x2b740, 0x2b81d, 0x2b820, 0x2cea1, 0x2ceb0, 0x2ebe0, 0x2f800, 0x2fa1d, 0x30000, 0x3134a, 0xe0001, 0xe0001, 0xe0020, 0xe007f, 0xe0100, 0xe01ef, ];
the_stack
import {clamp} from '@math.gl/core'; import Controller from './controller'; import ViewState from './view-state'; import {mod} from '../utils/math-utils'; import type Viewport from '../viewports/viewport'; import LinearInterpolator from '../transitions/linear-interpolator'; export type OrbitStateProps = { width: number; height: number; target?: number[]; zoom?: number | number[]; rotationX?: number; rotationOrbit?: number; /** Viewport constraints */ maxZoom?: number; minZoom?: number; minRotationX?: number; maxRotationX?: number; }; type OrbitStateInternal = { startPanPosition?: number[]; startRotatePos?: number[]; startRotationX?: number; startRotationOrbit?: number; startZoomPosition?: number[]; startZoom?: number | number[]; }; export class OrbitState extends ViewState<OrbitState, OrbitStateProps, OrbitStateInternal> { makeViewport: (props: Record<string, any>) => Viewport; constructor( options: OrbitStateProps & OrbitStateInternal & { makeViewport: (props: Record<string, any>) => Viewport; } ) { const { /* Viewport arguments */ width, // Width of viewport height, // Height of viewport rotationX = 0, // Rotation around x axis rotationOrbit = 0, // Rotation around orbit axis target = [0, 0, 0], zoom = 0, /* Viewport constraints */ minRotationX = -90, maxRotationX = 90, minZoom = -Infinity, maxZoom = Infinity, /** Interaction states, required to calculate change during transform */ // Model state when the pan operation first started startPanPosition, // Model state when the rotate operation first started startRotatePos, startRotationX, startRotationOrbit, // Model state when the zoom operation first started startZoomPosition, startZoom } = options; super( { width, height, rotationX, rotationOrbit, target, zoom, minRotationX, maxRotationX, minZoom, maxZoom }, { startPanPosition, startRotatePos, startRotationX, startRotationOrbit, startZoomPosition, startZoom } ); this.makeViewport = options.makeViewport; } /** * Start panning * @param {[Number, Number]} pos - position on screen where the pointer grabs */ panStart({pos}: {pos: [number, number]}): OrbitState { return this._getUpdatedState({ startPanPosition: this._unproject(pos) }); } /** * Pan * @param {[Number, Number]} pos - position on screen where the pointer is */ pan({pos, startPosition}: {pos: [number, number]; startPosition?: number[]}): OrbitState { const startPanPosition = this.getState().startPanPosition || startPosition; if (!startPanPosition) { return this; } const viewport = this.makeViewport(this.getViewportProps()); const newProps = viewport.panByPosition(startPanPosition, pos); return this._getUpdatedState(newProps); } /** * End panning * Must call if `panStart()` was called */ panEnd(): OrbitState { return this._getUpdatedState({ startPanPosition: null }); } /** * Start rotating * @param {[Number, Number]} pos - position on screen where the pointer grabs */ rotateStart({pos}: {pos: [number, number]}): OrbitState { return this._getUpdatedState({ startRotatePos: pos, startRotationX: this.getViewportProps().rotationX, startRotationOrbit: this.getViewportProps().rotationOrbit }); } /** * Rotate * @param {[Number, Number]} pos - position on screen where the pointer is */ rotate({ pos, deltaAngleX = 0, deltaAngleY = 0 }: { pos?: [number, number]; deltaAngleX?: number; deltaAngleY?: number; }): OrbitState { const {startRotatePos, startRotationX, startRotationOrbit} = this.getState(); const {width, height} = this.getViewportProps(); if (!startRotatePos || startRotationX === undefined || startRotationOrbit === undefined) { return this; } let newRotation; if (pos) { let deltaScaleX = (pos[0] - startRotatePos[0]) / width; const deltaScaleY = (pos[1] - startRotatePos[1]) / height; if (startRotationX < -90 || startRotationX > 90) { // When looking at the "back" side of the scene, invert horizontal drag // so that the camera movement follows user input deltaScaleX *= -1; } newRotation = { rotationX: startRotationX + deltaScaleY * 180, rotationOrbit: startRotationOrbit + deltaScaleX * 180 }; } else { newRotation = { rotationX: startRotationX + deltaAngleY, rotationOrbit: startRotationOrbit + deltaAngleX }; } return this._getUpdatedState(newRotation); } /** * End rotating * Must call if `rotateStart()` was called */ rotateEnd(): OrbitState { return this._getUpdatedState({ startRotationX: null, startRotationOrbit: null }); } // shortest path between two view states shortestPathFrom(viewState: OrbitState): OrbitStateProps { const fromProps = viewState.getViewportProps(); const props = {...this.getViewportProps()}; const {rotationOrbit} = props; if (Math.abs(rotationOrbit - fromProps.rotationOrbit) > 180) { props.rotationOrbit = rotationOrbit < 0 ? rotationOrbit + 360 : rotationOrbit - 360; } return props; } /** * Start zooming * @param {[Number, Number]} pos - position on screen where the pointer grabs */ zoomStart({pos}: {pos: [number, number]}): OrbitState { return this._getUpdatedState({ startZoomPosition: this._unproject(pos), startZoom: this.getViewportProps().zoom }); } /** * Zoom * @param {[Number, Number]} pos - position on screen where the current target is * @param {[Number, Number]} startPos - the target position at * the start of the operation. Must be supplied of `zoomStart()` was not called * @param {Number} scale - a number between [0, 1] specifying the accumulated * relative scale. */ zoom({ pos, startPos, scale }: { pos: [number, number]; startPos?: [number, number]; scale: number; }): OrbitState { let {startZoom, startZoomPosition} = this.getState(); if (!startZoomPosition) { // We have two modes of zoom: // scroll zoom that are discrete events (transform from the current zoom level), // and pinch zoom that are continuous events (transform from the zoom level when // pinch started). // If startZoom state is defined, then use the startZoom state; // otherwise assume discrete zooming startZoom = this.getViewportProps().zoom; startZoomPosition = this._unproject(startPos) || this._unproject(pos); } if (!startZoomPosition) { return this; } const newZoom = this._calculateNewZoom({scale, startZoom}); const zoomedViewport = this.makeViewport({...this.getViewportProps(), zoom: newZoom}); return this._getUpdatedState({ zoom: newZoom, ...zoomedViewport.panByPosition(startZoomPosition, pos) }); } /** * End zooming * Must call if `zoomStart()` was called */ zoomEnd(): OrbitState { return this._getUpdatedState({ startZoomPosition: null, startZoom: null }); } zoomIn(speed: number = 2): OrbitState { return this._getUpdatedState({ zoom: this._calculateNewZoom({scale: speed}) }); } zoomOut(speed: number = 2): OrbitState { return this._getUpdatedState({ zoom: this._calculateNewZoom({scale: 1 / speed}) }); } moveLeft(speed: number = 50): OrbitState { return this._panFromCenter([-speed, 0]); } moveRight(speed: number = 50): OrbitState { return this._panFromCenter([speed, 0]); } moveUp(speed: number = 50): OrbitState { return this._panFromCenter([0, -speed]); } moveDown(speed: number = 50): OrbitState { return this._panFromCenter([0, speed]); } rotateLeft(speed: number = 15): OrbitState { return this._getUpdatedState({ rotationOrbit: this.getViewportProps().rotationOrbit - speed }); } rotateRight(speed: number = 15): OrbitState { return this._getUpdatedState({ rotationOrbit: this.getViewportProps().rotationOrbit + speed }); } rotateUp(speed: number = 10): OrbitState { return this._getUpdatedState({ rotationX: this.getViewportProps().rotationX - speed }); } rotateDown(speed: number = 10): OrbitState { return this._getUpdatedState({ rotationX: this.getViewportProps().rotationX + speed }); } /* Private methods */ _unproject(pos?: number[]): number[] | undefined { const viewport = this.makeViewport(this.getViewportProps()); // @ts-ignore return pos && viewport.unproject(pos); } // Calculates new zoom _calculateNewZoom({ scale, startZoom }: { scale: number; startZoom?: number | number[]; }): number | number[] { const {maxZoom, minZoom} = this.getViewportProps(); if (startZoom === undefined) { startZoom = this.getViewportProps().zoom; } const zoom = (startZoom as number) + Math.log2(scale); return clamp(zoom, minZoom, maxZoom); } _panFromCenter(offset) { const {width, height, target} = this.getViewportProps(); return this.pan({ startPosition: target, pos: [width / 2 + offset[0], height / 2 + offset[1]] }); } _getUpdatedState(newProps): OrbitState { // @ts-ignore return new this.constructor({ makeViewport: this.makeViewport, ...this.getViewportProps(), ...this.getState(), ...newProps }); } // Apply any constraints (mathematical or defined by _viewportProps) to map state applyConstraints(props: Required<OrbitStateProps>): Required<OrbitStateProps> { // Ensure zoom is within specified range const {maxZoom, minZoom, zoom, maxRotationX, minRotationX, rotationOrbit} = props; props.zoom = Array.isArray(zoom) ? [clamp(zoom[0], minZoom, maxZoom), clamp(zoom[1], minZoom, maxZoom)] : clamp(zoom, minZoom, maxZoom); props.rotationX = clamp(props.rotationX, minRotationX, maxRotationX); if (rotationOrbit < -180 || rotationOrbit > 180) { props.rotationOrbit = mod(rotationOrbit + 180, 360) - 180; } return props; } } export default class OrbitController extends Controller<OrbitState> { ControllerState = OrbitState; transition = { transitionDuration: 300, transitionInterpolator: new LinearInterpolator({ transitionProps: { compare: ['target', 'zoom', 'rotationX', 'rotationOrbit'], required: ['target', 'zoom'] } }) }; }
the_stack
import { isSpace, isDigit, isAlpha, findGroupEnd } from './utils'; import { Token, TokenType, REVERSED_KEYWORDS } from './tokens'; export class Lexer { text: string; pos: number; _isFunc = false; // func setup and prop value setup _isID = false; // solve dict pairs setup and prop value setup, cause number|string: value and id: value current_char?: string; constructor(text: string) { this.text = text; this.pos = 0; this.current_char = this.text[this.pos]; } error(msg = 'Invalid charater'): never { throw Error(msg); } advance(step = 1): string | undefined { this.pos += step; this.current_char = this.pos > this.text.length - 1 ? undefined : this.text[this.pos]; return this.current_char; } peek(): string | undefined { if (this.pos + 1 < this.text.length) { return this.text[this.pos + 1]; } } skip_whitespace(): void { while (this.current_char !== undefined && isSpace(this.current_char)) { this.advance(); } } string(char: '\'' | '"' | '`'): Token { let result = ''; let prev = ''; while(this.current_char !== undefined && (this.current_char !== char || prev === '\\')) { result += this.current_char; prev = this.current_char; this.advance(); } if (result) this.advance(); // right quote if (char === '`') { return new Token(TokenType.TEMPLATE, result); } this._isID = false; return new Token(TokenType.STRING, result); } keyword(): Token { // handle reversed keywords let result = ''; while (this.current_char !== undefined && isAlpha(this.current_char)) { result += this.current_char; this.advance(); } if (result in REVERSED_KEYWORDS) { const token = REVERSED_KEYWORDS[result]; if (result === 'js') { this.skip_whitespace(); this.advance(); const end = findGroupEnd(this.text, this.pos); token.value = this.text.slice(this.pos, end); this.pos = end + 1; this.current_char = this.text[end + 1]; } else if (result === 'func') { this._isFunc = true; } else if (result === 'apply') { let result = ''; let prev = ''; this.skip_whitespace(); while (this.current_char !== undefined && (this.current_char !== ';' || prev === '\\')) { result += this.current_char; prev = this.current_char; this.advance(); } token.value = result; } else if (result === 'attr' && this.current_char === '[') { let meta = ''; let char = ''; while (char !== undefined && char !== ']') { meta += char; this.advance(); char = this.current_char; } this.advance(); token.meta = meta; this.skip_whitespace(); let result = ''; let prev = ''; char = this.current_char; while (char !== undefined && (char !== ';' || prev === '\\')) { result += char; prev = this.current_char; this.advance(); char = this.current_char; } token.value = result; } return token; } this.error(); } numeric(): Token { let result = ''; while (this.current_char !== undefined && isDigit(this.current_char)) { // int result += this.current_char; this.advance(); } if (this.current_char === '.') { // float result += '.'; this.advance(); while (this.current_char !== undefined && isDigit(this.current_char)) { result += this.current_char; this.advance(); } } // size const next = this.text.slice(this.pos,); if (next.startsWith('rem')) { this.advance(3); return new Token(TokenType.REM, +result); } if (next.startsWith('px')) { this.advance(2); return new Token(TokenType.PIXEL, +result); } if (next.startsWith('em')) { this.advance(2); return new Token(TokenType.EM, +result); } if (next.startsWith('%')) { this.advance(); return new Token(TokenType.PERCENTAGE, +result); } if (next.startsWith('s')) { this.advance(); return new Token(TokenType.SECOND, +result); } if (next.startsWith('deg')) { this.advance(3); return new Token(TokenType.DEGREE, +result); } this._isID = false; return new Token(TokenType.NUMBER, +result); } color(): Token { let result = ''; while (this.current_char !== undefined && isAlpha(this.current_char)) { result += this.current_char; this.advance(); } return new Token(TokenType.COLOR, '#' + result); } id(): Token { let result = ''; while (this.current_char !== undefined && isAlpha(this.current_char)) { result += this.current_char; this.advance(); } this._isID = true; switch (result) { case 'and': return new Token(TokenType.AND, result); case 'or': return new Token(TokenType.OR, result); case 'not': if (this.peek_next_token().type === TokenType.IN) return new Token(TokenType.NOTIN, 'not in'); return new Token(TokenType.NOT, result); case 'from': return new Token(TokenType.FROM, result); case 'as': return new Token(TokenType.AS, result); case 'in': return new Token(TokenType.IN, result); case 'await': return new Token(TokenType.AWAIT, result); case 'new': return new Token(TokenType.NEW, result); case 'True': return new Token(TokenType.TRUE, 1); case 'False': return new Token(TokenType.FALSE, 0); case 'None': return new Token(TokenType.NONE, undefined); default: return new Token(TokenType.ID, result); } } property(): Token { let result = ''; let prev = ''; while (this.current_char !== undefined && (this.current_char !== ';' || prev === '\\')) { result += this.current_char; prev = this.current_char; this.advance(); } return new Token(/\${.*}/.test(result)? TokenType.TEMPLATE : TokenType.STRING, result); } unknown(): Token { let result = ''; let prev = ''; while (this.current_char !== undefined && (!['{', ';'].includes(this.current_char) || prev === '\\')) { result += this.current_char; prev = this.current_char; this.advance(); } this._isID = true; return new Token(TokenType.ID, result.trimEnd()); } peek_next_token(count = 1): Token { const pos = this.pos; const char = this.current_char; let token = this.get_next_token(); while (count > 1) { token = this.get_next_token(); count--; } this.pos = pos; this.current_char = char; return token; } get_next_token(): Token { let next: string | undefined; while (this.current_char !== undefined) { if (isSpace(this.current_char)) { this.skip_whitespace(); continue; } if (isDigit(this.current_char)) { return this.numeric(); } if (isAlpha(this.current_char)) { return this.id(); } switch (this.current_char) { case '@': this.advance(); return this.keyword(); case '$': this.advance(); return new Token(TokenType.DOLLAR, '$'); case '=': this.advance(); if (this.current_char === '=') { this.advance(); return new Token(TokenType.EQUAL, '=='); } if (this.current_char === '>') { this.advance(); return new Token(TokenType.ARROW, '=>'); } return new Token(TokenType.ASSIGN, '='); case '!': next = this.advance(); if (next === '=') { this.advance(); return new Token(TokenType.NOTEQUAL, '!='); } return new Token(TokenType.NO, '!'); case ':': this.advance(); if (this._isFunc || !this._isID) return new Token(TokenType.COLON, ':'); // dict pairs assign this.skip_whitespace(); // prop assign return this.property(); case ';': this.advance(); this._isFunc = false; return new Token(TokenType.SEMI, ';'); case '\'': this.advance(); return this.string('\''); case '"': this.advance(); return this.string('"'); case '`': this.advance(); return this.string('`'); case '#': this.advance(); return this.color(); case '{': this.advance(); this._isFunc = false; return new Token(TokenType.LCURLY, '{'); case '}': this.advance(); return new Token(TokenType.RCURLY, '}'); case '+': next = this.advance(); switch(next) { case '=': this.advance(); return new Token(TokenType.ADDEQUAL, '+='); case '+': this.advance(); return new Token(TokenType.INCREASE, '++'); } return new Token(TokenType.PLUS, '+'); case '-': next = this.advance(); switch(next) { case '=': this.advance(); return new Token(TokenType.MINUSEQUAL, '-='); case '-': this.advance(); return new Token(TokenType.DECREASE, '--'); } return new Token(TokenType.MINUS, '-'); case '%': next = this.advance(); if (next === '=') { this.advance(); return new Token(TokenType.MODEQUAL, '%='); } return new Token(TokenType.MOD, '%'); case '*': next = this.advance(); switch(next) { case '=': this.advance(); return new Token(TokenType.MULEQUAL, '*='); case '*': next = this.advance(); if (next === '=') { this.advance(); return new Token(TokenType.EXPEQUAL, '**='); } return new Token(TokenType.EXP, '**'); } return new Token(TokenType.MUL, '*'); case '/': this.advance(); return new Token(TokenType.DIV, '/'); case '>': next = this.advance(); if (next === '=') { this.advance(); return new Token(TokenType.GERATEREQUAL, '>='); } return new Token(TokenType.GERATER, '>'); case '<': next = this.advance(); if (next === '=') { this.advance(); return new Token(TokenType.LESSEQUAL, '<='); } return new Token(TokenType.LESS, '<'); case '?': this.advance(); return new Token(TokenType.TERNARY, '?'); case '(': this.advance(); return new Token(TokenType.LPAREN, '('); case ')': this.advance(); return new Token(TokenType.RPAREN, ')'); case '[': this.advance(); return new Token(TokenType.LSQUARE, '['); case ']': this.advance(); return new Token(TokenType.RSQUARE, ']'); case ',': this.advance(); return new Token(TokenType.COMMA, ','); case '.': if (!/^\.[^;]+{/.test(this.text.slice(this.pos))) { // not a selector this.advance(); return new Token(TokenType.DOT, '.'); } return this.unknown(); default: return this.unknown(); } } return new Token(TokenType.EOF, undefined); } }
the_stack
import type {Class, Initable} from "@swim/util"; import {Affinity, MemberFastenerClass, Animator} from "@swim/component"; import {AnyLength, Length, AnyAngle, Angle, AnyR2Point, R2Point, R2Box} from "@swim/math"; import {AnyFont, Font, AnyColor, Color} from "@swim/style"; import {Look, ThemeAnimator} from "@swim/theme"; import {ViewContextType, AnyView, View, ViewRef, ViewSet} from "@swim/view"; import {GraphicsViewInit, GraphicsView, TypesetView, TextRunView} from "@swim/graphics"; import {AnySliceView, SliceView} from "../slice/SliceView"; import type {PieViewObserver} from "./PieViewObserver"; /** @public */ export type AnyPieView = PieView | PieViewInit; /** @public */ export interface PieViewInit extends GraphicsViewInit { limit?: number; center?: AnyR2Point; baseAngle?: AnyAngle; innerRadius?: AnyLength; outerRadius?: AnyLength; padAngle?: AnyAngle; padRadius?: AnyLength | null; cornerRadius?: AnyLength; labelRadius?: AnyLength; sliceColor?: AnyColor; tickAlign?: number; tickRadius?: AnyLength; tickLength?: AnyLength; tickWidth?: AnyLength; tickPadding?: AnyLength; tickColor?: AnyColor; font?: AnyFont; textColor?: AnyColor; title?: GraphicsView | string; slices?: AnySliceView[]; } /** @public */ export interface PieViewSliceExt { attachLabelView(labelView: GraphicsView): void; detachLabelView(labelView: GraphicsView): void; attachLegendView(legendView: GraphicsView): void; detachLegendView(legendView: GraphicsView): void; } /** @public */ export class PieView extends GraphicsView { override readonly observerType?: Class<PieViewObserver>; @Animator({type: Number, value: 0, updateFlags: View.NeedsLayout}) readonly limit!: Animator<this, number>; @Animator({type: R2Point, value: R2Point.origin(), updateFlags: View.NeedsLayout}) readonly center!: Animator<this, R2Point, AnyR2Point>; @ThemeAnimator({type: Angle, value: Angle.rad(-Math.PI / 2), updateFlags: View.NeedsLayout}) readonly baseAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Length, value: Length.pct(3)}) readonly innerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.pct(25)}) readonly outerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Angle, value: Angle.deg(2)}) readonly padAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Length, value: null}) readonly padRadius!: ThemeAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Length, value: Length.zero()}) readonly cornerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.pct(50)}) readonly labelRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, value: null, look: Look.accentColor}) readonly sliceColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Number, value: 0.5}) readonly tickAlign!: ThemeAnimator<this, number>; @ThemeAnimator({type: Length, value: Length.pct(30)}) readonly tickRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.pct(50)}) readonly tickLength!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(1)}) readonly tickWidth!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, value: Length.px(2)}) readonly tickPadding!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, value: null, look: Look.neutralColor}) readonly tickColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Font, value: null, inherits: true}) readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>; @ThemeAnimator({type: Color, value: null, look: Look.mutedColor}) readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ViewRef<PieView, GraphicsView & Initable<GraphicsViewInit | string>>({ key: true, type: TextRunView, binds: true, initView(titleView: GraphicsView): void { if (TypesetView.is(titleView)) { titleView.textAlign.setState("center", Affinity.Intrinsic); titleView.textBaseline.setState("middle", Affinity.Intrinsic); titleView.textOrigin.setState(this.owner.center.state, Affinity.Intrinsic); } }, willAttachView(titleView: GraphicsView): void { this.owner.callObservers("viewWillAttachPieTitle", titleView, this.owner); }, didDetachView(titleView: GraphicsView): void { this.owner.callObservers("viewDidDetachPieTitle", titleView, this.owner); }, fromAny(value: AnyView<GraphicsView> | string): GraphicsView { if (typeof value === "string") { if (this.view instanceof TextRunView) { this.view.text(value); return this.view; } else { return TextRunView.fromAny(value); } } else { return GraphicsView.fromAny(value); } }, }) readonly title!: ViewRef<this, GraphicsView & Initable<GraphicsViewInit | string>>; static readonly title: MemberFastenerClass<PieView, "title">; @ViewSet<PieView, SliceView, PieViewSliceExt>({ implements: true, type: SliceView, binds: true, observes: true, willAttachView(sliceView: SliceView, targetView: View | null): void { this.owner.callObservers("viewWillAttachSlice", sliceView, targetView, this.owner); }, didAttachView(sliceView: SliceView): void { const labelView = sliceView.label.view; if (labelView !== null) { this.attachLabelView(labelView); } const legendView = sliceView.legend.view; if (legendView !== null) { this.attachLegendView(legendView); } }, willDetachView(sliceView: SliceView): void { const legendView = sliceView.legend.view; if (legendView !== null) { this.detachLegendView(legendView); } const labelView = sliceView.label.view; if (labelView !== null) { this.detachLabelView(labelView); } }, didDetachView(sliceView: SliceView): void { this.owner.callObservers("viewDidDetachSlice", sliceView, this.owner); }, viewDidSetSliceValue(newValue: number, oldValue: number): void { this.owner.requireUpdate(View.NeedsLayout); }, viewWillAttachSliceLabel(labelView: GraphicsView): void { this.attachLabelView(labelView); }, viewDidDetachSliceLabel(labelView: GraphicsView): void { this.detachLabelView(labelView); }, attachLabelView(labelView: GraphicsView): void { // hook }, detachLabelView(labelView: GraphicsView): void { // hook }, viewWillAttachSliceLegend(legendView: GraphicsView): void { this.attachLegendView(legendView); }, viewDidDetachSliceLegend(legendView: GraphicsView): void { this.detachLegendView(legendView); }, attachLegendView(legendView: GraphicsView): void { // hook }, detachLegendView(legendView: GraphicsView): void { // hook }, }) readonly slices!: ViewSet<this, SliceView> & PieViewSliceExt; static readonly slices: MemberFastenerClass<PieView, "slices">; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.layoutPie(this.viewFrame); } protected layoutPie(frame: R2Box): void { if (this.center.hasAffinity(Affinity.Intrinsic)) { const cx = (frame.xMin + frame.xMax) / 2; const cy = (frame.yMin + frame.yMax) / 2; this.center.setState(new R2Point(cx, cy), Affinity.Intrinsic); } const sliceViews = this.slices.views; let total = 0; for (const viewId in sliceViews) { const sliceView = sliceViews[viewId]!; const value = sliceView.value.getValue(); if (isFinite(value)) { total += value; } } total = Math.max(total, this.limit.getValue()); let baseAngle = this.baseAngle.getValue().rad(); for (const viewId in sliceViews) { const sliceView = sliceViews[viewId]!; sliceView.total.setState(total, Affinity.Intrinsic); sliceView.phaseAngle.setState(baseAngle, Affinity.Intrinsic); const value = sliceView.value.getValue(); if (isFinite(value)) { const delta = total !== 0 ? value / total : 0; baseAngle = Angle.rad(baseAngle.value + 2 * Math.PI * delta); } } const titleView = this.title.view; if (TypesetView.is(titleView)) { titleView.textOrigin.setState(this.center.value, Affinity.Intrinsic); } } override init(init: PieViewInit): void { super.init(init); if (init.limit !== void 0) { this.limit(init.limit); } if (init.center !== void 0) { this.center(init.center); } if (init.baseAngle !== void 0) { this.baseAngle(init.baseAngle); } if (init.innerRadius !== void 0) { this.innerRadius(init.innerRadius); } if (init.outerRadius !== void 0) { this.outerRadius(init.outerRadius); } if (init.padAngle !== void 0) { this.padAngle(init.padAngle); } if (init.padRadius !== void 0) { this.padRadius(init.padRadius); } if (init.cornerRadius !== void 0) { this.cornerRadius(init.cornerRadius); } if (init.labelRadius !== void 0) { this.labelRadius(init.labelRadius); } if (init.sliceColor !== void 0) { this.sliceColor(init.sliceColor); } if (init.tickAlign !== void 0) { this.tickAlign(init.tickAlign); } if (init.tickRadius !== void 0) { this.tickRadius(init.tickRadius); } if (init.tickLength !== void 0) { this.tickLength(init.tickLength); } if (init.tickWidth !== void 0) { this.tickWidth(init.tickWidth); } if (init.tickPadding !== void 0) { this.tickPadding(init.tickPadding); } if (init.tickColor !== void 0) { this.tickColor(init.tickColor); } if (init.font !== void 0) { this.font(init.font); } if (init.textColor !== void 0) { this.textColor(init.textColor); } if (init.title !== void 0) { this.title(init.title); } const slices = init.slices; if (slices !== void 0) { for (let i = 0, n = slices.length; i < n; i += 1) { const slice = slices[i]!; this.appendChild(SliceView.fromAny(slice), slice.key); } } } }
the_stack
import { HalfFloatType, OrthographicCamera, RGBFormat, Texture, TextureLoader, UnsignedByteType, Vector2, Vector4, WebGLRenderer } from "three"; import { AdvectionPass } from "./passes/AdvectionPass"; import { BoundaryPass } from "./passes/BoundaryPass"; import { ColorInitPass } from "./passes/ColorInitPass"; import { CompositionPass } from "./passes/CompositionPass"; import { DivergencePass } from "./passes/DivergencePass"; import { GradientSubstractionPass } from "./passes/GradientSubstractionPass"; import { JacobiIterationsPass } from "./passes/JacobiIterationsPass"; import { TouchColorPass } from "./passes/TouchColorPass"; import { TouchForcePass } from "./passes/TouchForcePass"; import { VelocityInitPass } from "./passes/VelocityInitPass"; import { RenderTarget } from "./RenderTarget"; // tslint:disable:no-var-requires const Stats = require("stats.js"); const dat = require("dat.gui"); // tslint:enable:no-var-requires const gradients: string[] = ["gradient.jpg"]; const gradientTextures: Texture[] = []; loadGradients(); // App configuration options. const configuration = { Simulate: true, Iterations: 32, Radius: 0.25, Scale: 0.5, ColorDecay: 0.01, Boundaries: true, AddColor: true, Visualize: "Color", Mode: "Spectral", Timestep: "1/60", Reset: () => { velocityAdvectionPass.update({ inputTexture: velocityInitTexture, velocity: velocityInitTexture }); colorAdvectionPass.update({ inputTexture: colorInitTexture, velocity: velocityInitTexture }); v = undefined; c = undefined; }, Github: () => { window.open("https://github.com/amsXYZ/three-fluid-sim"); }, Twitter: () => { window.open("https://twitter.com/_amsXYZ"); } }; // Html/Three.js initialization. const canvas = document.getElementById("canvas") as HTMLCanvasElement; const stats = new Stats(); canvas.parentElement.appendChild(stats.dom); const gui = new dat.GUI(); initGUI(); const renderer = new WebGLRenderer({ canvas }); renderer.autoClear = false; renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); const camera = new OrthographicCamera(0, 0, 0, 0, 0, 0); let dt = 1 / 60; // Check floating point texture support. if ( !( renderer.context.getExtension("OES_texture_half_float") && renderer.context.getExtension("OES_texture_half_float_linear") ) ) { alert("This demo is not supported on your device."); } const resolution = new Vector2( configuration.Scale * window.innerWidth, configuration.Scale * window.innerHeight ); const aspect = new Vector2(resolution.x / resolution.y, 1.0); // RenderTargets initialization. const velocityRT = new RenderTarget(resolution, 2, RGBFormat, HalfFloatType); const divergenceRT = new RenderTarget(resolution, 1, RGBFormat, HalfFloatType); const pressureRT = new RenderTarget(resolution, 2, RGBFormat, HalfFloatType); const colorRT = new RenderTarget(resolution, 2, RGBFormat, UnsignedByteType); // These variables are used to store the result the result of the different // render passes. Not needed but nice for convenience. let c: Texture; let v: Texture; let d: Texture; let p: Texture; // Render passes initialization. const velocityInitPass = new VelocityInitPass(renderer, resolution); const velocityInitTexture = velocityInitPass.render(); const colorInitPass = new ColorInitPass(renderer, resolution); const colorInitTexture = colorInitPass.render(); const velocityAdvectionPass = new AdvectionPass( velocityInitTexture, velocityInitTexture, 0 ); const colorAdvectionPass = new AdvectionPass( velocityInitTexture, colorInitTexture, configuration.ColorDecay ); const touchForceAdditionPass = new TouchForcePass( resolution, configuration.Radius ); const touchColorAdditionPass = new TouchColorPass( resolution, configuration.Radius ); const velocityBoundary = new BoundaryPass(); const velocityDivergencePass = new DivergencePass(); const pressurePass = new JacobiIterationsPass(); const pressureSubstractionPass = new GradientSubstractionPass(); const compositionPass = new CompositionPass(); // Event listeners (resizing and mouse/touch input). window.addEventListener("resize", (event: UIEvent) => { renderer.setSize(window.innerWidth, window.innerHeight); renderer.setPixelRatio(window.devicePixelRatio); resolution.set( configuration.Scale * window.innerWidth, configuration.Scale * window.innerHeight ); velocityRT.resize(resolution); divergenceRT.resize(resolution); pressureRT.resize(resolution); colorRT.resize(resolution); aspect.set(resolution.x / resolution.y, 1.0); touchForceAdditionPass.update({ aspect }); touchColorAdditionPass.update({ aspect }); }); window.addEventListener("keyup", (event: KeyboardEvent) => { if (event.keyCode === 72) { stats.dom.hidden = !stats.dom.hidden; } }); interface ITouchInput { id: string | number; input: Vector4; } let inputTouches: ITouchInput[] = []; canvas.addEventListener("mousedown", (event: MouseEvent) => { if (event.button === 0) { const x = (event.clientX / canvas.clientWidth) * aspect.x; const y = 1.0 - (event.clientY + window.scrollY) / canvas.clientHeight; inputTouches.push({ id: "mouse", input: new Vector4(x, y, 0, 0) }); } }); canvas.addEventListener("mousemove", (event: MouseEvent) => { if (inputTouches.length > 0) { const x = (event.clientX / canvas.clientWidth) * aspect.x; const y = 1.0 - (event.clientY + window.scrollY) / canvas.clientHeight; inputTouches[0].input .setZ(x - inputTouches[0].input.x) .setW(y - inputTouches[0].input.y); inputTouches[0].input.setX(x).setY(y); } }); canvas.addEventListener("mouseup", (event: MouseEvent) => { if (event.button === 0) { inputTouches.pop(); } }); canvas.addEventListener("touchstart", (event: TouchEvent) => { for (const touch of event.changedTouches) { const x = (touch.clientX / canvas.clientWidth) * aspect.x; const y = 1.0 - (touch.clientY + window.scrollY) / canvas.clientHeight; inputTouches.push({ id: touch.identifier, input: new Vector4(x, y, 0, 0) }); } }); canvas.addEventListener("touchmove", (event: TouchEvent) => { event.preventDefault(); for (const touch of event.changedTouches) { const registeredTouch = inputTouches.find(value => { return value.id === touch.identifier; }); if (registeredTouch !== undefined) { const x = (touch.clientX / canvas.clientWidth) * aspect.x; const y = 1.0 - (touch.clientY + window.scrollY) / canvas.clientHeight; registeredTouch.input .setZ(x - registeredTouch.input.x) .setW(y - registeredTouch.input.y); registeredTouch.input.setX(x).setY(y); } } }); canvas.addEventListener("touchend", (event: TouchEvent) => { for (const touch of event.changedTouches) { const registeredTouch = inputTouches.find(value => { return value.id === touch.identifier; }); if (registeredTouch !== undefined) { inputTouches = inputTouches.filter(value => { return value.id !== registeredTouch.id; }); } } }); canvas.addEventListener("touchcancel", (event: TouchEvent) => { for (let i = 0; i < inputTouches.length; ++i) { for (let j = 0; j < event.touches.length; ++j) { if (inputTouches[i].id === event.touches.item(j).identifier) { break; } else if (j === event.touches.length - 1) { inputTouches.splice(i--, 1); } } } }); // Dat.GUI configuration. function loadGradients() { const textureLoader = new TextureLoader().setPath("./resources/"); for (let i = 0; i < gradients.length; ++i) { textureLoader.load(gradients[i], (texture: Texture) => { gradientTextures[i] = texture; }); } } // Dat.GUI configuration. function initGUI() { const sim = gui.addFolder("Simulation"); sim .add(configuration, "Scale", 0.1, 2.0, 0.1) .onFinishChange((value: number) => { resolution.set( configuration.Scale * window.innerWidth, configuration.Scale * window.innerHeight ); velocityRT.resize(resolution); divergenceRT.resize(resolution); pressureRT.resize(resolution); colorRT.resize(resolution); }); sim.add(configuration, "Iterations", 16, 128, 1); sim.add(configuration, "ColorDecay", 0.0, 0.1, 0.01); sim .add(configuration, "Timestep", ["1/15", "1/30", "1/60", "1/90", "1/120"]) .onChange((value: string) => { switch (value) { case "1/15": dt = 1 / 15; break; case "1/30": dt = 1 / 30; break; case "1/60": dt = 1 / 60; break; case "1/90": dt = 1 / 90; break; case "1/120": dt = 1 / 120; break; } }); sim.add(configuration, "Simulate"); sim.add(configuration, "Boundaries"); sim.add(configuration, "Reset"); const input = gui.addFolder("Input"); input.add(configuration, "Radius", 0.1, 1, 0.1); input.add(configuration, "AddColor"); gui.add(configuration, "Visualize", [ "Color", "Velocity", "Divergence", "Pressure" ]); gui.add(configuration, "Mode", [ "Normal", "Luminance", "Spectral", "Gradient" ]); const github = gui.add(configuration, "Github"); github.__li.className = "guiIconText"; github.__li.style.borderLeft = "3px solid #8C8C8C"; const githubIcon = document.createElement("span"); githubIcon.className = "guiIcon github"; github.domElement.parentElement.appendChild(githubIcon); const twitter = gui.add(configuration, "Twitter"); twitter.__li.className = "guiIconText"; twitter.__li.style.borderLeft = "3px solid #8C8C8C"; const twitterIcon = document.createElement("span"); twitterIcon.className = "guiIcon twitter"; twitter.domElement.parentElement.appendChild(twitterIcon); } // Render loop. function render() { if (configuration.Simulate) { // Advect the velocity vector field. velocityAdvectionPass.update({ timeDelta: dt }); v = velocityRT.set(renderer); renderer.render(velocityAdvectionPass.scene, camera); // Add external forces/colors according to input. if (inputTouches.length > 0) { touchForceAdditionPass.update({ touches: inputTouches, radius: configuration.Radius, velocity: v }); v = velocityRT.set(renderer); renderer.render(touchForceAdditionPass.scene, camera); if (configuration.AddColor) { touchColorAdditionPass.update({ touches: inputTouches, radius: configuration.Radius, color: c }); c = colorRT.set(renderer); renderer.render(touchColorAdditionPass.scene, camera); } } // Add velocity boundaries (simulation walls). if (configuration.Boundaries) { velocityBoundary.update({ velocity: v }); v = velocityRT.set(renderer); renderer.render(velocityBoundary.scene, camera); } // Compute the divergence of the advected velocity vector field. velocityDivergencePass.update({ timeDelta: dt, velocity: v }); d = divergenceRT.set(renderer); renderer.render(velocityDivergencePass.scene, camera); // Compute the pressure gradient of the advected velocity vector field (using // jacobi iterations). pressurePass.update({ divergence: d }); for (let i = 0; i < configuration.Iterations; ++i) { p = pressureRT.set(renderer); renderer.render(pressurePass.scene, camera); pressurePass.update({ previousIteration: p }); } // Substract the pressure gradient from to obtain a velocity vector field with // zero divergence. pressureSubstractionPass.update({ timeDelta: dt, velocity: v, pressure: p }); v = velocityRT.set(renderer); renderer.render(pressureSubstractionPass.scene, camera); // Advect the color buffer with the divergence-free velocity vector field. colorAdvectionPass.update({ timeDelta: dt, inputTexture: c, velocity: v, decay: configuration.ColorDecay }); c = colorRT.set(renderer); renderer.render(colorAdvectionPass.scene, camera); // Feed the input of the advection passes with the last advected results. velocityAdvectionPass.update({ inputTexture: v, velocity: v }); colorAdvectionPass.update({ inputTexture: c }); } // Render to the main framebuffer the desired visualization. renderer.setRenderTarget(null); let visualization; switch (configuration.Visualize) { case "Color": visualization = c; break; case "Velocity": visualization = v; break; case "Divergence": visualization = d; break; case "Pressure": visualization = p; break; } compositionPass.update({ colorBuffer: visualization, mode: configuration.Mode, gradient: gradientTextures[0] }); renderer.render(compositionPass.scene, camera); } function animate() { requestAnimationFrame(animate); stats.begin(); render(); stats.end(); } animate();
the_stack
declare class AXCategoricalDataAxisDescriptor extends NSObject implements AXDataAxisDescriptor { static alloc(): AXCategoricalDataAxisDescriptor; // inherited from NSObject static new(): AXCategoricalDataAxisDescriptor; // inherited from NSObject categoryOrder: NSArray<string>; attributedTitle: NSAttributedString; // inherited from AXDataAxisDescriptor title: string; // inherited from AXDataAxisDescriptor constructor(o: { attributedTitle: NSAttributedString; categoryOrder: NSArray<string> | string[]; }); constructor(o: { title: string; categoryOrder: NSArray<string> | string[]; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithAttributedTitleCategoryOrder(attributedTitle: NSAttributedString, categoryOrder: NSArray<string> | string[]): this; initWithTitleCategoryOrder(title: string, categoryOrder: NSArray<string> | string[]): this; } interface AXChart extends NSObjectProtocol { accessibilityChartDescriptor: AXChartDescriptor; } declare var AXChart: { prototype: AXChart; }; declare class AXChartDescriptor extends NSObject implements NSCopying { static alloc(): AXChartDescriptor; // inherited from NSObject static new(): AXChartDescriptor; // inherited from NSObject additionalAxes: NSArray<AXDataAxisDescriptor>; attributedTitle: NSAttributedString; contentDirection: AXChartDescriptorContentDirection; contentFrame: CGRect; series: NSArray<AXDataSeriesDescriptor>; summary: string; title: string; xAxis: AXDataAxisDescriptor; yAxis: AXNumericDataAxisDescriptor; constructor(o: { attributedTitle: NSAttributedString; summary: string; xAxisDescriptor: AXDataAxisDescriptor; yAxisDescriptor: AXNumericDataAxisDescriptor; additionalAxes: NSArray<AXDataAxisDescriptor> | AXDataAxisDescriptor[]; series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]; }); constructor(o: { attributedTitle: NSAttributedString; summary: string; xAxisDescriptor: AXDataAxisDescriptor; yAxisDescriptor: AXNumericDataAxisDescriptor; series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]; }); constructor(o: { title: string; summary: string; xAxisDescriptor: AXDataAxisDescriptor; yAxisDescriptor: AXNumericDataAxisDescriptor; additionalAxes: NSArray<AXDataAxisDescriptor> | AXDataAxisDescriptor[]; series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]; }); constructor(o: { title: string; summary: string; xAxisDescriptor: AXDataAxisDescriptor; yAxisDescriptor: AXNumericDataAxisDescriptor; series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithAttributedTitleSummaryXAxisDescriptorYAxisDescriptorAdditionalAxesSeries(attributedTitle: NSAttributedString, summary: string, xAxis: AXDataAxisDescriptor, yAxis: AXNumericDataAxisDescriptor, additionalAxes: NSArray<AXDataAxisDescriptor> | AXDataAxisDescriptor[], series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]): this; initWithAttributedTitleSummaryXAxisDescriptorYAxisDescriptorSeries(attributedTitle: NSAttributedString, summary: string, xAxis: AXDataAxisDescriptor, yAxis: AXNumericDataAxisDescriptor, series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]): this; initWithTitleSummaryXAxisDescriptorYAxisDescriptorAdditionalAxesSeries(title: string, summary: string, xAxis: AXDataAxisDescriptor, yAxis: AXNumericDataAxisDescriptor, additionalAxes: NSArray<AXDataAxisDescriptor> | AXDataAxisDescriptor[], series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]): this; initWithTitleSummaryXAxisDescriptorYAxisDescriptorSeries(title: string, summary: string, xAxis: AXDataAxisDescriptor, yAxis: AXNumericDataAxisDescriptor, series: NSArray<AXDataSeriesDescriptor> | AXDataSeriesDescriptor[]): this; } declare const enum AXChartDescriptorContentDirection { ContentDirectionLeftToRight = 0, ContentDirectionRightToLeft = 1, ContentDirectionTopToBottom = 2, ContentDirectionBottomToTop = 3, ContentDirectionRadialClockwise = 4, ContentDirectionRadialCounterClockwise = 5 } declare class AXCustomContent extends NSObject implements NSCopying, NSSecureCoding { static alloc(): AXCustomContent; // inherited from NSObject static customContentWithAttributedLabelAttributedValue(label: NSAttributedString, value: NSAttributedString): AXCustomContent; static customContentWithLabelValue(label: string, value: string): AXCustomContent; static new(): AXCustomContent; // inherited from NSObject readonly attributedLabel: NSAttributedString; readonly attributedValue: NSAttributedString; importance: AXCustomContentImportance; readonly label: string; readonly value: string; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare const enum AXCustomContentImportance { Default = 0, High = 1 } interface AXCustomContentProvider extends NSObjectProtocol { accessibilityCustomContent: NSArray<AXCustomContent>; } declare var AXCustomContentProvider: { prototype: AXCustomContentProvider; }; interface AXDataAxisDescriptor extends NSCopying { attributedTitle: NSAttributedString; title: string; } declare var AXDataAxisDescriptor: { prototype: AXDataAxisDescriptor; }; declare class AXDataPoint extends NSObject implements NSCopying { static alloc(): AXDataPoint; // inherited from NSObject static new(): AXDataPoint; // inherited from NSObject additionalValues: NSArray<AXDataPointValue>; attributedLabel: NSAttributedString; label: string; xValue: AXDataPointValue; yValue: AXDataPointValue; constructor(o: { x: AXDataPointValue; y: AXDataPointValue; }); constructor(o: { x: AXDataPointValue; y: AXDataPointValue; additionalValues: NSArray<AXDataPointValue> | AXDataPointValue[]; }); constructor(o: { x: AXDataPointValue; y: AXDataPointValue; additionalValues: NSArray<AXDataPointValue> | AXDataPointValue[]; label: string; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithXY(xValue: AXDataPointValue, yValue: AXDataPointValue): this; initWithXYAdditionalValues(xValue: AXDataPointValue, yValue: AXDataPointValue, additionalValues: NSArray<AXDataPointValue> | AXDataPointValue[]): this; initWithXYAdditionalValuesLabel(xValue: AXDataPointValue, yValue: AXDataPointValue, additionalValues: NSArray<AXDataPointValue> | AXDataPointValue[], label: string): this; } declare class AXDataPointValue extends NSObject implements NSCopying { static alloc(): AXDataPointValue; // inherited from NSObject static new(): AXDataPointValue; // inherited from NSObject static valueWithCategory(category: string): AXDataPointValue; static valueWithNumber(number: number): AXDataPointValue; category: string; number: number; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class AXDataSeriesDescriptor extends NSObject implements NSCopying { static alloc(): AXDataSeriesDescriptor; // inherited from NSObject static new(): AXDataSeriesDescriptor; // inherited from NSObject attributedName: NSAttributedString; dataPoints: NSArray<AXDataPoint>; isContinuous: boolean; name: string; constructor(o: { attributedName: NSAttributedString; isContinuous: boolean; dataPoints: NSArray<AXDataPoint> | AXDataPoint[]; }); constructor(o: { name: string; isContinuous: boolean; dataPoints: NSArray<AXDataPoint> | AXDataPoint[]; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithAttributedNameIsContinuousDataPoints(attributedName: NSAttributedString, isContinuous: boolean, dataPoints: NSArray<AXDataPoint> | AXDataPoint[]): this; initWithNameIsContinuousDataPoints(name: string, isContinuous: boolean, dataPoints: NSArray<AXDataPoint> | AXDataPoint[]): this; } declare const enum AXHearingDeviceEar { None = 0, Left = 2, Right = 4, Both = 6 } declare class AXLiveAudioGraph extends NSObject { static alloc(): AXLiveAudioGraph; // inherited from NSObject static new(): AXLiveAudioGraph; // inherited from NSObject static start(): void; static stop(): void; static updateValue(value: number): void; } declare function AXMFiHearingDevicePairedUUIDs(): NSArray<NSUUID>; declare var AXMFiHearingDevicePairedUUIDsDidChangeNotification: string; declare function AXMFiHearingDeviceStreamingEar(): AXHearingDeviceEar; declare var AXMFiHearingDeviceStreamingEarDidChangeNotification: string; declare function AXNameFromColor(color: any): string; declare class AXNumericDataAxisDescriptor extends NSObject implements AXDataAxisDescriptor { static alloc(): AXNumericDataAxisDescriptor; // inherited from NSObject static new(): AXNumericDataAxisDescriptor; // inherited from NSObject gridlinePositions: NSArray<number>; lowerBound: number; scaleType: AXNumericDataAxisDescriptorScale; upperBound: number; valueDescriptionProvider: (p1: number) => string; attributedTitle: NSAttributedString; // inherited from AXDataAxisDescriptor title: string; // inherited from AXDataAxisDescriptor constructor(o: { attributedTitle: NSAttributedString; lowerBound: number; upperBound: number; gridlinePositions: NSArray<number> | number[]; valueDescriptionProvider: (p1: number) => string; }); constructor(o: { title: string; lowerBound: number; upperBound: number; gridlinePositions: NSArray<number> | number[]; valueDescriptionProvider: (p1: number) => string; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; initWithAttributedTitleLowerBoundUpperBoundGridlinePositionsValueDescriptionProvider(attributedTitle: NSAttributedString, lowerbound: number, upperBound: number, gridlinePositions: NSArray<number> | number[], valueDescriptionProvider: (p1: number) => string): this; initWithTitleLowerBoundUpperBoundGridlinePositionsValueDescriptionProvider(title: string, lowerbound: number, upperBound: number, gridlinePositions: NSArray<number> | number[], valueDescriptionProvider: (p1: number) => string): this; } declare const enum AXNumericDataAxisDescriptorScale { ScaleTypeLinear = 0, ScaleTypeLog10 = 1, ScaleTypeLn = 2 } declare function AXSupportsBidirectionalAXMFiHearingDeviceStreaming(): boolean;
the_stack
import { BlockRegData, BlockParameterEnumRegData } from "../Define/BlockDef"; import { Block } from "../Define/Block"; import { BlockEditor } from "../Editor/BlockEditor"; import ParamTypeServiceInstance from "../../sevices/ParamTypeService"; import CommonUtils from "../../utils/CommonUtils"; import StringUtils from "../../utils/StringUtils"; import AllEditors from "../TypeEditors/AllEditors"; import { Vector2 } from "../Vector2"; import { BlockParameterType, createParameterTypeFromString } from "../Define/BlockParameterType"; export default { register() { return registerControl(); }, packageName: 'Control', version: 1, } function registerControl() { let blockBranch = new BlockRegData("E8DB1B75-FDBD-1A0A-6D99-F91FAEAB3131", "条件分支"); let blockSwitch = new BlockRegData("BC9184EA-2866-3C9A-5A22-75E79DA5AF181", "分支"); let blockSelect = new BlockRegData("144AB2CC-F807-7021-1442-A8E7CD1FF1BE", "选择"); let blockWhile = new BlockRegData("28ADE8D9-50E9-FA84-0BFB-A48AF754D1FD", "While 循环"); let blockDoWhile = new BlockRegData("18CD0C99-C47C-525F-D757-0712441B794E", "Do While 循环"); let blockFor = new BlockRegData("949F91AA-D35E-E9E8-8B4B-36EDBD5B1AAD", "For 循环"); let blockSequence = new BlockRegData("4253F127-DEDB-D1BE-AF0E-9795E421DFF0", "顺序执行"); let blockDoOnce = new BlockRegData("79EC0B90-F5B7-BAA3-C3C5-1D2371E8AF0F", "Do Once"); let blockDoN = new BlockRegData("38F76740-BE6A-23E4-1F6F-FC252314ADDB", "Do N"); let blockFlipFlop = new BlockRegData("6E4471BE-6022-5FA9-368D-8CB784E3F73B", "Flip Flop"); let blockToggle = new BlockRegData("A8AC23FE-EB32-D6B0-A9DA-BFAA1BC1EB8D", "开关"); //#region 条件分支 blockBranch.baseInfo.author = 'imengyu'; blockBranch.baseInfo.description = "通过判断条件为真或假分支流图"; blockBranch.baseInfo.category = '控制'; blockBranch.baseInfo.version = '2.0'; blockBranch.baseInfo.logo = require('../../assets/images/BlockIcon/branch.svg'); blockBranch.ports = [ { guid: 'PI0', paramType: 'execute', direction: 'input' }, { name: '条件', guid: 'PICON', paramType: 'boolean', paramDefaultValue: true, direction: 'input' }, { name: '为真', guid: 'POTRUE', paramType: 'execute', direction: 'output' }, { name: '为假', guid: 'POFALSE', paramType: 'execute', direction: 'output' }, ]; blockBranch.callbacks.onPortExecuteIn = (block, port) => { let condition = <boolean>block.getInputParamValue('PICON'); block.activeOutputPort(condition ? 'POTRUE' : 'POFALSE'); }; //#endregion //#region 分支 let changeBlockOutputPortsEditor = function(block : Block, newType : string) { block.allPorts.forEach((port) => { if(port.direction == 'output' && port.paramType.isExecute() && port.guid != 'PO0') { port.data["customEditorType"] = ParamTypeServiceInstance.getBaseTypeForCustomType(newType); (<BlockEditor>block).createOrReCreatePortCustomEditor(port); } }); } let reloadSwitchBlockPorts = function(block : Block) { let type = block.options['opType']; if(block.isEditorBlock) (<BlockEditor>block).portsChangeSettings.userCanAddOutputPort = true; block.changePortParamType(block.getPortByGUID('PICON'), type); //Delete old ports if(block.data['lastIsEnum'] || type == 'enum') { Object.keys(block.outputPorts).forEach((key) => { if(!CommonUtils.isNullOrEmpty(block.outputPorts[key].options['typeOutPort'])) block.deletePort(block.outputPorts[key]) }); block.data['lastIsEnum'] = false; } switch(type) { case 'string': changeBlockOutputPortsEditor(block, 'string'); break; case 'boolean': changeBlockOutputPortsEditor(block, 'boolean'); break; case 'number': changeBlockOutputPortsEditor(block, 'number'); break; case 'bigint': changeBlockOutputPortsEditor(block, 'bigint'); break; default: let typeData = ParamTypeServiceInstance.getCustomType(type); if(typeData != null) { if(typeData.prototypeName == 'enum') { if(block.isEditorBlock) (<BlockEditor>block).portsChangeSettings.userCanAddOutputPort = false; (<BlockParameterEnumRegData>typeData).allowTypes.forEach((type) => { let port = block.addPort({ name: type.value, description: '当输入条件为' + StringUtils.valueToStr(type.value) + '时执行\n' + type.description, guid: StringUtils.strToHexCharCode(type.value, false), direction: 'output', paramType: 'execute', }, false); port.options['typeOutPort'] = type.value; }); block.data['lastIsEnum'] = true; }else changeBlockOutputPortsEditor(block, typeData.name); }else changeBlockOutputPortsEditor(block, 'any'); break; } if(block.isEditorBlock) (<BlockEditor>block).updateContent(); } blockSwitch.baseInfo.author = 'imengyu'; blockSwitch.baseInfo.description = "通过判断指定的输入条件从而分支流图"; blockSwitch.baseInfo.category = '控制'; blockSwitch.baseInfo.version = '2.0'; blockSwitch.baseInfo.logo = require('../../assets/images/BlockIcon/switch.svg'); blockSwitch.callbacks.onCreate = (block) => { if(typeof block.options['opType'] == 'undefined') block.options['opType'] = 'any'; reloadSwitchBlockPorts(block); }; blockSwitch.ports = [ { guid: 'PI0', paramType: 'execute', direction: 'input' }, { name: '输入', guid: 'PICON', paramType: 'any', direction: 'input', forceNoEditorControl: true, }, { name: '默认', description: '如果没有匹配的输入条件,则执行默认端口', guid: 'PO0', paramType: 'execute', direction: 'output' }, ]; blockSwitch.settings.portsChangeSettings.userCanAddOutputPort = true; blockSwitch.callbacks.onPortExecuteIn = (block, port) => { let inCoon = block.getInputParamValue('PICON'); let keys = Object.keys(block.outputPorts); for (let i = 0; i < keys.length; i++) { if(!CommonUtils.isNullOrEmpty(block.outputPorts[i].options['typeOutPort']) && block.outputPorts[i].options['typeOutPort'] == inCoon) { block.activeOutputPort(block.outputPorts[i]); return; } } block.activeOutputPort('PO0'); }; blockSwitch.callbacks.onCreateCustomEditor = (parentEle, block : BlockEditor, regData) => { let el = document.createElement('div'); let typeSelector = document.createElement('input'); typeSelector.type = 'text'; typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(block.options['opType']); typeSelector.style.width = '111px'; typeSelector.readOnly = true; typeSelector.onclick = (e) => { block.editor.chooseType(new Vector2(e.x, e.y), (type, isBaseType) => { if(block.options['opType'] != type.name) { block.options['opType'] = type.name; typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(type.name); reloadSwitchBlockPorts(block); } }, false) }; el.innerText = '输入条件类型:'; el.style.whiteSpace = 'nowrap'; el.appendChild(typeSelector); parentEle.appendChild(el); }; blockSwitch.callbacks.onCreatePortCustomEditor = (parentEle, block, port) => { if(!CommonUtils.isNullOrEmpty(port.data["customEditorType"])) { let customType = ParamTypeServiceInstance.isBaseType(port.data["customEditorType"]) ? ParamTypeServiceInstance.getCustomType(port.data["customEditorType"]) : null; let typeEditor = ParamTypeServiceInstance.isBaseType(port.data["customEditorType"]) ? AllEditors.getBaseEditors(port.data["customEditorType"]) : (customType == null ? null : customType.editor); if(typeEditor != null) { return typeEditor.editorCreate(block, port, parentEle, (newV) => { port.options['typeOutPort'] = newV; port.description = '当输入为 ' + StringUtils.valueToStr(newV) + ' 时执行'; port.regData.description = port.description; block.updatePort(port); return newV; }, port.options['typeOutPort'], null, customType) } } return null; }; blockSwitch.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'PO' + block.data['portCount'], direction: 'output', paramType: 'execute', data: { "customEditorType": ParamTypeServiceInstance.getBaseTypeForCustomType(block.options['opType']) } } }; //#endregion //#region 选择 let changeBlockInputPortsEditor = function(block : Block, newType : string) { block.allPorts.forEach((port) => { if(port.direction == 'input' && !port.paramType.isExecute() && port.guid != 'PICON' && port.guid != 'PIDEF') { port.data["customEditorType"] = ParamTypeServiceInstance.getBaseTypeForCustomType(newType); (<BlockEditor>block).createOrReCreatePortCustomEditor(port); } }); } let reloadSelectBlockPorts = function(block : Block) { let type = block.options['opType']; if(block.isEditorBlock) (<BlockEditor>block).parametersChangeSettings.userCanAddInputParameter = true; block.changePortParamType(block.getPortByGUID('PICON'), createParameterTypeFromString(type), 'variable'); //Delete old ports if(block.data['lastIsEnum'] || type == 'enum') { Object.keys(block.inputPorts).forEach((key) => { if(!CommonUtils.isNullOrEmpty(block.inputPorts[key].options['typeOutPort'])) block.deletePort(block.inputPorts[key]) }); block.data['lastIsEnum'] = false; } switch(type) { case 'boolean': changeBlockInputPortsEditor(block, 'boolean'); break; case 'string': changeBlockInputPortsEditor(block, 'string'); break; case 'number': changeBlockInputPortsEditor(block, 'number'); break; case 'bigint': changeBlockInputPortsEditor(block, 'bigint'); break; default: let typeData = ParamTypeServiceInstance.getCustomType(type); if(typeData != null) { if(typeData.prototypeName == 'enum') { if(block.isEditorBlock) (<BlockEditor>block).parametersChangeSettings.userCanAddInputParameter = false; (<BlockParameterEnumRegData>typeData).allowTypes.forEach((type) => { let port = block.addPort({ name: type.value, description: '当输入条件为' + StringUtils.valueToStr(type.value) + '时输出该变量\n' + type.description, guid: StringUtils.strToHexCharCode(type.value, false), direction: 'input', paramType: 'any', }, false); port.options['typeOutPort'] = type.value; }); block.data['lastIsEnum'] = true; }else changeBlockInputPortsEditor(block, typeData.name); }else changeBlockInputPortsEditor(block, 'any'); break; } if(block.isEditorBlock) (<BlockEditor>block).updateContent(); } blockSelect.baseInfo.author = 'imengyu'; blockSelect.baseInfo.description = "通过判断指定的输入条件从而分支流图"; blockSelect.baseInfo.category = '控制'; blockSelect.baseInfo.version = '2.0'; blockSelect.baseInfo.logo = require('../../assets/images/BlockIcon/select.svg'); blockSelect.settings.parametersChangeSettings.userCanAddInputParameter = true; blockSelect.callbacks.onCreate = (block) => { if(typeof block.options['opType'] == 'undefined') block.options['opType'] = 'any'; reloadSelectBlockPorts(block); }; blockSelect.ports = [ { guid: 'PI0', paramType: 'execute', direction: 'input' }, { name: '默认', description: '如果没有匹配的输入条件,则输出默认端口参数', guid: 'PIDEF', paramType: 'any', direction: 'input' }, { name: '输入', guid: 'PICON', paramType: 'any', direction: 'input', forceNoEditorControl: true, }, { guid: 'PO0', paramType: 'execute', direction: 'output' }, { name: '输出', guid: 'PO', paramType: 'any', direction: 'output' }, ]; blockSelect.callbacks.onPortExecuteIn = (block, port) => { let inCoon = block.getInputParamValue('PICON'); let keys = Object.keys(block.outputPorts); for (let i = 0; i < keys.length; i++) { if(!CommonUtils.isNullOrEmpty(block.inputPorts[i].options['typeOutPort']) && block.inputPorts[i].options['typeOutPort'] == inCoon) { block.setOutputParamValue('PO', block.getInputParamValue(block.inputPorts[i])); return; } } block.setOutputParamValue('PO', block.getInputParamValue('PIDEF')); block.activeOutputPort('PO0'); }; blockSelect.callbacks.onCreateCustomEditor = (parentEle, block : BlockEditor, regData) => { let el = document.createElement('div'); let typeSelector = document.createElement('input'); typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(block.options['opType']); typeSelector.type = 'text'; typeSelector.style.width = '111px'; typeSelector.readOnly = true; typeSelector.onclick = (e) => { block.editor.chooseType(new Vector2(e.x, e.y), (type, isBaseType) => { if(block.options['opType'] != type.name) { block.options['opType'] = type.name; typeSelector.value = ParamTypeServiceInstance.getTypeNameForUserMapping(type.name); reloadSelectBlockPorts(block); } }, false) }; el.innerText = '输入条件类型:'; el.style.whiteSpace = 'nowrap'; el.appendChild(typeSelector); parentEle.appendChild(el); }; blockSelect.callbacks.onCreatePortCustomEditor = (parentEle, block, port) => { if(!CommonUtils.isNullOrEmpty(port.data["customEditorType"])) { let customType = ParamTypeServiceInstance.isBaseType(port.data["customEditorType"]) ? ParamTypeServiceInstance.getCustomType(port.data["customEditorType"]) : null; let typeEditor = ParamTypeServiceInstance.isBaseType(port.data["customEditorType"]) ? AllEditors.getBaseEditors(port.data["customEditorType"]) : (customType == null ? null : customType.editor); if(typeEditor != null) { let el = document.createElement('div'); let input = typeEditor.editorCreate(block, port, parentEle, (newV) => { port.options['typeOutPort'] = newV; port.description = '当输入为 ' + StringUtils.valueToStr(newV) + ' 时输出此变量'; port.regData.description = port.description; block.updatePort(port); return newV; }, port.options['typeOutPort'], null, customType); el.style.display = 'inline-block'; el.innerText = '输入 = '; el.appendChild(input); return el; } } return null; }; blockSelect.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'PO' + block.data['portCount'], direction: 'input', paramType: 'any', data: { "customEditorType": ParamTypeServiceInstance.getBaseTypeForCustomType(block.options['opType']) } } }; //#endregion //#region While blockWhile.baseInfo.author = 'imengyu'; blockWhile.baseInfo.description = "如果条件为真则循环"; blockWhile.baseInfo.category = '控制'; blockWhile.baseInfo.version = '2.0'; blockWhile.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); blockWhile.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PIBREAK', paramType: 'execute', direction: 'input', name: '终止', description: '终止循环', forceNoCycleDetection: true, }, { guid: 'PICON', paramType: 'boolean', paramDefaultValue: true, direction: 'input', name: '条件', }, { guid: 'POLOOP', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'POEXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; blockWhile.callbacks.onStartRun = (block) => { block.variables()['breakActived'] = false; } blockWhile.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); if(port.guid == 'PI') { let POLOOP = block.getPortByGUID('POLOOP'); let POEXIT = block.getPortByGUID('POEXIT'); let condition = <boolean>block.getInputParamValue('PICON'); let breakActived = variables['breakActived']; while(condition) { block.activeOutputPort(POLOOP); //update condition = <boolean>block.getInputParamValue('PICON'); breakActived = variables['breakActived']; if(breakActived) break; } block.activeOutputPort(POEXIT); }else if(port.guid == 'PIBREAK') { variables['breakActived'] = true; } }; //#endregion //#region DoWhile blockDoWhile.baseInfo.author = 'imengyu'; blockDoWhile.baseInfo.description = "先执行循环体,然后再判断条件是否为真, 如果为真则继续循环"; blockDoWhile.baseInfo.category = '控制'; blockDoWhile.baseInfo.version = '2.0'; blockDoWhile.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); blockDoWhile.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PIBREAK', paramType: 'execute', direction: 'input', name: '终止', description: '终止循环', forceNoCycleDetection: true, }, { guid: 'PICON', paramType: 'boolean', paramDefaultValue: true, direction: 'input', name: '条件', }, { guid: 'POLOOP', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'POEXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; blockDoWhile.callbacks.onStartRun = (block) => { block.variables()['breakActived'] = false; } blockDoWhile.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); if(port.guid == 'PI') { let POLOOP = block.getPortByGUID('POLOOP'); let POEXIT = block.getPortByGUID('POEXIT'); let condition = <boolean>block.getInputParamValue('PICON'); let breakActived = variables['breakActived']; do { block.activeOutputPort(POLOOP); //update condition = <boolean>block.getInputParamValue('PICON'); breakActived = variables['breakActived']; if(breakActived) break; } while(condition); block.activeOutputPort(POEXIT); }else if(port.guid == 'PIBREAK') { variables['breakActived'] = true; } }; //#endregion //#region FlipFlop blockFlipFlop.baseInfo.author = 'imengyu'; blockFlipFlop.baseInfo.description = "在A和B之间循环往复"; blockFlipFlop.baseInfo.category = '控制'; blockFlipFlop.baseInfo.version = '2.0'; blockFlipFlop.baseInfo.logo = require('../../assets/images/BlockIcon/flipflop.svg'); blockFlipFlop.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'POA', paramType: 'execute', direction: 'output', name: 'A', }, { guid: 'POB', paramType: 'execute', direction: 'output', name: 'B' }, { guid: 'POC', paramType: 'boolean', direction: 'output', name: '是否是A' }, ]; blockFlipFlop.callbacks.onStartRun = (block) => { block.variables()['isA'] = true; } blockFlipFlop.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); let POA = block.getPortByGUID('POA'); let POB = block.getPortByGUID('POB'); let POC = block.getPortByGUID('POC'); variables['isA'] = !variables['isA']; block.setOutputParamValue(POC, variables['isA']); block.activeOutputPort(variables['isA'] ? POA : POB); }; //#endregion //#region Toggle blockToggle.baseInfo.author = 'imengyu'; blockToggle.baseInfo.description = "开关门,通过一个开关来控制流程的通或断"; blockToggle.baseInfo.category = '控制'; blockToggle.baseInfo.version = '2.0'; blockToggle.baseInfo.logo = require('../../assets/images/BlockIcon/gate.svg'); blockToggle.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PION', paramType: 'execute', direction: 'input', name: '开', }, { guid: 'PIOFF', paramType: 'execute', direction: 'input', name: '关' }, { guid: 'PITOGGLE', paramType: 'execute', direction: 'input', name: '切换' }, { guid: 'PISTARTOFF', paramType: 'boolean', direction: 'input', name: '开始时是关闭的' }, { guid: 'PO', paramType: 'execute', direction: 'output', }, ]; blockToggle.callbacks.onStartRun = (block) => { block.variables()['isOn'] = !block.getInputParamValue('PISTARTOFF'); } blockToggle.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); if(port.guid == 'PI') { if(variables['isOn']) block.activeOutputPort('PO'); } else if(port.guid == 'PION') variables['isOn'] = true; else if(port.guid == 'PIOFF') variables['isOn'] = false; else if(port.guid == 'PITOGGGLE') variables['isOn'] = !variables['isOn']; }; //#endregion //#region For blockFor.baseInfo.author = 'imengyu'; blockFor.baseInfo.description = "从 起始索引值 至 结束索引值 按 步长 进行循环"; blockFor.baseInfo.category = '控制'; blockFor.baseInfo.version = '2.0'; blockFor.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); blockFor.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PISTINX', paramType: 'number', direction: 'input', name: '起始索引值', paramDefaultValue: 0, }, { guid: 'PIENINX', paramType: 'number', direction: 'input', name: '结束索引值', paramDefaultValue: 10, }, { guid: 'PISTEP', paramType: 'number', direction: 'input', name: '步长', description: '循环自增步长。可以为负数,但 结束索引值 必须 小于 起始索引值', paramDefaultValue: 1, }, { guid: 'PIBREAK', paramType: 'execute', direction: 'input', name: '终止', description: '终止循环', forceNoCycleDetection: true, }, { guid: 'POLOOP', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'POINDEX', paramType: 'number', direction: 'output', name: '当前索引', }, { guid: 'POEXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; blockFor.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'PI') { var variables = block.variables(); variables['breakActived'] = false; let POLOOP = block.getPortByGUID('POLOOP'); let POEXIT = block.getPortByGUID('POEXIT'); let POINDEX = block.getPortByGUID('POINDEX'); let startIndex = <number>block.getInputParamValue('PISTINX'); let endIndex = <number>block.getInputParamValue('PIENINX'); let stepIndex = <number>block.getInputParamValue('PISTEP'); let breakActived = variables['breakActived']; for(let i = startIndex; i < endIndex; i += stepIndex) { block.setOutputParamValue(POINDEX, i); block.activeOutputPort(POLOOP); breakActived = variables['breakActived']; if(breakActived) break; } block.activeOutputPort(POEXIT); }else if(port.guid == 'PIBREAK') { var variables = block.variables(); variables['breakActived'] = true; } }; //#endregion //#region DoN blockDoN.baseInfo.author = 'imengyu'; blockDoN.baseInfo.description = "使执行只通过N次"; blockDoN.baseInfo.category = '控制'; blockDoN.baseInfo.version = '2.0'; blockDoN.baseInfo.logo = require('../../assets/images/BlockIcon/do_n.svg'); blockDoN.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PIN', paramType: 'number', direction: 'input', name: 'N' }, { guid: 'PIRESET', paramType: 'execute', direction: 'input', name: '重置' }, { guid: 'PO', paramType: 'execute', direction: 'output', }, { guid: 'POCOUNT', paramType: 'number', direction: 'output', name: '当前计数', }, ]; blockDoN.callbacks.onStartRun = (block) => { block.variables()['count'] = 0; } blockDoN.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); if(port.guid == 'PI') { let N = <number>block.getInputParamValue('PIN'); if(N < variables['count']) { variables['count']++; block.setOutputParamValue('POCOUNT', variables['count']); block.activeOutputPort('PO'); } } else if(port.guid == 'PIRESET') { variables['count'] = 0; block.setOutputParamValue('POCOUNT', 0); } }; //#endregion //#region Do Once blockDoOnce.baseInfo.author = 'imengyu'; blockDoOnce.baseInfo.description = "使执行只通过1次"; blockDoOnce.baseInfo.category = '控制'; blockDoOnce.baseInfo.version = '2.0'; blockDoOnce.baseInfo.logo = require('../../assets/images/BlockIcon/do_once.svg'); blockDoOnce.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PIRESET', paramType: 'execute', direction: 'input', name: '重置' }, { guid: 'PISTARTOFF', paramType: 'boolean', direction: 'input', name: '开始时是关闭的' }, { guid: 'PO', paramType: 'execute', direction: 'output', }, ]; blockDoOnce.callbacks.onStartRun = (block) => { block.variables()['isOn'] = !block.getInputParamValue('PISTARTOFF'); } blockDoOnce.callbacks.onPortExecuteIn = (block, port) => { var variables = block.variables(); if(port.guid == 'PI') { if(variables['isOn']) { variables['isOn'] = false; block.activeOutputPort('PO'); } } else if(port.guid == 'PIRESET') variables['isOn'] = true; }; //#endregion //#region Sequence blockSequence.baseInfo.author = 'imengyu'; blockSequence.baseInfo.description = "按顺序执行一系列的端口"; blockSequence.baseInfo.category = '控制'; blockSequence.baseInfo.version = '2.0'; blockSequence.baseInfo.logo = require('../../assets/images/BlockIcon/sequence.svg'); blockSequence.settings.portsChangeSettings.userCanAddOutputPort = true; blockSequence.ports = [ { guid: 'PI', paramType: 'execute', direction: 'input' }, { guid: 'PO', paramType: 'execute', direction: 'output', name: '执行0' }, ]; blockSequence.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'PO' + block.data['portCount'], name: '执行' + block.data['portCount'], direction: 'output', paramType: 'execute', data: { "customEditorType": ParamTypeServiceInstance.getBaseTypeForCustomType(block.options['opType']) } } }; blockSequence.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'PI') { block.allPorts.forEach((port) => { block.activeOutputPort(port); }); } }; //#endregion return [ blockBranch, blockSwitch, blockSelect, blockFlipFlop, blockToggle, blockWhile, blockFor, blockDoN, blockDoOnce, blockSequence, ]; }
the_stack
import { Box, Button, Dialog, DialogActions, DialogContent, Divider, FormControl, FormControlLabel, Grid, Link, Switch, Typography } from '@material-ui/core' import { shell } from 'electron' import { ipcRenderer as ipc } from 'electron-better-ipc' import path from 'path' import * as React from 'react' import { Redirect } from 'react-router-dom' import infoIcon from 'space-eye-icons/dist/info_app.png' import styled from 'styled-components' import { GET_AUTO_UPDATE, GET_START_ON_LOGIN, QUIT_APPLICATION_CHANNEL, SET_AUTO_UPDATE, SET_START_ON_LOGIN } from '../../shared/IpcDefinitions' const SectionsContainer = styled.div` display: flex; flex-direction: row; flex-grow: 1; flex-basis: var(--sections-column-width); align-items: flex-start; justify-content: flex-end; background-color: rgb(48, 48, 48); ` const SectionsColumn = styled.div` display: flex; flex-direction: column; width: var(--sections-column-width); height: 100%; ` const SettingsColumn = styled.div` flex-grow: 1; flex-basis: 400px; ` const Row = styled.div` display: flex; flex-direction: row; ` const ProductTitle = styled.h1` font-family: Roboto, sans-serif; font-size: 25px; font-weight: normal; letter-spacing: 0.15px; color: white; ` const SettingsHeader = styled.h2` font-family: Roboto, sans-serif; font-size: 20px; font-weight: normal; letter-spacing: 0.15px; color: white; ` const Spacer = styled.div` flex-grow: 1; ` const SettingsContainer = styled.div` --top-padding: 75px; --sections-column-width: 200px; --settings-column-width: 400px; display: flex; flex-direction: row; height: 100%; top: 0; left: 0; bottom: 0; right: 0; position: absolute; ` const QuitButton = styled.button` text-decoration: none; appearance: none; outline: none; cursor: pointer; margin: 20px 0; background: transparent; border: 1px solid red; border-radius: 5px; color: red; padding: 8px 17px; font-family: Roboto, sans-serif; font-size: 16px; font-weight: normal; letter-spacing: 0.15px; ` const BackButton = styled.button` --button-color: #0075ff; text-decoration: none; appearance: none; outline: none; cursor: pointer; margin: 20px 0; background: transparent; border-width: 1px; border-style: solid; border-radius: 5px; border-color: var(--button-color); color: var(--button-color); padding: 8px 17px; font-family: Roboto, sans-serif; font-size: 16px; font-weight: normal; letter-spacing: 0.15px; ` interface SettingsSwitchProps { label: string isChecked: boolean onChange: (isChecked: boolean) => void } const SettingsSwitch: React.FC<SettingsSwitchProps> = props => { const { label, isChecked, onChange } = props return ( <FormControl component="fieldset"> <FormControlLabel control={ <Switch checked={isChecked} onChange={(_, checked) => onChange(checked)} name={label} color="primary" /> } label={label} labelPlacement="top" /> </FormControl> ) } const AppIcon = styled.img` width: 70px; height: 70px; margin-left: auto; margin-right: auto; ` interface AboutThisAppProps { onClickDone: () => void visible: boolean } const AboutThisApp: React.FC<AboutThisAppProps> = props => { return ( <Dialog open={props.visible} style={{ userSelect: 'none', textAlign: 'center' }}> <DialogContent> <AppIcon src={infoIcon} alt="SpaceEye icon" /> <Typography variant="h6">SpaceEye</Typography> <Typography variant="body2" style={{ userSelect: 'text' }}> Version {APP_VERSION} </Typography> <Typography variant="body2">Copyright &copy; 2020 Michael Galliers</Typography> <Typography variant="body2">License: {APP_LICENSE}</Typography> <Link component="button" variant="body2" onClick={() => shell.openExternal(APP_BUGS_URL)} > Report bugs </Link> <DialogActions> <Button onClick={() => shell.openPath(path.join(process.resourcesPath, 'legal_notices.txt')) } > Acknowledgements </Button> <Button onClick={props.onClickDone}>Done</Button> </DialogActions> </DialogContent> </Dialog> ) } interface SettingsProps { onClickBack: () => void onClickQuit: () => void onClickStartOnLoginSwitch: (shouldStart: boolean) => void onClickAutoUpdateSwitch: (autoUpdate: boolean) => void openAboutApp: () => void closeAboutApp: () => void shouldStartOnLogin: boolean autoUpdate: boolean aboutAppVisible: boolean } const Settings: React.FC<SettingsProps> = props => { const { onClickBack, onClickQuit, onClickStartOnLoginSwitch, onClickAutoUpdateSwitch, openAboutApp, closeAboutApp, shouldStartOnLogin, autoUpdate, aboutAppVisible } = props return ( <SettingsContainer> <SectionsContainer> <SectionsColumn> <Box my={1} /> <Grid container direction="row" justify="center"> <Typography variant="h5">SpaceEye</Typography> </Grid> <Box my={1} /> <Grid container direction="row" justify="center"> <Button variant="outlined" color="primary" onClick={onClickBack}> Back </Button> </Grid> <Spacer /> <Grid container direction="column" justify="center" alignItems="center"> <Link component="button" variant="body2" color="textSecondary" onClick={openAboutApp} > About </Link> <Box my={0.5} /> <Button variant="outlined" color="secondary" onClick={onClickQuit}> Quit </Button> </Grid> <Box my={1} /> </SectionsColumn> </SectionsContainer> <SettingsColumn> <Box my={2} /> <Grid container direction="row" justify="center"> <Typography variant="h6">Settings</Typography> </Grid> <Box my={2} mx={1}> <Divider variant="fullWidth" /> </Box> <Grid container direction="column" justify="flex-start" alignContent="flex-start"> <SettingsSwitch isChecked={shouldStartOnLogin} onChange={onClickStartOnLoginSwitch} label="Start on Login" /> {/* Don't show auto-update option if downloaded from an app store */} {!process.mas && !process.windowsStore && ( <SettingsSwitch isChecked={autoUpdate} onChange={onClickAutoUpdateSwitch} label="Auto update" /> )} </Grid> </SettingsColumn> <AboutThisApp onClickDone={closeAboutApp} visible={aboutAppVisible} /> </SettingsContainer> ) } interface SettingsManagerState { backCLicked: boolean startOnLogin: boolean autoUpdate: boolean isLoaded: boolean aboutAppVisible: boolean } export default class SettingsManager extends React.Component<{}, SettingsManagerState> { private static onClickQuit() { ipc.callMain(QUIT_APPLICATION_CHANNEL) } constructor(props: {}) { super(props) this.state = { backCLicked: false, startOnLogin: false, autoUpdate: false, isLoaded: false, aboutAppVisible: false } this.onChangeStartOnLogin = this.onChangeStartOnLogin.bind(this) this.onChangeAutoUpdate = this.onChangeAutoUpdate.bind(this) this.onClickBack = this.onClickBack.bind(this) } async componentDidMount(): Promise<void> { const [startOnLogin, autoUpdate] = await Promise.all([ ipc.callMain<void, boolean | undefined>(GET_START_ON_LOGIN), ipc.callMain<void, boolean>(GET_AUTO_UPDATE) ]) this.setState({ startOnLogin: startOnLogin ?? false, autoUpdate, isLoaded: true }) } private async onChangeStartOnLogin(shouldStart: boolean) { this.setState({ startOnLogin: shouldStart }) await ipc.callMain<boolean>(SET_START_ON_LOGIN, shouldStart) } private async onChangeAutoUpdate(autoUpdate: boolean) { this.setState({ autoUpdate }) await ipc.callMain<boolean>(SET_AUTO_UPDATE, autoUpdate) } private onClickBack() { this.setState({ backCLicked: true }) } render(): React.ReactNode { if (this.state.backCLicked) { return <Redirect to="/" /> } if (!this.state.isLoaded) { return <div /> } return ( <Settings onClickBack={this.onClickBack} onClickStartOnLoginSwitch={this.onChangeStartOnLogin} onClickAutoUpdateSwitch={this.onChangeAutoUpdate} openAboutApp={() => this.setState({ aboutAppVisible: true })} closeAboutApp={() => this.setState({ aboutAppVisible: false })} shouldStartOnLogin={this.state.startOnLogin} autoUpdate={this.state.autoUpdate} onClickQuit={SettingsManager.onClickQuit} aboutAppVisible={this.state.aboutAppVisible} /> ) } }
the_stack
import * as async from "../async"; import * as path from "path"; import * as os from "os"; import { Dictionary } from "../dictionary"; import { Workspace } from "./workspace" import { PuppetModulesInfo } from "./modules_info" import { PuppetClassInfo, PuppetDefinedTypeInfo, PuppetFunctionInfo } from "./class_info" import { Ruby } from "./ruby" import { PuppetASTParser, PuppetASTClass, PuppetASTEnvironment, Resolver, PuppetASTFunction, ResolveError } from "./ast" import { CompiledPromisesCallback, GlobalVariableResolver, CompilationError, WorkspaceError } from "./util" import { Hierarchy } from "./hiera" import { NodeContext } from "./node" import { Folder } from "./files"; import { PuppetHTTP } from "./http" import { isArray } from "util"; import { WorkspaceSettings } from "./workspace_settings"; import { EnvironmentTreeDump, NodeDump } from "../ipc/objects" import { HIERA_EDITOR_FIELD, HIERA_EDITOR_VALUE } from "./cert" const forge = require("node-forge"); const PromisePool = require('es6-promise-pool'); export class Environment { private readonly _name: string; private readonly _path: string; private readonly _cachePath: string; private readonly _workspace: Workspace; private readonly _hierarchy: Hierarchy; private readonly _global: Dictionary<string, string>; private readonly _nodes: Dictionary<string, NodeContext>; private readonly _roots: Dictionary<string, Folder>; private readonly _warnings: WorkspaceError[]; private readonly _offline: boolean; private readonly _nodeFacts: Dictionary<string, any>; private readonly _certificates: Dictionary<string, any>; private _modulesInfo: PuppetModulesInfo; constructor(workspace: Workspace, name: string, _path: string, cachePath: string, offline: boolean = false) { this._name = name; this._workspace = workspace; this._path = _path; this._warnings = []; this._hierarchy = new Hierarchy(path.join(_path, "hiera.yaml")); this._roots = new Dictionary(); this._cachePath = cachePath; this._global = new Dictionary(); this._global.put("environment", name); this._nodes = new Dictionary(); this._nodeFacts = new Dictionary(); this._certificates = new Dictionary(); this._offline = offline; } public get modulesInfo(): PuppetModulesInfo { return this._modulesInfo; } public get global() { return this._global; } public getRoot(_path: string): Folder { const existing = this._roots.get(_path); if (existing) return existing; const root = new Folder(this, "data", path.join(this._path, _path), this.name, null); this._roots.put(_path, root); return root; } public get warnings(): Error[] { return this._warnings; } public addWarning(warning: WorkspaceError) { this._warnings.push(warning); } public get certNodeFactsPath(): string { return path.join(this._cachePath, "facts") } public getNode(certname: string): NodeContext { return this._nodes.get(certname); } public getNodeFactsPath(certName: string): string { return path.join(this._cachePath, "facts", certName + ".json") } public get certificateCachePath(): string { return path.join(this._cachePath, "certs") } public get certListCachePath(): string { return path.join(this._cachePath, "certnames.json") } public get hierarchy(): Hierarchy { return this._hierarchy; } public get workspace(): Workspace { return this._workspace; } public async searchClasses(search: string): Promise<any[]> { const results: Array<any> = []; this._modulesInfo.searchClasses(search, results); this._workspace.modulesInfo.searchClasses(search, results) return results; } public async searchDefinedTypes(search: string): Promise<any[]> { const results: Array<any> = []; this._modulesInfo.searchDefinedTypes(search, results); this._workspace.modulesInfo.searchDefinedTypes(search, results) return results; } public findClassInfo(className: string): PuppetClassInfo { if (this._modulesInfo) { const localClassInfo = this._modulesInfo.findClass(className); if (localClassInfo) return localClassInfo; } return this._workspace.modulesInfo.findClass(className); } public findDefineTypeInfo(definedTypeName: string): PuppetDefinedTypeInfo { if (this._modulesInfo) { const localClassInfo = this._modulesInfo.findDefinedType(definedTypeName); if (localClassInfo) return localClassInfo; } return this._workspace.modulesInfo.findDefinedType(definedTypeName); } public findFunctionInfo(className: string): PuppetFunctionInfo { if (this._modulesInfo) { const localFunctionInfo = this._modulesInfo.findFunction(className); if (localFunctionInfo) return localFunctionInfo; } return this._workspace.modulesInfo.findFunction(className); } public async enterNodeContext(certname: string, facts?: any): Promise<NodeContext> { const existing = this._nodes.get(certname); if (existing != null) { return existing; } const new_ = new NodeContext(certname, this); this._nodes.put(certname, new_); try { await new_.init(facts); } catch (e) { if (e instanceof CompilationError || e instanceof ResolveError) { console.log(e); } else { throw e; } } return new_; } public async create() { if (!await async.isDirectory(this.dataPath)) await async.createDirectory(this.dataPath); if (!await async.isDirectory(this.modulesPath)) await async.createDirectory(this.modulesPath); if (!await async.isDirectory(this.manifestsPath)) await async.createDirectory(this.manifestsPath); } public async tree(): Promise<EnvironmentTreeDump> { const nodes: {[key: string]: NodeDump} = {}; for (const certname of this._nodes.getKeys()) { const node = this._nodes.get(certname); nodes[certname] = await node.dump(); } const warnings = []; for (const warn of this._warnings) { warnings.push({ title: warn.title, message: warn.message }) } return { "nodes": nodes, "warnings": warnings }; } public get root(): Folder { return this.getRoot(this._hierarchy.datadir); } public get dataPath(): string { return path.join(this._path, this._hierarchy.datadir); } public get name():string { return this._name; } public get path():string { return this._path; } private get cachePath(): string { return this._cachePath; } private get cacheManifestsFilePath(): string { return path.join(this.cachePath, "manifests"); } private get cacheModulesFilePath(): string { return path.join(this.cachePath, "modules.json"); } public get manifestsName(): string { return "manifests"; } public get manifestsPath(): string { return path.join(this.path, this.manifestsName); } private get modulesPath(): string { return path.join(this.path, "modules"); } public getClassInfo(): any { const classes: any = {}; const types: any = {}; this._workspace.modulesInfo.dump(classes, types); if (this._modulesInfo) this._modulesInfo.dump(classes, types); return { "classes": classes, "types": types } } public async installModules(callback: any): Promise<boolean> { return await Workspace.InstallModules(this._path, callback); } private async compileModules(progressCallback: any = null, updateProgressCategory: any = null): Promise<any> { // compile modules if (await async.isDirectory(this.modulesPath)) { let upToDate: boolean = false; const bStat = await async.fileStat(this.cacheModulesFilePath); if (bStat) { const mTime: Number = bStat.mtimeMs; const recentTime: Number = await async.mostRecentFileTime(this.modulesPath); if (recentTime <= mTime) { // cache is up to date upToDate = true; } } if (!upToDate) { await Ruby.CallScript("puppet-strings.rb", [this.cacheModulesFilePath], this.modulesPath); } } const modulesInfo = await this.loadModulesInfo(); if (modulesInfo != null) { const promiseCallback = new CompiledPromisesCallback(); const modulesInfoPromises = await modulesInfo.generateCompilePromises(promiseCallback); const originalPoolSize: number = modulesInfoPromises.length; function* promiseProducer() { for (const p of modulesInfoPromises) { const f = p[0]; p.splice(0, 1); yield f.apply(f, p); } } const logicalCpuCount = Math.max(os.cpus().length - 1, 1); const pool = new PromisePool(promiseProducer, logicalCpuCount); if (progressCallback) { promiseCallback.callback = (done: number) => { if (originalPoolSize != 0) { const progress: number = done / originalPoolSize; progressCallback(progress); } }; } if (updateProgressCategory) updateProgressCategory("Compiling environment modules...", true); await pool.start(); } } private async compileManifests(progressCallback: any = null, updateProgressCategory: any = null): Promise<any> { // compile manifests if (await async.isDirectory(this.manifestsPath)) { let upToDate: boolean = false; const bStat = await async.fileStat(this.cacheManifestsFilePath); if (bStat) { const mTime: Number = bStat.mtimeMs; const recentTime: Number = await async.mostRecentFileTime(this.manifestsPath); if (recentTime <= mTime) { // cache is up to date upToDate = true; } } if (!upToDate) { const files_ = await async.listFiles(this.manifestsPath); const files = files_.filter((name) => name.endsWith(".pp")); files.sort(); const promiseCallback = new CompiledPromisesCallback(); const compilePromises = await this.generateCompilePromises(files, this.manifestsName, promiseCallback); const originalPoolSize: number = compilePromises.length; function* promiseProducer() { for (const p of compilePromises) { const f = p[0]; p.splice(0, 1); yield f.apply(f, p); } } const logicalCpuCount = Math.max(os.cpus().length - 1, 1); const pool = new PromisePool(promiseProducer, logicalCpuCount); if (progressCallback) { promiseCallback.callback = (done: number) => { if (originalPoolSize != 0) { const progress: number = done / originalPoolSize; progressCallback(progress); } }; } if (updateProgressCategory) updateProgressCategory("Compiling manifests...", true); await pool.start(); } } } public getCertificate(certname: string): any { return this._certificates.get(certname); } private async loadCertificates(updateProgressCategory: any, certList: string[], settings: WorkspaceSettings) { if (!await async.isDirectory(this.certificateCachePath)) { await async.makeDirectory(this.certificateCachePath); } const certsExist = []; for (const certname of certList) { certsExist.push(async.isFile(path.join(this.certificateCachePath, certname + ".txt"))); } const ex = await Promise.all(certsExist.map(p => p.catch(() => undefined))); const loadCerts = []; for (let i = 0, t = certList.length; i < t; i++) { const certname = certList[i]; const exists = ex[i]; if (exists) { loadCerts.push(async.readFile(path.join(this.certificateCachePath, certname + ".txt"))); } else { loadCerts.push(Promise.resolve(null)); } } const certs = await Promise.all(loadCerts.map(p => p.catch((e: any): any => undefined))); for (let i = 0, t = certList.length; i < t; i++) { const certname = certList[i]; let certificate = certs[i]; if (certificate == null) { if (updateProgressCategory) updateProgressCategory( "[" + this.name + "] Downloading certificate for node " + certname + "...", false); certificate = await PuppetHTTP.GetCertificate(certname, this.name, settings); await async.writeFile(path.join(this.certificateCachePath, certname + ".txt"), certificate); } const cert = forge.pki.certificateFromPem(certificate); if (cert == null) continue; this._certificates.put(certname, cert); } } private async updateCertList(updateProgressCategory: any, settings: WorkspaceSettings): Promise<string[]> { if (updateProgressCategory) updateProgressCategory("[" + this.name + "] Updating certificate list...", false); let certList: string[]; try { certList = await PuppetHTTP.GetCertList(this.name, settings); } catch (e) { throw new WorkspaceError("Failed to obtain certificate list", e.toString()); } await this.loadCertificates(updateProgressCategory, certList, settings); await async.writeJSON(this.certListCachePath, certList); return certList; } public async init(progressCallback: any = null, updateProgressCategory: any = null): Promise<any> { const zis = this; this._warnings.length = 0; if (!await async.isDirectory(this.cachePath)) { if (!await async.makeDirectory(this.cachePath)) { throw "Failed to create cache directory"; } } try { await this._hierarchy.load() } catch (e) { this.addWarning(e); } if (await async.isFile(path.join(this._path, "Puppetfile")) && !await async.isDirectory(this.modulesPath)) { await this.installModules(updateProgressCategory); } if (!await async.isDirectory(this.compileDirectory)) { await async.makeDirectory(this.compileDirectory); } await this.compileModules(progressCallback, updateProgressCategory); await this.compileManifests(progressCallback, updateProgressCategory); const settings = await this.workspace.getSettings(); let nodeList: string[]; if (await async.isFile(this.certListCachePath)) { if (this._offline) { nodeList = await async.readJSON(this.certListCachePath); if (!isArray(nodeList)) { nodeList = []; await async.writeJSON(this.certListCachePath, nodeList); } try { await this.loadCertificates(updateProgressCategory, nodeList, settings); } catch (e) { this.addWarning(new WorkspaceError("Failed to load certificates in Offline Mode", e.toString())); } } else { try { nodeList = await this.updateCertList(updateProgressCategory, settings); } catch (e) { this.addWarning(e); nodeList = await async.readJSON(this.certListCachePath); if (!isArray(nodeList)) { nodeList = []; await async.writeJSON(this.certListCachePath, nodeList); throw e; } try { await this.loadCertificates(updateProgressCategory, nodeList, settings); } catch (e) { this.addWarning(new WorkspaceError("Failed to load backup certificates", e.toString())); } } } } else { if (this._offline) { nodeList = []; } else { nodeList = await this.updateCertList(updateProgressCategory, settings); } } const nodeIgnoreList = this.workspace.getNodeIgnoreList(); nodeList = nodeList.filter((certname: string) => { if (nodeIgnoreList.indexOf(certname) >= 0) return false; const cert = zis._certificates.get(certname); if (cert != null) { const ext = cert.getExtension({id: HIERA_EDITOR_FIELD}); if (ext != null) { // cut the fist two characters // https://puppet.com/docs/puppet/6.0/ssl_attributes_extensions.html#manually-checking-for-extensions-in-csrs-and-certificates if (ext.value.substr(2) == HIERA_EDITOR_VALUE) return false; } } return true; }); this._nodeFacts.clear(); if (!await async.isDirectory(this.certNodeFactsPath)) await async.makeDirectory(this.certNodeFactsPath); const count = { c: 0, total: nodeList.length }; const queries = []; for (const certName of nodeList) { queries.push(this.fetchNodeFacts(certName, count, progressCallback, settings, this._offline)); } if (queries.length > 0) { if (updateProgressCategory) updateProgressCategory("[" + this.name + "] Fetching node facts...", true); await Promise.all(queries); } if (updateProgressCategory) updateProgressCategory("[" + this.name + "] Resolving nodes...", true); this._nodes.clear(); for (const certname of this._nodeFacts.getKeys()) { const facts = this._nodeFacts.get(certname); const node = await this.enterNodeContext(certname, facts); this._nodes.put(certname, node); } } private async fetchNodeFacts(certname: string, count: any, progressCallback: any, settings: WorkspaceSettings, offline: boolean) { const p = this.getNodeFactsPath(certname); let facts; if (offline) { if (await async.isFile(p)) { try { facts = await async.readJSON(p); } catch (e) { // } } else { this.addWarning(new WorkspaceError("Missing facts for node '" + certname + '"', "Please restart with Offline Mode disabled to fetch those.")); } } else { try { facts = await PuppetHTTP.GetNodeFacts(this.name, certname, settings); await async.writeJSON(p, facts); } catch (e) { this.addWarning(new WorkspaceError("Failed to fetch facts for node '" + certname + '"', e.toString())); if (await async.isFile(p)) { try { facts = await async.readJSON(p); } catch (e) { try { await async.remove(p); } catch (e) { // } this.addWarning(new WorkspaceError("Failed to fetch back up facts for node '" + certname + '"', e.toString())); } } } } this._nodeFacts.put(certname, facts); if (progressCallback) { count.c++; progressCallback(count.c / count.total); } } public async loadModulesInfo(): Promise<PuppetModulesInfo> { if (this._modulesInfo != null) { return this._modulesInfo; } if (!await async.isFile(this.cacheModulesFilePath)) { return null; } const data: any = await async.readJSON(this.cacheModulesFilePath); this._modulesInfo = new PuppetModulesInfo(this.modulesPath, this.cachePath, data); return this._modulesInfo; } public async getModules(): Promise<any> { const modulesPath = this.modulesPath; if (!await async.isDirectory(modulesPath)) return {}; const files = await async.listFiles(modulesPath); const result: any = {}; for (const file of files) { const modulePath = path.join(modulesPath, file); const metadataPath = path.join(modulePath, "metadata.json"); const manifestsPath = path.join(modulePath, "manifests"); const filesPath = path.join(modulePath, "files"); if (await async.isFile(metadataPath) || await async.isDirectory(manifestsPath) || await async.isDirectory(filesPath) ) { result[file] = {}; } } return result; } public getCompiledPath(fileName: string) { return path.join(this._cachePath, "obj", fileName + ".o"); } public get compileDirectory() { return path.join(this._cachePath, "obj"); } public async generateCompilePromises(files: string[], directory: string, cb: CompiledPromisesCallback): Promise<Array<any>> { const result: Array<any> = []; const _cachedStats: any = {}; const _realStats: any = {}; for (let fileName of files) { const file = this.getCompiledPath(path.join(directory, fileName)); const realFile = path.join(this._path, directory, fileName); _cachedStats[file] = async.fileStat(file); _realStats[file] = async.fileStat(realFile); } const cachedStats = await async.PromiseAllObject(_cachedStats); const realStats = await async.PromiseAllObject(_realStats); const compileFileList: Array<[string, string]> = []; for (let fileName of files) { const file = this.getCompiledPath(path.join(directory, fileName)); if (cachedStats[file]) { const cachedStat = cachedStats[file]; if (cachedStat != null) { const cachedTime: Number = cachedStat.mtimeMs; const realStat = realStats[file]; if (realStat != null) { const realTime: Number = realStat.mtimeMs; if (cachedTime >= realTime) { // compiled file is up-to-date continue; } } } } const realFile = path.join(this._path, directory, fileName); let data; try { data = await async.readFile(realFile); } catch (e) { continue; } compileFileList.push([file, data]); } async function compileFiles(files: any, compilePath: string) { console.log("Compiling " + Object.keys(files).join(", ") + "..."); try { await Ruby.CallAndSendStdIn("puppet-parser.rb", [], compilePath, JSON.stringify(files)); console.log("Compiling done!"); } catch (e) { console.log("Failed to compile: " + e); } cb.done += 1; if (cb.callback) cb.callback(cb.done); } while (true) { const files: any = {}; let foundOne: boolean = false; for (let i = 0; i < 16; i++) { if (compileFileList.length == 0) break; const [file, source] = compileFileList.pop(); files[file] = source; foundOne = true; } if (!foundOne) break; result.push([compileFiles, files, this.compileDirectory]); } return result; } }
the_stack
import { flattenBinArray } from '../../format/hex'; import { AuthenticationInstruction, ParsedAuthenticationInstruction, ParsedAuthenticationInstructionMalformed, } from '../../vm/instruction-sets/instruction-sets-types'; import { authenticationInstructionIsMalformed, parseBytecode, serializeParsedAuthenticationInstructionMalformed, } from '../../vm/instruction-sets/instruction-sets-utils'; import { AuthenticationProgramStateExecutionStack } from '../../vm/vm'; import { createCompilerCommonSynchronous } from '../compiler'; import { CompilationError, CompilationErrorRecoverable, EvaluationSample, Range, ResolvedScript, ResolvedSegmentLiteralType, ScriptReductionTraceChildNode, ScriptReductionTraceScriptNode, } from './language-types'; const pluckStartPosition = (range: Range) => ({ startColumn: range.startColumn, startLineNumber: range.startLineNumber, }); const pluckEndPosition = (range: Range) => ({ endColumn: range.endColumn, endLineNumber: range.endLineNumber, }); /** * Combine an array of `Range`s into a single larger `Range`. * * @param ranges - an array of `Range`s * @param parentRange - the range to assume if `ranges` is an empty array */ export const mergeRanges = ( ranges: Range[], parentRange = { endColumn: 0, endLineNumber: 0, startColumn: 0, startLineNumber: 0, } as Range ) => { const minimumRangesToMerge = 2; const unsortedMerged = ranges.length < minimumRangesToMerge ? ranges.length === 1 ? ranges[0] : parentRange : ranges.reduce<Range>( // eslint-disable-next-line complexity (merged, range) => ({ ...(range.endLineNumber > merged.endLineNumber ? pluckEndPosition(range) : range.endLineNumber === merged.endLineNumber && range.endColumn > merged.endColumn ? pluckEndPosition(range) : pluckEndPosition(merged)), ...(range.startLineNumber < merged.startLineNumber ? pluckStartPosition(range) : range.startLineNumber === merged.startLineNumber && range.startColumn < merged.startColumn ? pluckStartPosition(range) : pluckStartPosition(merged)), }), ranges[0] ); return { ...pluckEndPosition(unsortedMerged), ...pluckStartPosition(unsortedMerged), }; }; /** * Returns true if the `outerRange` fully contains the `innerRange`, otherwise, * `false`. * * @param outerRange - the bounds of the outer range * @param innerRange - the inner range to test * @param exclusive - disallow the `innerRange` from overlapping the * `outerRange` (such that the outer start and end columns may not be equal) – * defaults to `true` */ // eslint-disable-next-line complexity export const containsRange = ( outerRange: Range, innerRange: Range, exclusive = true ) => { const startsAfter = outerRange.startLineNumber < innerRange.startLineNumber ? true : outerRange.startLineNumber === innerRange.startLineNumber ? exclusive ? outerRange.startColumn < innerRange.startColumn : outerRange.startColumn <= innerRange.startColumn : false; const endsBefore = outerRange.endLineNumber > innerRange.endLineNumber ? true : outerRange.endLineNumber === innerRange.endLineNumber ? exclusive ? outerRange.endColumn > innerRange.endColumn : outerRange.endColumn >= innerRange.endColumn : false; return startsAfter && endsBefore; }; /** * Perform a simplified compilation on a Bitauth Templating Language (BTL) * script containing only hex literals, bigint literals, UTF8 literals, and push * statements. Scripts may not contain variables/operations, evaluations, or * opcode identifiers (use hex literals instead). * * This is useful for accepting complex user input in advanced interfaces, * especially for `AddressData` and `WalletData`. * * Returns the compiled bytecode as a `Uint8Array`, or throws an error message. * * @param script - a simple BTL script containing no variables or evaluations */ export const compileBtl = (script: string) => { const result = createCompilerCommonSynchronous({ scripts: { script }, }).generateBytecode('script', {}); if (result.success) { return result.bytecode; } return `BTL compilation error:${result.errors.reduce( (all, { error, range }) => `${all} [${range.startLineNumber}, ${range.startColumn}]: ${error}`, '' )}`; }; /** * Extract a list of the errors which occurred while resolving a script. * * @param resolvedScript - the result of `resolveScript` from which to extract * errors */ export const getResolutionErrors = ( resolvedScript: ResolvedScript ): CompilationError[] => resolvedScript.reduce<CompilationError[]>((errors, segment) => { switch (segment.type) { case 'error': return [ ...errors, { error: segment.value, ...(segment.missingIdentifier === undefined ? {} : { missingIdentifier: segment.missingIdentifier, owningEntity: segment.owningEntity, }), range: segment.range, }, ]; case 'push': case 'evaluation': return [...errors, ...getResolutionErrors(segment.value)]; default: return errors; } }, []); /** * Verify that every error in the provided array can be resolved by providing * additional variables in the compilation data (rather than deeper issues, like * problems with the authentication template or wallet implementation). * * Note, errors are only recoverable if the "entity ownership" of each missing * identifier is known (specified in `CompilationData`'s `entityOwnership`). * * @param errors - an array of compilation errors */ export const allErrorsAreRecoverable = ( errors: CompilationError[] ): errors is CompilationErrorRecoverable[] => errors.every( (error) => 'missingIdentifier' in error && 'owningEntity' in error ); /** * A single resolution for a `ResolvedSegment`. The `variable`, `script`, or * `opcode` property contains the full identifier which resolved to `bytecode`. */ export interface BtlResolution { bytecode: Uint8Array; type: 'variable' | 'script' | 'opcode' | ResolvedSegmentLiteralType; text: string; } /** * Get an array of all resolutions used in a `ResolvedScript`. * @param resolvedScript - the resolved script to search */ export const extractBytecodeResolutions = ( resolvedScript: ResolvedScript ): BtlResolution[] => // eslint-disable-next-line complexity resolvedScript.reduce<BtlResolution[]>((all, segment) => { switch (segment.type) { case 'push': case 'evaluation': return [...all, ...extractBytecodeResolutions(segment.value)]; case 'bytecode': if ('variable' in segment) { return [ ...all, { bytecode: segment.value, text: segment.variable, type: 'variable', }, ]; } if ('script' in segment) { return [ ...all, ...extractBytecodeResolutions(segment.source), { bytecode: segment.value, text: segment.script, type: 'script', }, ]; } if ('opcode' in segment) { return [ ...all, { bytecode: segment.value, text: segment.opcode, type: 'opcode', }, ]; } return [ ...all, { bytecode: segment.value, text: segment.literal, type: segment.literalType, }, ]; default: return all; } }, []); /** * Extract an object mapping the variable identifiers used in a `ResolvedScript` * to their resolved bytecode. * * @param resolvedScript - the resolved script to search */ export const extractResolvedVariableBytecodeMap = ( resolvedScript: ResolvedScript ) => extractBytecodeResolutions(resolvedScript).reduce<{ [fullIdentifier: string]: Uint8Array; }>( (all, resolution) => resolution.type === 'variable' ? { ...all, [resolution.text]: resolution.bytecode } : all, {} ); /** * Format a list of `CompilationError`s into a single string, with an error * start position following each error. E.g. for line 1, column 2: * `The error message. [1, 2]` * * Errors are separated with the `separator`, which defaults to `; `, e.g.: * `The first error message. [1, 2]; The second error message. [3, 4]` * * @param errors - an array of compilation errors * @param separator - the characters with which to join the formatted errors. */ export const stringifyErrors = ( errors: CompilationError[], separator = '; ' ) => { return `${errors .map( (error) => `[${error.range.startLineNumber}, ${error.range.startColumn}] ${error.error}` ) .join(separator)}`; }; export interface SampleExtractionResult<ProgramState, Opcodes = number> { /** * The samples successfully extracted from the provided `nodes` and `trace`. * * In a successful evaluation, one sample will be produced for each state in * `trace` with the exception of the last state (the evaluation result) which * will be returned in `unmatchedStates`. * * In an unsuccessful evaluation, the `trace` states will be exhausted before * all `nodes` have been matched. In this case, all matched samples are * returned, and the final state (the evaluation result) is dropped. This can * be detected by checking if the length of `unmatchedStates` is `0`. */ samples: EvaluationSample<ProgramState, Opcodes>[]; /** * If the provided `nodes` are exhausted before all states from `trace` have * been matched, the remaining "unmatched" states are returned. This is useful * for extracting samples for an evaluation involving two or more * compilations. * * In a successful evaluation, after samples have been extracted from each set * of `nodes`, the final `trace` state (the evaluation result) will be * returned in `unmatchedStates`. */ unmatchedStates: ProgramState[]; } /** * Extract a set of "evaluation samples" from the result of a BTL compilation * and a matching debug trace (from `vm.debug`), pairing program states with the * source ranges which produced them – like a "source map" for complete * evaluations. This is useful for omniscient debuggers like Bitauth IDE. * * Returns an array of samples and an array of unmatched program states * remaining if `nodes` doesn't contain enough instructions to consume all * program states provided in `trace`. Returned samples are ordered by the * ending position (line and column) of their range. * * If all program states are consumed before the available nodes are exhausted, * the remaining nodes are ignored (the produced samples end at the last * instruction for which a program state exists). This usually occurs when an * error halts evaluation before the end of the script. (Note: if this occurs, * the final trace state will not be used, as it is expected to be the * duplicated final result produced by `vm.debug`, and should not be matched * with the next instruction. The returned `unmatchedStates` will have a length * of `0`.) * * This method allows for samples to be extracted from a single evaluation; * most applications should use `extractEvaluationSamplesRecursive` instead. * * @remarks * This method incrementally concatenates the reduced bytecode from each node, * parsing the result into evaluation samples. * * Each node can contain only a portion of an instruction (like a long push * operation), or it can contain multiple instructions (like a long hex literal * representing a string of bytecode or an evaluation which is not wrapped by a * push). * * If a node contains only a portion of an instruction, the bytecode from * additional nodes are concatenated (and ranges merged) until an instruction * can be created. If any bytecode remains after a sample has been created, the * next sample begins in the same range. (For this reason, it's possible that * samples overlap.) * * If a node contains more than one instruction, the intermediate states * produced before the final state for that sample are saved to the sample's * `intermediateStates` array. * * If the program states in `trace` are exhausted before the final instruction * in a sample (usually caused by an evaluation error), the last instruction * with a matching program state is used for the sample (with its program * state), and the unmatched instructions are ignored. (This allows the "last * known state" to be displayed for the sample which caused evaluation to halt.) * * --- * * For example, the following script demonstrates many of these cases: * * `0x00 0x01 0xab01 0xcd9300 $(OP_3 <0x00> OP_SWAP OP_CAT) 0x010203` * * Which compiles to `0x0001ab01cd93000003010203`, disassembled: * * `OP_0 OP_PUSHBYTES_1 0xab OP_PUSHBYTES_1 0xcd OP_ADD OP_0 OP_0 OP_PUSHBYTES_3 0x010203` * * In the script, there are 6 top-level nodes (identified below within `[]`): * * `[0x00] [0x01] [0xab01] [0xcd9300] [$(OP_3 <0x00> OP_SWAP OP_CAT)] [0x010203]` * * These nodes together encode 7 instructions, some within a single node, and * some split between several nodes. Below we substitute the evaluation for its * result `0x0003` to group instructions by `[]`: * * `[0x00] [0x01 0xab][01 0xcd][93][00] [0x00][03 0x010203]` * * The "resolution" of samples is limited to the range of single nodes: nodes * cannot always be introspected to determine where contained instructions begin * and end. For example, it is ambiguous which portions of the evaluation are * responsible for the initial `0x00` and which are responsible for the `0x03`. * * For this reason, the range of each sample is limited to the range(s) of one * or more adjacent nodes. Samples may overlap in the range of a node which is * responsible for both ending a previous sample and beginning a new sample. * (Though, only 2 samples can overlap. If a node is responsible for more than 2 * instructions, the second sample includes `internalStates` for instructions * which occur before the end of the second sample.) * * In this case, there are 6 samples identified below within `[]`, where each * `[` is closed by the closest following `]` (no nesting): * * `[0x00] [0x01 [0xab01] [0xcd9300]] [[$(OP_3 <0x00> OP_SWAP OP_CAT)] 0x010203]` * * The ranges for each sample (in terms of nodes) are as follows: * - Sample 1: node 1 * - Sample 2: node 2 + node 3 * - Sample 3: node 3 + node 4 * - Sample 4: node 4 * - Sample 5: node 5 * - Sample 6: node 5 + node 6 * * Note that the following samples overlap: * - Sample 2 and Sample 3 * - Sample 3 and Sample 4 * - Sample 5 and Sample 6 * * Finally, note that Sample 4 will have one internal state produced by the * `OP_ADD` instruction. Sample 4 then ends with the `OP_0` (`0x00`) instruction * at the end of the `0xcd9300` node. * * --- * * Note, this implementation relies on the expectation that `trace` begins with * the initial program state, contains a single program state per instruction, * and ends with the final program state (as produced by `vm.debug`). It also * expects the `bytecode` provided by nodes to be parsable by `parseBytecode`. * * @param evaluationRange - the range of the script node which was evaluated to * produce the `trace` * @param nodes - an array of reduced nodes to parse * @param trace - the `vm.debug` result to map to these nodes */ // eslint-disable-next-line complexity export const extractEvaluationSamples = <ProgramState, Opcodes = number>({ evaluationRange, nodes, trace, }: { evaluationRange: Range; nodes: ScriptReductionTraceScriptNode<ProgramState>['script']; trace: ProgramState[]; }): SampleExtractionResult<ProgramState, Opcodes> => { const traceWithoutFinalState = trace.length > 1 ? trace.slice(0, -1) : trace.slice(); if (traceWithoutFinalState.length === 0) { return { samples: [], unmatchedStates: [], }; } const samples: EvaluationSample<ProgramState, Opcodes>[] = [ { evaluationRange, internalStates: [], range: { endColumn: evaluationRange.startColumn, endLineNumber: evaluationRange.startLineNumber, startColumn: evaluationRange.startColumn, startLineNumber: evaluationRange.startLineNumber, }, state: traceWithoutFinalState[0], }, ]; // eslint-disable-next-line functional/no-let let nextState = 1; // eslint-disable-next-line functional/no-let let nextNode = 0; // eslint-disable-next-line functional/no-let, @typescript-eslint/init-declarations let incomplete: { bytecode: Uint8Array; range: Range } | undefined; // eslint-disable-next-line functional/no-loop-statement while (nextState < traceWithoutFinalState.length && nextNode < nodes.length) { const currentNode = nodes[nextNode]; const { mergedBytecode, mergedRange } = incomplete === undefined ? { mergedBytecode: currentNode.bytecode, mergedRange: currentNode.range, } : { mergedBytecode: flattenBinArray([ incomplete.bytecode, currentNode.bytecode, ]), mergedRange: mergeRanges([incomplete.range, currentNode.range]), }; const parsed = parseBytecode<Opcodes>(mergedBytecode); const hasNonMalformedInstructions = parsed.length !== 0 && !('malformed' in parsed[0]); if (hasNonMalformedInstructions) { const lastInstruction = parsed[parsed.length - 1]; const validInstructions = (authenticationInstructionIsMalformed( lastInstruction ) ? parsed.slice(0, parsed.length - 1) : parsed) as AuthenticationInstruction<Opcodes>[]; const firstUnmatchedStateIndex = nextState + validInstructions.length; const matchingStates = traceWithoutFinalState.slice( nextState, firstUnmatchedStateIndex ); const pairedStates = validInstructions.map((instruction, index) => ({ instruction, state: matchingStates[index] as ProgramState | undefined, })); /** * Guaranteed to have a defined `state` (or the loop would have exited). */ const firstPairedState = pairedStates[0] as { instruction: ParsedAuthenticationInstruction<Opcodes>; state: ProgramState; }; const closesCurrentlyOpenSample = incomplete !== undefined; // eslint-disable-next-line functional/no-conditional-statement if (closesCurrentlyOpenSample) { // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data samples.push({ evaluationRange, instruction: firstPairedState.instruction, internalStates: [], range: mergedRange, state: firstPairedState.state, }); } const firstUndefinedStateIndex = pairedStates.findIndex( ({ state }) => state === undefined ); const sampleHasError = firstUndefinedStateIndex !== -1; const sampleClosingIndex = sampleHasError ? firstUndefinedStateIndex - 1 : pairedStates.length - 1; const closesASecondSample = !closesCurrentlyOpenSample || sampleClosingIndex > 0; // eslint-disable-next-line functional/no-conditional-statement if (closesASecondSample) { const finalState = pairedStates[sampleClosingIndex] as { instruction: ParsedAuthenticationInstruction<Opcodes>; state: ProgramState; }; const secondSamplePairsBegin = closesCurrentlyOpenSample ? 1 : 0; const internalStates = pairedStates.slice( secondSamplePairsBegin, sampleClosingIndex ) as { instruction: ParsedAuthenticationInstruction<Opcodes>; state: ProgramState; }[]; // eslint-disable-next-line functional/no-expression-statement, functional/immutable-data samples.push({ evaluationRange, instruction: finalState.instruction, internalStates, range: currentNode.range, state: finalState.state, }); } // eslint-disable-next-line functional/no-expression-statement nextState = firstUnmatchedStateIndex; // eslint-disable-next-line functional/no-conditional-statement if (authenticationInstructionIsMalformed(lastInstruction)) { // eslint-disable-next-line functional/no-expression-statement incomplete = { bytecode: serializeParsedAuthenticationInstructionMalformed( lastInstruction ), range: currentNode.range, }; // eslint-disable-next-line functional/no-conditional-statement } else { // eslint-disable-next-line functional/no-expression-statement incomplete = undefined; } // eslint-disable-next-line functional/no-conditional-statement } else { const lastInstruction = parsed[parsed.length - 1] as | ParsedAuthenticationInstructionMalformed<Opcodes> | undefined; // eslint-disable-next-line functional/no-expression-statement incomplete = lastInstruction === undefined ? undefined : { bytecode: serializeParsedAuthenticationInstructionMalformed( lastInstruction ), range: mergedRange, }; } // eslint-disable-next-line functional/no-expression-statement nextNode += 1; } /** * Because we ran out of `trace` states before all `nodes` were matched, we * know an error occurred which halted evaluation. This error is indicated in * the result by returning an empty array of `unmatchedStates`. Successful * evaluations will always return at least one unmatched state: the final * "evaluation result" state produced by `vm.debug`. */ const errorOccurred = nextNode < nodes.length; const unmatchedStates: ProgramState[] = errorOccurred ? [] : trace.slice(nextState); return { samples, unmatchedStates, }; }; /** * Similar to `extractEvaluationSamples`, but recursively extracts samples from * evaluations within the provided array of nodes. * * Because BTL evaluations are fully self-contained, there should never be * unmatched states from evaluations within a script reduction trace tree. (For * this reason, this method does not return the `unmatchedStates` from nested * evaluations.) * * Returned samples are ordered by the ending position (line and column) of * their range. Samples from BTL evaluations which occur within an outer * evaluation appear before their parent sample (which uses their result). * * @param evaluationRange - the range of the script node which was evaluated to * produce the `trace` * @param nodes - an array of reduced nodes to parse * @param trace - the `vm.debug` result to map to these nodes */ export const extractEvaluationSamplesRecursive = < ProgramState, Opcodes = number >({ evaluationRange, nodes, trace, }: { evaluationRange: Range; nodes: ScriptReductionTraceScriptNode<ProgramState>['script']; trace: ProgramState[]; }): SampleExtractionResult<ProgramState, Opcodes> => { const extractEvaluations = ( node: ScriptReductionTraceChildNode<ProgramState>, depth = 1 ): EvaluationSample<ProgramState, Opcodes>[] => { if ('push' in node) { return node.push.script.reduce<EvaluationSample<ProgramState, Opcodes>[]>( (all, childNode) => [...all, ...extractEvaluations(childNode, depth)], [] ); } if ('source' in node) { const childSamples = node.source.script.reduce< EvaluationSample<ProgramState, Opcodes>[] >( (all, childNode) => [ ...all, ...extractEvaluations(childNode, depth + 1), ], [] ); const traceWithoutUnlockingPhase = node.trace.slice(1); const evaluationBeginToken = '$('; const evaluationEndToken = ')'; const extracted = extractEvaluationSamples<ProgramState, Opcodes>({ evaluationRange: { endColumn: node.range.endColumn - evaluationEndToken.length, endLineNumber: node.range.endLineNumber, startColumn: node.range.startColumn + evaluationBeginToken.length, startLineNumber: node.range.startLineNumber, }, nodes: node.source.script, trace: traceWithoutUnlockingPhase, }); return [...extracted.samples, ...childSamples]; } return []; }; const { samples, unmatchedStates } = extractEvaluationSamples< ProgramState, Opcodes >({ evaluationRange, nodes, trace, }); const childSamples = nodes.reduce<EvaluationSample<ProgramState, Opcodes>[]>( (all, node) => [...all, ...extractEvaluations(node)], [] ); const endingOrderedSamples = [...samples, ...childSamples].sort((a, b) => { const linesOrdered = a.range.endLineNumber - b.range.endLineNumber; return linesOrdered === 0 ? a.range.endColumn - b.range.endColumn : linesOrdered; }); return { samples: endingOrderedSamples, unmatchedStates, }; }; const stateIsExecuting = (state: AuthenticationProgramStateExecutionStack) => state.executionStack.every((item) => item); /** * Extract an array of ranges which were unused by an evaluation. This is useful * in development tooling for fading out or hiding code which is unimportant to * the current evaluation being tested. * * @remarks * Only ranges which are guaranteed to be unimportant to an evaluation are * returned by this method. These ranges are extracted from samples which: * - are preceded by a sample which ends with execution disabled (e.g. an * unsuccessful `OP_IF`) * - end with execution disabled, and * - contain no `internalStates` which enable execution. * * Note, internal states which temporarily re-enable and then disable execution * again can still have an effect on the parent evaluation, so this method * conservatively excludes such samples. For example, the hex literal * `0x675167`, which encodes `OP_ELSE OP_1 OP_ELSE`, could begin and end with * states in which execution is disabled, yet a `1` is pushed to the stack * during the sample's evaluation. (Samples like this are unusual, and can * almost always be reformatted to clearly separate the executed and unexecuted * instructions.) * * @param samples - an array of samples ordered by the ending position (line and * column) of their range. * @param evaluationBegins - the line and column at which the initial sample's * evaluation range begins (where the preceding state is assumed to be * executing), defaults to `1,1` */ export const extractUnexecutedRanges = < ProgramState extends AuthenticationProgramStateExecutionStack, Opcodes = number >( samples: EvaluationSample<ProgramState, Opcodes>[], evaluationBegins = '1,1' ) => { const reduced = samples.reduce<{ precedingStateSkipsByEvaluation: { [evaluationStartLineAndColumn: string]: boolean; }; unexecutedRanges: Range[]; }>( (all, sample) => { const { precedingStateSkipsByEvaluation, unexecutedRanges } = all; const currentEvaluationStartLineAndColumn = `${sample.evaluationRange.startLineNumber},${sample.evaluationRange.startColumn}`; const precedingStateSkips = precedingStateSkipsByEvaluation[currentEvaluationStartLineAndColumn]; const endsWithSkip = !stateIsExecuting(sample.state); const sampleHasNoExecutedInstructions = endsWithSkip && sample.internalStates.every((group) => !stateIsExecuting(group.state)); if (precedingStateSkips && sampleHasNoExecutedInstructions) { return { precedingStateSkipsByEvaluation: { ...precedingStateSkipsByEvaluation, [currentEvaluationStartLineAndColumn]: true, }, unexecutedRanges: [...unexecutedRanges, sample.range], }; } return { precedingStateSkipsByEvaluation: { ...precedingStateSkipsByEvaluation, [currentEvaluationStartLineAndColumn]: endsWithSkip, }, unexecutedRanges, }; }, { precedingStateSkipsByEvaluation: { [evaluationBegins]: false, }, unexecutedRanges: [], } ); const canHaveContainedRanges = 2; const containedRangesExcluded = reduced.unexecutedRanges.length < canHaveContainedRanges ? reduced.unexecutedRanges : reduced.unexecutedRanges.slice(0, -1).reduceRight<Range[]>( (all, range) => { if (containsRange(all[0], range)) { return all; } return [range, ...all]; }, [reduced.unexecutedRanges[reduced.unexecutedRanges.length - 1]] ); return containedRangesExcluded; };
the_stack
import $ from "jquery"; import { asArray, hasOwnProperty } from "../utils"; import { isIE } from "../utils/browser"; import type { BindScope } from "./bind"; import { shinyBindAll, shinyInitializeInputs, shinyUnbindAll, } from "./initedMethods"; import { sendImageSizeFns } from "./sendImageSize"; import { renderHtml as singletonsRenderHtml } from "./singletons"; import type { WherePosition } from "./singletons"; function renderDependencies(dependencies: HtmlDep[] | null): void { if (dependencies) { dependencies.forEach(renderDependency); } } // Render HTML in a DOM element, add dependencies, and bind Shiny // inputs/outputs. `content` can be null, a string, or an object with // properties 'html' and 'deps'. function renderContent( el: BindScope, content: string | { html: string; deps?: HtmlDep[] } | null, where: WherePosition = "replace" ): void { if (where === "replace") { shinyUnbindAll(el); } let html = ""; let dependencies: HtmlDep[] = []; if (content === null) { html = ""; } else if (typeof content === "string") { html = content; } else if (typeof content === "object") { html = content.html; dependencies = content.deps || []; } renderHtml(html, el, dependencies, where); let scope: BindScope = el; if (where === "replace") { shinyInitializeInputs(el); shinyBindAll(el); } else { const $parent = $(el).parent(); if ($parent.length > 0) { scope = $parent; if (where === "beforeBegin" || where === "afterEnd") { const $grandparent = $parent.parent(); if ($grandparent.length > 0) scope = $grandparent; } } shinyInitializeInputs(scope); shinyBindAll(scope); } } // Render HTML in a DOM element, inserting singletons into head as needed function renderHtml( html: string, el: BindScope, dependencies: HtmlDep[], where: WherePosition = "replace" ): ReturnType<typeof singletonsRenderHtml> { renderDependencies(dependencies); return singletonsRenderHtml(html, el, where); } type HtmlDepVersion = string; type MetaItem = { name: string; content: string; [x: string]: string; }; type StylesheetItem = { href: string; [x: string]: string; }; type ScriptItem = { src: string; [x: string]: string; }; type AttachmentItem = { key: string; href: string; [x: string]: string; }; // This supports the older R htmltools HtmlDependency structure, and it also // encompasses the newer, consistent HTMLDependency structure. type HtmlDep = { name: string; version: HtmlDepVersion; restyle?: boolean; src?: { href: string }; meta?: MetaItem[] | { [x: string]: string }; stylesheet?: string[] | StylesheetItem | StylesheetItem[] | string; script?: ScriptItem | ScriptItem[] | string[] | string; attachment?: AttachmentItem[] | string[] | string | { [key: string]: string }; head?: string; }; // This is the newer, consistent HTMLDependency structure. type HtmlDepNormalized = { name: string; version: HtmlDepVersion; restyle?: boolean; meta: MetaItem[]; stylesheet: StylesheetItem[]; script: ScriptItem[]; attachment: AttachmentItem[]; head?: string; }; const htmlDependencies: { [key: string]: HtmlDepVersion } = {}; function registerDependency(name: string, version: HtmlDepVersion): void { htmlDependencies[name] = version; } // Re-render stylesheet(s) if the dependency has specificially requested it // and it matches an existing dependency (name and version) function needsRestyle(dep: HtmlDepNormalized) { if (!dep.restyle) { return false; } const names = Object.keys(htmlDependencies); const idx = names.indexOf(dep.name); if (idx === -1) { return false; } return htmlDependencies[names[idx]] === dep.version; } // Client-side dependency resolution and rendering function renderDependency(dep_: HtmlDep) { const dep = normalizeHtmlDependency(dep_); // Convert stylesheet objs to links early, because if `restyle` is true, we'll // pass them through to `addStylesheetsAndRestyle` below. const stylesheetLinks = dep.stylesheet.map((x) => { // Add "rel" and "type" fields if not already present. if (!hasOwnProperty(x, "rel")) x.rel = "stylesheet"; if (!hasOwnProperty(x, "type")) x.type = "text/css"; const link = document.createElement("link"); Object.entries(x).forEach(function ([attr, val]) { if (attr === "href") { val = encodeURI(val); } // If val isn't truthy (e.g., null), consider it a boolean attribute link.setAttribute(attr, val ? val : ""); }); return link; }); // If a restyle is needed, do that stuff and return. Note that other items // (like scripts) aren't added, because they would have been added in a // previous run. if (needsRestyle(dep)) { addStylesheetsAndRestyle(stylesheetLinks); return true; } if (hasOwnProperty(htmlDependencies, dep.name)) return false; registerDependency(dep.name, dep.version); const $head = $("head").first(); // Add each type of element to the DOM. dep.meta.forEach((x) => { const meta = document.createElement("meta"); for (const [attr, val] of Object.entries(x)) { meta.setAttribute(attr, val); } $head.append(meta); }); if (stylesheetLinks.length !== 0) { $head.append(stylesheetLinks); } dep.script.forEach((x) => { const script = document.createElement("script"); Object.entries(x).forEach(function ([attr, val]) { if (attr === "src") { val = encodeURI(val); } // If val isn't truthy (e.g., null), consider it a boolean attribute script.setAttribute(attr, val ? val : ""); }); $head.append(script); }); dep.attachment.forEach((x) => { const link = $("<link rel='attachment'>") .attr("id", dep.name + "-" + x.key + "-attachment") .attr("href", encodeURI(x.href)); $head.append(link); }); if (dep.head) { const $newHead = $("<head></head>"); $newHead.html(dep.head); $head.append($newHead.children()); } return true; } function addStylesheetsAndRestyle(links: HTMLLinkElement[]): void { const $head = $("head").first(); // This inline <style> based approach works for IE11 const refreshStyle = function (href: string, oldSheet: CSSStyleSheet | null) { const xhr = new XMLHttpRequest(); xhr.open("GET", href); xhr.onload = function () { const id = "shiny_restyle_" + href.split("?restyle")[0].replace(/\W/g, "_"); const oldStyle = $head.find("style#" + id); const newStyle = $("<style>").attr("id", id).html(xhr.responseText); $head.append(newStyle); // We can remove the old styles immediately because the new styles // should have been applied synchronously. oldStyle.remove(); removeSheet(oldSheet); sendImageSizeFns.transitioned(); }; xhr.send(); }; const findSheet = function (href: string | undefined): CSSStyleSheet | null { if (!href) return null; for (let i = 0; i < document.styleSheets.length; i++) { const sheet = document.styleSheets[i]; // The sheet's href is a full URL if (typeof sheet.href === "string" && sheet.href.indexOf(href) > -1) { return sheet; } } return null; }; // Removes the stylesheet from document.styleSheets, and also removes // the owning <link> element, if present. const removeSheet = function (sheet: CSSStyleSheet | null) { if (!sheet) return; sheet.disabled = true; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore; .cssText doesn't normally exist, but it does on IE? if (isIE()) sheet.cssText = ""; if (sheet.ownerNode instanceof Element) { $(sheet.ownerNode).remove(); } }; links.map((link) => { const $link = $(link); // Find any document.styleSheets that match this link's href // so we can remove it after bringing in the new stylesheet const oldSheet = findSheet($link.attr("href")); // Add a timestamp to the href to prevent caching const href = $link.attr("href") + "?restyle=" + new Date().getTime(); // Use inline <style> approach for IE, otherwise use the more elegant // <link> -based approach if (isIE()) { refreshStyle(href, oldSheet); } else { $link.attr("href", href); // This part is a bit tricky. The link's onload callback will be // invoked after the file is loaded, but it can be _before_ the // styles are actually applied. The amount of time it takes for the // style to be applied is not predictable. We need to make sure the // styles are applied before we send updated size/style information // to the server. // // We do this by adding _another_ link, with CSS content // base64-encoded and inlined into the href. We also add a dummy DOM // element that the CSS applies to. The dummy CSS includes a // transition, and when the `transitionend` event happens, we call // sendImageSizeFns.transitioned() and remove the old sheet. We also remove the // dummy DOM element and dummy CSS content. // // The reason this works is because (we assume) that if multiple // <link> tags are added, they will be applied in the same order // that they are loaded. This seems to be true in the browsers we // have tested. // // Because it is common for multiple stylesheets to arrive close // together, but not on exactly the same tick, we call // sendImageSizeFns.transitioned(), which is debounced. Otherwise, it can result in // the same plot being redrawn multiple times with different // styling. $link.attr("onload", () => { const $dummyEl = $("<div>") .css("transition", "0.1s all") .css("position", "absolute") .css("top", "-1000px") .css("left", "0"); $dummyEl.one("transitionend", () => { $dummyEl.remove(); removeSheet(oldSheet); sendImageSizeFns.transitioned(); }); $(document.body).append($dummyEl); // To ensure a transition actually happens, change the inline style _after_ // the DOM element has been added, and also use a new random color each time // to prevent any potential caching done by the browser const color = "#" + Math.floor(Math.random() * 16777215).toString(16); setTimeout(() => $dummyEl.css("color", color), 10); }); $head.append(link); } }); } // Convert legacy HtmlDependency to new HTMLDependency format. This is // idempotent; new HTMLDependency objects are returned unchanged. function normalizeHtmlDependency(dep: HtmlDep): HtmlDepNormalized { const hrefPrefix: string | undefined = dep.src?.href; const result: HtmlDepNormalized = { name: dep.name, version: dep.version, restyle: dep.restyle, meta: [], stylesheet: [], script: [], attachment: [], head: dep.head, }; if (dep.meta) { if (Array.isArray(dep.meta)) { // Assume we already have the canonical format: // [{name: "myname", content: "mycontent"}, ...] result.meta = dep.meta; } else { // If here, then we have the legacy format, which we have to convert. // {myname: "mycontent", ...} result.meta = Object.entries(dep.meta).map(function ([attr, val]) { return { name: attr, content: val }; }); } } result.stylesheet = asArray(dep.stylesheet).map((s) => { if (typeof s === "string") { s = { href: s }; } if (hrefPrefix) { s.href = hrefPrefix + "/" + s.href; } return s; }); result.script = asArray(dep.script).map((s) => { if (typeof s === "string") { s = { src: s }; } if (hrefPrefix) { s.src = hrefPrefix + "/" + s.src; } return s; }); // dep.attachment might be one of the following types, which we will convert // as shown: // 0. undefined => [] // 1. A single string: // "foo.txt" // => [{key: "1", href: "foo.txt"}] // 2. An array of strings: // ["foo.txt" ,"bar.dat"] // => [{key: "1", href: "foo.txt"}, {key: "2", href: "bar.dat"}] // 3. An object: // {foo: "foo.txt", bar: "bar.dat"} // => [{key: "foo", href: "foo.txt"}, {key: "bar", href: "bar.dat"}] // 4. An array of objects: // [{key: "foo", href: "foo.txt"}, {key: "bar", href: "bar.dat"}] // => (Returned unchanged) // // Note that the first three formats are from legacy code, and the last format // is from new code. let attachments = dep.attachment; // Convert format 0 (undefined) to format 2 or 4. if (!attachments) attachments = []; // Convert format 1 to format 2. if (typeof attachments === "string") attachments = [attachments]; if (Array.isArray(attachments)) { // If we've gotten here, the format is either 2 or 4. Even though they are // quite different, we can handle them both in the same loop. // Need to give TypeScript a bit of help so that it's happy with .map() // below. Instead of a union of two array types, tell it it's an array of // a union of two types. const tmp = <Array<AttachmentItem | string>>attachments; // The contract for attachments is that arrays of attachments are // addressed using 1-based indexes. Convert this array to an object. attachments = tmp.map((attachment, index) => { if (typeof attachment === "string") { return { key: (index + 1).toString(), href: attachment, }; } else { return attachment; } }); } else { // If we got here, it's format 3. attachments = Object.entries(attachments).map(function ([attr, val]) { return { key: attr, href: val }; }); } // At this point, we've normalized the format to #4. Now we can iterate over // it and prepend `hrefPrefix`. result.attachment = attachments.map((s) => { if (hrefPrefix) { s.href = hrefPrefix + "/" + s.href; } return s; }); return result; } export { renderDependencies, renderContent, renderHtml, registerDependency }; export type { HtmlDep };
the_stack
import { wrapped } from "../functions"; import { expressionSkipsCopy, withPossibleRepresentations, FunctionMap, PossibleRepresentation, ReifiedType, TypeParameterHost } from "../reified"; import { addVariable, lookup, uniqueName, Scope } from "../scope"; import { concat, lookupForMap } from "../utils"; import { array, binary, call, callable, conditional, conformance, copy, expr, functionValue, ignore, literal, logical, member, read, reuse, set, statements, transform, typeFromValue, typeTypeValue, typeValue, undefinedValue, ArgGetter, Value } from "../values"; import { applyDefaultConformances, isEmptyFromLength, readLengthField, reuseArgs, startIndexOfZero, voidType } from "./common"; import { emptyOptional, wrapInOptional } from "./Optional"; import { blockStatement, breakStatement, forStatement, functionExpression, identifier, ifStatement, returnStatement, updateExpression, whileStatement } from "@babel/types"; const dummyType = typeValue({ kind: "name", name: "Dummy" }); export function arrayBoundsFailed(scope: Scope) { return call(functionValue("Swift.(swift-to-js).arrayBoundsFailed()", undefined, { kind: "function", arguments: voidType, return: voidType, throws: true, rethrows: false, attributes: [] }), [], [], scope); } function arrayBoundsCheck(arrayValue: Value, index: Value, scope: Scope, mode: "read" | "write") { return reuse(arrayValue, scope, "array", (reusableArray) => { return reuse(index, scope, "index", (reusableIndex) => { return member( reusableArray, conditional( logical( "&&", binary(mode === "write" ? ">=" : ">", member(reusableArray, "length", scope), reusableIndex, scope, ), binary(">=", reusableIndex, literal(0), scope, ), scope, ), reusableIndex, arrayBoundsFailed(scope), scope, ), scope, ); }); }); } export function Array(globalScope: Scope, typeParameters: TypeParameterHost): ReifiedType { const [ valueType ] = typeParameters("Value"); const reified = typeFromValue(valueType, globalScope); if (valueType.kind !== "type") { // TODO: Support runtime types throw new TypeError(`Runtime types are not supported as Self in [Self]`); } const optionalValueType = typeValue({ kind: "optional", type: valueType.type }); function arrayCompare(comparison: "equal" | "unequal") { return wrapped((scope, arg) => { return reuseArgs(arg, 0, scope, ["lhs", "rhs"], (lhs, rhs) => { const result = uniqueName(scope, comparison); const i = uniqueName(scope, "i"); return statements([ addVariable(scope, result, "Bool"), ifStatement( read(binary("!==", member(lhs, "length", scope), member(rhs, "length", scope), scope, ), scope), blockStatement(ignore(set(lookup(result, scope), literal(comparison === "unequal"), scope), scope)), blockStatement(concat( [ addVariable(scope, i, "Int", literal(0)), whileStatement( read(binary("<", lookup(i, scope), member(lhs, "length", scope), scope, ), scope), blockStatement(concat( ignore( transform( call( call( functionValue("!=", conformance(valueType, "Equatable", scope), "(Type) -> (Self, Self) -> Bool"), [valueType], [typeTypeValue], scope, ), [ member(lhs, lookup(i, scope), scope), member(rhs, lookup(i, scope), scope), ], [ valueType, valueType, ], scope, ), scope, (expression) => statements([ ifStatement(expression, breakStatement()), ]), ), scope, ), ignore(expr(updateExpression("++", read(lookup(i, scope), scope))), scope), )), ), ], ignore(set( lookup(result, scope), binary(comparison === "unequal" ? "!==" : "===", lookup(i, scope), member(lhs, "length", scope), scope, ), scope, ), scope), )), ), returnStatement(read(lookup(result, scope), scope)), ]); }); }, "(Self, Self) -> Bool"); } return { functions: lookupForMap({ // TODO: Fill in proper init "init(_:)": wrapped((scope, arg) => call(member("Array", "from", scope), [arg(0, "iterable")], [dummyType], scope), "(Any) -> Self"), "subscript(_:)": wrapped((scope, arg) => { return arrayBoundsCheck(arg(0, "array"), arg(1, "index"), scope, "read"); }, "(Self, Int) -> Self.Wrapped"), "subscript(_:)_set": wrapped((scope, arg) => { return set( arrayBoundsCheck(arg(0, "array"), arg(1, "index"), scope, "write"), copy(arg(2, "value"), valueType), scope, ); }, "(inout Self, Int, Self.Wrapped) -> Void"), "append()": wrapped((scope, arg) => { const pushExpression = member(arg(2, "array"), "push", scope); const newElement = copy(arg(2, "newElement"), valueType); return call(pushExpression, [newElement], [valueType], scope); }, "(inout Self, Self.Element) -> Void"), "insert(at:)": wrapped((scope, arg) => { const arrayValue = arg(1, "array"); const newElement = copy(arg(2, "newElement"), valueType); const i = arg(3, "i"); return call(functionValue("Swift.(swift-to-js).arrayInsertAt()", undefined, { kind: "function", arguments: { kind: "tuple", types: [] }, return: voidType, throws: true, rethrows: false, attributes: [] }), [arrayValue, newElement, i], [dummyType, valueType, dummyType], scope); }, "(inout Self, Self.Element, Int) -> Void"), "remove(at:)": wrapped((scope, arg) => { const arrayValue = arg(1, "array"); const i = arg(2, "i"); return call(functionValue("Swift.(swift-to-js).arrayRemoveAt()", undefined, { kind: "function", arguments: { kind: "tuple", types: [] }, return: voidType, throws: true, rethrows: false, attributes: [] }), [arrayValue, i], [dummyType, valueType], scope); }, "(inout Self, Int) -> Self.Element"), "removeFirst()": wrapped((scope, arg) => { return reuse(call(member(arg(1, "array"), "shift", scope), [], [], scope), scope, "element", (reusableArray) => { return conditional( binary("!==", reusableArray, undefinedValue, scope, ), reusableArray, arrayBoundsFailed(scope), scope, ); }); }, "(inout Self) -> Self.Element"), "removeLast()": wrapped((scope, arg) => { return reuse(call(member(arg(1, "array"), "pop", scope), [], [], scope), scope, "element", (reusableArray) => { return conditional( binary("!==", reusableArray, undefinedValue, scope, ), reusableArray, arrayBoundsFailed(scope), scope, ); }); }, "(inout Self) -> Self.Element"), "popLast()": wrapped((scope, arg) => { return reuse(call(member(arg(1, "array"), "pop", scope), [], [], scope), scope, "element", (reusableArray) => { return conditional( binary("!==", reusableArray, undefinedValue, scope, ), wrapInOptional(reusableArray, optionalValueType, scope), emptyOptional(optionalValueType, scope), scope, ); }); }, "(inout Self) -> Self.Element?"), "removeAll(keepingCapacity:)": wrapped((scope, arg) => { return set(member(arg(1, "array"), "length", scope), literal(0), scope); }, "(inout Self, Bool) -> Void"), "reserveCapacity()": wrapped((scope, arg) => undefinedValue, "(inout Self, Int) -> Void"), "index(after:)": wrapped((scope, arg) => { const arrayValue = arg(0, "array"); return reuseArgs(arg, 2, scope, ["index"], (index) => { return conditional( binary("<", arrayValue, index, scope), binary("+", index, literal(1), scope), arrayBoundsFailed(scope), scope, ); }); }, "(inout Self, Int) -> Int"), "index(before:)": wrapped((scope, arg) => { return reuseArgs(arg, 2, scope, ["index"], (index) => { return conditional( binary(">", index, literal(0), scope), binary("-", index, literal(1), scope), arrayBoundsFailed(scope), scope, ); }); }, "(inout Self, Int) -> Int"), "distance(from:to:)": wrapped((scope, arg) => { return reuseArgs(arg, 2, scope, ["start"], (start) => { const end = arg(3, "end"); return binary("-", end, start, scope); }); }, "(inout Self, Int, Int) -> Int"), "joined(separator:)": (scope, arg, type) => { return callable((innerScope, innerArg) => { return call( member(arg(2, "collection"), "join", scope), [innerArg(0, "separator")], [dummyType], scope, ); }, "(Self, String) -> String"); }, "count": readLengthField, "isEmpty": isEmptyFromLength, "capacity": readLengthField, "startIndex": startIndexOfZero, "endIndex": readLengthField, "first"(scope: Scope, arg: ArgGetter) { return reuseArgs(arg, 0, scope, ["array"], (reusableValue) => { return conditional( member(reusableValue, "length", scope), wrapInOptional(member(reusableValue, 0, scope), optionalValueType, scope), emptyOptional(optionalValueType, scope), scope, ); }); }, "last"(scope: Scope, arg: ArgGetter) { return reuseArgs(arg, 0, scope, ["array"], (reusableValue) => { return conditional( member(reusableValue, "length", scope), wrapInOptional(member(reusableValue, binary("-", member(reusableValue, "length", scope), literal(1), scope), scope), optionalValueType, scope), emptyOptional(optionalValueType, scope), scope, ); }); }, } as FunctionMap), conformances: withPossibleRepresentations(applyDefaultConformances({ ExpressibleByArrayLiteral: { functions: { "init(arrayLiteral:)": wrapped((scope, arg) => { return arg(0, "array"); }, "(Self.ArrayLiteralElement...) -> Self"), }, requirements: [], }, Equatable: { functions: { "==": arrayCompare("equal"), "!=": arrayCompare("unequal"), }, requirements: [], }, Hashable: { functions: { "hashValue": wrapped((scope, arg) => { const hashValue = call(functionValue("hashValue", conformance(valueType, "Hashable", scope), "(Type) -> (Self) -> Int"), [valueType], [typeTypeValue], scope); const hasherType = typeValue("Hasher"); const combine = call(functionValue("combine()", hasherType, "(Type) -> (inout Hasher, Int) -> Void"), [hasherType], [typeTypeValue], scope); return reuseArgs(arg, 0, scope, ["array"], (arrayValue) => { const result = uniqueName(scope, "hash"); const i = uniqueName(scope, "i"); return statements([ addVariable(scope, result, "Int", array([literal(0)], scope)), forStatement( addVariable(scope, i, "Int", literal(0)), read(binary("<", lookup(i, scope), member(arrayValue, "length", scope), scope, ), scope), updateExpression("++", read(lookup(i, scope), scope)), blockStatement( ignore( transform( call( hashValue, [member(arrayValue, lookup(i, scope), scope)], ["Self"], scope, ), scope, (elementHashValue) => call( combine, [ lookup(result, scope), expr(elementHashValue), ], [ "Hasher", "Int", ], scope, ), ), scope, ), ), ), returnStatement(read(binary("|", member(lookup(result, scope), 0, scope), literal(0), scope), scope)), ]); }); }, "(Self) -> Int"), "hash(into:)": wrapped((scope, arg) => { const hashValue = call(functionValue("hashValue", conformance(valueType, "Hashable", scope), "(Type) -> (Self) -> Int"), [valueType], [typeTypeValue], scope); const hasherType = typeValue("Hasher"); const combine = call(functionValue("combine()", hasherType, "(Type) -> (inout Hasher, Int) -> Void"), [hasherType], [typeTypeValue], scope); return reuseArgs(arg, 0, scope, ["array", "hasher"], (arrayValue, hasher) => { const i = uniqueName(scope, "i"); return statements([ forStatement( addVariable(scope, i, "Int", literal(0)), read(binary("<", lookup(i, scope), member(arrayValue, "length", scope), scope, ), scope), updateExpression("++", read(lookup(i, scope), scope)), blockStatement( ignore( transform( call( hashValue, [member(arrayValue, lookup(i, scope), scope)], ["Self"], scope, ), scope, (elementHashValue) => call( combine, [ hasher, expr(elementHashValue), ], [ "inout Hasher", "Int", ], scope, ), ), scope, ), ), ), ]); }); }, "(Self, inout Hasher) -> Void"), }, requirements: [], }, Collection: { functions: { "Element": wrapped(() => valueType, "() -> Type"), "subscript(_:)": wrapped((scope, arg) => member(arg(0, "array"), arg(1, "index"), scope), "(Self, Self.Index) -> Self.Element"), "startIndex": wrapped(() => literal(0), "(Self) -> Self.Index"), "endIndex": wrapped((scope, arg) => member(arg(0, "array"), "length", scope), "(Self) -> Self.Index"), "index(after:)": wrapped((scope, arg) => binary("+", arg(0, "index"), literal(1), scope), "(Self, Self.Index) -> Self.Index"), }, requirements: ["Sequence"], }, BidirectionalCollection: { functions: { "index(before:)": wrapped((scope, arg) => { return binary("-", arg(0, "index"), literal(1), scope); }, "(String, String.Index) -> String.Index"), "joined(separator:)": (scope, arg, type) => { const collection = arg(1, "collection"); return callable((innerScope, innerArg) => { return call( member(collection, "join", scope), [innerArg(0, "separator")], [dummyType], scope, ); }, "(String) -> String"); }, }, requirements: ["Collection"], }, Sequence: { functions: { "makeIterator()": wrapped((scope, arg) => { const iteratorType = typeValue({ kind: "generic", base: { kind: "name", name: "IndexingIterator" }, arguments: [{ kind: "generic", base: { kind: "name", name: "Array" }, arguments: [valueType.type] }] }); const iteratorInit = functionValue("init(_elements:)", iteratorType, "(Type) -> (Self.Elements) -> Self"); return call(call(iteratorInit, [iteratorType], ["Type"], scope), [arg(0, "array")], ["Self.Elements"], scope); }, "(Self) -> Self.Iterator"), "Iterator": (scope, arg) => { return typeValue({ kind: "generic", base: { kind: "name", name: "IndexingIterator" }, arguments: [{ kind: "generic", base: { kind: "name", name: "Array" }, arguments: [valueType.type] }] }); }, }, requirements: [], }, }, globalScope), PossibleRepresentation.Array), defaultValue() { return literal([]); }, copy(value, scope) { const expression = read(value, scope); if (expressionSkipsCopy(expression)) { return expr(expression); } if (reified.copy) { // Arrays of complex types are mapped using a generated copy function const id = uniqueName(scope, "value"); // TODO: Fill in addVariable // addVariable(); const converter = functionExpression(undefined, [identifier(id)], blockStatement([returnStatement(read(reified.copy(expr(identifier(id)), scope), scope))])); return call(member(expr(expression), "map", scope), [expr(converter)], ["Any"], scope); } else { // Simple arrays are sliced return call(member(expr(expression), "slice", scope), [], [], scope); } }, innerTypes: {}, }; }
the_stack
import {ResourceBase, ResourceTag} from '../resource' import {Value, List} from '../dataTypes' export class IncrementalPullConfig { DatetimeTypeFieldName?: Value<string> constructor(properties: IncrementalPullConfig) { Object.assign(this, properties) } } export class PrefixConfig { PrefixType?: Value<string> PrefixFormat?: Value<string> constructor(properties: PrefixConfig) { Object.assign(this, properties) } } export class S3OutputFormatConfig { FileType?: Value<string> PrefixConfig?: PrefixConfig AggregationConfig?: AggregationConfig constructor(properties: S3OutputFormatConfig) { Object.assign(this, properties) } } export class DestinationFlowConfig { ConnectorType!: Value<string> ConnectorProfileName?: Value<string> DestinationConnectorProperties!: DestinationConnectorProperties constructor(properties: DestinationFlowConfig) { Object.assign(this, properties) } } export class DatadogSourceProperties { Object!: Value<string> constructor(properties: DatadogSourceProperties) { Object.assign(this, properties) } } export class AggregationConfig { AggregationType?: Value<string> constructor(properties: AggregationConfig) { Object.assign(this, properties) } } export class ScheduledTriggerProperties { ScheduleExpression!: Value<string> DataPullMode?: Value<string> ScheduleStartTime?: Value<number> ScheduleEndTime?: Value<number> TimeZone?: Value<string> constructor(properties: ScheduledTriggerProperties) { Object.assign(this, properties) } } export class DestinationConnectorProperties { Redshift?: RedshiftDestinationProperties S3?: S3DestinationProperties Salesforce?: SalesforceDestinationProperties Snowflake?: SnowflakeDestinationProperties EventBridge?: EventBridgeDestinationProperties Upsolver?: UpsolverDestinationProperties LookoutMetrics?: LookoutMetricsDestinationProperties Zendesk?: ZendeskDestinationProperties constructor(properties: DestinationConnectorProperties) { Object.assign(this, properties) } } export class ConnectorOperator { Amplitude?: Value<string> Datadog?: Value<string> Dynatrace?: Value<string> GoogleAnalytics?: Value<string> InforNexus?: Value<string> Marketo?: Value<string> S3?: Value<string> Salesforce?: Value<string> ServiceNow?: Value<string> Singular?: Value<string> Slack?: Value<string> Trendmicro?: Value<string> Veeva?: Value<string> Zendesk?: Value<string> constructor(properties: ConnectorOperator) { Object.assign(this, properties) } } export class ZendeskSourceProperties { Object!: Value<string> constructor(properties: ZendeskSourceProperties) { Object.assign(this, properties) } } export class SalesforceDestinationProperties { Object!: Value<string> ErrorHandlingConfig?: ErrorHandlingConfig IdFieldNames?: List<Value<string>> WriteOperationType?: Value<string> constructor(properties: SalesforceDestinationProperties) { Object.assign(this, properties) } } export class ErrorHandlingConfig { FailOnFirstError?: Value<boolean> BucketPrefix?: Value<string> BucketName?: Value<string> constructor(properties: ErrorHandlingConfig) { Object.assign(this, properties) } } export class S3SourceProperties { BucketName!: Value<string> BucketPrefix!: Value<string> constructor(properties: S3SourceProperties) { Object.assign(this, properties) } } export class SalesforceSourceProperties { Object!: Value<string> EnableDynamicFieldUpdate?: Value<boolean> IncludeDeletedRecords?: Value<boolean> constructor(properties: SalesforceSourceProperties) { Object.assign(this, properties) } } export class SingularSourceProperties { Object!: Value<string> constructor(properties: SingularSourceProperties) { Object.assign(this, properties) } } export class EventBridgeDestinationProperties { Object!: Value<string> ErrorHandlingConfig?: ErrorHandlingConfig constructor(properties: EventBridgeDestinationProperties) { Object.assign(this, properties) } } export class MarketoSourceProperties { Object!: Value<string> constructor(properties: MarketoSourceProperties) { Object.assign(this, properties) } } export class SlackSourceProperties { Object!: Value<string> constructor(properties: SlackSourceProperties) { Object.assign(this, properties) } } export class RedshiftDestinationProperties { Object!: Value<string> IntermediateBucketName!: Value<string> BucketPrefix?: Value<string> ErrorHandlingConfig?: ErrorHandlingConfig constructor(properties: RedshiftDestinationProperties) { Object.assign(this, properties) } } export class LookoutMetricsDestinationProperties { Object?: Value<string> constructor(properties: LookoutMetricsDestinationProperties) { Object.assign(this, properties) } } export class SourceFlowConfig { ConnectorType!: Value<string> ConnectorProfileName?: Value<string> SourceConnectorProperties!: SourceConnectorProperties IncrementalPullConfig?: IncrementalPullConfig constructor(properties: SourceFlowConfig) { Object.assign(this, properties) } } export class UpsolverS3OutputFormatConfig { FileType?: Value<string> PrefixConfig!: PrefixConfig AggregationConfig?: AggregationConfig constructor(properties: UpsolverS3OutputFormatConfig) { Object.assign(this, properties) } } export class UpsolverDestinationProperties { BucketName!: Value<string> BucketPrefix?: Value<string> S3OutputFormatConfig!: UpsolverS3OutputFormatConfig constructor(properties: UpsolverDestinationProperties) { Object.assign(this, properties) } } export class ServiceNowSourceProperties { Object!: Value<string> constructor(properties: ServiceNowSourceProperties) { Object.assign(this, properties) } } export class ZendeskDestinationProperties { Object!: Value<string> ErrorHandlingConfig?: ErrorHandlingConfig IdFieldNames?: List<Value<string>> WriteOperationType?: Value<string> constructor(properties: ZendeskDestinationProperties) { Object.assign(this, properties) } } export class InforNexusSourceProperties { Object!: Value<string> constructor(properties: InforNexusSourceProperties) { Object.assign(this, properties) } } export class S3DestinationProperties { BucketName!: Value<string> BucketPrefix?: Value<string> S3OutputFormatConfig?: S3OutputFormatConfig constructor(properties: S3DestinationProperties) { Object.assign(this, properties) } } export class SourceConnectorProperties { Amplitude?: AmplitudeSourceProperties Datadog?: DatadogSourceProperties Dynatrace?: DynatraceSourceProperties GoogleAnalytics?: GoogleAnalyticsSourceProperties InforNexus?: InforNexusSourceProperties Marketo?: MarketoSourceProperties S3?: S3SourceProperties Salesforce?: SalesforceSourceProperties ServiceNow?: ServiceNowSourceProperties Singular?: SingularSourceProperties Slack?: SlackSourceProperties Trendmicro?: TrendmicroSourceProperties Veeva?: VeevaSourceProperties Zendesk?: ZendeskSourceProperties constructor(properties: SourceConnectorProperties) { Object.assign(this, properties) } } export class TrendmicroSourceProperties { Object!: Value<string> constructor(properties: TrendmicroSourceProperties) { Object.assign(this, properties) } } export class SnowflakeDestinationProperties { Object!: Value<string> IntermediateBucketName!: Value<string> BucketPrefix?: Value<string> ErrorHandlingConfig?: ErrorHandlingConfig constructor(properties: SnowflakeDestinationProperties) { Object.assign(this, properties) } } export class GoogleAnalyticsSourceProperties { Object!: Value<string> constructor(properties: GoogleAnalyticsSourceProperties) { Object.assign(this, properties) } } export class VeevaSourceProperties { Object!: Value<string> constructor(properties: VeevaSourceProperties) { Object.assign(this, properties) } } export class DynatraceSourceProperties { Object!: Value<string> constructor(properties: DynatraceSourceProperties) { Object.assign(this, properties) } } export class Task { SourceFields!: List<Value<string>> ConnectorOperator?: ConnectorOperator DestinationField?: Value<string> TaskType!: Value<string> TaskProperties?: List<TaskPropertiesObject> constructor(properties: Task) { Object.assign(this, properties) } } export class TaskPropertiesObject { Key!: Value<string> Value!: Value<string> constructor(properties: TaskPropertiesObject) { Object.assign(this, properties) } } export class TriggerConfig { TriggerType!: Value<string> TriggerProperties?: ScheduledTriggerProperties constructor(properties: TriggerConfig) { Object.assign(this, properties) } } export class AmplitudeSourceProperties { Object!: Value<string> constructor(properties: AmplitudeSourceProperties) { Object.assign(this, properties) } } export interface FlowProperties { FlowName: Value<string> Description?: Value<string> KMSArn?: Value<string> TriggerConfig: TriggerConfig SourceFlowConfig: SourceFlowConfig DestinationFlowConfigList: List<DestinationFlowConfig> Tasks: List<Task> Tags?: List<ResourceTag> } export default class Flow extends ResourceBase<FlowProperties> { static IncrementalPullConfig = IncrementalPullConfig static PrefixConfig = PrefixConfig static S3OutputFormatConfig = S3OutputFormatConfig static DestinationFlowConfig = DestinationFlowConfig static DatadogSourceProperties = DatadogSourceProperties static AggregationConfig = AggregationConfig static ScheduledTriggerProperties = ScheduledTriggerProperties static DestinationConnectorProperties = DestinationConnectorProperties static ConnectorOperator = ConnectorOperator static ZendeskSourceProperties = ZendeskSourceProperties static SalesforceDestinationProperties = SalesforceDestinationProperties static ErrorHandlingConfig = ErrorHandlingConfig static S3SourceProperties = S3SourceProperties static SalesforceSourceProperties = SalesforceSourceProperties static SingularSourceProperties = SingularSourceProperties static EventBridgeDestinationProperties = EventBridgeDestinationProperties static MarketoSourceProperties = MarketoSourceProperties static SlackSourceProperties = SlackSourceProperties static RedshiftDestinationProperties = RedshiftDestinationProperties static LookoutMetricsDestinationProperties = LookoutMetricsDestinationProperties static SourceFlowConfig = SourceFlowConfig static UpsolverS3OutputFormatConfig = UpsolverS3OutputFormatConfig static UpsolverDestinationProperties = UpsolverDestinationProperties static ServiceNowSourceProperties = ServiceNowSourceProperties static ZendeskDestinationProperties = ZendeskDestinationProperties static InforNexusSourceProperties = InforNexusSourceProperties static S3DestinationProperties = S3DestinationProperties static SourceConnectorProperties = SourceConnectorProperties static TrendmicroSourceProperties = TrendmicroSourceProperties static SnowflakeDestinationProperties = SnowflakeDestinationProperties static GoogleAnalyticsSourceProperties = GoogleAnalyticsSourceProperties static VeevaSourceProperties = VeevaSourceProperties static DynatraceSourceProperties = DynatraceSourceProperties static Task = Task static TaskPropertiesObject = TaskPropertiesObject static TriggerConfig = TriggerConfig static AmplitudeSourceProperties = AmplitudeSourceProperties constructor(properties: FlowProperties) { super('AWS::AppFlow::Flow', properties) } }
the_stack
/** * * @module GameObjects * @submodule Tilemap * */ module Kiwi.GameObjects.Tilemap { /** * Contains the code for managing and rendering Isometric types of TileMaps. * This class should not be directly created, but instead should be created via methods on the TileMap class. * * * @class TileMapLayerIsometric * @extends Kiwi.GameObjects.Tilemap.TileMapLayer * @namespace Kiwi.GameObjects.Tilemap * @since 1.3.0 * @constructor * @param tilemap {Kiwi.GameObjects.Tilemap.TileMap} The TileMap that this layer belongs to. * @param name {String} The name of this TileMapLayer. * @param atlas {Kiwi.Textures.TextureAtlas} The texture atlas that should be used when rendering this TileMapLayer onscreen. * @param data {Number[]} The information about the tiles. * @param tw {Number} The width of a single tile in pixels. Usually the same as the TileMap unless told otherwise. * @param th {Number} The height of a single tile in pixels. Usually the same as the TileMap unless told otherwise. * @param [x=0] {Number} The x coordinate of the tilemap in pixels. * @param [y=0] {Number} The y coordinate of the tilemap in pixels. * @param [w=0] {Number} The width of the whole tilemap in tiles. Usually the same as the TileMap unless told otherwise. * @param [h=0] {Number} The height of the whole tilemap in tiles. Usually the same as the TileMap unless told otherwise. * @return {TileMapLayer} */ export class TileMapLayerIsometric extends TileMapLayer { constructor(tilemap: Kiwi.GameObjects.Tilemap.TileMap, name: string, atlas: Kiwi.Textures.TextureAtlas, data: number[], tw: number, th: number, x: number = 0, y: number = 0, w: number = 0, h: number = 0) { super(tilemap, name, atlas, data, tw, th, x, y, w, h); } /** * The type of object that it is. * @method objType * @return {String} "TileMapLayer" * @public */ public objType() { return "TileMapLayer"; } /** * The orientation of the of tilemap. * TileMaps can be either 'orthogonal' (normal) or 'isometric'. * @property orientation * @type String * @default 'isometric' * @public */ public orientation: string = ISOMETRIC; /** * Returns the index of the tile based on the x and y pixel coordinates that are passed. * If no tile is a the coordinates given then -1 is returned instead. * Coordinates are in pixels not tiles and use the world coordinates of the tilemap. * * Functionality needs to be added by classes extending this class. * * @method getIndexFromCoords * @param x {Number} The x coordinate of the Tile you would like to retrieve. * @param y {Number} The y coordinate of the Tile you would like to retrieve. * @return {Number} Either the index of the tile retrieved or -1 if none was found. * @public */ public getIndexFromCoords(x: number, y: number): number { //Not within the bounds? var halfWidth = this.widthInPixels * 0.5; if (x > this.x + halfWidth || x < this.x - halfWidth) return -1; if (y > this.y + this.heightInPixels || y < this.y) return -1; var point = this.screenToChart({ x: x, y: y }); return this.getIndexFromXY(point.x, point.y); } /** * ChartToScreen maps a point in the game tile coordinates into screen pixel * coordinates that indicate where the tile should be drawn. * * @method chartToScreen * @param chartPt {any} A Object containing x/y properties of the tile. * @param [tileW] {Number} The width of the tile * @param [tileH] {Number} The height of the tile * @return {Object} With x/y properties of the location of the map onscreen. * @public */ public chartToScreen(chartPt: any, tileW: number = this.tileWidth, tileH: number = this.tileHeight): any { return { x: (chartPt.x - chartPt.y) * tileW * 0.5, y: (chartPt.x + chartPt.y) * tileH * 0.5 }; } /** * ScreenToChart maps a point in screen coordinates into the game tile chart * coordinates for the tile on which the screen point falls on. * * @method screenToChart * @param scrPt {any} An object containing x/y coordinates of the point on the screen you want to convert to tile coordinates. * @param [tileW] {Number} The width of a single tile. * @param [tileH] {Number} The height of a single tile. * @return {Object} With x/y properties of the location of tile on the screen. * @public */ public screenToChart(scrPt: any, tileW: number=this.tileWidth, tileH: number=this.tileHeight): any { var column = Math.floor( scrPt.x / (tileW * 0.5) ); var row = Math.floor( ( scrPt.y - column * ( tileH / 2 ) ) / tileH); return { x: column + row, y: row }; } /** * The render loop which is used when using the Canvas renderer. * @method render * @param camera {Camera} * @public */ public render(camera: Kiwi.Camera) { //When not to render the map. if (this.visible === false || this.alpha < 0.1 || this.exists === false) { return; } //Get the context. var ctx = this.game.stage.ctx; ctx.save(); //Make the map alphed out. if (this.alpha > 0 && this.alpha <= 1) { ctx.globalAlpha = this.alpha; } // Transform var t: Kiwi.Geom.Transform = this.transform; var m: Kiwi.Geom.Matrix = t.getConcatenatedMatrix(); ctx.transform(m.a, m.b, m.c, m.d, m.tx, m.ty); this._calculateBoundaries(camera, m); for (var y = this._startY; y < this._maxY; y++) { for (var x = this._startX; x < this._maxX; x++) { if ((this._temptype = this.getTileFromXY(x, y)) && this._temptype.cellIndex !== -1) { var cell = this.atlas.cells[this._temptype.cellIndex]; var offsetX = this._temptype.offset.x; var offsetY = this._temptype.offset.y; var w = this.tileWidth * (this.width * 2 - 1); var h = this.tileHeight * this.height; // We want <0,0>'s horizontal center point to be in the screen center, hence the -tileWidth/2. var shiftX = this.tileWidth / 2; var screenPos = this.chartToScreen( { x: x, y: y }, this.tileWidth, this.tileHeight); var drawX: number = screenPos.x + this._temptype.offset.x - shiftX; var drawY: number = screenPos.y - (cell.h - this.tileHeight) + this._temptype.offset.y; ctx.drawImage( this.atlas.image, cell.x, cell.y, cell.w, cell.h, drawX, drawY, cell.w, cell.h ); } } } ctx.restore(); return true; } public renderGL(gl: WebGLRenderingContext, camera: Kiwi.Camera, params: any = null) { //Setup var vertexItems = []; //Transform/Matrix var t: Kiwi.Geom.Transform = this.transform; var m: Kiwi.Geom.Matrix = t.getConcatenatedMatrix(); //Find which ones we need to render. this._calculateBoundaries(camera, m); //Loop through the tiles. for (var y = this._startY; y < this._maxY; y++) { for (var x = this._startX; x < this._maxX; x++) { //Get the tile type this._temptype = this.getTileFromXY(x, y); //Skip tiletypes that don't use a cellIndex. if (this._temptype.cellIndex == -1) continue; //Get the cell index var cell = this.atlas.cells[this._temptype.cellIndex]; // Isometric maps var offsetX = this._temptype.offset.x; var offsetY = this._temptype.offset.y; var w = this.tileWidth * (this.width * 2 - 1); var h = this.tileHeight * this.height; // We want <0,0>'s horizontal center point to be in the screen center, hence the -tileWidth/2. var shiftX = this.tileWidth / 2; var screenPos = this.chartToScreen( { x: x, y: y }, this.tileWidth, this.tileHeight); var tx = screenPos.x + this._temptype.offset.x - shiftX; var ty = screenPos.y + this._temptype.offset.y; //Set up the points this._corner1.setTo(tx - t.rotPointX, ty - t.rotPointY - (cell.h - this.tileHeight)); this._corner2.setTo(tx + cell.w - t.rotPointX, ty - t.rotPointY - (cell.h - this.tileHeight)); this._corner3.setTo(tx + cell.w - t.rotPointX, ty + cell.h - t.rotPointY - (cell.h - this.tileHeight)); this._corner4.setTo(tx - t.rotPointX, ty + cell.h - t.rotPointY - (cell.h - this.tileHeight)); //Add on the matrix to the points m.transformPoint(this._corner1); m.transformPoint(this._corner2); m.transformPoint(this._corner3); m.transformPoint(this._corner4); //Append to the xyuv array vertexItems.push( this._corner1.x + t.rotPointX, this._corner1.y + t.rotPointY, cell.x, cell.y, this.alpha, //Top Left Point this._corner2.x + t.rotPointX, this._corner2.y + t.rotPointY, cell.x + cell.w, cell.y, this.alpha, //Top Right Point this._corner3.x + t.rotPointX, this._corner3.y + t.rotPointY, cell.x + cell.w, cell.y + cell.h, this.alpha, //Bottom Right Point this._corner4.x + t.rotPointX, this._corner4.y + t.rotPointY, cell.x, cell.y + cell.h, this.alpha //Bottom Left Point ); } } //Concat points to the Renderer. (<Kiwi.Renderers.TextureAtlasRenderer>this.glRenderer).concatBatch(vertexItems); } } }
the_stack
import './strings.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {isTabElement, TabElement} from './tab.js'; import {isDragHandle, isTabGroupElement, TabGroupElement} from './tab_group.js'; import {Tab, TabNetworkState} from './tab_strip.mojom-webui.js'; import {TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js'; export const PLACEHOLDER_TAB_ID: number = -1; export const PLACEHOLDER_GROUP_ID: string = 'placeholder'; /** * The data type key for pinned state of a tab. Since drag events only expose * whether or not a data type exists (not the actual value), presence of this * data type means that the tab is pinned. */ const PINNED_DATA_TYPE: string = 'pinned'; /** * Gets the data type of tab IDs on DataTransfer objects in drag events. This * is a function so that loadTimeData can get overridden by tests. */ function getTabIdDataType(): string { return loadTimeData.getString('tabIdDataType'); } function getGroupIdDataType(): string { return loadTimeData.getString('tabGroupIdDataType'); } function getDefaultTabData(): Tab { return { active: false, alertStates: [], blocked: false, crashed: false, id: -1, index: -1, isDefaultFavicon: false, networkState: TabNetworkState.kNone, pinned: false, shouldHideThrobber: false, showIcon: true, title: '', url: {url: ''}, // Remove once Mojo can produce proper TypeScript or TypeScript definitions, // so that these properties are recognized as optional. faviconUrl: undefined, groupId: undefined, }; } export interface DragManagerDelegate { getIndexOfTab(tabElement: TabElement): number; placeTabElement( element: TabElement, index: number, pinned: boolean, groupId?: string): void; placeTabGroupElement(element: TabGroupElement, index: number): void; shouldPreventDrag(): boolean; } type DragManagerDelegateElement = DragManagerDelegate&HTMLElement; class DragSession { private delegate_: DragManagerDelegateElement; private element_: TabElement|TabGroupElement; private hasMoved_: boolean; private lastPoint_: {x: number, y: number} = {x: 0, y: 0}; srcIndex: number; srcGroup?: string; private tabsProxy_: TabsApiProxy = TabsApiProxyImpl.getInstance(); constructor( delegate: DragManagerDelegateElement, element: TabElement|TabGroupElement, srcIndex: number, srcGroup?: string) { this.delegate_ = delegate; this.element_ = element; /** * Flag indicating if during the drag session, the element has at least * moved once. */ this.hasMoved_ = false; this.srcIndex = srcIndex; this.srcGroup = srcGroup; } static createFromElement( delegate: DragManagerDelegateElement, element: TabElement|TabGroupElement): DragSession { if (isTabGroupElement(element)) { return new DragSession( delegate, element, delegate.getIndexOfTab(element.firstElementChild as TabElement)); } const srcIndex = delegate.getIndexOfTab(element as TabElement); const srcGroup = (element.parentElement && isTabGroupElement(element.parentElement)) ? element.parentElement.dataset.groupId : undefined; return new DragSession(delegate, element, srcIndex, srcGroup); } static createFromEvent( delegate: DragManagerDelegateElement, event: DragEvent): DragSession |null { if (event.dataTransfer!.types.includes(getTabIdDataType())) { const isPinned = event.dataTransfer!.types.includes(PINNED_DATA_TYPE); const placeholderTabElement = document.createElement('tabstrip-tab'); placeholderTabElement.tab = Object.assign( getDefaultTabData(), {id: PLACEHOLDER_TAB_ID, pinned: isPinned}); placeholderTabElement.setDragging(true); delegate.placeTabElement(placeholderTabElement, -1, isPinned); return DragSession.createFromElement(delegate, placeholderTabElement); } if (event.dataTransfer!.types.includes(getGroupIdDataType())) { const placeholderGroupElement = document.createElement('tabstrip-tab-group'); placeholderGroupElement.dataset.groupId = PLACEHOLDER_GROUP_ID; placeholderGroupElement.setDragging(true); delegate.placeTabGroupElement(placeholderGroupElement, -1); return DragSession.createFromElement(delegate, placeholderGroupElement); } return null; } get dstGroup(): string|undefined { if (isTabElement(this.element_) && this.element_.parentElement && isTabGroupElement(this.element_.parentElement)) { return this.element_.parentElement.dataset.groupId; } return undefined; } get dstIndex(): number { if (isTabElement(this.element_)) { return this.delegate_.getIndexOfTab(this.element_ as TabElement); } if (this.element_.children.length === 0) { // If this group element has no children, it was a placeholder element // being dragged. Find out the destination index by finding the index of // the tab closest to it and incrementing it by 1. const previousElement = this.element_.previousElementSibling; if (!previousElement) { return 0; } if (isTabElement(previousElement)) { return this.delegate_.getIndexOfTab(previousElement as TabElement) + 1; } assert(isTabGroupElement(previousElement)); return this.delegate_.getIndexOfTab( previousElement.lastElementChild as TabElement) + 1; } // If a tab group is moving backwards (to the front of the tab strip), the // new index is the index of the first tab in that group. If a tab group is // moving forwards (to the end of the tab strip), the new index is the index // of the last tab in that group. let dstIndex = this.delegate_.getIndexOfTab( this.element_.firstElementChild as TabElement); if (this.srcIndex <= dstIndex) { dstIndex += this.element_.childElementCount - 1; } return dstIndex; } cancel(event: DragEvent) { if (this.isDraggingPlaceholder()) { this.element_.remove(); return; } if (isTabGroupElement(this.element_)) { this.delegate_.placeTabGroupElement( this.element_ as TabGroupElement, this.srcIndex); } else if (isTabElement(this.element_)) { const tabElement = this.element_ as TabElement; this.delegate_.placeTabElement( tabElement, this.srcIndex, tabElement.tab.pinned, this.srcGroup); } if (this.element_.isDraggedOut() && event.dataTransfer!.dropEffect === 'move') { // The element was dragged out of the current tab strip and was dropped // into a new window. In this case, do not mark the element as no longer // being dragged out. The element needs to be kept hidden, and will be // automatically removed from the DOM with the next tab-removed event. return; } this.element_.setDragging(false); this.element_.setDraggedOut(false); } isDraggingPlaceholder(): boolean { return this.isDraggingPlaceholderTab_() || this.isDraggingPlaceholderGroup_(); } private isDraggingPlaceholderTab_(): boolean { return isTabElement(this.element_) && (this.element_ as TabElement).tab.id === PLACEHOLDER_TAB_ID; } private isDraggingPlaceholderGroup_(): boolean { return isTabGroupElement(this.element_) && this.element_.dataset.groupId === PLACEHOLDER_GROUP_ID; } finish(event: DragEvent) { const wasDraggingPlaceholder = this.isDraggingPlaceholderTab_(); if (wasDraggingPlaceholder) { const id = Number(event.dataTransfer!.getData(getTabIdDataType())); (this.element_ as TabElement).tab = Object.assign({}, (this.element_ as TabElement).tab, {id}); } else if (this.isDraggingPlaceholderGroup_()) { this.element_.dataset.groupId = event.dataTransfer!.getData(getGroupIdDataType()); } const dstIndex = this.dstIndex; if (isTabElement(this.element_)) { this.tabsProxy_.moveTab((this.element_ as TabElement).tab.id, dstIndex); } else if (isTabGroupElement(this.element_)) { this.tabsProxy_.moveGroup(this.element_.dataset.groupId!, dstIndex); } const dstGroup = this.dstGroup; if (dstGroup && dstGroup !== this.srcGroup) { this.tabsProxy_.groupTab((this.element_ as TabElement).tab.id, dstGroup); } else if (!dstGroup && this.srcGroup) { this.tabsProxy_.ungroupTab((this.element_ as TabElement).tab.id); } this.element_.setDragging(false); this.element_.setDraggedOut(false); } shouldOffsetIndexForGroup_(dragOverElement: TabElement| TabGroupElement): boolean { // Since TabGroupElements do not have any TabElements, they need to offset // the index for any elements that come after it as if there is at least // one element inside of it. return this.isDraggingPlaceholder() && !!(dragOverElement.compareDocumentPosition(this.element_) & Node.DOCUMENT_POSITION_PRECEDING); } start(event: DragEvent) { this.lastPoint_ = {x: event.clientX, y: event.clientY}; event.dataTransfer!.effectAllowed = 'move'; const draggedItemRect = (event.composedPath()[0] as HTMLElement).getBoundingClientRect(); this.element_.setDragging(true); const dragImage = this.element_.getDragImage(); const dragImageRect = dragImage.getBoundingClientRect(); let scaleFactor = 1; let verticalOffset = 0; // <if expr="chromeos"> // Touch on ChromeOS automatically scales drag images by 1.2 and adds a // vertical offset of 25px. See //ash/drag_drop/drag_drop_controller.cc. scaleFactor = 1.2; verticalOffset = 25; // </if> const eventXPercentage = (event.clientX - draggedItemRect.left) / draggedItemRect.width; const eventYPercentage = (event.clientY - draggedItemRect.top) / draggedItemRect.height; // First, align the top-left corner of the drag image's center element // to the event's coordinates. const dragImageCenterRect = this.element_.getDragImageCenter().getBoundingClientRect(); let xOffset = (dragImageCenterRect.left - dragImageRect.left) * scaleFactor; let yOffset = (dragImageCenterRect.top - dragImageRect.top) * scaleFactor; // Then, offset the drag image again by using the event's coordinates // within the dragged item itself so that the drag image appears positioned // as closely as its state before dragging. xOffset += dragImageCenterRect.width * eventXPercentage; yOffset += dragImageCenterRect.height * eventYPercentage; yOffset -= verticalOffset; event.dataTransfer!.setDragImage(dragImage, xOffset, yOffset); if (isTabElement(this.element_)) { const tabElement = this.element_ as TabElement; event.dataTransfer!.setData( getTabIdDataType(), tabElement.tab.id.toString()); if (tabElement.tab.pinned) { event.dataTransfer!.setData( PINNED_DATA_TYPE, tabElement.tab.pinned.toString()); } } else if (isTabGroupElement(this.element_)) { event.dataTransfer!.setData( getGroupIdDataType(), this.element_.dataset.groupId!); } } update(event: DragEvent) { this.lastPoint_ = {x: event.clientX, y: event.clientY}; if (event.type === 'dragleave') { this.element_.setDraggedOut(true); this.hasMoved_ = true; return; } event.dataTransfer!.dropEffect = 'move'; this.element_.setDraggedOut(false); if (isTabGroupElement(this.element_)) { this.updateForTabGroupElement_(event); } else if (isTabElement(this.element_)) { this.updateForTabElement_(event); } } private updateForTabGroupElement_(event: DragEvent) { const tabGroupElement = this.element_ as TabGroupElement; const composedPath = event.composedPath() as Element[]; if (composedPath.includes(assert(this.element_))) { // Dragging over itself or a child of itself. return; } const dragOverTabElement = composedPath.find(isTabElement) as TabElement | undefined; if (dragOverTabElement && !dragOverTabElement.tab.pinned && dragOverTabElement.isValidDragOverTarget) { let dragOverIndex = this.delegate_.getIndexOfTab(dragOverTabElement); dragOverIndex += this.shouldOffsetIndexForGroup_(dragOverTabElement) ? 1 : 0; this.delegate_.placeTabGroupElement(tabGroupElement, dragOverIndex); this.hasMoved_ = true; return; } const dragOverGroupElement = composedPath.find(isTabGroupElement) as TabGroupElement | undefined; if (dragOverGroupElement && dragOverGroupElement.isValidDragOverTarget) { let dragOverIndex = this.delegate_.getIndexOfTab( dragOverGroupElement.firstElementChild as TabElement); dragOverIndex += this.shouldOffsetIndexForGroup_(dragOverGroupElement) ? 1 : 0; this.delegate_.placeTabGroupElement(tabGroupElement, dragOverIndex); this.hasMoved_ = true; } } private updateForTabElement_(event: DragEvent) { const tabElement = this.element_ as TabElement; const composedPath = event.composedPath() as Element[]; const dragOverTabElement = composedPath.find(isTabElement) as TabElement | undefined; if (dragOverTabElement && (dragOverTabElement.tab.pinned !== tabElement.tab.pinned || !dragOverTabElement.isValidDragOverTarget)) { // Can only drag between the same pinned states and valid TabElements. return; } const previousGroupId = (tabElement.parentElement && isTabGroupElement(tabElement.parentElement)) ? tabElement.parentElement.dataset.groupId : undefined; const dragOverTabGroup = composedPath.find(isTabGroupElement) as TabGroupElement | undefined; if (dragOverTabGroup && dragOverTabGroup.dataset.groupId !== previousGroupId && dragOverTabGroup.isValidDragOverTarget) { this.delegate_.placeTabElement( tabElement, this.dstIndex, false, dragOverTabGroup.dataset.groupId); this.hasMoved_ = true; return; } if (!dragOverTabGroup && previousGroupId) { this.delegate_.placeTabElement( tabElement, this.dstIndex, false, undefined); this.hasMoved_ = true; return; } if (!dragOverTabElement) { return; } const dragOverIndex = this.delegate_.getIndexOfTab(dragOverTabElement); this.delegate_.placeTabElement( tabElement, dragOverIndex, tabElement.tab.pinned, previousGroupId); this.hasMoved_ = true; } } export class DragManager { private delegate_: DragManagerDelegateElement; private dragSession_: DragSession|null = null; private tabsProxy_: TabsApiProxy = TabsApiProxyImpl.getInstance(); constructor(delegate: DragManagerDelegateElement) { this.delegate_ = delegate; } private onDragLeave_(event: DragEvent) { if (this.dragSession_ && this.dragSession_.isDraggingPlaceholder()) { this.dragSession_.cancel(event); this.dragSession_ = null; return; } this.dragSession_!.update(event); } private onDragOver_(event: DragEvent) { event.preventDefault(); if (!this.dragSession_) { return; } this.dragSession_.update(event); } private onDragStart_(event: DragEvent) { const composedPath = event.composedPath() as Element[]; const draggedItem = composedPath.find(item => { return isTabElement(item) || isTabGroupElement(item); }); if (!draggedItem) { return; } // If we are dragging a tab or tab group element ensure its touch pressed // state is reset to avoid any associated css effects making it onto the // drag image. if (isTabElement(draggedItem) || isTabGroupElement(draggedItem)) { (draggedItem as TabElement | TabGroupElement).setTouchPressed(false); } // Make sure drag handle is under touch point when dragging a tab group. if (isTabGroupElement(draggedItem) && !composedPath.find(isDragHandle)) { return; } if (this.delegate_.shouldPreventDrag()) { event.preventDefault(); return; } this.dragSession_ = DragSession.createFromElement( this.delegate_, draggedItem as TabElement | TabGroupElement); this.dragSession_.start(event); } private onDragEnd_(event: DragEvent) { if (!this.dragSession_) { return; } this.dragSession_.cancel(event); this.dragSession_ = null; } private onDragEnter_(event: DragEvent) { if (this.dragSession_) { // TODO(crbug.com/843556): Do not update the drag session on dragenter. // An incorrect event target on dragenter causes tabs to move around // erroneously. return; } this.dragSession_ = DragSession.createFromEvent(this.delegate_, event); } private onDrop_(event: DragEvent) { if (!this.dragSession_) { return; } this.dragSession_.finish(event); this.dragSession_ = null; } startObserving() { this.delegate_.addEventListener('dragstart', e => this.onDragStart_(e)); this.delegate_.addEventListener('dragend', e => this.onDragEnd_(e)); this.delegate_.addEventListener('dragenter', e => this.onDragEnter_(e)); this.delegate_.addEventListener('dragleave', e => this.onDragLeave_(e)); this.delegate_.addEventListener('dragover', e => this.onDragOver_(e)); this.delegate_.addEventListener('drop', e => this.onDrop_(e)); } }
the_stack
import { browser, protractor, $, $$, Browser} from 'protractor'; import {AssetList} from '../page-objects/asset-list.po'; import { Menu } from '../page-objects/menu.po'; import { Login } from '../page-objects/login.po'; import { OverviewCompliance } from '../page-objects/overview.po'; import { CONFIGURATIONS } from '../../src/config/configurations'; import { DigitalDevDashboard } from '../page-objects/digital-dev-dashboard.po'; import { AssetGroups } from '../page-objects/asset-groups.po'; const config = CONFIGURATIONS.optional.general.e2e; describe('DigitalDevDashboard', () => { let menu_po: Menu; let assetList_po: AssetList; const EC = protractor.ExpectedConditions; let login_po: Login; let OverviewCompliance_po: OverviewCompliance; let digitalDevDashboard_po: DigitalDevDashboard; let assetGroups_po: AssetGroups; const maxTimeOut = 120000; let pr_count; beforeAll(() => { menu_po = new Menu(); assetList_po = new AssetList(); login_po = new Login(); OverviewCompliance_po = new OverviewCompliance(); digitalDevDashboard_po = new DigitalDevDashboard(); assetGroups_po = new AssetGroups(); }); it('navigate to Digital dev dashboard page', () => { browser.wait(EC.visibilityOf(OverviewCompliance_po.changeAssetGroupPath()), maxTimeOut); browser.wait(EC.elementToBeClickable(OverviewCompliance_po.changeAssetGroupPath()), maxTimeOut); OverviewCompliance_po.changeAssetGroupPath().click(); browser.wait(EC.visibilityOf(OverviewCompliance_po.getAssetGroupSearch()), maxTimeOut); OverviewCompliance_po.getAssetGroupSearch().sendKeys('digital development'); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.wait(EC.visibilityOf(assetGroups_po.clickFirstAssetGroup()), maxTimeOut); browser.wait(EC.elementToBeClickable(assetGroups_po.clickFirstAssetGroup()), maxTimeOut); assetGroups_po.clickFirstAssetGroup().click().then( function() { browser.wait(EC.elementToBeClickable(OverviewCompliance_po.selectFirstAssetgroupInList()), maxTimeOut); OverviewCompliance_po.selectFirstAssetgroupInList().click(); browser.wait(EC.visibilityOf(OverviewCompliance_po.getPageTitle()), maxTimeOut); const page_title = OverviewCompliance_po.getPageTitle().getText(); expect(page_title).toEqual('Overview'); browser.wait(EC.elementToBeClickable(menu_po.MenuClick()), maxTimeOut); menu_po.MenuClick().click(); browser.wait(EC.elementToBeClickable(menu_po.digitalDashboardClick()), maxTimeOut); menu_po.digitalDashboardClick().click(); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getDigitalDashboardHeaderText()), maxTimeOut); const header_path = digitalDevDashboard_po.getDigitalDashboardHeaderText().getText(); expect(header_path).toEqual('Digital Dev'); }); }); it('Check if repository distribution donut graph legend percentage sums to 100', () => { browser.wait(EC.visibilityOf(digitalDevDashboard_po.getRepositoryDistributionDonutGraph()), maxTimeOut); const total_percent = 100; let each_pass = 0; digitalDevDashboard_po.getRepositoryDistributionDonutlegend().then(function(items) { for (let i = 0; i < items.length; i++) { browser.wait(EC.visibilityOf($$('.digital-dev-strategy-distribution-wrapper .legend-each .legend-text-right').get(i)), maxTimeOut); $$('.digital-dev-strategy-distribution-wrapper .legend-each .legend-text-right').get(i).getText().then(function (text) { text = text.split('(')[1].replace('%)', ''); each_pass = each_pass + parseInt(text, 10); if ( i === items.length - 1) { expect(each_pass).toEqual(total_percent); } }); } }); }); it('verify total PR metrics count of a quarter with total PR count of all weeks using bar graph', () => { let total_created = 0; let total_merged = 0; let total_declined = 0; let total_open = 0; let weeks = 0; let weeks_total_created = 0; let weeks_total_merged = 0; let weeks_total_declined = 0; let weeks_total_open = 0; browser.wait(EC.visibilityOf(digitalDevDashboard_po.getQuarterSelector()), maxTimeOut); browser.actions().mouseMove(digitalDevDashboard_po.getQuarterSelector()); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getQuarterDisplay()), maxTimeOut); // browser.driver.executeScript('arguments[0].scrollIntoView();', digitalDevDashboard_po.getQuarterDisplay()); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getQuarterDisplay()), maxTimeOut); digitalDevDashboard_po.getQuarterDisplay().click(); // browser.actions().mouseMove(digitalDevDashboard_po.getQuarterDisplay()).click().perform(); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getQuarterViewButton()), maxTimeOut); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getQuarterViewButton()), maxTimeOut); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFirstQuaterTotalCreatedCount()), maxTimeOut).then(function () { digitalDevDashboard_po.getFirstQuaterTotalCreatedCount().getText().then( function (count) { total_created = parseInt(count, 10); }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFirstQuaterTotalMergedCount()), maxTimeOut); digitalDevDashboard_po.getFirstQuaterTotalMergedCount().getText().then( function (count) { total_merged = parseInt(count, 10); }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFirstQuaterTotalDeclinedCount()), maxTimeOut); digitalDevDashboard_po.getFirstQuaterTotalDeclinedCount().getText().then( function (count) { total_declined = parseInt(count, 10); }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFirstQuaterTotalOpenCount()), maxTimeOut); digitalDevDashboard_po.getFirstQuaterTotalOpenCount().getText().then( function (count) { total_open = parseInt(count, 10); }); digitalDevDashboard_po.getQuarterViewButton().click(); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getTotalWeeksInSelectedQuarter()), maxTimeOut); digitalDevDashboard_po.getTotalWeeksInSelectedQuarter().getText().then( function (text) { text = text.split(' ')[1]; weeks = parseInt(text, 10); console.log('weeks:', weeks); for (let i = weeks - 1; i >= 0; i--) { browser.wait(EC.visibilityOf($$('.pull-request-matrix-line-chart .graph-container .z-3').$$('.each-column').get(i)), maxTimeOut); $$('.pull-request-matrix-line-chart .graph-container .z-3').$$('.each-column').get(i).click().then(function () { browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink()), maxTimeOut); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink()), maxTimeOut); digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink().getText().then( function (count) { weeks_total_created = weeks_total_created + parseInt(count, 10); if (i === 0 ) { expect(total_created).toEqual(weeks_total_created); } }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRMetricsMergedBarChartTextLink()), maxTimeOut); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRMetricsMergedBarChartTextLink()), maxTimeOut); digitalDevDashboard_po.getPRMetricsMergedBarChartTextLink().getText().then( function (count) { weeks_total_merged = weeks_total_merged + parseInt(count, 10); if (i === 0 ) { expect(total_merged).toEqual(weeks_total_merged); } }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRMetricsDeclinedBarChartTextLink()), maxTimeOut); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRMetricsDeclinedBarChartTextLink()), maxTimeOut); digitalDevDashboard_po.getPRMetricsDeclinedBarChartTextLink().getText().then( function (count) { weeks_total_declined = weeks_total_declined + parseInt(count, 10); if (i === 0 ) { expect(total_declined).toEqual(weeks_total_declined); } }); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRMetricsOpenBarChartTextLink()), maxTimeOut); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRMetricsOpenBarChartTextLink()), maxTimeOut); digitalDevDashboard_po.getPRMetricsOpenBarChartTextLink().getText().then( function (count) { weeks_total_open = weeks_total_open + parseInt(count, 10); if (i === 0) { expect(total_open).toEqual(weeks_total_open); } }); }); } }); }); }); it('verify navigation of PR age bar graph text link to asset list with verification of pagination count', () => { browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRAgeBarChartTextLink()), maxTimeOut); browser.actions().mouseMove(digitalDevDashboard_po.getPRAgeBarChartTextLink()).perform(); browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRAgeBarChartTextLink()), maxTimeOut); pr_count = digitalDevDashboard_po.getPRAgeBarChartTextLink().getText(); digitalDevDashboard_po.getPRAgeBarChartTextLink().click(); browser.wait(EC.visibilityOf(assetList_po.getAssetHeaderText()), maxTimeOut); const asset_list_header_path = assetList_po.getAssetHeaderText().getText(); expect(asset_list_header_path).toEqual('Asset List'); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), maxTimeOut); assetList_po.getAssetTotalRows().getText().then( function(text){ expect(text).toEqual(pr_count); browser.wait(EC.elementToBeClickable(assetList_po.goBack()), maxTimeOut); assetList_po.goBack().click(); }); }); it('Check if stale branch donut graph legend percentage sums to 100', () => { browser.wait(EC.visibilityOf(digitalDevDashboard_po.getStaleBranchDonutGraph()), maxTimeOut); browser.actions().mouseMove(digitalDevDashboard_po.getPRAgeBarChartTextLink()).perform(); const total_percent = 100; let each_pass = 0; digitalDevDashboard_po.getStaleBranchDonutlegend().then(function(items) { for (let i = 0; i < items.length; i++) { browser.wait(EC.visibilityOf($$('.donut-container-staleBranchDonut .legend-each .legend-text-right').get(i)), maxTimeOut); $$('.donut-container-staleBranchDonut .legend-each .legend-text-right').get(i).getText().then(function (text) { text = text.split('(')[1].replace('%)', ''); each_pass = each_pass + parseInt(text, 10); if ( i === items.length - 1) { expect(each_pass).toEqual(total_percent); } }); } }); }); it('Check if PR age bar graph text sums to Open PR', () => { let total_percent = 0; browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRAgeBarChartTextLink()), maxTimeOut); browser.actions().mouseMove(digitalDevDashboard_po.getPRAgeBarChartTextLink()).perform(); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getTotalOpenPR()), maxTimeOut); digitalDevDashboard_po.getTotalOpenPR().getText().then( function(count) { total_percent = parseInt(count, 10); }); let each_pass = 0; digitalDevDashboard_po.getPRAgeBarGraph().then(function(items) { for (let i = 0; i < items.length; i++) { browser.wait(EC.visibilityOf($$('app-dev-standard-pull-request-age .show-links text.bar.bar-links').get(i)), maxTimeOut); $$('app-dev-standard-pull-request-age .show-links text.bar.bar-links').get(i).getText().then(function (text) { each_pass = each_pass + parseInt(text, 10); if ( i === items.length - 1) { expect(each_pass).toEqual(total_percent); } }); } }); }); it('Check if stale branch age bar graph text sums to stale branches legend in donut graph', () => { let total_percent = 0; browser.wait(EC.visibilityOf(digitalDevDashboard_po.getStaleBranchesDonutlegendCount()), maxTimeOut); browser.actions().mouseMove(digitalDevDashboard_po.getStaleBranchesDonutlegendCount()).perform(); digitalDevDashboard_po.getStaleBranchesDonutlegendCount().getText().then( function(count) { count = count.split('(')[0]; total_percent = parseInt(count, 10); }); let each_pass = 0; digitalDevDashboard_po.getStaleBranchBarGraph().then(function(items) { for (let i = 0; i < items.length; i++) { browser.wait(EC.visibilityOf($$('app-dev-standard-stale-branch-age text.bar.bar-links').get(i)), maxTimeOut); $$('app-dev-standard-stale-branch-age text.bar.bar-links').get(i).getText().then(function (text) { each_pass = each_pass + parseInt(text, 10); if ( i === items.length - 1) { expect(each_pass).toEqual(total_percent); } }); } }); }); it('verify filter for policy violation table', () => { // click on filter dropdown to get list browser.wait(EC.presenceOf(digitalDevDashboard_po.getFilterArrow()), maxTimeOut); digitalDevDashboard_po.getFilterArrow().click(); browser.sleep(2000); let filterKey, filterValue; // select first filter type browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFilterType()), maxTimeOut); digitalDevDashboard_po.getFilterType().getText().then( function(text) { filterKey = text; }); digitalDevDashboard_po.getFilterType().click(); // verify whether filter tags present browser.sleep(3000); // select first filter tag digitalDevDashboard_po.getFilterTagInput().click(); browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFilterTags()), maxTimeOut); digitalDevDashboard_po.getFilterTags().getText().then( function(text) { filterValue = text; }); digitalDevDashboard_po.getFilterTags().click(); // equate selected filter key and value with filter tags displayed browser.wait(EC.visibilityOf(digitalDevDashboard_po.getFilterSelected()), maxTimeOut); digitalDevDashboard_po.getFilterSelected().getText().then( function(text) { const textArray = text.split(':'); expect(textArray[0]).toContain(filterKey); expect(textArray[1]).toContain(filterValue); }); digitalDevDashboard_po.getClearAllFilter().click(); }); it('verify navigation of PR metrics bar graph text link to asset list with verification of pagination count', () => { browser.wait(EC.visibilityOf(digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink()), maxTimeOut).then (function() { browser.wait(EC.elementToBeClickable(digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink()), maxTimeOut); pr_count = digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink().getText(); digitalDevDashboard_po.getPRMetricsCreatedBarChartTextLink().click(); browser.wait(EC.visibilityOf(assetList_po.getAssetHeaderText()), maxTimeOut); const asset_list_header_path = assetList_po.getAssetHeaderText().getText(); expect(asset_list_header_path).toEqual('Asset List'); browser.wait(EC.visibilityOf(assetList_po.getAssetTotalRows()), maxTimeOut); assetList_po.getAssetTotalRows().getText().then( function(text){ expect(text).toEqual(pr_count); browser.wait(EC.elementToBeClickable(assetList_po.goBack()), maxTimeOut); assetList_po.goBack().click(); }); }); }); it('change asset group back to aws all', () => { browser.wait(EC.visibilityOf(OverviewCompliance_po.changeAssetGroupPath()), maxTimeOut); browser.wait(EC.elementToBeClickable(OverviewCompliance_po.changeAssetGroupPath()), maxTimeOut); OverviewCompliance_po.changeAssetGroupPath().click(); browser.wait(EC.visibilityOf(OverviewCompliance_po.getAssetGroupSearch()), maxTimeOut); OverviewCompliance_po.getAssetGroupSearch().sendKeys('aws all'); browser.actions().sendKeys(protractor.Key.ENTER).perform(); browser.wait(EC.visibilityOf(assetGroups_po.clickFirstAssetGroup()), maxTimeOut); browser.wait(EC.elementToBeClickable(assetGroups_po.clickFirstAssetGroup()), maxTimeOut); assetGroups_po.clickFirstAssetGroup().click().then( function() { browser.wait(EC.elementToBeClickable(OverviewCompliance_po.selectFirstAssetgroupInList()), maxTimeOut); OverviewCompliance_po.selectFirstAssetgroupInList().click(); browser.wait(EC.visibilityOf(OverviewCompliance_po.getPageTitle()), maxTimeOut); const page_title = OverviewCompliance_po.getPageTitle().getText(); expect(page_title).toEqual('Overview'); }); }); });
the_stack
import { DOMParser, Node } from 'prosemirror-model'; import { EditorState, Plugin, Selection, Transaction } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import 'prosemirror-view/style/prosemirror.css'; import ResizeObserver from 'resize-observer-polyfill'; import Vue from 'vue'; import { Component, Emit, Prop, ProvideReactive, Watch } from 'vue-property-decorator'; import { propOptional, propRequired } from '../../../utils/vue'; import { AppObserveDimensions } from '../../observe-dimensions/observe-dimensions.directive'; import AppScrollScroller from '../../scroll/scroller/scroller.vue'; import { ContentContext, ContextCapabilities } from '../content-context'; import { ContentDocument } from '../content-document'; import { ContentFormatAdapter, ProsemirrorEditorFormat } from '../content-format-adapter'; import { ContentHydrator } from '../content-hydrator'; import { ContentOwner } from '../content-owner'; import { ContentEditorController, ContentEditorControllerKey, editorEnsureEndNode, editorFocus, editorSyncScope, editorSyncWindow, } from './content-editor-controller'; import { ContentRules } from './content-rules'; import { ContentTempResource } from './content-temp-resource.service'; import AppContentEditorBlockControls from './controls/block-controls.vue'; import AppContentEditorControlsEmojiTS from './controls/emoji/emoji'; import AppContentEditorControlsEmoji from './controls/emoji/emoji.vue'; import AppContentEditorControlsGif from './controls/gif/gif.vue'; import AppContentEditorInsetControls from './controls/inset-controls.vue'; import AppContentEditorControlsMentionAutocomplete from './controls/mention/autocomplete.vue'; import AppContentEditorTextControls from './controls/text-controls.vue'; import buildEvents from './events/build-events'; import { FocusWatcher } from './focus-watcher'; import { buildNodeViews } from './node-views/node-view-builder'; import { createPlugins } from './plugins/plugins'; import { ContentEditorSchema, generateSchema } from './schemas/content-editor-schema'; @Component({ components: { AppContentEditorBlockControls, AppContentEditorTextControls, AppContentEditorControlsEmoji, AppContentEditorControlsGif, AppContentEditorInsetControls, AppContentEditorControlsMentionAutocomplete, AppScrollScroller, }, directives: { AppObserveDimensions, }, }) export default class AppContentEditor extends Vue implements ContentOwner { @Prop(propRequired(String)) contentContext!: ContentContext; @Prop(propRequired(String)) value!: string; @Prop(propOptional(String, '')) placeholder!: string; @Prop(propOptional(Boolean, false)) autofocus!: boolean; @Prop(propOptional(Boolean, false)) disabled!: boolean; @Prop(propOptional(Number, null)) modelId!: number; @Prop(propOptional(Number, 0)) minHeight!: number; // Seems to be used somewhere in vee-validate and AppForms. Forms break without this. @Prop(propOptional(String, '')) name!: string; /** * Used to send more information with the create temp resource request. * Passed in object is directly handed to the Api. By default `undefined`, * resulting in a GET request. */ @Prop(propOptional(Object)) tempResourceContextData?: Record<string, any>; /** * In single line mode the editor emits an event on enter and does not * insert a new paragraph. Mod + Enter inserts a new paragraph instead. */ @Prop(propOptional(Boolean, false)) singleLineMode!: boolean; /** * Sets the max height of the editor before it starts scrolling. Passing 0 * or a negative value will unrestrict the height. */ @Prop(propOptional(Number, 200)) maxHeight!: number; @Prop(propOptional(ContentRules)) displayRules?: ContentRules; @Prop(propOptional(Boolean, false)) focusEnd!: boolean; @ProvideReactive(ContentEditorControllerKey) controller: ContentEditorController = new ContentEditorController(this.syncWindow.bind(this)); $_veeValidate = { value: () => this.value, name: () => 'app-content-editor', }; schema: ContentEditorSchema | null = null; plugins: Plugin<ContentEditorSchema>[] | null = null; focusWatcher: FocusWatcher | null = null; resizeObserver: ResizeObserver | null = null; stateCounter = 0; isFocused = false; emojiPanelVisible = false; controlsCollapsed = true; /** * Gets updated through the update-is-empty-plugin. */ isEmpty = true; /** * Indicates whether we want to currently show the mention suggestion panel. * Values > 0 indicate true. * * This and [mentionUserCount] are both checked elsewhere to prevent certain * mouse/keyboard events from triggering. */ canShowMentionSuggestions = 0; mentionUserCount = 0; /** * If no model id if gets passed in, we store a temp model's id here. */ _tempModelId: number | null = null; // Keep a copy of the json version of the doc, to only set the content if the external source changed. _sourceControlVal: string | null = null; readonly GJ_IS_APP = GJ_IS_APP; $refs!: { editor: HTMLElement; doc: HTMLElement; emojiPanel: AppContentEditorControlsEmojiTS; }; @Emit('submit') emitSubmit() { ++this.stateCounter; } @Emit('insert-block-node') emitInsertBlockNode(_nodeType: string) {} get canShowMention() { return this.canShowMentionSuggestions > 0; } get view() { return this.controller.view ?? null; } get contextCapabilities() { return this.controller.contextCapabilities; } get shouldShowControls() { return !this.disabled && this.isFocused && this.contextCapabilities.hasAnyBlock; } get shouldShowTextControls() { return ( !this.disabled && this.isFocused && this.contextCapabilities.hasAnyText && !this.emojiPanelVisible ); } get shouldShowEmojiPanel() { return !GJ_IS_APP && !this.disabled && this.contextCapabilities.emoji && this.isFocused; } get couldShowEmojiPanel() { return !GJ_IS_APP && this.contextCapabilities.emoji; } get couldShowGifPanel() { return !GJ_IS_APP && this.contextCapabilities.gif; } get editorGutterSize() { return [this.couldShowEmojiPanel, this.couldShowGifPanel].filter(i => !!i).length; } get shouldShowPlaceholder() { return ( this.placeholder.length > 0 && this.isEmpty && (!this.shouldShowControls || this.controlsCollapsed) ); } get editorStyleClass() { return this.contentContext + '-content'; } get containerMinHeight() { if (!this.minHeight) { return 'auto'; } return this.minHeight + 'px'; } get shouldShowGifButton() { return !this.disabled && this.contextCapabilities.gif && this.isFocused; } getContext() { return this.contentContext; } getHydrator() { return this.controller.hydrator; } getContextCapabilities() { return this.contextCapabilities; } async getModelId() { if (this.modelId === null) { if (!this._tempModelId) { this._tempModelId = await ContentTempResource.getTempModelId( this.contentContext, this.tempResourceContextData ); } return this._tempModelId; } else { return this.modelId; } } @Watch('stateCounter') onStateCounterChange() { editorSyncScope(this.controller, this.disabled, this.isFocused); } @Watch('value') onSourceUpdated() { if (this._sourceControlVal === this.value) { return; } this._sourceControlVal = this.value; // When we receive an empty string as the document json, the caller // probably wants to clear the document. if (this.value === '') { this.reset(); } else { const wasFocused = this.isFocused; const doc = ContentDocument.fromJson(this.value); // Don't await this since we want to make sure we focus within the // same tick if they were focused previously. this.setContent(doc); if (wasFocused) { editorFocus(this.controller); } } } onUpdate(state: EditorState<ContentEditorSchema>) { const source = ContentFormatAdapter.adaptOut( state.doc.toJSON() as ProsemirrorEditorFormat, this.contentContext ).toJson(); this._sourceControlVal = source; this.$emit('input', source); } private reset() { this._tempModelId = null; const doc = new ContentDocument(this.contentContext, []); this.setContent(doc); this.isEmpty = true; } async mounted() { this.controller.contextCapabilities = ContextCapabilities.getForContext( this.contentContext ); this.schema = generateSchema(this.contextCapabilities); this.plugins = createPlugins(this, this.schema); // We have to wait a frame here before we can start using the $refs.doc variable. // Due to the scroller around it also initializing on mounted, we have to wait for it to finish. // The scroller v-ifs the slot element away until it's fully mounted. // The next frame after that we have our doc ref available. await this.$nextTick(); if (this.value) { const doc = ContentDocument.fromJson(this.value); await this.setContent(doc); } else { const state = EditorState.create({ doc: DOMParser.fromSchema(this.schema).parse(this.$refs.doc), plugins: this.plugins, }); this.createView(state); } ++this.stateCounter; this.focusWatcher = new FocusWatcher(this.$refs.editor, this.onFocusIn, this.onFocusOut); this.focusWatcher.start(); if (this.view instanceof EditorView && this.autofocus) { this.focus(); } } beforeDestroy() { if (this.focusWatcher instanceof FocusWatcher) { this.focusWatcher.destroy(); } if (this.resizeObserver instanceof ResizeObserver) { this.resizeObserver.disconnect(); } } /** * Creates a new prosemirror view instance based on an editor state. */ private createView(state: EditorState<ContentEditorSchema>) { this.controller.view?.destroy(); const nodeViews = buildNodeViews(this); const eventHandlers = buildEvents(this); const view = (this.controller.view = new EditorView<ContentEditorSchema>(this.$refs.doc, { state, nodeViews, handleDOMEvents: eventHandlers, editable: () => !this.disabled, attributes: { 'data-prevent-shortkey': '', }, })); this.updateIsEmpty(state); // Make sure we have a paragraph when loading in a new state if (!this.disabled || view.state.doc.childCount === 0) { const tr = editorEnsureEndNode(view.state.tr, view.state.schema.nodes.paragraph); if (tr instanceof Transaction) { view.dispatch(tr); } } return view!; } getContent() { if (this.view instanceof EditorView) { const data = ContentFormatAdapter.adaptOut( this.view.state.doc.toJSON() as ProsemirrorEditorFormat, this.contentContext ); return data; } return null; } async setContent(doc: ContentDocument) { if (doc.context !== this.contentContext) { throw new Error( `The passed in content context is invalid. ${doc.context} != ${this.contentContext}` ); } if (this.schema instanceof ContentEditorSchema) { // Do this here so we don't fire an update directly after populating. doc.ensureEndParagraph(); this.controller.hydrator = new ContentHydrator(doc.hydration); const jsonObj = ContentFormatAdapter.adaptIn(doc); const state = EditorState.create({ doc: Node.fromJSON(this.schema, jsonObj), plugins: this.plugins, }); const view = this.createView(state); if (this.focusEnd) { // Wait here so images and other content can render in and scale properly. // Otherwise the scroll at the end of the transaction below would not cover the entire doc. await this.$nextTick(); // Set selection at the end of the document. const tr = view.state.tr; const selection = Selection.atEnd(view.state.doc); tr.setSelection(selection); tr.scrollIntoView(); view.dispatch(tr); } ++this.stateCounter; } } onDimensionsChange() { ++this.stateCounter; } // Gets called by the ContentEditorController while updating scope. We // increment the stateCounter on dimension change, which updates scope, // which calls this. syncWindow() { const rect = this.$refs.editor.getBoundingClientRect(); editorSyncWindow(this.controller, rect); } onFocusOuter() { // Focus the content editable when the outer doc gets focused. const child = this.$refs.doc.firstChild; if (child instanceof HTMLElement) { child.focus(); } } private onFocusIn() { if (this.isFocused) { return; } this.$emit('editor-focus'); this.isFocused = true; ++this.stateCounter; } private onFocusOut() { if (!this.isFocused) { return; } this.canShowMentionSuggestions = 0; // When the editor goes out of focus, hide the mention suggestions panel. this.$emit('editor-blur'); this.isFocused = false; ++this.stateCounter; } private async highlightCurrentSelection() { console.warn('highlightCurrentSelection'); // TODO: Not sure we need this anymore - might already be handled in the // editor functions. return; // When an outside control got clicked, store the previous selection, // focus the editor and then apply the selection. // We do this so the focused text doesn't visibly lose focus after the outside control // button assumed focus. const prevSelection = this.view!.state.selection; this.$refs.editor.focus(); const tr = this.view!.state.tr; tr.setSelection(prevSelection); this.view!.dispatch(tr); // Wait a tick for the editor's doc to update, then force an update to reposition the controls. await this.$nextTick(); ++this.stateCounter; } showEmojiPanel() { if (this.$refs.emojiPanel instanceof AppContentEditorControlsEmoji) { this.$refs.emojiPanel.show(); } } updateIsEmpty(state: EditorState) { // The "empty" prosemirror document takes up a length of 4. this.isEmpty = state.doc.nodeSize <= 4; } onEmojiPanelVisibilityChanged(visible: boolean) { this.emojiPanelVisible = visible; if (this.emojiPanelVisible) { this.highlightCurrentSelection(); } } onControlsCollapsedChanged(collapsed: boolean) { this.controlsCollapsed = collapsed; } onInsertMention() { this.highlightCurrentSelection(); this.canShowMentionSuggestions = 0; // Hide control } onMentionUsersChange(num: number) { this.mentionUserCount = num; } onScroll() { // When the doc scroller gets scrolled, we want to make sure we position // the controls appropriately. ++this.stateCounter; } focus() { this.$refs.editor.focus(); if (this.view) { this.view.focus(); } ++this.stateCounter; } getContentRules() { if (this.displayRules) { return this.displayRules; } // Return default values. return new ContentRules(); } }
the_stack
import { ColorHSL, ColorLAB, ColorRGBA64, hslToRGB, interpolateRGB, labToRGB, rgbToHSL, rgbToLAB, roundToPrecisionSmall, } from "@microsoft/fast-colors"; import { BasePalette } from "./palette.js"; import { SwatchRGB } from "./swatch.js"; import { contrast } from "./utilities/relative-luminance.js"; /** * A utility Palette that generates many Swatches used for selection in the actual Palette. * The algorithm uses the LAB color space and keeps the saturation from the source color throughout. */ class HighResolutionPaletteRGB extends BasePalette<SwatchRGB> { /** * Bump the saturation if it falls below the reference color saturation. * * @param reference - Color with target saturation * @param color - Color to check and bump if below target saturation * @returns Original or adjusted color */ private static saturationBump( reference: ColorRGBA64, color: ColorRGBA64 ): ColorRGBA64 { const hslReference = rgbToHSL(reference); const saturationTarget = hslReference.s; const hslColor = rgbToHSL(color); if (hslColor.s < saturationTarget) { const hslNew = new ColorHSL(hslColor.h, saturationTarget, hslColor.l); return hslToRGB(hslNew); } return color; } /** * Scales input from 0 to 100 to 0 to 0.5. * * @param l - Input number, 0 to 100 * @returns Output number, 0 to 0.5 */ private static ramp(l: number) { const inputval = l / 100; if (inputval > 0.5) return (inputval - 0.5) / 0.5; //from 0.500001in = 0.00000001out to 1.0in = 1.0out return 2 * inputval; //from 0in = 0out to 0.5in = 1.0out } /** * Creates a new high-resolution Palette. * * @param source - The source color * @returns The Palette based on the `source` color */ static from(source: SwatchRGB): HighResolutionPaletteRGB { const swatches: SwatchRGB[] = []; const labSource = rgbToLAB(ColorRGBA64.fromObject(source)!.roundToPrecision(4)); const lab0 = labToRGB(new ColorLAB(0, labSource.a, labSource.b)) .clamp() .roundToPrecision(4); const lab50 = labToRGB(new ColorLAB(50, labSource.a, labSource.b)) .clamp() .roundToPrecision(4); const lab100 = labToRGB(new ColorLAB(100, labSource.a, labSource.b)) .clamp() .roundToPrecision(4); const rgbMin = new ColorRGBA64(0, 0, 0); const rgbMax = new ColorRGBA64(1, 1, 1); const lAbove = lab100.equalValue(rgbMax) ? 0 : 14; const lBelow = lab0.equalValue(rgbMin) ? 0 : 14; // 257 levels max, depending on whether lab0 or lab100 are black or white respectively. for (let l = 100 + lAbove; l >= 0 - lBelow; l -= 0.5) { let rgb: ColorRGBA64; if (l < 0) { // For L less than 0, scale from black to L=0 const percentFromRgbMinToLab0 = l / lBelow + 1; rgb = interpolateRGB(percentFromRgbMinToLab0, rgbMin, lab0); } else if (l <= 50) { // For L less than 50, we scale from L=0 to the base color rgb = interpolateRGB(HighResolutionPaletteRGB.ramp(l), lab0, lab50); } else if (l <= 100) { // For L less than 100, scale from the base color to L=100 rgb = interpolateRGB(HighResolutionPaletteRGB.ramp(l), lab50, lab100); } else { // For L greater than 100, scale from L=100 to white const percentFromLab100ToRgbMax = (l - 100.0) / lAbove; rgb = interpolateRGB(percentFromLab100ToRgbMax, lab100, rgbMax); } rgb = HighResolutionPaletteRGB.saturationBump(lab50, rgb).roundToPrecision(4); swatches.push(SwatchRGB.from(rgb)); } return new HighResolutionPaletteRGB(source, swatches); } } /** * Options to tailor the generation of PaletteRGB. * * @public */ export interface PaletteRGBOptions { /** * The minimum amount of contrast between steps in the palette. Default 1.05. * Recommended increments by hundredths. */ stepContrast: number; /** * Multiplier for increasing step contrast as the swatches darken. Default 0. * Recommended increments by hundredths. */ stepContrastRamp: number; /** * Whether to keep the exact source color in the target palette. Default false. * Only recommended when the exact color is required and used in stateful interaction recipes like hover. * Note that custom recipes can still access the source color even if it's not in the ramp, * but turning this on will potentially increase the contrast between steps toward the ends of the palette. */ preserveSource: boolean; } const defaultPaletteRGBOptions: PaletteRGBOptions = { stepContrast: 1.05, stepContrastRamp: 0, preserveSource: false, }; /** * An implementation of a {@link Palette} that has a consistent minimum contrast value between Swatches. * This is useful for UI as it means the perception of the difference between colors the same distance * apart in the Palette will be consistent whether the colors are light yellow or dark red. * It generates its curve using the LAB color space and maintains the saturation of the source color throughout. * * @public */ export class PaletteRGB extends BasePalette<SwatchRGB> { /** * Adjust one end of the contrast-based palette so it doesn't abruptly fall to black (or white). * * @param swatchContrast - Function to get the target contrast for the next swatch * @param referencePalette - The high resolution palette * @param targetPalette - The contrast-based palette to adjust * @param direction - The end to adjust */ private static adjustEnd( swatchContrast: (swatch: SwatchRGB) => number, referencePalette: HighResolutionPaletteRGB, targetPalette: SwatchRGB[], direction: 1 | -1 ) { // Careful with the use of referencePalette as only the refSwatches is reversed. const refSwatches = direction === -1 ? referencePalette.swatches : referencePalette.reversedSwatches; const refIndex = (swatch: SwatchRGB) => { const index = referencePalette.closestIndexOf(swatch); return direction === 1 ? referencePalette.lastIndex - index : index; }; // Only operates on the 'end' end of the array, so flip if we're adjusting the 'beginning' if (direction === 1) { targetPalette.reverse(); } const targetContrast = swatchContrast(targetPalette[targetPalette.length - 2]); const actualContrast = roundToPrecisionSmall( contrast( targetPalette[targetPalette.length - 1], targetPalette[targetPalette.length - 2] ), 2 ); if (actualContrast < targetContrast) { // Remove last swatch if not sufficient contrast targetPalette.pop(); // Distribute to the last swatch const safeSecondSwatch = referencePalette.colorContrast( refSwatches[referencePalette.lastIndex], targetContrast, undefined, direction ); const safeSecondRefIndex = refIndex(safeSecondSwatch); const targetSwatchCurrentRefIndex = refIndex( targetPalette[targetPalette.length - 2] ); const swatchesToSpace = safeSecondRefIndex - targetSwatchCurrentRefIndex; let space = 1; for ( let i = targetPalette.length - swatchesToSpace - 1; i < targetPalette.length; i++ ) { const currentRefIndex = refIndex(targetPalette[i]); const nextRefIndex = i === targetPalette.length - 1 ? referencePalette.lastIndex : currentRefIndex + space; targetPalette[i] = refSwatches[nextRefIndex]; space++; } } if (direction === 1) { targetPalette.reverse(); } } /** * Generate a Palette with consistent minimum contrast between Swatches. * * @param source - The source color * @param options - Palette generation options * @returns A Palette meeting the requested contrast between Swatches. */ private static createColorPaletteByContrast( source: SwatchRGB, options: PaletteRGBOptions ): SwatchRGB[] { const referencePalette = HighResolutionPaletteRGB.from(source); // Ramp function to increase contrast as the swatches get darker const nextContrast = (swatch: SwatchRGB) => { const c = options.stepContrast + options.stepContrast * (1 - swatch.relativeLuminance) * options.stepContrastRamp; return roundToPrecisionSmall(c, 2); }; const swatches: SwatchRGB[] = []; // Start with the source color or the light end color let ref = options.preserveSource ? source : referencePalette.swatches[0]; swatches.push(ref); // Add swatches with contrast toward dark do { const targetContrast = nextContrast(ref); ref = referencePalette.colorContrast(ref, targetContrast, undefined, 1); swatches.push(ref); } while (ref.relativeLuminance > 0); // Add swatches with contrast toward light if (options.preserveSource) { ref = source; do { // This is off from the dark direction because `ref` here is the darker swatch, probably subtle const targetContrast = nextContrast(ref); ref = referencePalette.colorContrast(ref, targetContrast, undefined, -1); swatches.unshift(ref); } while (ref.relativeLuminance < 1); } // Validate dark end this.adjustEnd(nextContrast, referencePalette, swatches, -1); // Validate light end if (options.preserveSource) { this.adjustEnd(nextContrast, referencePalette, swatches, 1); } return swatches; } /** * Create a color Palette from a provided Swatch. * * @param source - The source Swatch to create a Palette from * @returns The Palette */ static from(source: SwatchRGB, options?: Partial<PaletteRGBOptions>): PaletteRGB { const opts = options === void 0 || null ? defaultPaletteRGBOptions : { ...defaultPaletteRGBOptions, ...options }; return new PaletteRGB( source, Object.freeze(PaletteRGB.createColorPaletteByContrast(source, opts)) ); } }
the_stack
import { State, Agile, StateObserver, Observer, StatePersistent, EnhancedState, } from '../../../src'; import * as Utils from '@agile-ts/utils'; import { LogMock } from '../../helper/logMock'; jest.mock('../../../src/state/state.persistent'); describe('Enhanced State Tests', () => { let dummyAgile: Agile; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); jest.spyOn(State.prototype, 'set'); jest.clearAllMocks(); }); it('should create Enhanced State and should call initial set (default config)', () => { // Overwrite select once to not call it jest .spyOn(EnhancedState.prototype, 'set') .mockReturnValueOnce(undefined as any); const state = new EnhancedState(dummyAgile, 'coolValue'); expect(state.isPersisted).toBeFalsy(); expect(state.persistent).toBeUndefined(); expect(state.computeValueMethod).toBeUndefined(); expect(state.computeExistsMethod).toBeInstanceOf(Function); expect(state.currentInterval).toBeUndefined(); // Check if State was called with correct parameters expect(state._key).toBeUndefined(); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([]); expect(state.observers['value'].key).toBeUndefined(); expect(state.sideEffects).toStrictEqual({}); }); it('should create Enhanced State and should call initial set (specific config)', () => { // Overwrite select once to not call it jest .spyOn(EnhancedState.prototype, 'set') .mockReturnValueOnce(undefined as any); const dummyObserver = new Observer(dummyAgile); const state = new EnhancedState(dummyAgile, 'coolValue', { key: 'coolState', dependents: [dummyObserver], }); expect(state.isPersisted).toBeFalsy(); expect(state.persistent).toBeUndefined(); expect(state.computeValueMethod).toBeUndefined(); expect(state.computeExistsMethod).toBeInstanceOf(Function); expect(state.currentInterval).toBeUndefined(); // Check if State was called with correct parameters expect(state._key).toBe('coolState'); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([ dummyObserver, ]); expect(state.observers['value'].key).toBe('coolState'); expect(state.sideEffects).toStrictEqual({}); }); it("should create Enhanced State and shouldn't call initial set (config.isPlaceholder = true)", () => { // Overwrite select once to not call it jest .spyOn(EnhancedState.prototype, 'set') .mockReturnValueOnce(undefined as any); const state = new EnhancedState(dummyAgile, 'coolValue', { isPlaceholder: true, }); expect(state.isPersisted).toBeFalsy(); expect(state.persistent).toBeUndefined(); expect(state.computeValueMethod).toBeUndefined(); expect(state.computeExistsMethod).toBeInstanceOf(Function); expect(state.currentInterval).toBeUndefined(); // Check if State was called with correct parameters expect(state._key).toBeUndefined(); expect(state.isSet).toBeFalsy(); expect(state.isPlaceholder).toBeTruthy(); expect(state.initialStateValue).toBe('coolValue'); expect(state._value).toBe('coolValue'); expect(state.previousStateValue).toBe('coolValue'); expect(state.nextStateValue).toBe('coolValue'); expect(state.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(state.observers['value'].dependents)).toStrictEqual([]); expect(state.observers['value'].key).toBeUndefined(); expect(state.sideEffects).toStrictEqual({}); }); describe('State Function Tests', () => { let numberState: EnhancedState<number>; let objectState: EnhancedState<{ name: string; age: number }>; let arrayState: EnhancedState<string[]>; let booleanState: EnhancedState<boolean>; beforeEach(() => { numberState = new EnhancedState<number>(dummyAgile, 10, { key: 'numberStateKey', }); objectState = new EnhancedState<{ name: string; age: number }>( dummyAgile, { name: 'jeff', age: 10 }, { key: 'objectStateKey', } ); arrayState = new EnhancedState<string[]>(dummyAgile, ['jeff'], { key: 'arrayStateKey', }); booleanState = new EnhancedState<boolean>(dummyAgile, false, { key: 'booleanStateKey', }); }); describe('setKey function tests', () => { beforeEach(() => { numberState.persistent = new StatePersistent(numberState); numberState.persistent.setKey = jest.fn(); jest.spyOn(State.prototype, 'setKey'); }); it("should call 'setKey()' in the State and update the Persistent key", () => { if (numberState.persistent) numberState.persistent._key = numberState._key as any; numberState.setKey('newKey'); expect(State.prototype.setKey).toHaveBeenCalledWith('newKey'); expect(numberState.persistent?.setKey).toHaveBeenCalledWith('newKey'); }); it( "should call 'setKey()' in the State " + "and shouldn't update the Persistent key if the specified StateKey and PersistKey differentiate", () => { if (numberState.persistent) numberState.persistent._key = 'randomKey'; numberState.setKey('newKey'); expect(State.prototype.setKey).toHaveBeenCalledWith('newKey'); expect(numberState.persistent?.setKey).not.toHaveBeenCalled(); } ); it( "should call 'setKey()' in the State " + "and shouldn't update the Persistent key if the specified StateKey is undefined", () => { if (numberState.persistent) numberState.persistent._key = numberState._key as any; numberState.setKey(undefined); expect(State.prototype.setKey).toHaveBeenCalledWith(undefined); expect(numberState.persistent?.setKey).not.toHaveBeenCalled(); } ); }); describe('undo function tests', () => { beforeEach(() => { numberState.set = jest.fn(); }); it('should assign previousStateValue to currentValue (default config)', () => { numberState.previousStateValue = 99; numberState.undo(); expect(numberState.set).toHaveBeenCalledWith( numberState.previousStateValue, {} ); }); it('should assign previousStateValue to currentValue (specific config)', () => { numberState.previousStateValue = 99; numberState.undo({ force: true, storage: false, }); expect(numberState.set).toHaveBeenCalledWith( numberState.previousStateValue, { force: true, storage: false, } ); }); }); describe('reset function tests', () => { beforeEach(() => { numberState.set = jest.fn(); }); it('should assign initialStateValue to currentValue (default config)', () => { numberState.initialStateValue = 99; numberState.reset(); expect(numberState.set).toHaveBeenCalledWith( numberState.initialStateValue, {} ); }); it('should assign initialStateValue to currentValue (specific config)', () => { numberState.initialStateValue = 99; numberState.reset({ force: true, storage: false, }); expect(numberState.set).toHaveBeenCalledWith( numberState.initialStateValue, { force: true, storage: false, } ); }); }); describe('patch function tests', () => { beforeEach(() => { objectState.ingest = jest.fn(); numberState.ingest = jest.fn(); arrayState.ingest = jest.fn(); jest.spyOn(Utils, 'flatMerge'); }); it("shouldn't patch specified object value into a not object based State (default config)", () => { numberState.patch({ changed: 'object' }); LogMock.hasLoggedCode('14:03:02'); expect(objectState.ingest).not.toHaveBeenCalled(); }); it("shouldn't patch specified non object value into a object based State (default config)", () => { objectState.patch('number' as any); LogMock.hasLoggedCode('00:03:01', ['TargetWithChanges', 'object']); expect(objectState.ingest).not.toHaveBeenCalled(); }); it('should patch specified object value into a object based State (default config)', () => { objectState.patch({ name: 'frank' }); expect(Utils.flatMerge).toHaveBeenCalledWith( { age: 10, name: 'jeff' }, { name: 'frank' }, { addNewProperties: true } ); expect(objectState.nextStateValue).toStrictEqual({ age: 10, name: 'frank', }); expect(objectState.ingest).toHaveBeenCalledWith({ addNewProperties: true, // Not required but passed for simplicity }); }); it('should patch specified object value into a object based State (specific config)', () => { objectState.patch( { name: 'frank' }, { addNewProperties: false, background: true, force: true, overwrite: true, sideEffects: { enabled: false, }, } ); expect(Utils.flatMerge).toHaveBeenCalledWith( { age: 10, name: 'jeff' }, { name: 'frank' }, { addNewProperties: false } ); expect(objectState.nextStateValue).toStrictEqual({ age: 10, name: 'frank', }); expect(objectState.ingest).toHaveBeenCalledWith({ background: true, force: true, overwrite: true, sideEffects: { enabled: false, }, addNewProperties: false, // Not required but passed for simplicity }); }); it('should patch specified array value into a array based State (default config)', () => { arrayState.patch(['hi']); expect(Utils.flatMerge).not.toHaveBeenCalled(); expect(arrayState.nextStateValue).toStrictEqual(['jeff', 'hi']); expect(arrayState.ingest).toHaveBeenCalledWith({ addNewProperties: true, // Not required but passed for simplicity }); }); it('should patch specified array value into a object based State', () => { objectState.patch(['hi'], { addNewProperties: true }); expect(Utils.flatMerge).toHaveBeenCalledWith( { age: 10, name: 'jeff' }, ['hi'], { addNewProperties: true } ); expect(objectState.nextStateValue).toStrictEqual({ 0: 'hi', age: 10, name: 'jeff', }); expect(objectState.ingest).toHaveBeenCalledWith({ addNewProperties: true, // Not required but passed for simplicity }); }); }); describe('watch function tests', () => { let dummyCallbackFunction; beforeEach(() => { jest.spyOn(numberState, 'addSideEffect'); dummyCallbackFunction = jest.fn(); }); it('should add passed watcherFunction to watchers at passed key', () => { const response = numberState.watch('dummyKey', dummyCallbackFunction); expect(response).toBe(numberState); expect(numberState.addSideEffect).toHaveBeenCalledWith( 'dummyKey', expect.any(Function), { weight: 0 } ); // Test whether registered callback function is called numberState.sideEffects['dummyKey'].callback(numberState); expect(dummyCallbackFunction).toHaveBeenCalledWith( numberState._value, 'dummyKey' ); }); it('should add passed watcherFunction to watchers at random key if no key passed and return that generated key', () => { jest.spyOn(Utils, 'generateId').mockReturnValue('randomKey'); const response = numberState.watch(dummyCallbackFunction); expect(response).toBe('randomKey'); expect(numberState.addSideEffect).toHaveBeenCalledWith( 'randomKey', expect.any(Function), { weight: 0 } ); expect(Utils.generateId).toHaveBeenCalled(); // Test whether registered callback function is called numberState.sideEffects['randomKey'].callback(numberState); expect(dummyCallbackFunction).toHaveBeenCalledWith( numberState._value, 'randomKey' ); }); it("shouldn't add passed invalid watcherFunction to watchers at passed key", () => { const response = numberState.watch( 'dummyKey', 'noFunction hehe' as any ); expect(response).toBe(numberState); expect(numberState.addSideEffect).not.toHaveBeenCalled(); LogMock.hasLoggedCode('00:03:01', ['Watcher Callback', 'function']); }); }); describe('removeWatcher function tests', () => { beforeEach(() => { jest.spyOn(numberState, 'removeSideEffect'); }); it('should remove watcher at key from State', () => { numberState.removeWatcher('dummyKey'); expect(numberState.removeSideEffect).toHaveBeenCalledWith('dummyKey'); }); }); describe('onInaugurated function tests', () => { let dummyCallbackFunction; beforeEach(() => { jest.spyOn(numberState, 'watch'); jest.spyOn(numberState, 'removeSideEffect'); dummyCallbackFunction = jest.fn(); }); it('should add watcher called InauguratedWatcherKey to State', () => { numberState.onInaugurated(dummyCallbackFunction); expect(numberState.watch).toHaveBeenCalledWith( 'InauguratedWatcherKey', expect.any(Function) ); }); it('should remove itself after invoking', () => { numberState.onInaugurated(dummyCallbackFunction); // Call Inaugurated Watcher numberState.sideEffects['InauguratedWatcherKey'].callback(numberState); expect(dummyCallbackFunction).toHaveBeenCalledWith( numberState.value, 'InauguratedWatcherKey' ); expect(numberState.removeSideEffect).toHaveBeenCalledWith( 'InauguratedWatcherKey' ); }); }); describe('persist function tests', () => { it('should create Persistent (default config)', () => { numberState.persist(); expect(numberState.persistent).toBeInstanceOf(StatePersistent); expect(StatePersistent).toHaveBeenCalledWith(numberState, { key: numberState._key, }); }); it('should create Persistent (specific config)', () => { numberState.persist({ key: 'specificKey', storageKeys: ['test1', 'test2'], loadValue: false, defaultStorageKey: 'test1', }); expect(numberState.persistent).toBeInstanceOf(StatePersistent); expect(StatePersistent).toHaveBeenCalledWith(numberState, { loadValue: false, storageKeys: ['test1', 'test2'], key: 'specificKey', defaultStorageKey: 'test1', }); }); it("shouldn't overwrite existing Persistent", () => { const dummyPersistent = new StatePersistent(numberState); numberState.persistent = dummyPersistent; numberState.isPersisted = true; jest.clearAllMocks(); numberState.persist({ key: 'newPersistentKey' }); expect(numberState.persistent).toBe(dummyPersistent); // expect(numberState.persistent._key).toBe("newPersistentKey"); // Can not test because of Mocking Persistent expect(StatePersistent).not.toHaveBeenCalled(); }); }); describe('onLoad function tests', () => { const dummyCallbackFunction = jest.fn(); it("should set onLoad function if State is persisted and shouldn't call it initially (state.isPersisted = false)", () => { numberState.persistent = new StatePersistent(numberState); numberState.isPersisted = false; numberState.onLoad(dummyCallbackFunction); expect(numberState.persistent.onLoad).toBe(dummyCallbackFunction); expect(dummyCallbackFunction).not.toHaveBeenCalled(); LogMock.hasNotLogged('warn'); }); it('should set onLoad function if State is persisted and should call it initially (state.isPersisted = true)', () => { numberState.persistent = new StatePersistent(numberState); numberState.isPersisted = true; numberState.onLoad(dummyCallbackFunction); expect(numberState.persistent.onLoad).toBe(dummyCallbackFunction); expect(dummyCallbackFunction).toHaveBeenCalledWith(true); LogMock.hasNotLogged('warn'); }); it("shouldn't set onLoad function if State isn't persisted", () => { numberState.onLoad(dummyCallbackFunction); expect(numberState?.persistent?.onLoad).toBeUndefined(); expect(dummyCallbackFunction).not.toHaveBeenCalled(); LogMock.hasNotLogged('warn'); }); it("shouldn't set invalid onLoad callback function", () => { numberState.persistent = new StatePersistent(numberState); numberState.isPersisted = false; numberState.onLoad(10 as any); expect(numberState?.persistent?.onLoad).toBeUndefined(); LogMock.hasLoggedCode('00:03:01', ['OnLoad Callback', 'function']); }); }); describe('interval function tests', () => { const dummyCallbackFunction = jest.fn(); const dummyCallbackFunction2 = jest.fn(); beforeEach(() => { jest.useFakeTimers(); numberState.set = jest.fn(); }); afterEach(() => { jest.clearAllTimers(); }); it('should create an interval (without custom milliseconds)', () => { dummyCallbackFunction.mockReturnValueOnce(10); numberState.interval(dummyCallbackFunction); jest.runTimersToTime(1000); // travel 1000s in time -> execute interval expect(setInterval).toHaveBeenCalledTimes(1); expect(setInterval).toHaveBeenLastCalledWith( expect.any(Function), 1000 ); expect(dummyCallbackFunction).toHaveBeenCalledWith(numberState._value); expect(numberState.set).toHaveBeenCalledWith(10); expect(numberState.currentInterval).toEqual({ id: expect.anything(), ref: expect.anything(), unref: expect.anything(), }); LogMock.hasNotLogged('warn'); }); it('should create an interval (with custom milliseconds)', () => { dummyCallbackFunction.mockReturnValueOnce(10); numberState.interval(dummyCallbackFunction, 2000); jest.runTimersToTime(2000); // travel 2000 in time -> execute interval expect(setInterval).toHaveBeenCalledTimes(1); expect(setInterval).toHaveBeenLastCalledWith( expect.any(Function), 2000 ); expect(dummyCallbackFunction).toHaveBeenCalledWith(numberState._value); expect(numberState.set).toHaveBeenCalledWith(10); expect(numberState.currentInterval).toEqual({ id: expect.anything(), ref: expect.anything(), unref: expect.anything(), }); LogMock.hasNotLogged('warn'); }); it("shouldn't be able to create second interval and print warning", () => { numberState.interval(dummyCallbackFunction, 3000); const currentInterval = numberState.currentInterval; numberState.interval(dummyCallbackFunction2); expect(setInterval).toHaveBeenCalledTimes(1); expect(setInterval).toHaveBeenLastCalledWith( expect.any(Function), 3000 ); expect(numberState.currentInterval).toStrictEqual(currentInterval); LogMock.hasLoggedCode('14:03:03', [], numberState.currentInterval); }); it("shouldn't set invalid interval callback function", () => { numberState.interval(10 as any); expect(setInterval).not.toHaveBeenCalled(); expect(numberState.currentInterval).toBeUndefined(); LogMock.hasLoggedCode('00:03:01', ['Interval Callback', 'function']); }); }); describe('clearInterval function tests', () => { const dummyCallbackFunction = jest.fn(); beforeEach(() => { jest.useFakeTimers(); numberState.set = jest.fn(); }); afterEach(() => { jest.clearAllTimers(); }); it('should clear existing interval', () => { numberState.interval(dummyCallbackFunction); const currentInterval = numberState.currentInterval; numberState.clearInterval(); expect(clearInterval).toHaveBeenCalledTimes(1); expect(clearInterval).toHaveBeenLastCalledWith(currentInterval); expect(numberState.currentInterval).toBeUndefined(); }); it("shouldn't clear not existing interval", () => { numberState.clearInterval(); expect(clearInterval).not.toHaveBeenCalled(); expect(numberState.currentInterval).toBeUndefined(); }); }); describe('exists get function tests', () => { it('should return true if State is no placeholder and computeExistsMethod returns true', () => { numberState.computeExistsMethod = jest.fn().mockReturnValueOnce(true); numberState.isPlaceholder = false; expect(numberState.exists).toBeTruthy(); expect(numberState.computeExistsMethod).toHaveBeenCalledWith( numberState.value ); }); it('should return false if State is no placeholder and computeExistsMethod returns false', () => { numberState.computeExistsMethod = jest.fn().mockReturnValueOnce(false); numberState.isPlaceholder = false; expect(numberState.exists).toBeFalsy(); expect(numberState.computeExistsMethod).toHaveBeenCalledWith( numberState.value ); }); it('should return false if State is placeholder"', () => { numberState.computeExistsMethod = jest.fn(() => true); numberState.isPlaceholder = true; expect(numberState.exists).toBeFalsy(); expect(numberState.computeExistsMethod).not.toHaveBeenCalled(); // since isPlaceholder gets checked first }); }); describe('computeExists function tests', () => { it('should assign passed function to computeExistsMethod', () => { const computeMethod = (value) => value === null; numberState.computeExists(computeMethod); expect(numberState.computeExistsMethod).toBe(computeMethod); LogMock.hasNotLogged('warn'); }); it("shouldn't assign passed invalid function to computeExistsMethod", () => { numberState.computeExists(10 as any); expect(numberState.computeExistsMethod).toBeInstanceOf(Function); LogMock.hasLoggedCode('00:03:01', [ 'Compute Exists Method', 'function', ]); }); }); describe('is function tests', () => { beforeEach(() => { jest.spyOn(Utils, 'equal'); }); it('should return true if passed value is equal to the current StateValue', () => { const response = numberState.is(10); expect(response).toBeTruthy(); expect(Utils.equal).toHaveBeenCalledWith(10, numberState._value); }); it('should return false if passed value is not equal to the current StateValue', () => { const response = numberState.is(20); expect(response).toBeFalsy(); expect(Utils.equal).toHaveBeenCalledWith(20, numberState._value); }); }); describe('isNot function tests', () => { beforeEach(() => { jest.spyOn(Utils, 'notEqual'); }); it('should return false if passed value is equal to the current StateValue', () => { const response = numberState.isNot(10); expect(response).toBeFalsy(); expect(Utils.notEqual).toHaveBeenCalledWith(10, numberState._value); }); it('should return true if passed value is not equal to the current StateValue', () => { const response = numberState.isNot(20); expect(response).toBeTruthy(); expect(Utils.notEqual).toHaveBeenCalledWith(20, numberState._value); }); }); describe('invert function tests', () => { let dummyState: EnhancedState; beforeEach(() => { dummyState = new EnhancedState(dummyAgile, null); dummyState.set = jest.fn(); }); it('should invert value of the type boolean', () => { dummyState.nextStateValue = false; dummyState.invert(); expect(dummyState.set).toHaveBeenCalledWith(true); }); it('should invert value of the type number', () => { dummyState.nextStateValue = 10; dummyState.invert(); expect(dummyState.set).toHaveBeenCalledWith(-10); }); it('should invert value of the type array', () => { dummyState.nextStateValue = ['1', '2', '3']; dummyState.invert(); expect(dummyState.set).toHaveBeenCalledWith(['3', '2', '1']); }); it('should invert value of the type string', () => { dummyState.nextStateValue = 'jeff'; dummyState.invert(); expect(dummyState.set).toHaveBeenCalledWith('ffej'); }); it("shouldn't invert not invertible types like function, null, undefined, object", () => { dummyState.nextStateValue = () => { // empty }; dummyState.invert(); expect(dummyState.set).not.toHaveBeenCalled(); LogMock.hasLoggedCode('14:03:04', ['function']); }); }); describe('computeValue function tests', () => { beforeEach(() => { numberState.set = jest.fn(); }); it('should assign passed function to computeValueMethod and compute State value initially', () => { const computeMethod = () => 10; numberState.computeValue(computeMethod); expect(numberState.set).toHaveBeenCalledWith(10); expect(numberState.computeValueMethod).toBe(computeMethod); LogMock.hasNotLogged('warn'); }); it("shouldn't assign passed invalid function to computeValueMethod", () => { numberState.computeValue(10 as any); expect(numberState.set).not.toHaveBeenCalled(); expect(numberState.computeValueMethod).toBeUndefined(); LogMock.hasLoggedCode('00:03:01', ['Compute Value Method', 'function']); }); }); }); });
the_stack
import * as ts from 'typescript' import { FieldDefinition, FunctionDefinition, Identifier, ServiceDefinition, SyntaxType, ThriftStatement, } from '@creditkarma/thrift-parser' import { ContextType, TProtocolType } from './types' import { createStructArgsName, createStructResultName, renderMethodNamesProperty, renderMethodNamesStaticProperty, renderServiceNameProperty, renderServiceNameStaticProperty, } from './utils' import { IRenderState } from '../../../types' import { COMMON_IDENTIFIERS, MESSAGE_TYPE, THRIFT_IDENTIFIERS, THRIFT_TYPES, } from '../identifiers' import { createApplicationException, createAssignmentStatement, createCallStatement, createClassConstructor, createConstStatement, createFunctionParameter, createMethodCall, createMethodCallStatement, createPromise, createPublicMethod, } from '../utils' import { constructorNameForFieldType, createAnyType, createNumberType, createStringType, createVoidType, typeNodeForFieldType, } from '../types' import { renderMethodAnnotationsProperty, renderMethodAnnotationsStaticProperty, renderServiceAnnotationsProperty, renderServiceAnnotationsStaticProperty, } from '../annotations' import { Resolver } from '../../../resolver' import { collectAllMethods } from '../../shared/service' import { createBufferType, createErrorType, createPromiseType, } from '../../shared/types' import { className, looseName, strictName, toolkitName } from '../struct/utils' function objectLiteralForServiceFunctions( node: ThriftStatement, ): ts.ObjectLiteralExpression { switch (node.type) { case SyntaxType.ServiceDefinition: return ts.createObjectLiteral( node.functions.map( (next: FunctionDefinition): ts.PropertyAssignment => { return ts.createPropertyAssignment( ts.createIdentifier(next.name.value), ts.createIdentifier(`handler.${next.name.value}`), ) }, ), true, ) default: throw new TypeError( `A service can only extend another service. Found: ${node.type}`, ) } } function createHandlerType(node: ServiceDefinition): ts.TypeNode { return ts.createTypeReferenceNode(COMMON_IDENTIFIERS.IHandler, [ ts.createTypeReferenceNode(COMMON_IDENTIFIERS.Context, undefined), ]) } export function extendsService( service: Identifier, state: IRenderState, ): ts.HeritageClause { return ts.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [ ts.createExpressionWithTypeArguments( [ts.createTypeReferenceNode(COMMON_IDENTIFIERS.Context, undefined)], ts.createIdentifier( `${ Resolver.resolveIdentifierName(service.value, { currentNamespace: state.currentNamespace, currentDefinitions: state.currentDefinitions, namespaceMap: state.project.namespaces, }).fullName }.Processor`, ), ), ]) } export function extendsAbstract(): ts.HeritageClause { return ts.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [ ts.createExpressionWithTypeArguments( [ ts.createTypeReferenceNode( COMMON_IDENTIFIERS.Context, undefined, ), ts.createTypeReferenceNode(COMMON_IDENTIFIERS.IHandler, [ ts.createTypeReferenceNode( COMMON_IDENTIFIERS.Context, undefined, ), ]), ], THRIFT_IDENTIFIERS.ThriftProcessor, ), ]) } export function renderProcessor( service: ServiceDefinition, state: IRenderState, ): ts.ClassDeclaration { const handler: ts.PropertyDeclaration = ts.createProperty( undefined, [ ts.createToken(ts.SyntaxKind.ProtectedKeyword), ts.createToken(ts.SyntaxKind.ReadonlyKeyword), ], COMMON_IDENTIFIERS._handler, undefined, ts.createTypeReferenceNode(COMMON_IDENTIFIERS.IHandler, [ ts.createTypeReferenceNode(COMMON_IDENTIFIERS.Context, undefined), ]), undefined, ) const staticServiceName: ts.PropertyDeclaration = renderServiceNameStaticProperty() const staticAnnotations: ts.PropertyDeclaration = renderServiceAnnotationsStaticProperty() const staticMethodAnnotations: ts.PropertyDeclaration = renderMethodAnnotationsStaticProperty() const staticMethodNames: ts.PropertyDeclaration = renderMethodNamesStaticProperty() const serviceName: ts.PropertyDeclaration = renderServiceNameProperty() const annotations: ts.PropertyDeclaration = renderServiceAnnotationsProperty() const methodAnnotations: ts.PropertyDeclaration = renderMethodAnnotationsProperty() const methodNames: ts.PropertyDeclaration = renderMethodNamesProperty() const processMethod: ts.MethodDeclaration = createProcessMethod( service, state, ) const processFunctions: Array<ts.MethodDeclaration> = service.functions.map( (next: FunctionDefinition) => { return createProcessFunctionMethod(service, next, state) }, ) const heritage: Array<ts.HeritageClause> = service.extends !== null ? [extendsService(service.extends, state)] : [extendsAbstract()] // export class <node.name> { ... } return ts.createClassDeclaration( undefined, // decorators [ts.createToken(ts.SyntaxKind.ExportKeyword)], // modifiers 'Processor', // name [ ts.createTypeParameterDeclaration( 'Context', undefined, createAnyType(), ), ], // type parameters heritage, // heritage [ handler, staticServiceName, staticAnnotations, staticMethodAnnotations, staticMethodNames, serviceName, annotations, methodAnnotations, methodNames, createCtor(service, state), processMethod, ...processFunctions, ], // body ) } function createCtor( service: ServiceDefinition, state: IRenderState, ): ts.ConstructorDeclaration { if (service.extends !== null) { return createClassConstructor( [createFunctionParameter('handler', createHandlerType(service))], [ createSuperCall(service.extends, state), createAssignmentStatement( ts.createIdentifier('this._handler'), ts.createIdentifier('handler'), ), ], ) } else { return createClassConstructor( [createFunctionParameter('handler', createHandlerType(service))], [ ts.createStatement(ts.createCall(ts.createSuper(), [], [])), createAssignmentStatement( ts.createIdentifier('this._handler'), ts.createIdentifier('handler'), ), ], ) } } function createSuperCall( service: Identifier, state: IRenderState, ): ts.Statement { return ts.createStatement( ts.createCall( ts.createSuper(), [], [ objectLiteralForServiceFunctions( Resolver.resolveIdentifierDefinition(service, { currentNamespace: state.currentNamespace, namespaceMap: state.project.namespaces, }).definition, ), ], ), ) } function createProcessFunctionMethod( service: ServiceDefinition, funcDef: FunctionDefinition, state: IRenderState, ): ts.MethodDeclaration { return createPublicMethod( ts.createIdentifier(`process_${funcDef.name.value}`), [ createFunctionParameter( COMMON_IDENTIFIERS.requestId, createNumberType(), ), createFunctionParameter(COMMON_IDENTIFIERS.input, TProtocolType), createFunctionParameter(COMMON_IDENTIFIERS.output, TProtocolType), createFunctionParameter( COMMON_IDENTIFIERS.context, ContextType, undefined, ), ], // parameters createPromiseType(createBufferType()), // return type [ // new Promise<{{typeName}}>((resolve, reject) => { ts.createReturn( createMethodCall( createMethodCall( createPromise( typeNodeForFieldType( funcDef.returnType, state, true, ), createVoidType(), [ // try { // resolve( // this._handler.{{name}}({{#args}}args.{{fieldName}}, {{/args}}context) // ) // } catch (e) { // reject(e) // } ts.createTry( ts.createBlock( [ ...createArgsVariable( funcDef, state, ), // input.readMessageEnd(); createMethodCallStatement( COMMON_IDENTIFIERS.input, 'readMessageEnd', ), createCallStatement( COMMON_IDENTIFIERS.resolve, [ createMethodCall( ts.createIdentifier( 'this._handler', ), funcDef.name.value, [ ...funcDef.fields.map( ( next: FieldDefinition, ) => { return ts.createIdentifier( `args.${next.name.value}`, ) }, ), COMMON_IDENTIFIERS.context, ], ), ], ), ], true, ), ts.createCatchClause( ts.createVariableDeclaration('err'), ts.createBlock( [ createCallStatement( COMMON_IDENTIFIERS.reject, [COMMON_IDENTIFIERS.err], ), ], true, ), ), undefined, ), ], ), COMMON_IDENTIFIERS.then, [ // }).then((data: {{typeName}}) => { ts.createArrowFunction( undefined, undefined, [ createFunctionParameter( COMMON_IDENTIFIERS.data, typeNodeForFieldType( funcDef.returnType, state, true, ), ), ], createBufferType(), undefined, ts.createBlock( [ // const result: StructType = {success: data} createConstStatement( COMMON_IDENTIFIERS.result, ts.createTypeReferenceNode( ts.createIdentifier( looseName( createStructResultName( funcDef, ), SyntaxType.StructDefinition, state, ), ), undefined, ), ts.createObjectLiteral([ ts.createPropertyAssignment( COMMON_IDENTIFIERS.success, COMMON_IDENTIFIERS.data, ), ]), ), // output.writeMessageBegin("{{name}}", Thrift.MessageType.REPLY, requestId) createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageBegin', [ ts.createLiteral( funcDef.name.value, ), MESSAGE_TYPE.REPLY, COMMON_IDENTIFIERS.requestId, ], ), // StructCodec.encode(result, output) createMethodCallStatement( ts.createIdentifier( toolkitName( createStructResultName( funcDef, ), state, ), ), 'encode', [ COMMON_IDENTIFIERS.result, COMMON_IDENTIFIERS.output, ], ), // output.writeMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageEnd', [], ), // return output.flush() ts.createReturn( ts.createCall( ts.createPropertyAccess( COMMON_IDENTIFIERS.output, 'flush', ), undefined, [], ), ), ], true, ), ), ], ), 'catch', [ ts.createArrowFunction( undefined, undefined, [ createFunctionParameter( COMMON_IDENTIFIERS.err, createErrorType(), ), ], createBufferType(), undefined, ts.createBlock( [ // if (def.throws.length > 0) ...createExceptionHandlers(funcDef, state), ], true, ), ), ], ), ), ], // body ) } function createArgsVariable( funcDef: FunctionDefinition, state: IRenderState, ): Array<ts.Statement> { if (funcDef.fields.length > 0) { // const args: type: StructType = StructCodec.decode(input) return [ createConstStatement( COMMON_IDENTIFIERS.args, ts.createTypeReferenceNode( ts.createIdentifier( strictName( createStructArgsName(funcDef), SyntaxType.StructDefinition, state, ), ), undefined, ), ts.createCall( ts.createPropertyAccess( ts.createIdentifier( toolkitName(createStructArgsName(funcDef), state), ), ts.createIdentifier('decode'), ), undefined, [COMMON_IDENTIFIERS.input], ), ), ] } else { return [] } } function createElseForExceptions( exp: FieldDefinition, remaining: Array<FieldDefinition>, funcDef: FunctionDefinition, state: IRenderState, ): ts.Statement { if (remaining.length > 0) { const [next, ...tail] = remaining return ts.createIf( ts.createBinary( COMMON_IDENTIFIERS.err, ts.SyntaxKind.InstanceOfKeyword, constructorNameForFieldType(next.fieldType, className, state), ), createThenForException(next, funcDef, state), createElseForExceptions(next, tail, funcDef, state), ) } else { return ts.createBlock( [ // const result: Thrift.TApplicationException = new thrift.TApplicationException(Thrift.TApplicationExceptionType.UNKNOWN, err.message) createConstStatement( COMMON_IDENTIFIERS.result, ts.createTypeReferenceNode( THRIFT_IDENTIFIERS.TApplicationException, undefined, ), createApplicationException( 'UNKNOWN', ts.createIdentifier('err.message'), ), ), // output.writeMessageBegin("{{name}}", Thrift.MessageType.EXCEPTION, requestId) createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageBegin', [ ts.createLiteral(funcDef.name.value), MESSAGE_TYPE.EXCEPTION, COMMON_IDENTIFIERS.requestId, ], ), // thrift.TApplicationExceptionCodec.encode(result, output) createMethodCallStatement( THRIFT_IDENTIFIERS.TApplicationExceptionCodec, 'encode', [COMMON_IDENTIFIERS.result, COMMON_IDENTIFIERS.output], ), // output.writeMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageEnd', ), // return output.flush() ts.createReturn( ts.createCall( ts.createPropertyAccess( COMMON_IDENTIFIERS.output, 'flush', ), undefined, [], ), ), ], true, ) } } function createThenForException( throwDef: FieldDefinition, funcDef: FunctionDefinition, state: IRenderState, ): ts.Statement { return ts.createBlock( [ // const result: {{throwType}} = new {{ServiceName}}{{nameTitleCase}}Result({{{throwName}}: err as {{throwType}}}); createConstStatement( COMMON_IDENTIFIERS.result, ts.createTypeReferenceNode( ts.createIdentifier( looseName( createStructResultName(funcDef), SyntaxType.StructDefinition, state, ), ), undefined, ), ts.createObjectLiteral([ ts.createPropertyAssignment( ts.createIdentifier(throwDef.name.value), COMMON_IDENTIFIERS.err, ), ]), ), // output.writeMessageBegin("{{name}}", Thrift.MessageType.REPLY, requestId) createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageBegin', [ ts.createLiteral(funcDef.name.value), MESSAGE_TYPE.REPLY, COMMON_IDENTIFIERS.requestId, ], ), // StructCodec.encode(result, output) createMethodCallStatement( ts.createIdentifier( toolkitName(createStructResultName(funcDef), state), ), 'encode', [COMMON_IDENTIFIERS.result, COMMON_IDENTIFIERS.output], ), // output.writeMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageEnd', ), // return output.flush() ts.createReturn( ts.createCall( ts.createPropertyAccess(COMMON_IDENTIFIERS.output, 'flush'), undefined, [], ), ), ], true, ) } function createIfForExceptions( exps: Array<FieldDefinition>, funcDef: FunctionDefinition, state: IRenderState, ): ts.Statement { const [throwDef, ...tail] = exps return ts.createIf( ts.createBinary( COMMON_IDENTIFIERS.err, ts.SyntaxKind.InstanceOfKeyword, constructorNameForFieldType(throwDef.fieldType, className, state), ), createThenForException(throwDef, funcDef, state), createElseForExceptions(throwDef, tail, funcDef, state), ) } function createExceptionHandlers( funcDef: FunctionDefinition, state: IRenderState, ): Array<ts.Statement> { if (funcDef.throws.length > 0) { // if (err instanceof {{throwType}}) { return [createIfForExceptions(funcDef.throws, funcDef, state)] } else { return [ // const result: Thrift.TApplicationException = new thrift.TApplicationException(Thrift.TApplicationExceptionType.UNKNOWN, err.message) createConstStatement( COMMON_IDENTIFIERS.result, ts.createTypeReferenceNode( THRIFT_IDENTIFIERS.TApplicationException, undefined, ), createApplicationException( 'UNKNOWN', ts.createIdentifier('err.message'), ), ), // output.writeMessageBegin("{{name}}", Thrift.MessageType.EXCEPTION, requestId) createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageBegin', [ ts.createLiteral(funcDef.name.value), MESSAGE_TYPE.EXCEPTION, COMMON_IDENTIFIERS.requestId, ], ), // thrift.TApplicationExceptionCodec.encode(result, output) createMethodCallStatement( THRIFT_IDENTIFIERS.TApplicationExceptionCodec, 'encode', [COMMON_IDENTIFIERS.result, COMMON_IDENTIFIERS.output], ), // output.writeMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageEnd', ), // return output.flush() ts.createReturn( ts.createCall( ts.createPropertyAccess(COMMON_IDENTIFIERS.output, 'flush'), undefined, [], ), ), ] } } // public process(input: TProtocol, output: TProtocol, context: Context): Promise<Buffer> { // const metadata = input.readMessageBegin() // const fieldName = metadata.fieldName; // const requestId = metadata.requestId; // const methodName: string = "process_" + fieldName; // switch (methodName) { // case "process_ping": // return this.process_ping(requestId, input, output, context) // // default: // ...skip logic // } // } function createProcessMethod( service: ServiceDefinition, state: IRenderState, ): ts.MethodDeclaration { return createPublicMethod( COMMON_IDENTIFIERS.process, [ createFunctionParameter(COMMON_IDENTIFIERS.input, TProtocolType), createFunctionParameter(COMMON_IDENTIFIERS.output, TProtocolType), createFunctionParameter( COMMON_IDENTIFIERS.context, ContextType, undefined, ), ], // parameters createPromiseType(createBufferType()), // return type [ ts.createReturn( createPromise(createBufferType(), createVoidType(), [ createConstStatement( COMMON_IDENTIFIERS.metadata, ts.createTypeReferenceNode( THRIFT_IDENTIFIERS.IThriftMessage, undefined, ), createMethodCall( COMMON_IDENTIFIERS.input, 'readMessageBegin', [], ), ), createConstStatement( COMMON_IDENTIFIERS.fieldName, createStringType(), ts.createPropertyAccess( COMMON_IDENTIFIERS.metadata, COMMON_IDENTIFIERS.fieldName, ), ), createConstStatement( COMMON_IDENTIFIERS.requestId, createNumberType(), ts.createPropertyAccess( COMMON_IDENTIFIERS.metadata, COMMON_IDENTIFIERS.requestId, ), ), createConstStatement( COMMON_IDENTIFIERS.methodName, createStringType(), ts.createBinary( ts.createLiteral('process_'), ts.SyntaxKind.PlusToken, COMMON_IDENTIFIERS.fieldName, ), ), createMethodCallForFname(service, state), ]), ), ], // body ) } function createMethodCallForFunction(func: FunctionDefinition): ts.CaseClause { const processMethodName: string = `process_${func.name.value}` return ts.createCaseClause(ts.createLiteral(processMethodName), [ ts.createBlock( [ ts.createStatement( ts.createCall(COMMON_IDENTIFIERS.resolve, undefined, [ createMethodCall( COMMON_IDENTIFIERS.this, processMethodName, [ COMMON_IDENTIFIERS.requestId, COMMON_IDENTIFIERS.input, COMMON_IDENTIFIERS.output, COMMON_IDENTIFIERS.context, ], ), ]), ), ts.createStatement(COMMON_IDENTIFIERS.break), ], true, ), ]) } /** * In Scrooge we did something like this: * * if (this["process_" + fieldName]) { * retrun this["process_" + fieldName].call(this, requestId, input, output, context) * } else { * ...skip logic * } * * When doing this we lose type safety. When we use the dynamic index access to call the method * the method and this are inferred to be of type any. * * We can maintain type safety through the generated code by removing the dynamic index access * and replace with a switch that will do static method calls. * * const methodName: string = "process_" + fieldName; * switch (methodName) { * case "process_ping": * return this.process_ping(requestId, input, output, context) * * default: * ...skip logic * } */ function createMethodCallForFname( service: ServiceDefinition, state: IRenderState, ): ts.SwitchStatement { return ts.createSwitch( COMMON_IDENTIFIERS.methodName, ts.createCaseBlock([ ...collectAllMethods(service, state).map( createMethodCallForFunction, ), ts.createDefaultClause([ ts.createBlock( [ // input.skip(Thrift.Type.STRUCT) createMethodCallStatement( COMMON_IDENTIFIERS.input, 'skip', [THRIFT_TYPES.STRUCT], ), // input.readMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.input, 'readMessageEnd', ), // const err = `Unknown function ${fieldName}` createConstStatement( ts.createIdentifier('errMessage'), undefined, ts.createBinary( ts.createLiteral('Unknown function '), ts.SyntaxKind.PlusToken, COMMON_IDENTIFIERS.fieldName, ), ), // const x = new Thrift.TApplicationException(Thrift.TApplicationExceptionType.UNKNOWN_METHOD, err) createConstStatement( COMMON_IDENTIFIERS.err, undefined, createApplicationException( 'UNKNOWN_METHOD', ts.createIdentifier('errMessage'), ), ), // output.writeMessageBegin(fieldName, Thrift.MessageType.EXCEPTION, requestId) createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageBegin', [ COMMON_IDENTIFIERS.fieldName, MESSAGE_TYPE.EXCEPTION, COMMON_IDENTIFIERS.requestId, ], ), // thrift.TApplicationExceptionCodec.encode(err, output) createMethodCallStatement( THRIFT_IDENTIFIERS.TApplicationExceptionCodec, 'encode', [COMMON_IDENTIFIERS.err, COMMON_IDENTIFIERS.output], ), // output.writeMessageEnd() createMethodCallStatement( COMMON_IDENTIFIERS.output, 'writeMessageEnd', ), // return output.flush() ts.createStatement( ts.createCall( COMMON_IDENTIFIERS.resolve, undefined, [ createMethodCall( COMMON_IDENTIFIERS.output, 'flush', ), ], ), ), ts.createStatement(COMMON_IDENTIFIERS.break), ], true, ), ]), ]), ) }
the_stack
import chunk from 'lodash/chunk' import flatMap from 'lodash/flatMap' import { getWellDepth } from '@opentrons/shared-data' import { AIR_GAP_OFFSET_FROM_TOP } from '../../constants' import * as errorCreators from '../../errorCreators' import { getPipetteWithTipMaxVol } from '../../robotStateSelectors' import type { ConsolidateArgs, CommandCreator, CurriedCommandCreator, } from '../../types' import { blowoutUtil, curryCommandCreator, reduceCommandCreators, } from '../../utils' import { airGap, aspirate, delay, dispense, dropTip, moveToWell, replaceTip, touchTip, } from '../atomic' import { mixUtil } from './mix' export const consolidate: CommandCreator<ConsolidateArgs> = ( args, invariantContext, prevRobotState ) => { /** Consolidate will aspirate several times in sequence from multiple source wells, then dispense into a single destination. If the volume to aspirate from the source wells exceeds the max volume of the pipette, then consolidate will be broken up into multiple asp-asp-disp, asp-asp-disp cycles. A single uniform volume will be aspirated from every source well. ===== For consolidate, changeTip means: * 'always': before the first aspirate in a single asp-asp-disp cycle, get a fresh tip * 'once': get a new tip at the beginning of the consolidate step, and use it throughout * 'never': reuse the tip from the last step */ const actionName = 'consolidate' const pipetteData = prevRobotState.pipettes[args.pipette] if (!pipetteData) { // bail out before doing anything else return { errors: [ errorCreators.pipetteDoesNotExist({ actionName, pipette: args.pipette, }), ], } } // TODO: BC 2019-07-08 these argument names are a bit misleading, instead of being values bound // to the action of aspiration of dispensing in a given command, they are actually values bound // to a given labware associated with a command (e.g. Source, Destination). For this reason we // currently remapping the inner mix values. Those calls to mixUtil should become easier to read // when we decide to rename these fields/args... probably all the way up to the UI level. const { aspirateDelay, aspirateFlowRateUlSec, aspirateOffsetFromBottomMm, blowoutFlowRateUlSec, blowoutOffsetFromTopMm, dispenseAirGapVolume, dispenseDelay, dispenseFlowRateUlSec, dispenseOffsetFromBottomMm, mixFirstAspirate, mixInDestination, } = args const aspirateAirGapVolume = args.aspirateAirGapVolume || 0 const maxWellsPerChunk = Math.floor( getPipetteWithTipMaxVol(args.pipette, invariantContext) / (args.volume + aspirateAirGapVolume) ) const sourceLabwareDef = invariantContext.labwareEntities[args.sourceLabware].def const destLabwareDef = invariantContext.labwareEntities[args.destLabware].def const airGapOffsetDestWell = getWellDepth(destLabwareDef, args.destWell) + AIR_GAP_OFFSET_FROM_TOP const sourceWellChunks = chunk(args.sourceWells, maxWellsPerChunk) const commandCreators = flatMap( sourceWellChunks, ( sourceWellChunk: string[], chunkIndex: number ): CurriedCommandCreator[] => { const isLastChunk = chunkIndex + 1 === sourceWellChunks.length // Aspirate commands for all source wells in the chunk const aspirateCommands = flatMap( sourceWellChunk, (sourceWell: string, wellIndex: number): CurriedCommandCreator[] => { const airGapOffsetSourceWell = getWellDepth(sourceLabwareDef, sourceWell) + AIR_GAP_OFFSET_FROM_TOP const airGapAfterAspirateCommands = aspirateAirGapVolume ? [ curryCommandCreator(airGap, { pipette: args.pipette, volume: aspirateAirGapVolume, labware: args.sourceLabware, well: sourceWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: airGapOffsetSourceWell, }), ...(aspirateDelay != null ? [ curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : []), ] : [] const delayAfterAspirateCommands = aspirateDelay != null ? [ curryCommandCreator(moveToWell, { pipette: args.pipette, labware: args.sourceLabware, well: sourceWell, offset: { x: 0, y: 0, z: aspirateDelay.mmFromBottom, }, }), curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : [] const touchTipAfterAspirateCommand = args.touchTipAfterAspirate ? [ curryCommandCreator(touchTip, { pipette: args.pipette, labware: args.sourceLabware, well: sourceWell, offsetFromBottomMm: args.touchTipAfterAspirateOffsetMmFromBottom, }), ] : [] return [ curryCommandCreator(aspirate, { pipette: args.pipette, volume: args.volume, labware: args.sourceLabware, well: sourceWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: aspirateOffsetFromBottomMm, }), ...delayAfterAspirateCommands, ...touchTipAfterAspirateCommand, ...airGapAfterAspirateCommands, ] } ) let tipCommands: CurriedCommandCreator[] = [] if ( args.changeTip === 'always' || (args.changeTip === 'once' && chunkIndex === 0) ) { tipCommands = [ curryCommandCreator(replaceTip, { pipette: args.pipette, }), ] } const touchTipAfterDispenseCommands: CurriedCommandCreator[] = args.touchTipAfterDispense ? [ curryCommandCreator(touchTip, { pipette: args.pipette, labware: args.destLabware, well: args.destWell, offsetFromBottomMm: args.touchTipAfterDispenseOffsetMmFromBottom, }), ] : [] const mixBeforeCommands = mixFirstAspirate != null ? mixUtil({ pipette: args.pipette, labware: args.sourceLabware, well: sourceWellChunk[0], volume: mixFirstAspirate.volume, times: mixFirstAspirate.times, aspirateOffsetFromBottomMm, dispenseOffsetFromBottomMm: aspirateOffsetFromBottomMm, aspirateFlowRateUlSec, dispenseFlowRateUlSec, aspirateDelaySeconds: aspirateDelay?.seconds, dispenseDelaySeconds: dispenseDelay?.seconds, }) : [] const preWetTipCommands = args.preWetTip // Pre-wet tip is equivalent to a single mix, with volume equal to the consolidate volume. ? mixUtil({ pipette: args.pipette, labware: args.sourceLabware, well: sourceWellChunk[0], volume: args.volume, times: 1, aspirateOffsetFromBottomMm, dispenseOffsetFromBottomMm: aspirateOffsetFromBottomMm, aspirateFlowRateUlSec, dispenseFlowRateUlSec, aspirateDelaySeconds: aspirateDelay?.seconds, dispenseDelaySeconds: dispenseDelay?.seconds, }) : [] const mixAfterCommands = mixInDestination != null ? mixUtil({ pipette: args.pipette, labware: args.destLabware, well: args.destWell, volume: mixInDestination.volume, times: mixInDestination.times, aspirateOffsetFromBottomMm: dispenseOffsetFromBottomMm, dispenseOffsetFromBottomMm, aspirateFlowRateUlSec, dispenseFlowRateUlSec, aspirateDelaySeconds: aspirateDelay?.seconds, dispenseDelaySeconds: dispenseDelay?.seconds, }) : [] const delayAfterDispenseCommands = dispenseDelay != null ? [ curryCommandCreator(moveToWell, { pipette: args.pipette, labware: args.destLabware, well: args.destWell, offset: { x: 0, y: 0, z: dispenseDelay.mmFromBottom, }, }), curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: dispenseDelay.seconds, }), ] : [] const willReuseTip = args.changeTip !== 'always' && !isLastChunk const airGapAfterDispenseCommands = dispenseAirGapVolume && !willReuseTip ? [ curryCommandCreator(airGap, { pipette: args.pipette, volume: dispenseAirGapVolume, labware: args.destLabware, well: args.destWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: airGapOffsetDestWell, }), ...(aspirateDelay != null ? [ curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : []), ] : [] // if using dispense > air gap, drop or change the tip at the end const dropTipAfterDispenseAirGap = airGapAfterDispenseCommands.length > 0 ? [ curryCommandCreator(dropTip, { pipette: args.pipette, }), ] : [] const blowoutCommand = blowoutUtil({ pipette: args.pipette, sourceLabwareId: args.sourceLabware, sourceWell: sourceWellChunk[0], destLabwareId: args.destLabware, destWell: args.destWell, blowoutLocation: args.blowoutLocation, flowRate: blowoutFlowRateUlSec, offsetFromTopMm: blowoutOffsetFromTopMm, invariantContext, }) return [ ...tipCommands, ...mixBeforeCommands, ...preWetTipCommands, // NOTE when you both mix-before and pre-wet tip, it's kinda redundant. Prewet is like mixing once. ...aspirateCommands, curryCommandCreator(dispense, { pipette: args.pipette, volume: args.volume * sourceWellChunk.length + aspirateAirGapVolume * sourceWellChunk.length, labware: args.destLabware, well: args.destWell, flowRate: dispenseFlowRateUlSec, offsetFromBottomMm: dispenseOffsetFromBottomMm, }), ...delayAfterDispenseCommands, ...mixAfterCommands, ...touchTipAfterDispenseCommands, ...blowoutCommand, ...airGapAfterDispenseCommands, ...dropTipAfterDispenseAirGap, ] } ) return reduceCommandCreators( commandCreators, invariantContext, prevRobotState ) }
the_stack
import {Mutable, Proto, AnyTiming, Timing} from "@swim/util"; import {FastenerContext, FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component"; import type { AnyConstraintExpression, ConstraintVariable, ConstraintProperty, ConstraintRelation, AnyConstraintStrength, Constraint, ConstraintScope, } from "@swim/constraint"; import {Look, Feel, Mood, MoodVector, ThemeMatrix, ThemeContext} from "@swim/theme"; import type {CssContext} from "./CssContext"; import {CssRule} from "./CssRule"; /** @public */ export interface StyleSheetInit extends FastenerInit { extends?: {prototype: StyleSheet<any>} | string | boolean | null; css?: string | (() => string | undefined); createStylesheet?(): CSSStyleSheet; initStylesheet?(stylesheet: CSSStyleSheet): void; } /** @public */ export type StyleSheetDescriptor<O = unknown, I = {}> = ThisType<StyleSheet<O> & I> & StyleSheetInit & Partial<I>; /** @public */ export interface StyleSheetClass<F extends StyleSheet<any> = StyleSheet<any>> extends FastenerClass<F> { } /** @public */ export interface StyleSheetFactory<F extends StyleSheet<any> = StyleSheet<any>> extends StyleSheetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): StyleSheetFactory<F> & I; define<O>(className: string, descriptor: StyleSheetDescriptor<O>): StyleSheetFactory<StyleSheet<any>>; define<O, I = {}>(className: string, descriptor: {implements: unknown} & StyleSheetDescriptor<O, I>): StyleSheetFactory<StyleSheet<any> & I>; <O>(descriptor: StyleSheetDescriptor<O>): PropertyDecorator; <O, I = {}>(descriptor: {implements: unknown} & StyleSheetDescriptor<O, I>): PropertyDecorator; } /** @public */ export interface StyleSheet<O = unknown> extends Fastener<O>, FastenerContext, ConstraintScope, ThemeContext, CssContext { /** @override */ get fastenerType(): Proto<StyleSheet<any>>; readonly stylesheet: CSSStyleSheet; /** @override */ getRule(index: number): CSSRule | null; /** @override */ insertRule(cssText: string, index?: number): number; /** @override */ removeRule(index: number): void; /** @internal */ readonly fasteners: {[fastenerName: string]: Fastener | undefined} | null; /** @override */ hasFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean; /** @override */ getFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @override */ setFastener(fastenerName: string, fastener: Fastener | null): void; /** @override */ getLazyFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @override */ getSuperFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; /** @internal @override */ getSuperFastener(): Fastener | null; /** @internal @protected */ mountFasteners(): void; /** @internal @protected */ unmountFasteners(): void; /** @override */ requireUpdate(updateFlags: number): void; /** @internal */ readonly decoherent: ReadonlyArray<Fastener> | null; /** @override */ decohereFastener(fastener: Fastener): void; /** @override */ recohere(t: number): void /** @internal @protected */ recohereFasteners(t: number): void /** @override */ constraint(lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint; /** @override */ hasConstraint(constraint: Constraint): boolean; /** @override */ addConstraint(constraint: Constraint): void; /** @override */ removeConstraint(constraint: Constraint): void; /** @override */ constraintVariable(name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number>; /** @override */ hasConstraintVariable(variable: ConstraintVariable): boolean; /** @override */ addConstraintVariable(variable: ConstraintVariable): void; /** @override */ removeConstraintVariable(variable: ConstraintVariable): void; /** @internal @override */ setConstraintVariable(constraintVariable: ConstraintVariable, state: number): void; /** @override */ getLook<T>(look: Look<T, unknown>, mood?: MoodVector<Feel> | null): T | undefined; /** @override */ getLookOr<T, E>(look: Look<T, unknown>, elseValue: E): T | E; /** @override */ getLookOr<T, E>(look: Look<T, unknown>, mood: MoodVector<Feel> | null, elseValue: E): T | E; applyTheme(theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean | null): void; /** @protected @override */ onMount(): void; /** @protected @override */ onUnmount(): void; /** @internal */ createStylesheet(): CSSStyleSheet; /** @internal */ initStylesheet?(stylesheet: CSSStyleSheet): void; /** @internal */ initCss?(): string | undefined; } /** @public */ export const StyleSheet = (function (_super: typeof Fastener) { const StyleSheet: StyleSheetFactory = _super.extend("StyleSheet"); Object.defineProperty(StyleSheet.prototype, "fastenerType", { get: function (this: StyleSheet): Proto<StyleSheet<any>> { return StyleSheet; }, configurable: true, }); StyleSheet.prototype.getRule = function (this: StyleSheet, index: number): CSSRule | null { return this.stylesheet.cssRules.item(index); }; StyleSheet.prototype.insertRule = function (this: StyleSheet, cssText: string, index?: number): number { return this.stylesheet.insertRule(cssText, index); }; StyleSheet.prototype.removeRule = function (this: StyleSheet, index: number): void { this.stylesheet.deleteRule(index); }; StyleSheet.prototype.hasFastener = function (this: StyleSheet, fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return true; } } return false; }; StyleSheet.prototype.getFastener = function (this: StyleSheet, fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return fastener; } } return null; }; StyleSheet.prototype.setFastener = function (this: StyleSheet, fastenerName: string, newFastener: Fastener | null): void { let fasteners = this.fasteners; if (fasteners === null) { fasteners = {}; (this as Mutable<typeof this>).fasteners = fasteners; } const oldFastener = fasteners[fastenerName]; if (oldFastener !== void 0 && this.mounted) { oldFastener.unmount(); } if (newFastener !== null) { fasteners[fastenerName] = newFastener; if (this.mounted) { newFastener.mount(); } } else { delete fasteners[fastenerName]; } }; StyleSheet.prototype.getLazyFastener = function (this: StyleSheet, fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { return FastenerContext.getLazyFastener(this, fastenerName, fastenerBound); }; StyleSheet.prototype.getSuperFastener = function (this: StyleSheet, fastenerName?: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { if (arguments.length === 0) { return _super.prototype.getSuperFastener.call(this); } else { return null; } }; StyleSheet.prototype.mountFasteners = function (this: StyleSheet): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.mount(); } }; StyleSheet.prototype.unmountFasteners = function (this: StyleSheet): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.unmount(); } }; StyleSheet.prototype.requireUpdate = function (this: StyleSheet, updateFlags: number): void { const fastenerContext = this.owner; if (FastenerContext.has(fastenerContext, "requireUpdate")) { fastenerContext.requireUpdate(updateFlags); } }; StyleSheet.prototype.decohereFastener = function (this: StyleSheet, fastener: Fastener): void { let decoherent = this.decoherent as Fastener[]; if (decoherent === null) { decoherent = []; (this as Mutable<typeof this>).decoherent = decoherent; } decoherent.push(fastener); if ((this.flags & Fastener.DecoherentFlag) === 0) { this.setCoherent(false); this.decohere(); } }; StyleSheet.prototype.recohereFasteners = function (this: StyleSheet, t: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { (this as Mutable<typeof this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; fastener.recohere(t); } } } }; StyleSheet.prototype.recohere = function (this: StyleSheet, t: number): void { this.recohereFasteners(t); if (this.decoherent === null || this.decoherent.length === 0) { this.setCoherent(true); } else { this.setCoherent(false); this.decohere(); } }; StyleSheet.prototype.constraint = function (this: StyleSheet<ConstraintScope>, lhs: AnyConstraintExpression, relation: ConstraintRelation, rhs?: AnyConstraintExpression, strength?: AnyConstraintStrength): Constraint { return this.owner.constraint(lhs, relation, rhs, strength); }; StyleSheet.prototype.hasConstraint = function (this: StyleSheet<ConstraintScope>, constraint: Constraint): boolean { return this.owner.hasConstraint(constraint); }; StyleSheet.prototype.addConstraint = function (this: StyleSheet<ConstraintScope>, constraint: Constraint): void { this.owner.addConstraint(constraint); }; StyleSheet.prototype.removeConstraint = function (this: StyleSheet<ConstraintScope>, constraint: Constraint): void { this.owner.removeConstraint(constraint); }; StyleSheet.prototype.constraintVariable = function (this: StyleSheet<ConstraintScope>, name: string, value?: number, strength?: AnyConstraintStrength): ConstraintProperty<unknown, number> { return this.owner.constraintVariable(name, value, strength); }; StyleSheet.prototype.hasConstraintVariable = function (this: StyleSheet<ConstraintScope>, constraintVariable: ConstraintVariable): boolean { return this.owner.hasConstraintVariable(constraintVariable); }; StyleSheet.prototype.addConstraintVariable = function (this: StyleSheet<ConstraintScope>, constraintVariable: ConstraintVariable): void { this.owner.addConstraintVariable(constraintVariable); }; StyleSheet.prototype.removeConstraintVariable = function (this: StyleSheet<ConstraintScope>, constraintVariable: ConstraintVariable): void { this.owner.removeConstraintVariable(constraintVariable); }; StyleSheet.prototype.setConstraintVariable = function (this: StyleSheet<ConstraintScope>, constraintVariable: ConstraintVariable, state: number): void { this.owner.setConstraintVariable(constraintVariable, state); }; StyleSheet.prototype.getLook = function <T>(this: StyleSheet, look: Look<T, unknown>, mood?: MoodVector<Feel> | null): T | undefined { const themeContext = this.owner; if (ThemeContext.is(themeContext)) { return themeContext.getLook(look, mood); } else { return void 0; } }; StyleSheet.prototype.getLookOr = function <T, E>(this: StyleSheet, look: Look<T, unknown>, mood: MoodVector<Feel> | null | E, elseValue?: E): T | E { const themeContext = this.owner; if (ThemeContext.is(themeContext)) { if (arguments.length === 2) { return themeContext.getLookOr(look, mood as E); } else { return themeContext.getLookOr(look, mood as MoodVector<Feel> | null, elseValue!); } } else if (arguments.length === 2) { return mood as E; } else { return elseValue!; } }; StyleSheet.prototype.applyTheme = function (this: StyleSheet, theme: ThemeMatrix, mood: MoodVector, timing?: AnyTiming | boolean | null): void { if (timing === void 0 || timing === true) { timing = theme.getOr(Look.timing, Mood.ambient, false); } else { timing = Timing.fromAny(timing); } const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; if (fastener instanceof CssRule) { fastener.applyTheme(theme, mood, timing); } } }; StyleSheet.prototype.onMount = function (this: StyleSheet): void { _super.prototype.onMount.call(this); this.mountFasteners(); }; StyleSheet.prototype.onUnmount = function (this: StyleSheet): void { this.unmountFasteners(); _super.prototype.onUnmount.call(this); }; StyleSheet.prototype.createStylesheet = function (this: StyleSheet): CSSStyleSheet { return new CSSStyleSheet(); }; StyleSheet.construct = function <F extends StyleSheet<any>>(sheetClass: {prototype: F}, sheet: F | null, owner: FastenerOwner<F>): F { sheet = _super.construct(sheetClass, sheet, owner) as F; (sheet as Mutable<typeof sheet>).fasteners = null; (sheet as Mutable<typeof sheet>).decoherent = null; (sheet as Mutable<typeof sheet>).stylesheet = null as unknown as CSSStyleSheet; FastenerContext.init(sheet); return sheet; }; StyleSheet.define = function <O>(className: string, descriptor: StyleSheetDescriptor<O>): StyleSheetFactory<StyleSheet<any>> { let superClass = descriptor.extends as StyleSheetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; let css = descriptor.css; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.css; if (superClass === void 0 || superClass === null) { superClass = this; } const sheetClass = superClass.extend(className, descriptor); if (typeof css === "function") { sheetClass.prototype.initCss = css; css = void 0; } sheetClass.construct = function (sheetClass: {prototype: StyleSheet<any>}, sheet: StyleSheet<O> | null, owner: O): StyleSheet<O> { sheet = superClass!.construct(sheetClass, sheet, owner); if (affinity !== void 0) { sheet.initAffinity(affinity); } if (inherits !== void 0) { sheet.initInherits(inherits); } //let cssText: string | undefined; //if (css !== void 0) { // cssText = css as string; //} else if (sheet.initCss !== void 0) { // cssText = sheet.initCss(); //} (sheet as Mutable<typeof sheet>).stylesheet = sheet.createStylesheet(); if (sheet.initStylesheet !== void 0) { sheet.initStylesheet(sheet.stylesheet); } return sheet; }; return sheetClass; }; return StyleSheet; })(Fastener);
the_stack
import { take } from "rxjs/operators"; import { IBApi, IBApiNext, IBApiNextError, EventName } from "../../.."; describe("RxJS Wrapper: getAccountSummary()", () => { test("Error Event", (done) => { const apiNext = new IBApiNext(); const api = ((apiNext as unknown) as Record<string, unknown>).api as IBApi; // emit a error event and verify RxJS result const testValue = "We want this error"; apiNext .getAccountSummary("All", "NetLiquidation") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: () => { fail(); }, error: (error: IBApiNextError) => { expect(error.error.message).toEqual(testValue); done(); }, }); api.emit(EventName.error, new Error(testValue), -1, 1); }); test("Update multicast", (done) => { const apiNext = new IBApiNext(); const api = ((apiNext as unknown) as Record<string, unknown>).api as IBApi; // testing values const accountId1 = "DU123456"; const accountId2 = "DU123456"; const currency = "USD"; const testValueReqId1 = "1111111"; // emit as accountSummary event and verify all subscribers receive it // reqId 1 (All / NetLiquidation): let receivedNetLiquidation = 0; let receivedTotalCashValue = 0; apiNext .getAccountSummary("All", "NetLiquidation") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.all.get(accountId1)?.get("NetLiquidation")?.get(currency) ?.value ).toEqual(testValueReqId1); receivedNetLiquidation++; if (receivedNetLiquidation == 2 && receivedTotalCashValue == 2) { done(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); apiNext .getAccountSummary("All", "NetLiquidation") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.all.get(accountId1)?.get("NetLiquidation")?.get(currency) ?.value ).toEqual(testValueReqId1); receivedNetLiquidation++; if (receivedNetLiquidation == 2 && receivedTotalCashValue == 2) { done(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); // reqId 2 (used on All / TotalCashValue): apiNext .getAccountSummary("All", "TotalCashValue") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.all.get(accountId2)?.get("TotalCashValue")?.get(currency) ?.value ).toEqual(testValueReqId1); receivedTotalCashValue++; if (receivedNetLiquidation == 2 && receivedTotalCashValue == 2) { done(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); apiNext .getAccountSummary("All", "TotalCashValue") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.all.get(accountId2)?.get("TotalCashValue")?.get(currency) ?.value ).toEqual(testValueReqId1); receivedTotalCashValue++; if (receivedNetLiquidation == 2 && receivedTotalCashValue == 2) { done(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); api.emit( EventName.accountSummary, 1, accountId1, "NetLiquidation", testValueReqId1, currency ); api.emit( EventName.accountSummary, 2, accountId2, "TotalCashValue", testValueReqId1, currency ); }); test("Aggregate into all", (done) => { const apiNext = new IBApiNext(); const api = ((apiNext as unknown) as Record<string, unknown>).api as IBApi; // testing values const accountId1 = "DU123456"; const accountId2 = "DU654321"; const tagName1 = "NetLiquidation"; const tagName2 = "TotalCashValue"; const currency1 = "USD"; const currency1Value = "1111111"; const currency2 = "EUR"; const currency2Value = "2222222"; // emit a accountSummary events and verify RxJS result apiNext .getAccountSummary("All", `${tagName1},${tagName2}`) // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect(update.all).toBeDefined(); expect(update.added).toBeDefined(); expect(update.added.size).toEqual(1); let totalValuesCount = 0; update.all.forEach((tagValues) => tagValues.forEach((currencyValues) => { totalValuesCount += currencyValues.size; }) ); switch (totalValuesCount) { case 6: expect( update.all.get(accountId2)?.get(tagName2)?.get(currency2)?.value ).toEqual(currency2Value); // no break by intention case 5: expect( update.all.get(accountId2)?.get(tagName2)?.get(currency1)?.value ).toEqual(currency1Value); // no break by intention case 4: expect( update.all.get(accountId2)?.get(tagName1)?.get(currency2)?.value ).toEqual(currency2Value); // no break by intention case 3: expect( update.all.get(accountId2)?.get(tagName1)?.get(currency1)?.value ).toEqual(currency1Value); // no break by intention case 2: expect( update.all.get(accountId1)?.get(tagName1)?.get(currency2)?.value ).toEqual(currency2Value); // no break by intention case 1: expect( update.all.get(accountId1)?.get(tagName1)?.get(currency1)?.value ).toEqual(currency1Value); break; } if (totalValuesCount === 6) { done(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); // emit values api.emit( EventName.accountSummary, 1, accountId1, tagName1, currency1Value, currency1 ); api.emit( EventName.accountSummary, 1, accountId1, tagName1, currency2Value, currency2 ); api.emit( EventName.accountSummary, 1, accountId2, tagName1, currency1Value, currency1 ); api.emit( EventName.accountSummary, 1, accountId2, tagName1, currency2Value, currency2 ); api.emit( EventName.accountSummary, 1, accountId2, tagName2, currency1Value, currency1 ); api.emit( EventName.accountSummary, 1, accountId2, tagName2, currency2Value, currency2 ); }); test("Detected changes", (done) => { const apiNext = new IBApiNext(); const api = ((apiNext as unknown) as Record<string, unknown>).api as IBApi; // testing values const accountId = "DU123456"; const tagName = "NetLiquidation"; const currency = "USD"; const testValue1 = "1111111"; const testValue2 = "2222222"; // emit a accountSummary events and verify RxJS result apiNext .getAccountSummary("All", "NetLiquidation") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { if (update.added?.size) { expect( update.added.get(accountId)?.get(tagName)?.get(currency)?.value ).toEqual(testValue1); } else if (update.changed?.size) { expect( update.changed.get(accountId)?.get(tagName)?.get(currency)?.value ).toEqual(testValue2); done(); } else { fail(); } }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); api.emit( EventName.accountSummary, 1, accountId, tagName, testValue1, currency ); api.emit( EventName.accountSummary, 1, accountId, tagName, testValue2, currency ); }); test("Initial value replay to late observers", (done) => { // create IBApiNext and reqId counter const apiNext = new IBApiNext(); const api = ((apiNext as unknown) as Record<string, unknown>).api as IBApi; // testing values const accountId = "DU123456"; const tagName = "NetLiquidation"; const currency = "USD"; const testValue = "1111111"; // emit a single accountSummary event and verify that subscribers which join afterwards get it via initial event apiNext .getAccountSummary("All", "NetLiquidation") // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.added.get(accountId)?.get(tagName)?.get(currency)?.value ).toEqual(testValue); apiNext .getAccountSummary("All", "NetLiquidation") .pipe(take(1)) // eslint-disable-next-line rxjs/no-ignored-subscription .subscribe({ next: (update) => { expect( update.added.get(accountId)?.get(tagName)?.get(currency) ?.value ).toEqual(testValue); done(); }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); }, error: (error: IBApiNextError) => { fail(error.error.message); }, }); api.emit( EventName.accountSummary, 1, accountId, tagName, testValue, currency ); }); });
the_stack
require("./index.scss"); require("datatables.net-dt/css/jquery.dataTables.css"); require("datatables.net"); //@ts-ignore (jquery _does_ expose a default. In es6, it's the one we should use) import $ from "jquery"; import Parser from "../../parsers"; import { escape } from "lodash-es"; import { Plugin, DownloadInfo } from "../"; import Yasr from "../../"; import { drawSvgStringAsElement, drawFontAwesomeIconAsSvg, addClass, removeClass } from "@triply/yasgui-utils"; import * as faTableIcon from "@fortawesome/free-solid-svg-icons/faTable"; import { DeepReadonly } from "ts-essentials"; import { cloneDeep } from "lodash-es"; const ColumnResizer = require("column-resizer"); const DEFAULT_PAGE_SIZE = 50; export interface PluginConfig { openIriInNewWindow: boolean; tableConfig: DataTables.Settings; } export interface PersistentConfig { pageSize?: number; compact?: boolean; isEllipsed?: boolean; } type DataRow = [number, ...(Parser.BindingValue | "")[]]; function expand(this: HTMLDivElement, event: MouseEvent) { addClass(this, "expanded"); event.preventDefault(); } export default class Table implements Plugin<PluginConfig> { private config: DeepReadonly<PluginConfig>; private persistentConfig: PersistentConfig = {}; private yasr: Yasr; private tableControls: Element | undefined; private tableEl: HTMLTableElement | undefined; private dataTable: DataTables.Api | undefined; private tableFilterField: HTMLInputElement | undefined; private tableSizeField: HTMLSelectElement | undefined; private tableCompactSwitch: HTMLInputElement | undefined; private tableEllipseSwitch: HTMLInputElement | undefined; private tableResizer: | { reset: (options: { disable: boolean; onResize?: () => void; partialRefresh?: boolean; headerOnly?: boolean; }) => void; onResize: () => {}; } | undefined; public helpReference = "https://triply.cc/docs/yasgui#table"; public label = "Table"; public priority = 10; public getIcon() { return drawSvgStringAsElement(drawFontAwesomeIconAsSvg(faTableIcon)); } constructor(yasr: Yasr) { this.yasr = yasr; //TODO read options from constructor this.config = Table.defaults; } public static defaults: PluginConfig = { openIriInNewWindow: true, tableConfig: { dom: "tip", // tip: Table, Page Information and Pager, change to ipt for showing pagination on top pageLength: DEFAULT_PAGE_SIZE, //default page length lengthChange: true, //allow changing page length data: [], columns: [], order: [], deferRender: true, orderClasses: false, language: { paginate: { first: "&lt;&lt;", // Have to specify these two due to TS defs, << last: "&gt;&gt;", // Have to specify these two due to TS defs, >> next: "&gt;", // > previous: "&lt;", // < }, }, }, }; private getRows(): DataRow[] { if (!this.yasr.results) return []; const bindings = this.yasr.results.getBindings(); if (!bindings) return []; // Vars decide the columns const vars = this.yasr.results.getVariables(); // Use "" as the empty value, undefined will throw runtime errors return bindings.map((binding, rowId) => [rowId + 1, ...vars.map((variable) => binding[variable] ?? "")]); } private getUriLinkFromBinding(binding: Parser.BindingValue, prefixes?: { [key: string]: string }) { const href = binding.value; let visibleString = href; let prefixed = false; if (prefixes) { for (const prefixLabel in prefixes) { if (visibleString.indexOf(prefixes[prefixLabel]) == 0) { visibleString = prefixLabel + ":" + href.substring(prefixes[prefixLabel].length); prefixed = true; break; } } } // Hide brackets when prefixed or compact const hideBrackets = prefixed || this.persistentConfig.compact; return `${hideBrackets ? "" : "&lt;"}<a class='iri' target='${ this.config.openIriInNewWindow ? "_blank" : "_self" }'${this.config.openIriInNewWindow ? " ref='noopener noreferrer'" : ""} href='${href}'>${visibleString}</a>${ hideBrackets ? "" : "&gt;" }`; } private getCellContent(binding: Parser.BindingValue, prefixes?: { [label: string]: string }): string { let content: string; if (binding.type == "uri") { content = `<span>${this.getUriLinkFromBinding(binding, prefixes)}</span>`; } else { content = `<span class='nonIri'>${this.formatLiteral(binding, prefixes)}</span>`; } return `<div>${content}</div>`; } private formatLiteral(literalBinding: Parser.BindingValue, prefixes?: { [key: string]: string }) { let stringRepresentation = escape(literalBinding.value); // Return now when in compact mode. if (this.persistentConfig.compact) return stringRepresentation; if (literalBinding["xml:lang"]) { stringRepresentation = `"${stringRepresentation}"<sup>@${literalBinding["xml:lang"]}</sup>`; } else if (literalBinding.datatype) { const dataType = this.getUriLinkFromBinding({ type: "uri", value: literalBinding.datatype }, prefixes); stringRepresentation = `"${stringRepresentation}"<sup>^^${dataType}</sup>`; } return stringRepresentation; } private getColumns(): DataTables.ColumnSettings[] { if (!this.yasr.results) return []; const prefixes = this.yasr.getPrefixes(); return [ { name: "", searchable: false, width: `${this.getSizeFirstColumn()}px`, type: "num", orderable: false, visible: this.persistentConfig.compact !== true, render: (data: number, type: any) => type === "filter" || type === "sort" || !type ? data : `<div class="rowNumber">${data}</div>`, }, //prepend with row numbers column ...this.yasr.results?.getVariables().map((name) => { return <DataTables.ColumnSettings>{ name: name, title: name, render: (data: Parser.BindingValue | "", type: any, _row: any, _meta: DataTables.CellMetaSettings) => { // Handle empty rows if (data === "") return data; if (type === "filter" || type === "sort" || !type) return data.value; return this.getCellContent(data, prefixes); }, }; }), ]; } private getSizeFirstColumn() { const numResults = this.yasr.results?.getBindings()?.length || 0; return numResults.toString().length * 8; } public draw(persistentConfig: PersistentConfig) { this.persistentConfig = { ...this.persistentConfig, ...persistentConfig }; this.tableEl = document.createElement("table"); const rows = this.getRows(); const columns = this.getColumns(); if (rows.length <= (persistentConfig?.pageSize || DEFAULT_PAGE_SIZE)) { this.yasr.pluginControls; addClass(this.yasr.rootEl, "isSinglePage"); } else { removeClass(this.yasr.rootEl, "isSinglePage"); } if (this.dataTable) { this.destroyResizer(); this.dataTable.destroy(true); this.dataTable = undefined; } this.yasr.resultsEl.appendChild(this.tableEl); // reset some default config properties as they couldn't be initialized beforehand const dtConfig: DataTables.Settings = { ...((cloneDeep(this.config.tableConfig) as unknown) as DataTables.Settings), pageLength: persistentConfig?.pageSize ? persistentConfig.pageSize : DEFAULT_PAGE_SIZE, data: rows, columns: columns, }; this.dataTable = $(this.tableEl).DataTable(dtConfig); this.tableEl.style.removeProperty("width"); this.tableEl.style.width = this.tableEl.clientWidth + "px"; const widths = Array.from(this.tableEl.querySelectorAll("th")).map((h) => h.offsetWidth - 26); this.tableResizer = new ColumnResizer.default(this.tableEl, { widths: this.persistentConfig.compact === true ? widths : [this.getSizeFirstColumn(), ...widths.slice(1)], partialRefresh: true, onResize: this.persistentConfig.isEllipsed !== false && this.setEllipsisHandlers, headerOnly: true, }); // DataTables uses the rendered style to decide the widths of columns. // Before a draw remove the ellipseTable styling if (this.persistentConfig.isEllipsed !== false) { this.dataTable?.on("preDraw", () => { this.tableResizer?.reset({ disable: true }); removeClass(this.tableEl, "ellipseTable"); this.tableEl?.style.removeProperty("width"); this.tableEl?.style.setProperty("width", this.tableEl.clientWidth + "px"); return true; // Indicate it should re-render }); // After a draw this.dataTable?.on("draw", () => { if (!this.tableEl) return; // Width of table after render, removing width will make it fall back to 100% let targetSize = this.tableEl.clientWidth; this.tableEl.style.removeProperty("width"); // Let's make sure the new size is not bigger if (targetSize > this.tableEl.clientWidth) targetSize = this.tableEl.clientWidth; this.tableEl?.style.setProperty("width", `${targetSize}px`); // Enable the re-sizer this.tableResizer?.reset({ disable: false, partialRefresh: true, onResize: this.setEllipsisHandlers, headerOnly: true, }); // Re-add the ellipsis addClass(this.tableEl, "ellipseTable"); // Check if cells need the ellipsisHandlers this.setEllipsisHandlers(); }); } this.drawControls(); // Draw again but with the events if (this.persistentConfig.isEllipsed !== false) { addClass(this.tableEl, "ellipseTable"); this.setEllipsisHandlers(); } // if (this.tableEl.clientWidth > width) this.tableEl.parentElement?.style.setProperty("overflow", "hidden"); } private setEllipsisHandlers = () => { this.dataTable?.cells({ page: "current" }).every((rowIdx, colIdx) => { const cell = this.dataTable?.cell(rowIdx, colIdx); if (cell?.data() === "") return; const cellNode = cell?.node() as HTMLTableCellElement; if (cellNode) { const content = cellNode.firstChild as HTMLDivElement; if ((content.firstElementChild?.getBoundingClientRect().width || 0) > content.getBoundingClientRect().width) { if (!content.classList.contains("expandable")) { addClass(content, "expandable"); content.addEventListener("click", expand, { once: true }); } } else { if (content.classList.contains("expandable")) { removeClass(content, "expandable"); content.removeEventListener("click", expand); } } } }); }; private handleTableSearch = (event: KeyboardEvent) => { this.dataTable?.search((event.target as HTMLInputElement).value).draw("page"); }; private handleTableSizeSelect = (event: Event) => { const pageLength = parseInt((event.target as HTMLSelectElement).value); // Set page length this.dataTable?.page.len(pageLength).draw("page"); // Store in persistentConfig this.persistentConfig.pageSize = pageLength; this.yasr.storePluginConfig("table", this.persistentConfig); }; private handleSetCompactToggle = (event: Event) => { // Store in persistentConfig this.persistentConfig.compact = (event.target as HTMLInputElement).checked; // Update the table this.draw(this.persistentConfig); this.yasr.storePluginConfig("table", this.persistentConfig); }; private handleSetEllipsisToggle = (event: Event) => { // Store in persistentConfig this.persistentConfig.isEllipsed = (event.target as HTMLInputElement).checked; // Update the table this.draw(this.persistentConfig); this.yasr.storePluginConfig("table", this.persistentConfig); }; /** * Draws controls on each update */ drawControls() { // Remove old header this.removeControls(); this.tableControls = document.createElement("div"); this.tableControls.className = "tableControls"; // Compact switch const toggleWrapper = document.createElement("div"); const switchComponent = document.createElement("label"); const textComponent = document.createElement("span"); textComponent.innerText = "Simple view"; addClass(textComponent, "label"); switchComponent.appendChild(textComponent); addClass(switchComponent, "switch"); toggleWrapper.appendChild(switchComponent); this.tableCompactSwitch = document.createElement("input"); switchComponent.addEventListener("change", this.handleSetCompactToggle); this.tableCompactSwitch.type = "checkbox"; switchComponent.appendChild(this.tableCompactSwitch); this.tableCompactSwitch.defaultChecked = !!this.persistentConfig.compact; this.tableControls.appendChild(toggleWrapper); // Ellipsis switch const ellipseToggleWrapper = document.createElement("div"); const ellipseSwitchComponent = document.createElement("label"); const ellipseTextComponent = document.createElement("span"); ellipseTextComponent.innerText = "Ellipse"; addClass(ellipseTextComponent, "label"); ellipseSwitchComponent.appendChild(ellipseTextComponent); addClass(ellipseSwitchComponent, "switch"); ellipseToggleWrapper.appendChild(ellipseSwitchComponent); this.tableEllipseSwitch = document.createElement("input"); ellipseSwitchComponent.addEventListener("change", this.handleSetEllipsisToggle); this.tableEllipseSwitch.type = "checkbox"; ellipseSwitchComponent.appendChild(this.tableEllipseSwitch); this.tableEllipseSwitch.defaultChecked = this.persistentConfig.isEllipsed !== false; this.tableControls.appendChild(ellipseToggleWrapper); // Create table filter this.tableFilterField = document.createElement("input"); this.tableFilterField.className = "tableFilter"; this.tableFilterField.placeholder = "Filter query results"; this.tableFilterField.setAttribute("aria-label", "Filter query results"); this.tableControls.appendChild(this.tableFilterField); this.tableFilterField.addEventListener("keyup", this.handleTableSearch); // Create page wrapper const pageSizerWrapper = document.createElement("div"); pageSizerWrapper.className = "pageSizeWrapper"; // Create label for page size element const pageSizerLabel = document.createElement("span"); pageSizerLabel.textContent = "Page size: "; pageSizerLabel.className = "pageSizerLabel"; pageSizerWrapper.appendChild(pageSizerLabel); // Create page size element this.tableSizeField = document.createElement("select"); this.tableSizeField.className = "tableSizer"; // Create options for page sizer const options = [10, 50, 100, 1000, -1]; for (const option of options) { const element = document.createElement("option"); element.value = option + ""; // -1 selects everything so we should call it All element.innerText = option > 0 ? option + "" : "All"; // Set initial one as selected if (this.dataTable?.page.len() === option) element.selected = true; this.tableSizeField.appendChild(element); } pageSizerWrapper.appendChild(this.tableSizeField); this.tableSizeField.addEventListener("change", this.handleTableSizeSelect); this.tableControls.appendChild(pageSizerWrapper); this.yasr.pluginControls.appendChild(this.tableControls); } download(filename?: string) { return { getData: () => this.yasr.results?.asCsv() || "", contentType: "text/csv", title: "Download result", filename: `${filename || "queryResults"}.csv`, } as DownloadInfo; } public canHandleResults() { return !!this.yasr.results && this.yasr.results.getVariables() && this.yasr.results.getVariables().length > 0; } private removeControls() { // Unregister listeners and remove references to old fields this.tableFilterField?.removeEventListener("keyup", this.handleTableSearch); this.tableFilterField = undefined; this.tableSizeField?.removeEventListener("change", this.handleTableSizeSelect); this.tableSizeField = undefined; this.tableCompactSwitch?.removeEventListener("change", this.handleSetCompactToggle); this.tableCompactSwitch = undefined; this.tableEllipseSwitch?.removeEventListener("change", this.handleSetEllipsisToggle); this.tableEllipseSwitch = undefined; // Empty controls while (this.tableControls?.firstChild) this.tableControls.firstChild.remove(); this.tableControls?.remove(); } private destroyResizer() { if (this.tableResizer) { this.tableResizer.reset({ disable: true }); window.removeEventListener("resize", this.tableResizer.onResize); this.tableResizer = undefined; } } destroy() { this.removeControls(); this.destroyResizer(); // According to datatables docs, destroy(true) will also remove all events this.dataTable?.destroy(true); this.dataTable = undefined; removeClass(this.yasr.rootEl, "isSinglePage"); } }
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterator, empty } from '@lumino/algorithm'; import { IObservableDisposable } from '@lumino/disposable'; import { ConflatableMessage, IMessageHandler, Message, MessageLoop } from '@lumino/messaging'; import { AttachedProperty } from '@lumino/properties'; import { ISignal, Signal } from '@lumino/signaling'; import { Layout } from './layout'; import { Title } from './title'; /** * The base class of the lumino widget hierarchy. * * #### Notes * This class will typically be subclassed in order to create a useful * widget. However, it can be used directly to host externally created * content. */ export class Widget implements IMessageHandler, IObservableDisposable { /** * Construct a new widget. * * @param options - The options for initializing the widget. */ constructor(options: Widget.IOptions = {}) { this.node = Private.createNode(options); this.addClass('lm-Widget'); /* <DEPRECATED> */ this.addClass('p-Widget'); /* </DEPRECATED> */ } /** * Dispose of the widget and its descendant widgets. * * #### Notes * It is unsafe to use the widget after it has been disposed. * * All calls made to this method after the first are a no-op. */ dispose(): void { // Do nothing if the widget is already disposed. if (this.isDisposed) { return; } // Set the disposed flag and emit the disposed signal. this.setFlag(Widget.Flag.IsDisposed); this._disposed.emit(undefined); // Remove or detach the widget if necessary. if (this.parent) { this.parent = null; } else if (this.isAttached) { Widget.detach(this); } // Dispose of the widget layout. if (this._layout) { this._layout.dispose(); this._layout = null; } // Clear the extra data associated with the widget. Signal.clearData(this); MessageLoop.clearData(this); AttachedProperty.clearData(this); } /** * A signal emitted when the widget is disposed. */ get disposed(): ISignal<this, void> { return this._disposed; } /** * Get the DOM node owned by the widget. */ readonly node: HTMLElement; /** * Test whether the widget has been disposed. */ get isDisposed(): boolean { return this.testFlag(Widget.Flag.IsDisposed); } /** * Test whether the widget's node is attached to the DOM. */ get isAttached(): boolean { return this.testFlag(Widget.Flag.IsAttached); } /** * Test whether the widget is explicitly hidden. */ get isHidden(): boolean { return this.testFlag(Widget.Flag.IsHidden); } /** * Test whether the widget is visible. * * #### Notes * A widget is visible when it is attached to the DOM, is not * explicitly hidden, and has no explicitly hidden ancestors. */ get isVisible(): boolean { return this.testFlag(Widget.Flag.IsVisible); } /** * The title object for the widget. * * #### Notes * The title object is used by some container widgets when displaying * the widget alongside some title, such as a tab panel or side bar. * * Since not all widgets will use the title, it is created on demand. * * The `owner` property of the title is set to this widget. */ get title(): Title<Widget> { return Private.titleProperty.get(this); } /** * Get the id of the widget's DOM node. */ get id(): string { return this.node.id; } /** * Set the id of the widget's DOM node. */ set id(value: string) { this.node.id = value; } /** * The dataset for the widget's DOM node. */ get dataset(): DOMStringMap { return this.node.dataset; } /** * Get the parent of the widget. */ get parent(): Widget | null { return this._parent; } /** * Set the parent of the widget. * * #### Notes * Children are typically added to a widget by using a layout, which * means user code will not normally set the parent widget directly. * * The widget will be automatically removed from its old parent. * * This is a no-op if there is no effective parent change. */ set parent(value: Widget | null) { if (this._parent === value) { return; } if (value && this.contains(value)) { throw new Error('Invalid parent widget.'); } if (this._parent && !this._parent.isDisposed) { let msg = new Widget.ChildMessage('child-removed', this); MessageLoop.sendMessage(this._parent, msg); } this._parent = value; if (this._parent && !this._parent.isDisposed) { let msg = new Widget.ChildMessage('child-added', this); MessageLoop.sendMessage(this._parent, msg); } if (!this.isDisposed) { MessageLoop.sendMessage(this, Widget.Msg.ParentChanged); } } /** * Get the layout for the widget. */ get layout(): Layout | null { return this._layout; } /** * Set the layout for the widget. * * #### Notes * The layout is single-use only. It cannot be changed after the * first assignment. * * The layout is disposed automatically when the widget is disposed. */ set layout(value: Layout | null) { if (this._layout === value) { return; } if (this.testFlag(Widget.Flag.DisallowLayout)) { throw new Error('Cannot set widget layout.'); } if (this._layout) { throw new Error('Cannot change widget layout.'); } if (value!.parent) { throw new Error('Cannot change layout parent.'); } this._layout = value; value!.parent = this; } /** * Create an iterator over the widget's children. * * @returns A new iterator over the children of the widget. * * #### Notes * The widget must have a populated layout in order to have children. * * If a layout is not installed, the returned iterator will be empty. */ children(): IIterator<Widget> { return this._layout ? this._layout.iter() : empty<Widget>(); } /** * Test whether a widget is a descendant of this widget. * * @param widget - The descendant widget of interest. * * @returns `true` if the widget is a descendant, `false` otherwise. */ contains(widget: Widget): boolean { for (let value: Widget | null = widget; value; value = value._parent) { if (value === this) { return true; } } return false; } /** * Test whether the widget's DOM node has the given class name. * * @param name - The class name of interest. * * @returns `true` if the node has the class, `false` otherwise. */ hasClass(name: string): boolean { return this.node.classList.contains(name); } /** * Add a class name to the widget's DOM node. * * @param name - The class name to add to the node. * * #### Notes * If the class name is already added to the node, this is a no-op. * * The class name must not contain whitespace. */ addClass(name: string): void { this.node.classList.add(name); } /** * Remove a class name from the widget's DOM node. * * @param name - The class name to remove from the node. * * #### Notes * If the class name is not yet added to the node, this is a no-op. * * The class name must not contain whitespace. */ removeClass(name: string): void { this.node.classList.remove(name); } /** * Toggle a class name on the widget's DOM node. * * @param name - The class name to toggle on the node. * * @param force - Whether to force add the class (`true`) or force * remove the class (`false`). If not provided, the presence of * the class will be toggled from its current state. * * @returns `true` if the class is now present, `false` otherwise. * * #### Notes * The class name must not contain whitespace. */ toggleClass(name: string, force?: boolean): boolean { if (force === true) { this.node.classList.add(name); return true; } if (force === false) { this.node.classList.remove(name); return false; } return this.node.classList.toggle(name); } /** * Post an `'update-request'` message to the widget. * * #### Notes * This is a simple convenience method for posting the message. */ update(): void { MessageLoop.postMessage(this, Widget.Msg.UpdateRequest); } /** * Post a `'fit-request'` message to the widget. * * #### Notes * This is a simple convenience method for posting the message. */ fit(): void { MessageLoop.postMessage(this, Widget.Msg.FitRequest); } /** * Post an `'activate-request'` message to the widget. * * #### Notes * This is a simple convenience method for posting the message. */ activate(): void { MessageLoop.postMessage(this, Widget.Msg.ActivateRequest); } /** * Send a `'close-request'` message to the widget. * * #### Notes * This is a simple convenience method for sending the message. */ close(): void { MessageLoop.sendMessage(this, Widget.Msg.CloseRequest); } /** * Show the widget and make it visible to its parent widget. * * #### Notes * This causes the [[isHidden]] property to be `false`. * * If the widget is not explicitly hidden, this is a no-op. */ show(): void { if (!this.testFlag(Widget.Flag.IsHidden)) { return; } if (this.isAttached && (!this.parent || this.parent.isVisible)) { MessageLoop.sendMessage(this, Widget.Msg.BeforeShow); } this.clearFlag(Widget.Flag.IsHidden); this.removeClass('lm-mod-hidden'); /* <DEPRECATED> */ this.removeClass('p-mod-hidden'); /* </DEPRECATED> */ if (this.isAttached && (!this.parent || this.parent.isVisible)) { MessageLoop.sendMessage(this, Widget.Msg.AfterShow); } if (this.parent) { let msg = new Widget.ChildMessage('child-shown', this); MessageLoop.sendMessage(this.parent, msg); } } /** * Hide the widget and make it hidden to its parent widget. * * #### Notes * This causes the [[isHidden]] property to be `true`. * * If the widget is explicitly hidden, this is a no-op. */ hide(): void { if (this.testFlag(Widget.Flag.IsHidden)) { return; } if (this.isAttached && (!this.parent || this.parent.isVisible)) { MessageLoop.sendMessage(this, Widget.Msg.BeforeHide); } this.setFlag(Widget.Flag.IsHidden); this.addClass('lm-mod-hidden'); /* <DEPRECATED> */ this.addClass('p-mod-hidden'); /* </DEPRECATED> */ if (this.isAttached && (!this.parent || this.parent.isVisible)) { MessageLoop.sendMessage(this, Widget.Msg.AfterHide); } if (this.parent) { let msg = new Widget.ChildMessage('child-hidden', this); MessageLoop.sendMessage(this.parent, msg); } } /** * Show or hide the widget according to a boolean value. * * @param hidden - `true` to hide the widget, or `false` to show it. * * #### Notes * This is a convenience method for `hide()` and `show()`. */ setHidden(hidden: boolean): void { if (hidden) { this.hide(); } else { this.show(); } } /** * Test whether the given widget flag is set. * * #### Notes * This will not typically be called directly by user code. */ testFlag(flag: Widget.Flag): boolean { return (this._flags & flag) !== 0; } /** * Set the given widget flag. * * #### Notes * This will not typically be called directly by user code. */ setFlag(flag: Widget.Flag): void { this._flags |= flag; } /** * Clear the given widget flag. * * #### Notes * This will not typically be called directly by user code. */ clearFlag(flag: Widget.Flag): void { this._flags &= ~flag; } /** * Process a message sent to the widget. * * @param msg - The message sent to the widget. * * #### Notes * Subclasses may reimplement this method as needed. */ processMessage(msg: Message): void { switch (msg.type) { case 'resize': this.notifyLayout(msg); this.onResize(msg as Widget.ResizeMessage); break; case 'update-request': this.notifyLayout(msg); this.onUpdateRequest(msg); break; case 'fit-request': this.notifyLayout(msg); this.onFitRequest(msg); break; case 'before-show': this.notifyLayout(msg); this.onBeforeShow(msg); break; case 'after-show': this.setFlag(Widget.Flag.IsVisible); this.notifyLayout(msg); this.onAfterShow(msg); break; case 'before-hide': this.notifyLayout(msg); this.onBeforeHide(msg); break; case 'after-hide': this.clearFlag(Widget.Flag.IsVisible); this.notifyLayout(msg); this.onAfterHide(msg); break; case 'before-attach': this.notifyLayout(msg); this.onBeforeAttach(msg); break; case 'after-attach': if (!this.isHidden && (!this.parent || this.parent.isVisible)) { this.setFlag(Widget.Flag.IsVisible); } this.setFlag(Widget.Flag.IsAttached); this.notifyLayout(msg); this.onAfterAttach(msg); break; case 'before-detach': this.notifyLayout(msg); this.onBeforeDetach(msg); break; case 'after-detach': this.clearFlag(Widget.Flag.IsVisible); this.clearFlag(Widget.Flag.IsAttached); this.notifyLayout(msg); this.onAfterDetach(msg); break; case 'activate-request': this.notifyLayout(msg); this.onActivateRequest(msg); break; case 'close-request': this.notifyLayout(msg); this.onCloseRequest(msg); break; case 'child-added': this.notifyLayout(msg); this.onChildAdded(msg as Widget.ChildMessage); break; case 'child-removed': this.notifyLayout(msg); this.onChildRemoved(msg as Widget.ChildMessage); break; default: this.notifyLayout(msg); break; } } /** * Invoke the message processing routine of the widget's layout. * * @param msg - The message to dispatch to the layout. * * #### Notes * This is a no-op if the widget does not have a layout. * * This will not typically be called directly by user code. */ protected notifyLayout(msg: Message): void { if (this._layout) { this._layout.processParentMessage(msg); } } /** * A message handler invoked on a `'close-request'` message. * * #### Notes * The default implementation unparents or detaches the widget. */ protected onCloseRequest(msg: Message): void { if (this.parent) { this.parent = null; } else if (this.isAttached) { Widget.detach(this); } } /** * A message handler invoked on a `'resize'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onResize(msg: Widget.ResizeMessage): void { } /** * A message handler invoked on an `'update-request'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onUpdateRequest(msg: Message): void { } /** * A message handler invoked on a `'fit-request'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onFitRequest(msg: Message): void { } /** * A message handler invoked on an `'activate-request'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onActivateRequest(msg: Message): void { } /** * A message handler invoked on a `'before-show'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onBeforeShow(msg: Message): void { } /** * A message handler invoked on an `'after-show'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onAfterShow(msg: Message): void { } /** * A message handler invoked on a `'before-hide'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onBeforeHide(msg: Message): void { } /** * A message handler invoked on an `'after-hide'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onAfterHide(msg: Message): void { } /** * A message handler invoked on a `'before-attach'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onBeforeAttach(msg: Message): void { } /** * A message handler invoked on an `'after-attach'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onAfterAttach(msg: Message): void { } /** * A message handler invoked on a `'before-detach'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onBeforeDetach(msg: Message): void { } /** * A message handler invoked on an `'after-detach'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onAfterDetach(msg: Message): void { } /** * A message handler invoked on a `'child-added'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onChildAdded(msg: Widget.ChildMessage): void { } /** * A message handler invoked on a `'child-removed'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onChildRemoved(msg: Widget.ChildMessage): void { } private _flags = 0; private _layout: Layout | null = null; private _parent: Widget | null = null; private _disposed = new Signal<this, void>(this); } /** * The namespace for the `Widget` class statics. */ export namespace Widget { /** * An options object for initializing a widget. */ export interface IOptions { /** * The optional node to use for the widget. * * If a node is provided, the widget will assume full ownership * and control of the node, as if it had created the node itself. * * The default is a new `<div>`. */ node?: HTMLElement; /** * The optional element tag, used for constructing the widget's node. * * If a pre-constructed node is provided via the `node` arg, this * value is ignored. */ tag?: keyof HTMLElementTagNameMap; } /** * An enum of widget bit flags. */ export enum Flag { /** * The widget has been disposed. */ IsDisposed = 0x1, /** * The widget is attached to the DOM. */ IsAttached = 0x2, /** * The widget is hidden. */ IsHidden = 0x4, /** * The widget is visible. */ IsVisible = 0x8, /** * A layout cannot be set on the widget. */ DisallowLayout = 0x10 } /** * A collection of stateless messages related to widgets. */ export namespace Msg { /** * A singleton `'before-show'` message. * * #### Notes * This message is sent to a widget before it becomes visible. * * This message is **not** sent when the widget is being attached. */ export const BeforeShow = new Message('before-show'); /** * A singleton `'after-show'` message. * * #### Notes * This message is sent to a widget after it becomes visible. * * This message is **not** sent when the widget is being attached. */ export const AfterShow = new Message('after-show'); /** * A singleton `'before-hide'` message. * * #### Notes * This message is sent to a widget before it becomes not-visible. * * This message is **not** sent when the widget is being detached. */ export const BeforeHide = new Message('before-hide'); /** * A singleton `'after-hide'` message. * * #### Notes * This message is sent to a widget after it becomes not-visible. * * This message is **not** sent when the widget is being detached. */ export const AfterHide = new Message('after-hide'); /** * A singleton `'before-attach'` message. * * #### Notes * This message is sent to a widget before it is attached. */ export const BeforeAttach = new Message('before-attach'); /** * A singleton `'after-attach'` message. * * #### Notes * This message is sent to a widget after it is attached. */ export const AfterAttach = new Message('after-attach'); /** * A singleton `'before-detach'` message. * * #### Notes * This message is sent to a widget before it is detached. */ export const BeforeDetach = new Message('before-detach'); /** * A singleton `'after-detach'` message. * * #### Notes * This message is sent to a widget after it is detached. */ export const AfterDetach = new Message('after-detach'); /** * A singleton `'parent-changed'` message. * * #### Notes * This message is sent to a widget when its parent has changed. */ export const ParentChanged = new Message('parent-changed'); /** * A singleton conflatable `'update-request'` message. * * #### Notes * This message can be dispatched to supporting widgets in order to * update their content based on the current widget state. Not all * widgets will respond to messages of this type. * * For widgets with a layout, this message will inform the layout to * update the position and size of its child widgets. */ export const UpdateRequest = new ConflatableMessage('update-request'); /** * A singleton conflatable `'fit-request'` message. * * #### Notes * For widgets with a layout, this message will inform the layout to * recalculate its size constraints to fit the space requirements of * its child widgets, and to update their position and size. Not all * layouts will respond to messages of this type. */ export const FitRequest = new ConflatableMessage('fit-request'); /** * A singleton conflatable `'activate-request'` message. * * #### Notes * This message should be dispatched to a widget when it should * perform the actions necessary to activate the widget, which * may include focusing its node or descendant node. */ export const ActivateRequest = new ConflatableMessage('activate-request'); /** * A singleton conflatable `'close-request'` message. * * #### Notes * This message should be dispatched to a widget when it should close * and remove itself from the widget hierarchy. */ export const CloseRequest = new ConflatableMessage('close-request'); } /** * A message class for child related messages. */ export class ChildMessage extends Message { /** * Construct a new child message. * * @param type - The message type. * * @param child - The child widget for the message. */ constructor(type: string, child: Widget) { super(type); this.child = child; } /** * The child widget for the message. */ readonly child: Widget; } /** * A message class for `'resize'` messages. */ export class ResizeMessage extends Message { /** * Construct a new resize message. * * @param width - The **offset width** of the widget, or `-1` if * the width is not known. * * @param height - The **offset height** of the widget, or `-1` if * the height is not known. */ constructor(width: number, height: number) { super('resize'); this.width = width; this.height = height; } /** * The offset width of the widget. * * #### Notes * This will be `-1` if the width is unknown. */ readonly width: number; /** * The offset height of the widget. * * #### Notes * This will be `-1` if the height is unknown. */ readonly height: number; } /** * The namespace for the `ResizeMessage` class statics. */ export namespace ResizeMessage { /** * A singleton `'resize'` message with an unknown size. */ export const UnknownSize = new ResizeMessage(-1, -1); } /** * Attach a widget to a host DOM node. * * @param widget - The widget of interest. * * @param host - The DOM node to use as the widget's host. * * @param ref - The child of `host` to use as the reference element. * If this is provided, the widget will be inserted before this * node in the host. The default is `null`, which will cause the * widget to be added as the last child of the host. * * #### Notes * This will throw an error if the widget is not a root widget, if * the widget is already attached, or if the host is not attached * to the DOM. */ export function attach(widget: Widget, host: HTMLElement, ref: HTMLElement | null = null): void { if (widget.parent) { throw new Error('Cannot attach a child widget.'); } if (widget.isAttached || document.body.contains(widget.node)) { throw new Error('Widget is already attached.'); } if (!document.body.contains(host)) { throw new Error('Host is not attached.'); } MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach); host.insertBefore(widget.node, ref); MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach); } /** * Detach the widget from its host DOM node. * * @param widget - The widget of interest. * * #### Notes * This will throw an error if the widget is not a root widget, * or if the widget is not attached to the DOM. */ export function detach(widget: Widget): void { if (widget.parent) { throw new Error('Cannot detach a child widget.'); } if (!widget.isAttached || !document.body.contains(widget.node)) { throw new Error('Widget is not attached.'); } MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach); widget.node.parentNode!.removeChild(widget.node); MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach); } } /** * The namespace for the module implementation details. */ namespace Private { /** * An attached property for the widget title object. */ export const titleProperty = new AttachedProperty<Widget, Title<Widget>>({ name: 'title', create: owner => new Title<Widget>({ owner }), }); /** * Create a DOM node for the given widget options. */ export function createNode(options: Widget.IOptions): HTMLElement { return options.node || document.createElement(options.tag || 'div'); } }
the_stack
import { Event, Emitter } from 'vs/base/common/event'; import { IEditorFactoryRegistry, GroupIdentifier, EditorsOrder, EditorExtensions, IUntypedEditorInput, SideBySideEditor, EditorCloseContext, IMatchEditorOptions, GroupModelChangeKind } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { dispose, Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { coalesce } from 'vs/base/common/arrays'; const EditorOpenPositioning = { LEFT: 'left', RIGHT: 'right', FIRST: 'first', LAST: 'last' }; export interface IEditorOpenOptions { readonly pinned?: boolean; sticky?: boolean; active?: boolean; readonly index?: number; readonly supportSideBySide?: SideBySideEditor.ANY | SideBySideEditor.BOTH; } export interface IEditorOpenResult { readonly editor: EditorInput; readonly isNew: boolean; } export interface ISerializedEditorInput { readonly id: string; readonly value: string; } export interface ISerializedEditorGroupModel { readonly id: number; readonly locked?: boolean; readonly editors: ISerializedEditorInput[]; readonly mru: number[]; readonly preview?: number; sticky?: number; } export function isSerializedEditorGroupModel(group?: unknown): group is ISerializedEditorGroupModel { const candidate = group as ISerializedEditorGroupModel | undefined; return !!(candidate && typeof candidate === 'object' && Array.isArray(candidate.editors) && Array.isArray(candidate.mru)); } export interface IMatchOptions { /** * Whether to consider a side by side editor as matching. * By default, side by side editors will not be considered * as matching, even if the editor is opened in one of the sides. */ readonly supportSideBySide?: SideBySideEditor.ANY | SideBySideEditor.BOTH; /** * Only consider an editor to match when the * `candidate === editor` but not when * `candidate.matches(editor)`. */ readonly strictEquals?: boolean; } export interface IGroupModelChangeEvent { /** * The kind of change that occurred in the group model. */ readonly kind: GroupModelChangeKind; /** * Only applies when editors change providing * access to the editor the event is about. */ readonly editor?: EditorInput; /** * Only applies when editors change providing * access to the index of the editor the event * is about. */ readonly editorIndex?: number; } export interface IGroupEditorChangeEvent extends IGroupModelChangeEvent { readonly editor: EditorInput; readonly editorIndex: number; } export function isGroupEditorChangeEvent(e: IGroupModelChangeEvent): e is IGroupEditorChangeEvent { const candidate = e as IGroupEditorOpenEvent; return candidate.editor && candidate.editorIndex !== undefined; } export interface IGroupEditorOpenEvent extends IGroupEditorChangeEvent { readonly kind: GroupModelChangeKind.EDITOR_OPEN; } export function isGroupEditorOpenEvent(e: IGroupModelChangeEvent): e is IGroupEditorOpenEvent { const candidate = e as IGroupEditorOpenEvent; return candidate.kind === GroupModelChangeKind.EDITOR_OPEN && candidate.editorIndex !== undefined; } export interface IGroupEditorMoveEvent extends IGroupEditorChangeEvent { readonly kind: GroupModelChangeKind.EDITOR_MOVE; /** * Signifies the index the editor is moving from. * `editorIndex` will contain the index the editor * is moving to. */ readonly oldEditorIndex: number; } export function isGroupEditorMoveEvent(e: IGroupModelChangeEvent): e is IGroupEditorMoveEvent { const candidate = e as IGroupEditorMoveEvent; return candidate.kind === GroupModelChangeKind.EDITOR_MOVE && candidate.editorIndex !== undefined && candidate.oldEditorIndex !== undefined; } export interface IGroupEditorCloseEvent extends IGroupEditorChangeEvent { readonly kind: GroupModelChangeKind.EDITOR_CLOSE; /** * Signifies the context in which the editor * is being closed. This allows for understanding * if a replace or reopen is occurring */ readonly context: EditorCloseContext; /** * Signifies whether or not the closed editor was * sticky. This is necessary becasue state is lost * after closing. */ readonly sticky: boolean; } export function isGroupEditorCloseEvent(e: IGroupModelChangeEvent): e is IGroupEditorCloseEvent { const candidate = e as IGroupEditorCloseEvent; return candidate.kind === GroupModelChangeKind.EDITOR_CLOSE && candidate.editorIndex !== undefined && candidate.context !== undefined && candidate.sticky !== undefined; } interface IEditorCloseResult { readonly editor: EditorInput; readonly context: EditorCloseContext; readonly editorIndex: number; readonly sticky: boolean; } export class EditorGroupModel extends Disposable { private static IDS = 0; //#region events private readonly _onDidModelChange = this._register(new Emitter<IGroupModelChangeEvent>()); readonly onDidModelChange = this._onDidModelChange.event; //#endregion private _id: GroupIdentifier; get id(): GroupIdentifier { return this._id; } private editors: EditorInput[] = []; private mru: EditorInput[] = []; private locked = false; private preview: EditorInput | null = null; // editor in preview state private active: EditorInput | null = null; // editor in active state private sticky = -1; // index of first editor in sticky state private editorOpenPositioning: ('left' | 'right' | 'first' | 'last') | undefined; private focusRecentEditorAfterClose: boolean | undefined; constructor( labelOrSerializedGroup: ISerializedEditorGroupModel | undefined, @IInstantiationService private readonly instantiationService: IInstantiationService, @IConfigurationService private readonly configurationService: IConfigurationService ) { super(); if (isSerializedEditorGroupModel(labelOrSerializedGroup)) { this._id = this.deserialize(labelOrSerializedGroup); } else { this._id = EditorGroupModel.IDS++; } this.onConfigurationUpdated(); this.registerListeners(); } private registerListeners(): void { this._register(this.configurationService.onDidChangeConfiguration(() => this.onConfigurationUpdated())); } private onConfigurationUpdated(): void { this.editorOpenPositioning = this.configurationService.getValue('workbench.editor.openPositioning'); this.focusRecentEditorAfterClose = this.configurationService.getValue('workbench.editor.focusRecentEditorAfterClose'); } get count(): number { return this.editors.length; } get stickyCount(): number { return this.sticky + 1; } getEditors(order: EditorsOrder, options?: { excludeSticky?: boolean }): EditorInput[] { const editors = order === EditorsOrder.MOST_RECENTLY_ACTIVE ? this.mru.slice(0) : this.editors.slice(0); if (options?.excludeSticky) { // MRU: need to check for index on each if (order === EditorsOrder.MOST_RECENTLY_ACTIVE) { return editors.filter(editor => !this.isSticky(editor)); } // Sequential: simply start after sticky index return editors.slice(this.sticky + 1); } return editors; } getEditorByIndex(index: number): EditorInput | undefined { return this.editors[index]; } get activeEditor(): EditorInput | null { return this.active; } isActive(editor: EditorInput | IUntypedEditorInput): boolean { return this.matches(this.active, editor); } get previewEditor(): EditorInput | null { return this.preview; } openEditor(candidate: EditorInput, options?: IEditorOpenOptions): IEditorOpenResult { const makeSticky = options?.sticky || (typeof options?.index === 'number' && this.isSticky(options.index)); const makePinned = options?.pinned || options?.sticky; const makeActive = options?.active || !this.activeEditor || (!makePinned && this.matches(this.preview, this.activeEditor)); const existingEditorAndIndex = this.findEditor(candidate, options); // New editor if (!existingEditorAndIndex) { const newEditor = candidate; const indexOfActive = this.indexOf(this.active); // Insert into specific position let targetIndex: number; if (options && typeof options.index === 'number') { targetIndex = options.index; } // Insert to the BEGINNING else if (this.editorOpenPositioning === EditorOpenPositioning.FIRST) { targetIndex = 0; // Always make sure targetIndex is after sticky editors // unless we are explicitly told to make the editor sticky if (!makeSticky && this.isSticky(targetIndex)) { targetIndex = this.sticky + 1; } } // Insert to the END else if (this.editorOpenPositioning === EditorOpenPositioning.LAST) { targetIndex = this.editors.length; } // Insert to LEFT or RIGHT of active editor else { // Insert to the LEFT of active editor if (this.editorOpenPositioning === EditorOpenPositioning.LEFT) { if (indexOfActive === 0 || !this.editors.length) { targetIndex = 0; // to the left becoming first editor in list } else { targetIndex = indexOfActive; // to the left of active editor } } // Insert to the RIGHT of active editor else { targetIndex = indexOfActive + 1; } // Always make sure targetIndex is after sticky editors // unless we are explicitly told to make the editor sticky if (!makeSticky && this.isSticky(targetIndex)) { targetIndex = this.sticky + 1; } } // If the editor becomes sticky, increment the sticky index and adjust // the targetIndex to be at the end of sticky editors unless already. if (makeSticky) { this.sticky++; if (!this.isSticky(targetIndex)) { targetIndex = this.sticky; } } // Insert into our list of editors if pinned or we have no preview editor if (makePinned || !this.preview) { this.splice(targetIndex, false, newEditor); } // Handle preview if (!makePinned) { // Replace existing preview with this editor if we have a preview if (this.preview) { const indexOfPreview = this.indexOf(this.preview); if (targetIndex > indexOfPreview) { targetIndex--; // accomodate for the fact that the preview editor closes } this.replaceEditor(this.preview, newEditor, targetIndex, !makeActive); } this.preview = newEditor; } // Listeners this.registerEditorListeners(newEditor); // Event const event: IGroupEditorOpenEvent = { kind: GroupModelChangeKind.EDITOR_OPEN, editor: newEditor, editorIndex: targetIndex }; this._onDidModelChange.fire(event); // Handle active if (makeActive) { this.doSetActive(newEditor, targetIndex); } return { editor: newEditor, isNew: true }; } // Existing editor else { const [existingEditor, existingEditorIndex] = existingEditorAndIndex; // Pin it if (makePinned) { this.doPin(existingEditor, existingEditorIndex); } // Activate it if (makeActive) { this.doSetActive(existingEditor, existingEditorIndex); } // Respect index if (options && typeof options.index === 'number') { this.moveEditor(existingEditor, options.index); } // Stick it (intentionally after the moveEditor call in case // the editor was already moved into the sticky range) if (makeSticky) { this.doStick(existingEditor, this.indexOf(existingEditor)); } return { editor: existingEditor, isNew: false }; } } private registerEditorListeners(editor: EditorInput): void { const listeners = new DisposableStore(); // Re-emit disposal of editor input as our own event listeners.add(Event.once(editor.onWillDispose)(() => { const editorIndex = this.editors.indexOf(editor); if (editorIndex >= 0) { const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_WILL_DISPOSE, editor, editorIndex }; this._onDidModelChange.fire(event); } })); // Re-Emit dirty state changes listeners.add(editor.onDidChangeDirty(() => { const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_DIRTY, editor, editorIndex: this.editors.indexOf(editor) }; this._onDidModelChange.fire(event); })); // Re-Emit label changes listeners.add(editor.onDidChangeLabel(() => { const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_LABEL, editor, editorIndex: this.editors.indexOf(editor) }; this._onDidModelChange.fire(event); })); // Re-Emit capability changes listeners.add(editor.onDidChangeCapabilities(() => { const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_CAPABILITIES, editor, editorIndex: this.editors.indexOf(editor) }; this._onDidModelChange.fire(event); })); // Clean up dispose listeners once the editor gets closed listeners.add(this.onDidModelChange(event => { if (event.kind === GroupModelChangeKind.EDITOR_CLOSE && event.editor?.matches(editor)) { dispose(listeners); } })); } private replaceEditor(toReplace: EditorInput, replaceWith: EditorInput, replaceIndex: number, openNext = true): void { const closeResult = this.doCloseEditor(toReplace, EditorCloseContext.REPLACE, openNext); // optimization to prevent multiple setActive() in one call // We want to first add the new editor into our model before emitting the close event because // firing the close event can trigger a dispose on the same editor that is now being added. // This can lead into opening a disposed editor which is not what we want. this.splice(replaceIndex, false, replaceWith); if (closeResult) { const event: IGroupEditorCloseEvent = { kind: GroupModelChangeKind.EDITOR_CLOSE, ...closeResult }; this._onDidModelChange.fire(event); } } closeEditor(candidate: EditorInput, context = EditorCloseContext.UNKNOWN, openNext = true): IEditorCloseResult | undefined { const closeResult = this.doCloseEditor(candidate, context, openNext); if (closeResult) { const event: IGroupEditorCloseEvent = { kind: GroupModelChangeKind.EDITOR_CLOSE, ...closeResult }; this._onDidModelChange.fire(event); return closeResult; } return undefined; } private doCloseEditor(candidate: EditorInput, context: EditorCloseContext, openNext: boolean): IEditorCloseResult | undefined { const index = this.indexOf(candidate); if (index === -1) { return undefined; // not found } const editor = this.editors[index]; const sticky = this.isSticky(index); // Active Editor closed if (openNext && this.matches(this.active, editor)) { // More than one editor if (this.mru.length > 1) { let newActive: EditorInput; if (this.focusRecentEditorAfterClose) { newActive = this.mru[1]; // active editor is always first in MRU, so pick second editor after as new active } else { if (index === this.editors.length - 1) { newActive = this.editors[index - 1]; // last editor is closed, pick previous as new active } else { newActive = this.editors[index + 1]; // pick next editor as new active } } this.doSetActive(newActive, this.editors.indexOf(newActive)); } // One Editor else { this.active = null; } } // Preview Editor closed if (this.matches(this.preview, editor)) { this.preview = null; } // Remove from arrays this.splice(index, true); // Event return { editor, sticky, editorIndex: index, context }; } moveEditor(candidate: EditorInput, toIndex: number): EditorInput | undefined { // Ensure toIndex is in bounds of our model if (toIndex >= this.editors.length) { toIndex = this.editors.length - 1; } else if (toIndex < 0) { toIndex = 0; } const index = this.indexOf(candidate); if (index < 0 || toIndex === index) { return; } const editor = this.editors[index]; // Adjust sticky index: editor moved out of sticky state into unsticky state if (this.isSticky(index) && toIndex > this.sticky) { this.sticky--; } // ...or editor moved into sticky state from unsticky state else if (!this.isSticky(index) && toIndex <= this.sticky) { this.sticky++; } // Move this.editors.splice(index, 1); this.editors.splice(toIndex, 0, editor); // Event const event: IGroupEditorMoveEvent = { kind: GroupModelChangeKind.EDITOR_MOVE, editor, oldEditorIndex: index, editorIndex: toIndex, }; this._onDidModelChange.fire(event); return editor; } setActive(candidate: EditorInput | undefined): EditorInput | undefined { let result: EditorInput | undefined = undefined; if (!candidate) { this.setGroupActive(); } else { result = this.setEditorActive(candidate); } return result; } private setGroupActive(): void { // We do not really keep the `active` state in our model because // it has no special meaning to us here. But for consistency // we emit a `onDidModelChange` event so that components can // react. this._onDidModelChange.fire({ kind: GroupModelChangeKind.GROUP_ACTIVE }); } private setEditorActive(candidate: EditorInput): EditorInput | undefined { const res = this.findEditor(candidate); if (!res) { return; // not found } const [editor, editorIndex] = res; this.doSetActive(editor, editorIndex); return editor; } private doSetActive(editor: EditorInput, editorIndex: number): void { if (this.matches(this.active, editor)) { return; // already active } this.active = editor; // Bring to front in MRU list const mruIndex = this.indexOf(editor, this.mru); this.mru.splice(mruIndex, 1); this.mru.unshift(editor); // Event const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_ACTIVE, editor, editorIndex }; this._onDidModelChange.fire(event); } setIndex(index: number) { // We do not really keep the `index` in our model because // it has no special meaning to us here. But for consistency // we emit a `onDidModelChange` event so that components can // react. this._onDidModelChange.fire({ kind: GroupModelChangeKind.GROUP_INDEX }); } pin(candidate: EditorInput): EditorInput | undefined { const res = this.findEditor(candidate); if (!res) { return; // not found } const [editor, editorIndex] = res; this.doPin(editor, editorIndex); return editor; } private doPin(editor: EditorInput, editorIndex: number): void { if (this.isPinned(editor)) { return; // can only pin a preview editor } // Convert the preview editor to be a pinned editor this.preview = null; // Event const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_PIN, editor, editorIndex }; this._onDidModelChange.fire(event); } unpin(candidate: EditorInput): EditorInput | undefined { const res = this.findEditor(candidate); if (!res) { return; // not found } const [editor, editorIndex] = res; this.doUnpin(editor, editorIndex); return editor; } private doUnpin(editor: EditorInput, editorIndex: number): void { if (!this.isPinned(editor)) { return; // can only unpin a pinned editor } // Set new const oldPreview = this.preview; this.preview = editor; // Event const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_PIN, editor, editorIndex }; this._onDidModelChange.fire(event); // Close old preview editor if any if (oldPreview) { this.closeEditor(oldPreview, EditorCloseContext.UNPIN); } } isPinned(editorOrIndex: EditorInput | number): boolean { let editor: EditorInput; if (typeof editorOrIndex === 'number') { editor = this.editors[editorOrIndex]; } else { editor = editorOrIndex; } return !this.matches(this.preview, editor); } stick(candidate: EditorInput): EditorInput | undefined { const res = this.findEditor(candidate); if (!res) { return; // not found } const [editor, editorIndex] = res; this.doStick(editor, editorIndex); return editor; } private doStick(editor: EditorInput, editorIndex: number): void { if (this.isSticky(editorIndex)) { return; // can only stick a non-sticky editor } // Pin editor this.pin(editor); // Move editor to be the last sticky editor this.moveEditor(editor, this.sticky + 1); // Adjust sticky index this.sticky++; // Event const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_STICKY, editor, editorIndex: this.sticky }; this._onDidModelChange.fire(event); } unstick(candidate: EditorInput): EditorInput | undefined { const res = this.findEditor(candidate); if (!res) { return; // not found } const [editor, editorIndex] = res; this.doUnstick(editor, editorIndex); return editor; } private doUnstick(editor: EditorInput, editorIndex: number): void { if (!this.isSticky(editorIndex)) { return; // can only unstick a sticky editor } // Move editor to be the first non-sticky editor this.moveEditor(editor, this.sticky); // Adjust sticky index this.sticky--; // Event const event: IGroupEditorChangeEvent = { kind: GroupModelChangeKind.EDITOR_STICKY, editor, editorIndex }; this._onDidModelChange.fire(event); } isSticky(candidateOrIndex: EditorInput | number): boolean { if (this.sticky < 0) { return false; // no sticky editor } let index: number; if (typeof candidateOrIndex === 'number') { index = candidateOrIndex; } else { index = this.indexOf(candidateOrIndex); } if (index < 0) { return false; } return index <= this.sticky; } private splice(index: number, del: boolean, editor?: EditorInput): void { const editorToDeleteOrReplace = this.editors[index]; // Perform on sticky index if (del && this.isSticky(index)) { this.sticky--; } // Perform on editors array if (editor) { this.editors.splice(index, del ? 1 : 0, editor); } else { this.editors.splice(index, del ? 1 : 0); } // Perform on MRU { // Add if (!del && editor) { if (this.mru.length === 0) { // the list of most recent editors is empty // so this editor can only be the most recent this.mru.push(editor); } else { // we have most recent editors. as such we // put this newly opened editor right after // the current most recent one because it cannot // be the most recently active one unless // it becomes active. but it is still more // active then any other editor in the list. this.mru.splice(1, 0, editor); } } // Remove / Replace else { const indexInMRU = this.indexOf(editorToDeleteOrReplace, this.mru); // Remove if (del && !editor) { this.mru.splice(indexInMRU, 1); // remove from MRU } // Replace else if (del && editor) { this.mru.splice(indexInMRU, 1, editor); // replace MRU at location } } } } indexOf(candidate: EditorInput | null, editors = this.editors, options?: IMatchEditorOptions): number { let index = -1; if (!candidate) { return index; } for (let i = 0; i < editors.length; i++) { const editor = editors[i]; if (this.matches(editor, candidate, options)) { // If we are to support side by side matching, it is possible that // a better direct match is found later. As such, we continue finding // a matching editor and prefer that match over the side by side one. if (options?.supportSideBySide && editor instanceof SideBySideEditorInput && !(candidate instanceof SideBySideEditorInput)) { index = i; } else { index = i; break; } } } return index; } private findEditor(candidate: EditorInput | null, options?: IMatchEditorOptions): [EditorInput, number /* index */] | undefined { const index = this.indexOf(candidate, this.editors, options); if (index === -1) { return undefined; } return [this.editors[index], index]; } isFirst(candidate: EditorInput | null): boolean { return this.matches(this.editors[0], candidate); } isLast(candidate: EditorInput | null): boolean { return this.matches(this.editors[this.editors.length - 1], candidate); } contains(candidate: EditorInput | IUntypedEditorInput, options?: IMatchEditorOptions): boolean { for (const editor of this.editors) { if (this.matches(editor, candidate, options)) { return true; } } return false; } private matches(editor: EditorInput | null, candidate: EditorInput | IUntypedEditorInput | null, options?: IMatchEditorOptions): boolean { if (!editor || !candidate) { return false; } if (options?.supportSideBySide && editor instanceof SideBySideEditorInput && !(candidate instanceof SideBySideEditorInput)) { switch (options.supportSideBySide) { case SideBySideEditor.ANY: if (this.matches(editor.primary, candidate, options) || this.matches(editor.secondary, candidate, options)) { return true; } break; case SideBySideEditor.BOTH: if (this.matches(editor.primary, candidate, options) && this.matches(editor.secondary, candidate, options)) { return true; } break; } } const strictEquals = editor === candidate; if (options?.strictEquals) { return strictEquals; } return strictEquals || editor.matches(candidate); } get isLocked(): boolean { return this.locked; } lock(locked: boolean): void { if (this.isLocked !== locked) { this.locked = locked; this._onDidModelChange.fire({ kind: GroupModelChangeKind.GROUP_LOCKED }); } } clone(): EditorGroupModel { const clone = this.instantiationService.createInstance(EditorGroupModel, undefined); // Copy over group properties clone.editors = this.editors.slice(0); clone.mru = this.mru.slice(0); clone.preview = this.preview; clone.active = this.active; clone.sticky = this.sticky; // Ensure to register listeners for each editor for (const editor of clone.editors) { clone.registerEditorListeners(editor); } return clone; } serialize(): ISerializedEditorGroupModel { const registry = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory); // Serialize all editor inputs so that we can store them. // Editors that cannot be serialized need to be ignored // from mru, active, preview and sticky if any. let serializableEditors: EditorInput[] = []; let serializedEditors: ISerializedEditorInput[] = []; let serializablePreviewIndex: number | undefined; let serializableSticky = this.sticky; for (let i = 0; i < this.editors.length; i++) { const editor = this.editors[i]; let canSerializeEditor = false; const editorSerializer = registry.getEditorSerializer(editor); if (editorSerializer) { const value = editorSerializer.serialize(editor); // Editor can be serialized if (typeof value === 'string') { canSerializeEditor = true; serializedEditors.push({ id: editor.typeId, value }); serializableEditors.push(editor); if (this.preview === editor) { serializablePreviewIndex = serializableEditors.length - 1; } } // Editor cannot be serialized else { canSerializeEditor = false; } } // Adjust index of sticky editors if the editor cannot be serialized and is pinned if (!canSerializeEditor && this.isSticky(i)) { serializableSticky--; } } const serializableMru = this.mru.map(editor => this.indexOf(editor, serializableEditors)).filter(i => i >= 0); return { id: this.id, locked: this.locked ? true : undefined, editors: serializedEditors, mru: serializableMru, preview: serializablePreviewIndex, sticky: serializableSticky >= 0 ? serializableSticky : undefined }; } private deserialize(data: ISerializedEditorGroupModel): number { const registry = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory); if (typeof data.id === 'number') { this._id = data.id; EditorGroupModel.IDS = Math.max(data.id + 1, EditorGroupModel.IDS); // make sure our ID generator is always larger } else { this._id = EditorGroupModel.IDS++; // backwards compatibility } if (data.locked) { this.locked = true; } this.editors = coalesce(data.editors.map((e, index) => { let editor: EditorInput | undefined = undefined; const editorSerializer = registry.getEditorSerializer(e.id); if (editorSerializer) { const deserializedEditor = editorSerializer.deserialize(this.instantiationService, e.value); if (deserializedEditor instanceof EditorInput) { editor = deserializedEditor; this.registerEditorListeners(editor); } } if (!editor && typeof data.sticky === 'number' && index <= data.sticky) { data.sticky--; // if editor cannot be deserialized but was sticky, we need to decrease sticky index } return editor; })); this.mru = coalesce(data.mru.map(i => this.editors[i])); this.active = this.mru[0]; if (typeof data.preview === 'number') { this.preview = this.editors[data.preview]; } if (typeof data.sticky === 'number') { this.sticky = data.sticky; } return this._id; } }
the_stack
import React from "react" import PropTypes from "prop-types" import { action, observable, makeObservable } from "mobx" import { observer, inject, Provider } from "../src" import { IValueMap } from "../src/types/IValueMap" import { render, act } from "@testing-library/react" import { withConsole } from "./utils/withConsole" import { IReactComponent } from "../src/types/IReactComponent" describe("inject based context", () => { test("basic context", () => { const C = inject("foo")( observer( class X extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar") }) test("props override context", () => { const C = inject("foo")( class T extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B = () => <C foo={42} /> const A = class T extends React.Component<any, any> { render() { return ( <Provider foo="bar"> <B /> </Provider> ) } } const { container } = render(<A />) expect(container).toHaveTextContent("context:42") }) test("wraps displayName of original component", () => { const A: React.ComponentClass = inject("foo")( class ComponentA extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const B: React.ComponentClass = inject()( class ComponentB extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) const C: React.ComponentClass = inject(() => ({}))( class ComponentC extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) expect(A.displayName).toBe("inject-with-foo(ComponentA)") expect(B.displayName).toBe("inject(ComponentB)") expect(C.displayName).toBe("inject(ComponentC)") }) // FIXME: see other comments related to error catching in React // test does work as expected when running manually test("store should be available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C /> const A = class A extends React.Component<any, any> { render() { return ( <Provider baz={42}> <B /> </Provider> ) } } withConsole(() => { expect(() => render(<A />)).toThrow( /Store 'foo' is not available! Make sure it is provided by some Provider/ ) }) }) test("store is not required if prop is available", () => { const C = inject("foo")( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) ) const B = () => <C foo="bar" /> const { container } = render(<B />) expect(container).toHaveTextContent("context:bar") }) test("inject merges (and overrides) props", () => { const C = inject(() => ({ a: 1 }))( observer( class C extends React.Component<any, any> { render() { expect(this.props).toEqual({ a: 1, b: 2 }) return null } } ) ) const B = () => <C a={2} b={2} /> render(<B />) }) test("custom storesToProps", () => { const C = inject((stores: IValueMap, props: any) => { expect(stores).toEqual({ foo: "bar" }) expect(props).toEqual({ baz: 42 }) return { zoom: stores.foo, baz: props.baz * 2 } })( observer( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.zoom} {this.props.baz} </div> ) } } ) ) const B = class B extends React.Component<any, any> { render() { return <C baz={42} /> } } const A = () => ( <Provider foo="bar"> <B /> </Provider> ) const { container } = render(<A />) expect(container).toHaveTextContent("context:bar84") }) test("inject forwards ref", () => { class FancyComp extends React.Component<any, any> { didRender render() { this.didRender = true return null } doSomething() {} } const ref = React.createRef<FancyComp>() render(<FancyComp ref={ref} />) expect(typeof ref.current?.doSomething).toBe("function") expect(ref.current?.didRender).toBe(true) const InjectedFancyComp = inject("bla")(FancyComp) const ref2 = React.createRef<FancyComp>() render( <Provider bla={42}> <InjectedFancyComp ref={ref2} /> </Provider> ) expect(typeof ref2.current?.doSomething).toBe("function") expect(ref2.current?.didRender).toBe(true) }) test("inject should work with components that use forwardRef", () => { const FancyComp = React.forwardRef((_: any, ref: React.Ref<HTMLDivElement>) => { return <div ref={ref} /> }) const InjectedFancyComp = inject("bla")(FancyComp) const ref = React.createRef<HTMLDivElement>() render( <Provider bla={42}> <InjectedFancyComp ref={ref} /> </Provider> ) expect(ref.current).not.toBeNull() expect(ref.current).toBeInstanceOf(HTMLDivElement) }) test("support static hoisting, wrappedComponent and ref forwarding", () => { class B extends React.Component<any, any> { static foo static bar testField render() { this.testField = 1 return null } } ;(B as React.ComponentClass).propTypes = { x: PropTypes.object } B.foo = 17 B.bar = {} const C = inject("booh")(B) expect(C.wrappedComponent).toBe(B) expect(B.foo).toBe(17) expect(C.foo).toBe(17) expect(C.bar === B.bar).toBeTruthy() expect(Object.keys(C.wrappedComponent.propTypes!)).toEqual(["x"]) const ref = React.createRef<B>() render(<C booh={42} ref={ref} />) expect(ref.current?.testField).toBe(1) }) test("propTypes and defaultProps are forwarded", () => { const msg: Array<string> = [] const baseError = console.error console.error = m => msg.push(m) const C: React.ComponentClass<any> = inject("foo")( class C extends React.Component<any, any> { render() { expect(this.props.y).toEqual(3) expect(this.props.x).toBeUndefined() return null } } ) C.propTypes = { x: PropTypes.func.isRequired, z: PropTypes.string.isRequired } // @ts-ignore C.wrappedComponent.propTypes = { a: PropTypes.func.isRequired } C.defaultProps = { y: 3 } const B = () => <C z="test" /> const A = () => ( <Provider foo="bar"> <B /> </Provider> ) render(<A />) expect(msg.length).toBe(2) expect(msg[0].split("\n")[0]).toBe( "Warning: Failed prop type: The prop `x` is marked as required in `inject-with-foo(C)`, but its value is `undefined`." ) expect(msg[1].split("\n")[0]).toBe( "Warning: Failed prop type: The prop `a` is marked as required in `C`, but its value is `undefined`." ) console.error = baseError }) test("warning is not printed when attaching propTypes to injected component", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C: React.ComponentClass = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("warning is not printed when attaching propTypes to wrappedComponent", () => { let msg = [] const baseWarn = console.warn console.warn = m => (msg = m) const C = inject("foo")( class C extends React.Component<any, any> { render() { return ( <div> context: {this.props.foo} </div> ) } } ) C.wrappedComponent.propTypes = {} expect(msg.length).toBe(0) console.warn = baseWarn }) test("using a custom injector is reactive", () => { const user = observable({ name: "Noa" }) const mapper = stores => ({ name: stores.user.name }) const DisplayName = props => <h1>{props.name}</h1> const User = inject(mapper)(DisplayName) const App = () => ( <Provider user={user}> <User /> </Provider> ) const { container } = render(<App />) expect(container).toHaveTextContent("Noa") act(() => { user.name = "Veria" }) expect(container).toHaveTextContent("Veria") }) test("using a custom injector is not too reactive", () => { let listRender = 0 let itemRender = 0 let injectRender = 0 function connect() { const args = arguments return (component: IReactComponent) => // @ts-ignore inject.apply(this, args)(observer(component)) } class State { @observable highlighted = null isHighlighted(item) { return this.highlighted == item } @action highlight = item => { this.highlighted = item } constructor() { makeObservable(this) } } const items = observable([ { title: "ItemA" }, { title: "ItemB" }, { title: "ItemC" }, { title: "ItemD" }, { title: "ItemE" }, { title: "ItemF" } ]) const state = new State() class ListComponent extends React.PureComponent<any> { render() { listRender++ const { items } = this.props return ( <ul> {items.map(item => ( <ItemComponent key={item.title} item={item} /> ))} </ul> ) } } // @ts-ignore @connect(({ state }, { item }) => { injectRender++ if (injectRender > 6) { // debugger; } return { // Using // highlighted: expr(() => state.isHighlighted(item)) // seems to fix the problem highlighted: state.isHighlighted(item), highlight: state.highlight } }) class ItemComponent extends React.PureComponent<any> { highlight = () => { const { item, highlight } = this.props highlight(item) } render() { itemRender++ const { highlighted, item } = this.props return ( <li className={"hl_" + item.title} onClick={this.highlight}> {item.title} {highlighted ? "(highlighted)" : ""}{" "} </li> ) } } const { container } = render( <Provider state={state}> <ListComponent items={items} /> </Provider> ) expect(listRender).toBe(1) expect(injectRender).toBe(6) expect(itemRender).toBe(6) container.querySelectorAll(".hl_ItemB").forEach((e: Element) => (e as HTMLElement).click()) expect(listRender).toBe(1) expect(injectRender).toBe(12) // ideally, 7 expect(itemRender).toBe(7) container.querySelectorAll(".hl_ItemF").forEach((e: Element) => (e as HTMLElement).click()) expect(listRender).toBe(1) expect(injectRender).toBe(18) // ideally, 9 expect(itemRender).toBe(9) }) }) test("#612 - mixed context types", () => { const SomeContext = React.createContext(true) class MainCompClass extends React.Component<any, any> { static contextType = SomeContext render() { let active = this.context return active ? this.props.value : "Inactive" } } const MainComp = inject((stores: any) => ({ value: stores.appState.value }))(MainCompClass) const appState = observable({ value: "Something" }) function App() { return ( <Provider appState={appState}> <SomeContext.Provider value={true}> <MainComp /> </SomeContext.Provider> </Provider> ) } render(<App />) })
the_stack
import { IHttpPostMessageResponse } from 'http-post-message'; import { CommonErrorCodes, DisplayOption, FiltersOperations, ICustomPageSize, IFilter, IPage, IUpdateFiltersRequest, IVisual, LayoutType, PageLevelFilters, PageSizeType, SectionVisibility, VisualContainerDisplayMode, IPageBackground, IPageWallpaper, } from 'powerbi-models'; import { IFilterable } from './ifilterable'; import { IReportNode, Report } from './report'; import { VisualDescriptor } from './visualDescriptor'; import { isRDLEmbed } from './util'; import { APINotSupportedForRDLError } from './errors'; /** * A Page node within a report hierarchy * * @export * @interface IPageNode */ export interface IPageNode { report: IReportNode; name: string; } /** * A Power BI report page * * @export * @class Page * @implements {IPageNode} * @implements {IFilterable} */ export class Page implements IPageNode, IFilterable { /** * The parent Power BI report that this page is a member of * * @type {IReportNode} */ report: IReportNode; /** * The report page name * * @type {string} */ name: string; /** * The user defined display name of the report page, which is undefined if the page is created manually * * @type {string} */ displayName: string; /** * Is this page is the active page * * @type {boolean} */ isActive: boolean; /** * The visibility of the page. * 0 - Always Visible * 1 - Hidden in View Mode * * @type {SectionVisibility} */ visibility: SectionVisibility; /** * Page size as saved in the report. * * @type {ICustomPageSize} */ defaultSize: ICustomPageSize; /** * Mobile view page size (if defined) as saved in the report. * * @type {ICustomPageSize} */ mobileSize: ICustomPageSize; /** * Page display options as saved in the report. * * @type {ICustomPageSize} */ defaultDisplayOption: DisplayOption; /** * Page background color. * * @type {IPageBackground} */ background: IPageBackground; /** * Page wallpaper color. * * @type {IPageWallpaper} */ wallpaper: IPageWallpaper; /** * Creates an instance of a Power BI report page. * * @param {IReportNode} report * @param {string} name * @param {string} [displayName] * @param {boolean} [isActivePage] * @param {SectionVisibility} [visibility] * @hidden */ constructor(report: IReportNode, name: string, displayName?: string, isActivePage?: boolean, visibility?: SectionVisibility, defaultSize?: ICustomPageSize, defaultDisplayOption?: DisplayOption, mobileSize?: ICustomPageSize, background?: IPageBackground, wallpaper?: IPageWallpaper) { this.report = report; this.name = name; this.displayName = displayName; this.isActive = isActivePage; this.visibility = visibility; this.defaultSize = defaultSize; this.mobileSize = mobileSize; this.defaultDisplayOption = defaultDisplayOption; this.background = background; this.wallpaper = wallpaper; } /** * Gets all page level filters within the report. * * ```javascript * page.getFilters() * .then(filters => { ... }); * ``` * * @returns {(Promise<IFilter[]>)} */ async getFilters(): Promise<IFilter[]> { try { const response = await this.report.service.hpm.get<IFilter[]>(`/report/pages/${this.name}/filters`, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); return response.body; } catch (response) { throw response.body; } } /** * Update the filters for the current page according to the operation: Add, replace all, replace by target or remove. * * ```javascript * page.updateFilters(FiltersOperations.Add, filters) * .catch(errors => { ... }); * ``` * * @param {(IFilter[])} filters * @returns {Promise<IHttpPostMessageResponse<void>>} */ async updateFilters(operation: FiltersOperations, filters?: IFilter[]): Promise<IHttpPostMessageResponse<void>> { const updateFiltersRequest: IUpdateFiltersRequest = { filtersOperation: operation, filters: filters as PageLevelFilters[] }; try { return await this.report.service.hpm.post<void>(`/report/pages/${this.name}/filters`, updateFiltersRequest, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); } catch (response) { throw response.body; } } /** * Removes all filters from this page of the report. * * ```javascript * page.removeFilters(); * ``` * * @returns {Promise<IHttpPostMessageResponse<void>>} */ async removeFilters(): Promise<IHttpPostMessageResponse<void>> { return await this.updateFilters(FiltersOperations.RemoveAll); } /** * Sets all filters on the current page. * * ```javascript * page.setFilters(filters) * .catch(errors => { ... }); * ``` * * @param {(IFilter[])} filters * @returns {Promise<IHttpPostMessageResponse<void>>} */ async setFilters(filters: IFilter[]): Promise<IHttpPostMessageResponse<void>> { try { return await this.report.service.hpm.put<void>(`/report/pages/${this.name}/filters`, filters, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); } catch (response) { throw response.body; } } /** * Delete the page from the report * * ```javascript * // Delete the page from the report * page.delete(); * ``` * * @returns {Promise<void>} */ async delete(): Promise<void> { try { const response = await this.report.service.hpm.delete<void>(`/report/pages/${this.name}`, {}, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); return response.body; } catch (response) { throw response.body; } } /** * Makes the current page the active page of the report. * * ```javascript * page.setActive(); * ``` * * @returns {Promise<IHttpPostMessageResponse<void>>} */ async setActive(): Promise<IHttpPostMessageResponse<void>> { const page: IPage = { name: this.name, displayName: null, isActive: true }; try { return await this.report.service.hpm.put<void>('/report/pages/active', page, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); } catch (response) { throw response.body; } } /** * Set displayName to the current page. * * ```javascript * page.setName(displayName); * ``` * * @returns {Promise<IHttpPostMessageResponse<void>>} */ async setDisplayName(displayName: string): Promise<IHttpPostMessageResponse<void>> { const page: IPage = { name: this.name, displayName: displayName, }; try { return await this.report.service.hpm.put<void>(`/report/pages/${this.name}/name`, page, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); } catch (response) { throw response.body; } } /** * Gets all the visuals on the page. * * ```javascript * page.getVisuals() * .then(visuals => { ... }); * ``` * * @returns {Promise<VisualDescriptor[]>} */ async getVisuals(): Promise<VisualDescriptor[]> { if (isRDLEmbed(this.report.config.embedUrl)) { return Promise.reject(APINotSupportedForRDLError); } try { const response = await this.report.service.hpm.get<IVisual[]>(`/report/pages/${this.name}/visuals`, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); return response.body .map((visual) => new VisualDescriptor(this, visual.name, visual.title, visual.type, visual.layout)); } catch (response) { throw response.body; } } /** * Gets a visual by name on the page. * * ```javascript * page.getVisualByName(visualName: string) * .then(visual => { * ... * }); * ``` * * @param {string} visualName * @returns {Promise<VisualDescriptor>} */ async getVisualByName(visualName: string): Promise<VisualDescriptor> { if (isRDLEmbed(this.report.config.embedUrl)) { return Promise.reject(APINotSupportedForRDLError); } try { const response = await this.report.service.hpm.get<IVisual[]>(`/report/pages/${this.name}/visuals`, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); const visual = response.body.find((v: IVisual) => v.name === visualName); if (!visual) { return Promise.reject(CommonErrorCodes.NotFound); } return new VisualDescriptor(this, visual.name, visual.title, visual.type, visual.layout); } catch (response) { throw response.body; } } /** * Updates the display state of a visual in a page. * * ```javascript * page.setVisualDisplayState(visualName, displayState) * .catch(error => { ... }); * ``` * * @param {string} visualName * @param {VisualContainerDisplayMode} displayState * @returns {Promise<IHttpPostMessageResponse<void>>} */ async setVisualDisplayState(visualName: string, displayState: VisualContainerDisplayMode): Promise<IHttpPostMessageResponse<void>> { const pageName = this.name; const report = this.report as Report; return report.setVisualDisplayState(pageName, visualName, displayState); } /** * Updates the position of a visual in a page. * * ```javascript * page.moveVisual(visualName, x, y, z) * .catch(error => { ... }); * ``` * * @param {string} visualName * @param {number} x * @param {number} y * @param {number} z * @returns {Promise<IHttpPostMessageResponse<void>>} */ async moveVisual(visualName: string, x: number, y: number, z?: number): Promise<IHttpPostMessageResponse<void>> { const pageName = this.name; const report = this.report as Report; return report.moveVisual(pageName, visualName, x, y, z); } /** * Resize a visual in a page. * * ```javascript * page.resizeVisual(visualName, width, height) * .catch(error => { ... }); * ``` * * @param {string} visualName * @param {number} width * @param {number} height * @returns {Promise<IHttpPostMessageResponse<void>>} */ async resizeVisual(visualName: string, width: number, height: number): Promise<IHttpPostMessageResponse<void>> { const pageName = this.name; const report = this.report as Report; return report.resizeVisual(pageName, visualName, width, height); } /** * Updates the size of active page. * * ```javascript * page.resizePage(pageSizeType, width, height) * .catch(error => { ... }); * ``` * * @param {PageSizeType} pageSizeType * @param {number} width * @param {number} height * @returns {Promise<IHttpPostMessageResponse<void>>} */ async resizePage(pageSizeType: PageSizeType, width?: number, height?: number): Promise<IHttpPostMessageResponse<void>> { if (!this.isActive) { return Promise.reject('Cannot resize the page. Only the active page can be resized'); } const report = this.report as Report; return report.resizeActivePage(pageSizeType, width, height); } /** * Gets the list of slicer visuals on the page. * * ```javascript * page.getSlicers() * .then(slicers => { * ... * }); * ``` * * @returns {Promise<IVisual[]>} */ async getSlicers(): Promise<IVisual[]> { if (isRDLEmbed(this.report.config.embedUrl)) { return Promise.reject(APINotSupportedForRDLError); } try { const response = await this.report.service.hpm.get<IVisual[]>(`/report/pages/${this.name}/visuals`, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); return response.body .filter((visual: IVisual) => visual.type === 'slicer') .map((visual: IVisual) => new VisualDescriptor(this, visual.name, visual.title, visual.type, visual.layout)); } catch (response) { throw response.body; } } /** * Checks if page has layout. * * ```javascript * page.hasLayout(layoutType) * .then(hasLayout: boolean => { ... }); * ``` * * @returns {(Promise<boolean>)} */ async hasLayout(layoutType: LayoutType): Promise<boolean> { if (isRDLEmbed(this.report.config.embedUrl)) { return Promise.reject(APINotSupportedForRDLError); } const layoutTypeEnum = LayoutType[layoutType]; try { const response = await this.report.service.hpm.get<boolean>(`/report/pages/${this.name}/layoutTypes/${layoutTypeEnum}`, { uid: this.report.config.uniqueId }, this.report.iframe.contentWindow); return response.body; } catch (response) { throw response.body; } } }
the_stack
import { ParseQueryConfig } from '../src/parser/parser'; export interface TestCaseForFormat { testCase: number; soql: string; isValid: boolean; options?: ParseQueryConfig; } export const testCases: TestCaseForFormat[] = [ { testCase: 1, soql: 'SELECT Id, Name, BillingCity FROM Account', isValid: true, }, { testCase: 2, soql: 'SELECT Name FROM Account ORDER BY Name DESC NULLS LAST', isValid: true, }, { testCase: 3, soql: 'SELECT COUNT() FROM Contact', isValid: true, }, { testCase: 4, soql: 'SELECT LeadSource, COUNT(Name) FROM Lead GROUP BY LeadSource', isValid: true, }, { testCase: 5, soql: 'SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING COUNT(Id) > 1', isValid: true, }, { testCase: 6, soql: 'SELECT Name, Id FROM Merchandise__c ORDER BY Name OFFSET 100', isValid: true, }, { testCase: 7, soql: 'SELECT Name, Id FROM Merchandise__c ORDER BY Name LIMIT 20 OFFSET 100', isValid: true, }, { testCase: 8, soql: 'SELECT Contact.FirstName, Contact.Account.Name FROM Contact', isValid: true, }, { testCase: 9, soql: 'SELECT Name, (SELECT LastName FROM Contacts) FROM Account', isValid: true, }, { testCase: 10, soql: 'SELECT Account.Name, (SELECT Contact.LastName FROM Account.Contacts) FROM Account', isValid: true, }, { testCase: 11, soql: 'SELECT Id, What.Name FROM Event', isValid: true, }, { testCase: 12, soql: 'SELECT Name, (SELECT CreatedBy.Name FROM Notes) FROM Account', isValid: true, }, { testCase: 13, soql: 'SELECT UserId, LoginTime FROM LoginHistory', isValid: true, }, { testCase: 14, soql: 'SELECT Id, Name, IsActive, SobjectType, DeveloperName, Description FROM RecordType', isValid: true, }, { testCase: 15, soql: 'SELECT CampaignId, AVG(Amount) avg FROM Opportunity GROUP BY CampaignId HAVING COUNT(Id, Name) > 1', isValid: true, }, { testCase: 16, soql: 'SELECT LeadSource, COUNT(Name) cnt FROM Lead GROUP BY ROLLUP(LeadSource)', isValid: true, }, { testCase: 17, soql: 'SELECT Status, LeadSource, COUNT(Name) cnt FROM Lead GROUP BY ROLLUP(Status, LeadSource)', isValid: true, }, { testCase: 18, soql: 'SELECT Id, Name, BillingCity FROMAccount', isValid: false, }, { testCase: 19, soql: 'SELECTName FROM Account ORDER BY Name DESC NULLS LAST', isValid: false, }, { testCase: 20, soql: 'SELECT COUNT()FROM Contact', isValid: true, }, { testCase: 21, soql: 'SELECT LeadSourceCOUNT(Name) FROM Lead GROUP BY LeadSource', isValid: false, }, { testCase: 22, soql: 'SELECT Name, COUNT(Id) FROM Account GROUPBY Name HAVING COUNT(Id) > 1', isValid: false, }, { testCase: 23, soql: 'SELECT Name, Id FROM Merchandise__c ORDER BY Name OFFSET100', isValid: false, }, { testCase: 24, soql: 'SELECT Name, Id FROM ORDER BY Name LIMIT 20 OFFSET 100', isValid: false, }, { testCase: 25, soql: 'SELECT Contact..FirstName, Contact.Account.Name FROM Contact', isValid: false, }, { testCase: 26, soql: 'SELECT Name (SELECT LastName FROM Contacts) FROM Account', isValid: false, }, { testCase: 27, soql: 'SELECT Account.Name, (SELECT Contact.LastName FROM Account.Contacts) FROMAccount', isValid: false, }, { testCase: 28, soql: 'SELECT Id, What.Name FROMEvent', isValid: false, }, { testCase: 29, soql: 'select some fake text', isValid: false, }, { testCase: 30, soql: 'SELECT Id, Format FROM Account', isValid: true, }, { testCase: 31, soql: `SELECT Id, FirstName__c, Mother_of_Child__r.FirstName__c FROM Daughter__c WHERE Mother_of_Child__r.LastName__c LastName__c LIKE 'C%'`, isValid: false, }, { testCase: 32, soql: `SELECT Id FROM Contact WHERE Name LIKE 'A%' AND MailingCity = 'California' fds`, isValid: false, }, { testCase: 33, soql: `SELECT Name, (SELECT LastName FROM Contacts WHERE CreatedBy.Alias='x') FROM Account WHERE Industry='media' AND Id = foo`, isValid: false, }, { testCase: 34, soql: `SELECT Name FROM Account WHERE Id = foo`, isValid: false }, // this parses incorrectly { testCase: 35, soql: `SELECT Name FROM Account WHERE`, isValid: false }, // throws exception { testCase: 36, soql: `SELECT Name FROM Account ORDER BY`, isValid: false }, { testCase: 37, soql: `SELECT Name FROM Account LIMIT`, isValid: false }, { testCase: 38, soql: `SELECT Name FROM Account LIMIT 'foo'`, isValid: false }, { testCase: 39, soql: `SELECT Name FROM Account OFFSET`, isValid: true }, { testCase: 40, soql: `SELECT Name FROM Account OFFSET 'foo'`, isValid: false }, { testCase: 41, soql: `SELECT Name FROM Account OFFSET 1`, isValid: true }, { testCase: 42, soql: `SELECT Name, COUNT(Id) FROM Account GROUP BY Name HAVING`, isValid: false }, // this throws exception { testCase: 43, soql: `SELECT FROM Account WHERE Id = foo`, isValid: false }, { testCase: 44, soql: `SELECT Name FROM Account FROM Account WHERE Id = foo`, isValid: false }, { testCase: 45, soql: `SELECT Name FROM Account HAVING COUNT(Id) > 1`, isValid: false }, { testCase: 46, soql: `SELECT Name FROM Account WHERE`, isValid: false }, { testCase: 47, soql: `SELECT Name FROM Account WITH`, isValid: false }, { testCase: 48, soql: `SELECT Name FROM Account WITH SECURITY_ENFORCED`, isValid: true }, { testCase: 49, soql: `SELECT Name FROM Account GROUP BY`, isValid: false }, { testCase: 50, soql: `SELECT Name FROM Account ORDER BY`, isValid: false }, { testCase: 51, soql: `SELECT Name FROM Account LIMIT`, isValid: false }, { testCase: 52, soql: `SELECT Name FROM Account For`, isValid: false }, { testCase: 53, soql: `SELECT Name FROM Account For View`, isValid: true }, { testCase: 54, soql: `SELECT Name FROM Account For Reference`, isValid: true }, { testCase: 55, soql: `SELECT Name FROM Account For Update`, isValid: true }, // { testCase: 56, soql: `SELECT Name myAlias FROM Account`, isValid: false }, // FIXME: this should be invalid because alias is not used in groupby { testCase: 57, soql: `SELECT Count() myAlias FROM Account`, isValid: true }, { testCase: 58, soql: `SELECT CALENDAR_YEAR(CreatedDate), SUM(Amount) mySum FROM Opportunity GROUP BY CALENDAR_YEAR(CreatedDate)`, isValid: true, }, { testCase: 59, soql: `SELECT CALENDAR_YEAR(CreatedDate) calYear, SUM(Amount) mySum FROM Opportunity GROUP BY CALENDAR_YEAR(CreatedDate)`, isValid: true, }, { testCase: 60, soql: `select count() myalias from account`, isValid: true }, { testCase: 61, soql: `SELECT COUNT() MYALIAS FROM ACCOUNT`, isValid: true }, { testCase: 63, soql: `SeLEct CouNt() myAlias frOM Account`, isValid: true }, { testCase: 64, soql: `SELECT Id FROM Account WHERE CreatedDate = YESTERDAY`, isValid: true }, { testCase: 65, soql: `SELECT Id FROM Account WHERE CreatedDate > TODAY`, isValid: true }, { testCase: 66, soql: `SELECT Id FROM Opportunity WHERE CloseDate = TOMORROW`, isValid: true }, { testCase: 67, soql: `SELECT Id FROM Account WHERE CreatedDate > LAST_WEEK`, isValid: true }, { testCase: 68, soql: `SELECT Id FROM Account WHERE CreatedDate < THIS_WEEK`, isValid: true }, { testCase: 69, soql: `SELECT Id FROM Opportunity WHERE CloseDate = NEXT_WEEK`, isValid: true }, { testCase: 70, soql: `SELECT Id FROM Opportunity WHERE CloseDate > LAST_MONTH`, isValid: true }, { testCase: 71, soql: `SELECT Id FROM Account WHERE CreatedDate < THIS_MONTH`, isValid: true }, { testCase: 73, soql: `SELECT Id FROM Opportunity WHERE CloseDate = NEXT_MONTH`, isValid: true }, { testCase: 74, soql: `SELECT Id FROM Account WHERE CreatedDate = LAST_90_DAYS`, isValid: true }, { testCase: 75, soql: `SELECT Id FROM Opportunity WHERE CloseDate > NEXT_90_DAYS`, isValid: true }, { testCase: 76, soql: `SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:365`, isValid: true }, { testCase: 77, soql: `SELECT Id FROM Opportunity WHERE CloseDate > NEXT_N_DAYS:15`, isValid: true }, { testCase: 78, soql: `SELECT Id FROM Opportunity WHERE CloseDate > NEXT_N_WEEKS:4`, isValid: true }, { testCase: 79, soql: `SELECT Id FROM Account WHERE CreatedDate = LAST_N_WEEKS:52`, isValid: true }, { testCase: 80, soql: `SELECT Id FROM Opportunity WHERE CloseDate > NEXT_N_MONTHS:2`, isValid: true }, { testCase: 81, soql: `SELECT Id FROM Account WHERE CreatedDate = LAST_N_MONTHS:12`, isValid: true }, { testCase: 83, soql: `SELECT Id FROM Account WHERE CreatedDate = THIS_QUARTER`, isValid: true }, { testCase: 84, soql: `SELECT Id FROM Account WHERE CreatedDate > LAST_QUARTER`, isValid: true }, { testCase: 85, soql: `SELECT Id FROM Account WHERE CreatedDate < NEXT_QUARTER`, isValid: true }, { testCase: 86, soql: `SELECT Id FROM Account WHERE CreatedDate < NEXT_N_QUARTERS:2`, isValid: true }, { testCase: 87, soql: `SELECT Id FROM Account WHERE CreatedDate > LAST_N_QUARTERS:2`, isValid: true }, { testCase: 88, soql: `SELECT Id FROM Opportunity WHERE CloseDate = THIS_YEAR`, isValid: true }, { testCase: 89, soql: `SELECT Id FROM Opportunity WHERE CloseDate > LAST_YEAR`, isValid: true }, { testCase: 90, soql: `SELECT Id FROM Opportunity WHERE CloseDate < NEXT_YEAR`, isValid: true }, { testCase: 91, soql: `SELECT Id FROM Opportunity WHERE CloseDate < NEXT_N_YEARS:5`, isValid: true }, { testCase: 93, soql: `SELECT Id FROM Opportunity WHERE CloseDate > LAST_N_YEARS:5`, isValid: true }, { testCase: 94, soql: `SELECT Id FROM Account WHERE CreatedDate = THIS_FISCAL_QUARTER`, isValid: true }, { testCase: 95, soql: `SELECT Id FROM Account WHERE CreatedDate > LAST_FISCAL_QUARTER`, isValid: true }, { testCase: 96, soql: `SELECT Id FROM Account WHERE CreatedDate < NEXT_FISCAL_QUARTER`, isValid: true }, { testCase: 97, soql: `SELECT Id FROM Account WHERE CreatedDate < NEXT_N_FISCAL_QUARTERS:6`, isValid: true }, { testCase: 98, soql: `SELECT Id FROM Account WHERE CreatedDate > LAST_N_FISCAL_QUARTERS:6`, isValid: true }, { testCase: 99, soql: `SELECT Id FROM Opportunity WHERE CloseDate = THIS_FISCAL_YEAR`, isValid: true }, { testCase: 100, soql: `SELECT Id FROM Opportunity WHERE CloseDate > LAST_FISCAL_YEAR`, isValid: true }, { testCase: 101, soql: `SELECT Id FROM Opportunity WHERE CloseDate < NEXT_FISCAL_YEAR`, isValid: true }, { testCase: 102, soql: `SELECT Id FROM Opportunity WHERE CloseDate < NEXT_N_FISCAL_YEARS:3`, isValid: true }, { testCase: 103, soql: `SELECT Id FROM Opportunity WHERE CloseDate > LAST_N_FISCAL_YEARS:3`, isValid: true }, { testCase: 104, soql: `SELECT Name FROM Account WHERE Id = :foo`, isValid: false }, { testCase: 105, soql: `SELECT Name FROM Account WHERE Id = :foo`, isValid: true, options: { allowApexBindVariables: true } }, { testCase: 106, soql: `SELECT Id, Title FROM Dashboard USING SCOPE allPrivate WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 107, soql: `SELECT Id, Title FROM Dashboard USING SCOPE Delegated WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 108, soql: `SELECT Id, Title FROM Dashboard USING SCOPE Mine WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 109, soql: `SELECT Id, Title FROM Dashboard USING SCOPE Everything WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 110, soql: `SELECT Id, Title FROM Dashboard USING SCOPE MineAndMyGroups WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 111, soql: `SELECT Id, Title FROM Dashboard USING SCOPE My_Territory WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 112, soql: `SELECT Id, Title FROM Dashboard USING SCOPE My_Team_Territory WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 113, soql: `SELECT Id, Title FROM Dashboard USING SCOPE Team WHERE Type != 'SpecifiedUser'`, isValid: true }, { testCase: 114, soql: `SELECT Name, Id FROM Merchandise__c ORDER BY Name LIMIT 100 OFFSET 0`, isValid: true }, { testCase: 115, soql: `SELECT Name, Id FROM Merchandise__c ORDER BY Name LIMIT 100 OFFSET -10`, isValid: false }, { testCase: 116, soql: `SELECT Name, Id FROM Merchandise__c ORDER BY Name LIMIT -10 OFFSET 10`, isValid: false }, { testCase: 117, soql: `SELECT Title FROM Question WHERE LastReplyDate < 2005-10-08T01:02:03Z WITH DATA CATEGORY Product__c AT mobile_phones__c`, isValid: true, }, { testCase: 118, soql: `SELECT Title, Summary FROM KnowledgeArticleVersion WHERE PublishStatus='Online' AND Language = 'en_US' WITH DATA CATEGORY Geography__c ABOVE_OR_BELOW europe__c AND Product__c BELOW All__c`, isValid: true, }, { testCase: 119, soql: `SELECT Id, Title FROM Offer__kav WHERE PublishStatus='Draft' AND Language = 'en_US' WITH DATA CATEGORY Geography__c AT (france__c,usa__c) AND Product__c ABOVE dsl__c`, isValid: true, }, { testCase: 120, soql: `SELECT FORMAT(MIN(closedate)) Amt FROM opportunity`, isValid: true }, { testCase: 121, soql: `SELECT amount, FORMAT(amount) Amt, convertCurrency(amount) editDate, FORMAT(convertCurrency(amount)) convertedCurrency FROM Opportunity where id = '12345'`, isValid: true, }, { testCase: 122, soql: `SELECT Id, Name FROM Opportunity WHERE Amount > USD5000`, isValid: true, }, { testCase: 123, soql: `SELECT Id, Name FROM Opportunity WHERE (((((Amount > USD5000`, isValid: false, }, { testCase: 124, soql: `SELECT Id, Name FROM Opportunity WHERE (((((Amount > USD5000))))`, isValid: false, }, { testCase: 125, soql: `SELECT Id, Name FROM Opportunity WHERE (((((Amount > USD5000)))))`, isValid: true, }, { testCase: 126, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3')) AND (((Description = '4') OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: true, }, { testCase: 127, soql: `SELECT Id FROM Account WHERE ((Name = '1' OR Name = '2') AND Name = '3')) AND (((Description = '4') OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 128, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2' AND Name = '3')) AND (((Description = '4') OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 129, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3') AND (((Description = '4') OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 130, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3') AND (((Description = '4') OR (Id = '5' AND Id = '6')) AND Id = '7'`, isValid: false, }, { testCase: 131, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3')) AND ((Description = '4') OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 132, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3')) AND (((Description = '4' OR (Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 133, soql: `SELECT Id FROM Account WHERE (((Name = '1' OR Name = '2') AND Name = '3')) AND (((Description = '4') OR Id = '5' AND Id = '6'))) AND Id = '7'`, isValid: false, }, { testCase: 134, soql: `SELECT Name, Count(Id) FROM Account GROUP BY Name HAVING Count(Id) > 0 AND (Name LIKE '%testing%)`, isValid: false, }, { testCase: 135, soql: `SELECT Name, Count(Id) FROM Account GROUP BY Name HAVING Count(Id) > 0 AND (Name LIKE '%testing%' OR Name LIKE '%123%')`, isValid: true, }, { testCase: 136, soql: `SELECT Name, Count(Id) FROM Account GROUP BY Name HAVING Count(Id) > 0 AND (Name LIKE '%testing%' OR Name LIKE '%123%'`, isValid: false, }, { testCase: 137, soql: `SELECT Name, StreetAddress__c FROM Warehouse__c WHERE GEOLOCATION(Location__c, DISTANCE(37.775, -122.418), 'mi') < 20`, isValid: false, }, { testCase: 138, soql: `SELECT Name, StreetAddress__c FROM Warehouse__c WHERE GEOLOCATION(37.775, -122.418) < 20`, isValid: false, }, { testCase: 139, soql: `SELECT Name, GEOLOCATION(37.775, -122.418) FROM Warehouse__c`, isValid: false, }, { testCase: 140, soql: `SELECT Name, DISTANCE(37.775, -122.418) FROM Warehouse__c`, isValid: false, }, { testCase: 141, soql: `SELECT Id, Name, Location, DISTANCE(Location, GEOLOCATION(10, 10), 'mi') FROM CONTACT`, isValid: true, }, { testCase: 142, soql: `SELECT Id, Name, Location, DISTANCE(Location, GEOLOCATION(10, 10), 'km') FROM CONTACT`, isValid: true, }, { testCase: 143, soql: `SELECT Id, Name, Location, DISTANCE(Location, GEOLOCATION(-10, -10), 'km') FROM CONTACT`, isValid: true, }, { testCase: 144, soql: `SELECT Id, Name, Location, DISTANCE(Location, GEOLOCATION(-10.775, -10.775), 'mi') FROM CONTACT`, isValid: true, }, { testCase: 145, soql: `SELECT Id, Name, Location, DISTANCE(Location, GEOLOCATION(10, 10), 'm') FROM CONTACT`, isValid: false, }, { testCase: 146, soql: `SELECT Id, Name, Location, DISTANCE(GEOLOCATION(37.775,-122.418), warehouse_location__c, 'km') FROM CONTACT`, isValid: false, }, { testCase: 147, soql: `SELECT Id, Name FROM Account ORDER BY CreatedDate Desc`, isValid: true, }, { testCase: 148, soql: `SELECT Id, Name FROM Account ORDER BY CreatedDate desc`, isValid: true, }, { testCase: 149, soql: `SELECT Id, Name FROM Account ORDER BY CreatedDate Asc`, isValid: true, }, { testCase: 150, soql: `SELECT Id, Name FROM Account ORDER BY CreatedDate asc`, isValid: true, }, { testCase: 151, soql: `SELECT sbqq__product__r.name foo, sbqq__quote__c bar FROM SBQQ__Quoteline__c group by sbqq__quote__c, sbqq__product__r.name`, isValid: true, }, { testCase: 152, soql: `SELECT sbqq__product__r.name foo, sbqq__quote__c foo1 FROM SBQQ__Quoteline__c group by sbqq__quote__c, sbqq__product__r.name`, isValid: true, }, { testCase: 153, soql: `SELECT AnnualRevenue FROM Account WHERE NOT (AnnualRevenue > 0 AND AnnualRevenue < 200000)`, isValid: true, }, { testCase: 154, soql: `SELECT AnnualRevenue FROM Account WHERE ((NOT AnnualRevenue > 0) AND AnnualRevenue < 200000) LIMIT 1`, isValid: true, }, { testCase: 155, soql: `SELECT Id FROM Account WHERE ((NOT (Name = '2' OR Name = '3')))`, isValid: true, }, { testCase: 156, soql: `SELECT Id FROM Account WHERE NOT (Name = '2' OR Name = '3')`, isValid: true, }, { testCase: 157, soql: `SELECT Id FROM Account WHERE NOT (Name = '2')`, isValid: true, }, { testCase: 158, soql: `SELECT Id FROM Account WHERE NOT Name = '2'`, isValid: true, }, { testCase: 158, options: { allowApexBindVariables: true }, soql: ` SELECT Id FROM Account WHERE Id IN :new Map< Id, SObject > (someVar) .getSomeClass() .records `, isValid: true, }, ]; export default testCases;
the_stack
import * as React from "react"; import { DraggableEventHandler, default as DraggableRoot } from "react-draggable"; import { Enable, Resizable, ResizeDirection } from "re-resizable"; // FIXME: https://github.com/mzabriskie/react-draggable/issues/381 // I can not find `scale` too... type $TODO = any; const Draggable: any = DraggableRoot; export type Grid = [number, number]; export type Position = { x: number; y: number; }; export type DraggableData = { node: HTMLElement; deltaX: number; deltaY: number; lastX: number; lastY: number; } & Position; export type RndDragCallback = DraggableEventHandler; export type RndDragEvent = | React.MouseEvent<HTMLElement | SVGElement> | React.TouchEvent<HTMLElement | SVGElement> | MouseEvent | TouchEvent; export type RndResizeStartCallback = ( e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>, dir: ResizeDirection, elementRef: HTMLElement, ) => void | boolean; export type ResizableDelta = { width: number; height: number; }; export type RndResizeCallback = ( e: MouseEvent | TouchEvent, dir: ResizeDirection, elementRef: HTMLElement, delta: ResizableDelta, position: Position, ) => void; type Size = { width: string | number; height: string | number; }; type State = { resizing: boolean; bounds: { top: number; right: number; bottom: number; left: number; }; maxWidth?: number | string; maxHeight?: number | string; }; type MaxSize = { maxWidth: number | string; maxHeight: number | string; }; export type ResizeEnable = | { bottom?: boolean; bottomLeft?: boolean; bottomRight?: boolean; left?: boolean; right?: boolean; top?: boolean; topLeft?: boolean; topRight?: boolean; } | boolean; export type HandleClasses = { bottom?: string; bottomLeft?: string; bottomRight?: string; left?: string; right?: string; top?: string; topLeft?: string; topRight?: string; }; export type HandleStyles = { bottom?: React.CSSProperties; bottomLeft?: React.CSSProperties; bottomRight?: React.CSSProperties; left?: React.CSSProperties; right?: React.CSSProperties; top?: React.CSSProperties; topLeft?: React.CSSProperties; topRight?: React.CSSProperties; }; export type HandleComponent = { top?: React.ReactElement<any>; right?: React.ReactElement<any>; bottom?: React.ReactElement<any>; left?: React.ReactElement<any>; topRight?: React.ReactElement<any>; bottomRight?: React.ReactElement<any>; bottomLeft?: React.ReactElement<any>; topLeft?: React.ReactElement<any>; }; export interface Props { dragGrid?: Grid; default?: { x: number; y: number; } & Size; position?: { x: number; y: number; }; size?: Size; resizeGrid?: Grid; bounds?: string; onMouseDown?: (e: MouseEvent) => void; onMouseUp?: (e: MouseEvent) => void; onResizeStart?: RndResizeStartCallback; onResize?: RndResizeCallback; onResizeStop?: RndResizeCallback; onDragStart?: RndDragCallback; onDrag?: RndDragCallback; onDragStop?: RndDragCallback; className?: string; style?: React.CSSProperties; children?: React.ReactNode; enableResizing?: ResizeEnable; resizeHandleClasses?: HandleClasses; resizeHandleStyles?: HandleStyles; resizeHandleWrapperClass?: string; resizeHandleWrapperStyle?: React.CSSProperties; resizeHandleComponent?: HandleComponent; lockAspectRatio?: boolean | number; lockAspectRatioExtraWidth?: number; lockAspectRatioExtraHeight?: number; maxHeight?: number | string; maxWidth?: number | string; minHeight?: number | string; minWidth?: number | string; dragAxis?: "x" | "y" | "both" | "none"; dragHandleClassName?: string; disableDragging?: boolean; cancel?: string; enableUserSelectHack?: boolean; allowAnyClick?: boolean; scale?: number; [key: string]: any; } const resizableStyle = { width: "auto" as "auto", height: "auto" as "auto", display: "inline-block" as "inline-block", position: "absolute" as "absolute", top: 0, left: 0, }; const getEnableResizingByFlag = (flag: boolean): Enable => ({ bottom: flag, bottomLeft: flag, bottomRight: flag, left: flag, right: flag, top: flag, topLeft: flag, topRight: flag, }); interface DefaultProps { maxWidth: number; maxHeight: number; onResizeStart: RndResizeStartCallback; onResize: RndResizeCallback; onResizeStop: RndResizeCallback; onDragStart: RndDragCallback; onDrag: RndDragCallback; onDragStop: RndDragCallback; scale: number; } export class Rnd extends React.PureComponent<Props, State> { public static defaultProps: DefaultProps = { maxWidth: Number.MAX_SAFE_INTEGER, maxHeight: Number.MAX_SAFE_INTEGER, scale: 1, onResizeStart: () => {}, onResize: () => {}, onResizeStop: () => {}, onDragStart: () => {}, onDrag: () => {}, onDragStop: () => {}, }; resizable!: Resizable; draggable!: $TODO; // Draggable; resizingPosition = { x: 0, y: 0 }; offsetFromParent = { left: 0, top: 0 }; resizableElement: { current: HTMLElement | null } = { current: null }; originalPosition = { x: 0, y: 0 }; constructor(props: Props) { super(props); this.state = { resizing: false, bounds: { top: 0, right: 0, bottom: 0, left: 0, }, maxWidth: props.maxWidth, maxHeight: props.maxHeight, }; this.onResizeStart = this.onResizeStart.bind(this); this.onResize = this.onResize.bind(this); this.onResizeStop = this.onResizeStop.bind(this); this.onDragStart = this.onDragStart.bind(this); this.onDrag = this.onDrag.bind(this); this.onDragStop = this.onDragStop.bind(this); this.getMaxSizesFromProps = this.getMaxSizesFromProps.bind(this); } componentDidMount() { this.updateOffsetFromParent(); const { left, top } = this.offsetFromParent; const { x, y } = this.getDraggablePosition(); this.draggable.setState({ x: x - left, y: y - top, }); // HACK: Apply position adjustment this.forceUpdate(); } // HACK: To get `react-draggable` state x and y. getDraggablePosition(): { x: number; y: number } { const { x, y } = (this.draggable as any).state; return { x, y }; } getParent() { return this.resizable && (this.resizable as any).parentNode; } getParentSize(): { width: number; height: number } { return (this.resizable as any).getParentSize(); } getMaxSizesFromProps(): MaxSize { const maxWidth = typeof this.props.maxWidth === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxWidth; const maxHeight = typeof this.props.maxHeight === "undefined" ? Number.MAX_SAFE_INTEGER : this.props.maxHeight; return { maxWidth, maxHeight }; } getSelfElement(): HTMLElement | null { return this.resizable && this.resizable.resizable; } getOffsetHeight(boundary: HTMLElement) { const scale = this.props.scale as number; switch (this.props.bounds) { case "window": return window.innerHeight / scale; case "body": return document.body.offsetHeight / scale; default: return boundary.offsetHeight; } } getOffsetWidth(boundary: HTMLElement) { const scale = this.props.scale as number; switch (this.props.bounds) { case "window": return window.innerWidth / scale; case "body": return document.body.offsetWidth / scale; default: return boundary.offsetWidth; } } onDragStart(e: RndDragEvent, data: DraggableData) { if (this.props.onDragStart) { this.props.onDragStart(e, data); } const pos = this.getDraggablePosition(); this.originalPosition = pos; if (!this.props.bounds) return; const parent = this.getParent(); const scale = this.props.scale as number; let boundary; if (this.props.bounds === "parent") { boundary = parent; } else if (this.props.bounds === "body") { const parentRect = parent.getBoundingClientRect(); const parentLeft = parentRect.left; const parentTop = parentRect.top; const bodyRect = document.body.getBoundingClientRect(); const left = -(parentLeft - parent.offsetLeft * scale - bodyRect.left) / scale; const top = -(parentTop - parent.offsetTop * scale - bodyRect.top) / scale; const right = (document.body.offsetWidth - this.resizable.size.width * scale) / scale + left; const bottom = (document.body.offsetHeight - this.resizable.size.height * scale) / scale + top; return this.setState({ bounds: { top, right, bottom, left } }); } else if (this.props.bounds === "window") { if (!this.resizable) return; const parentRect = parent.getBoundingClientRect(); const parentLeft = parentRect.left; const parentTop = parentRect.top; const left = -(parentLeft - parent.offsetLeft * scale) / scale; const top = -(parentTop - parent.offsetTop * scale) / scale; const right = (window.innerWidth - this.resizable.size.width * scale) / scale + left; const bottom = (window.innerHeight - this.resizable.size.height * scale) / scale + top; return this.setState({ bounds: { top, right, bottom, left } }); } else { boundary = document.querySelector(this.props.bounds); } if (!(boundary instanceof HTMLElement) || !(parent instanceof HTMLElement)) { return; } const boundaryRect = boundary.getBoundingClientRect(); const boundaryLeft = boundaryRect.left; const boundaryTop = boundaryRect.top; const parentRect = parent.getBoundingClientRect(); const parentLeft = parentRect.left; const parentTop = parentRect.top; const left = (boundaryLeft - parentLeft) / scale; const top = boundaryTop - parentTop; if (!this.resizable) return; this.updateOffsetFromParent(); const offset = this.offsetFromParent; this.setState({ bounds: { top: top - offset.top, right: left + (boundary.offsetWidth - this.resizable.size.width) - offset.left / scale, bottom: top + (boundary.offsetHeight - this.resizable.size.height) - offset.top, left: left - offset.left / scale, }, }); } onDrag(e: RndDragEvent, data: DraggableData) { if (!this.props.onDrag) return; const { left, top } = this.offsetFromParent; if (!this.props.dragAxis || this.props.dragAxis === "both") { return this.props.onDrag(e, { ...data, x: data.x - left, y: data.y - top }); } else if (this.props.dragAxis === "x") { return this.props.onDrag(e, { ...data, x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 }); } else if (this.props.dragAxis === "y") { return this.props.onDrag(e, { ...data, x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 }); } } onDragStop(e: RndDragEvent, data: DraggableData) { if (!this.props.onDragStop) return; const { left, top } = this.offsetFromParent; if (!this.props.dragAxis || this.props.dragAxis === "both") { return this.props.onDragStop(e, { ...data, x: data.x + left, y: data.y + top }); } else if (this.props.dragAxis === "x") { return this.props.onDragStop(e, { ...data, x: data.x + left, y: this.originalPosition.y + top, deltaY: 0 }); } else if (this.props.dragAxis === "y") { return this.props.onDragStop(e, { ...data, x: this.originalPosition.x + left, y: data.y + top, deltaX: 0 }); } } onResizeStart( e: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>, dir: ResizeDirection, elementRef: HTMLElement, ) { e.stopPropagation(); this.setState({ resizing: true, }); const scale = this.props.scale as number; const offset = this.offsetFromParent; const pos = this.getDraggablePosition(); this.resizingPosition = { x: pos.x + offset.left, y: pos.y + offset.top }; this.originalPosition = pos; if (this.props.bounds) { const parent = this.getParent(); let boundary; if (this.props.bounds === "parent") { boundary = parent; } else if (this.props.bounds === "body") { boundary = document.body; } else if (this.props.bounds === "window") { boundary = window; } else { boundary = document.querySelector(this.props.bounds); } const self = this.getSelfElement(); if ( self instanceof Element && (boundary instanceof HTMLElement || boundary === window) && parent instanceof HTMLElement ) { let { maxWidth, maxHeight } = this.getMaxSizesFromProps(); const parentSize = this.getParentSize(); if (maxWidth && typeof maxWidth === "string") { if (maxWidth.endsWith("%")) { const ratio = Number(maxWidth.replace("%", "")) / 100; maxWidth = parentSize.width * ratio; } else if (maxWidth.endsWith("px")) { maxWidth = Number(maxWidth.replace("px", "")); } } if (maxHeight && typeof maxHeight === "string") { if (maxHeight.endsWith("%")) { const ratio = Number(maxHeight.replace("%", "")) / 100; maxHeight = parentSize.width * ratio; } else if (maxHeight.endsWith("px")) { maxHeight = Number(maxHeight.replace("px", "")); } } const selfRect = self.getBoundingClientRect(); const selfLeft = selfRect.left; const selfTop = selfRect.top; const boundaryRect = this.props.bounds === "window" ? { left: 0, top: 0 } : boundary.getBoundingClientRect(); const boundaryLeft = boundaryRect.left; const boundaryTop = boundaryRect.top; const offsetWidth = this.getOffsetWidth(boundary); const offsetHeight = this.getOffsetHeight(boundary); const hasLeft = dir.toLowerCase().endsWith("left"); const hasRight = dir.toLowerCase().endsWith("right"); const hasTop = dir.startsWith("top"); const hasBottom = dir.startsWith("bottom"); if ((hasLeft || hasTop) && this.resizable) { const max = (selfLeft - boundaryLeft) / scale + this.resizable.size.width; this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max }); } // INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story. if (hasRight || (this.props.lockAspectRatio && !hasLeft && !hasTop)) { const max = offsetWidth + (boundaryLeft - selfLeft) / scale; this.setState({ maxWidth: max > Number(maxWidth) ? maxWidth : max }); } if ((hasTop || hasLeft) && this.resizable) { const max = (selfTop - boundaryTop) / scale + this.resizable.size.height; this.setState({ maxHeight: max > Number(maxHeight) ? maxHeight : max, }); } // INFO: To set bounds in `lock aspect ratio with bounds` case. See also that story. if (hasBottom || (this.props.lockAspectRatio && !hasTop && !hasLeft)) { const max = offsetHeight + (boundaryTop - selfTop) / scale; this.setState({ maxHeight: max > Number(maxHeight) ? maxHeight : max, }); } } } else { this.setState({ maxWidth: this.props.maxWidth, maxHeight: this.props.maxHeight, }); } if (this.props.onResizeStart) { this.props.onResizeStart(e, dir, elementRef); } } onResize( e: MouseEvent | TouchEvent, direction: ResizeDirection, elementRef: HTMLElement, delta: { height: number; width: number }, ) { // INFO: Apply x and y position adjustments caused by resizing to draggable const newPos = { x: this.originalPosition.x, y: this.originalPosition.y }; const left = -delta.width; const top = -delta.height; const directions = ["top", "left", "topLeft", "bottomLeft", "topRight"]; if (directions.indexOf(direction) !== -1) { if (direction === "bottomLeft") { newPos.x += left; } else if (direction === "topRight") { newPos.y += top; } else { newPos.x += left; newPos.y += top; } } if (newPos.x !== this.draggable.state.x || newPos.y !== this.draggable.state.y) { this.draggable.setState(newPos); } this.updateOffsetFromParent(); const offset = this.offsetFromParent; const x = this.getDraggablePosition().x + offset.left; const y = this.getDraggablePosition().y + offset.top; this.resizingPosition = { x, y }; if (!this.props.onResize) return; this.props.onResize(e, direction, elementRef, delta, { x, y, }); } onResizeStop( e: MouseEvent | TouchEvent, direction: ResizeDirection, elementRef: HTMLElement, delta: { height: number; width: number }, ) { this.setState({ resizing: false, }); const { maxWidth, maxHeight } = this.getMaxSizesFromProps(); this.setState({ maxWidth, maxHeight }); if (this.props.onResizeStop) { this.props.onResizeStop(e, direction, elementRef, delta, this.resizingPosition); } } updateSize(size: { width: number | string; height: number | string }) { if (!this.resizable) return; this.resizable.updateSize({ width: size.width, height: size.height }); } updatePosition(position: Position) { this.draggable.setState(position); } updateOffsetFromParent() { const scale = this.props.scale as number; const parent = this.getParent(); const self = this.getSelfElement(); if (!parent || self === null) { return { top: 0, left: 0, }; } const parentRect = parent.getBoundingClientRect(); const parentLeft = parentRect.left; const parentTop = parentRect.top; const selfRect = self.getBoundingClientRect(); const position = this.getDraggablePosition(); const scrollLeft = parent.scrollLeft; const scrollTop = parent.scrollTop; this.offsetFromParent = { left: selfRect.left - parentLeft + scrollLeft - position.x * scale, top: selfRect.top - parentTop + scrollTop - position.y * scale, }; } refDraggable = (c: $TODO) => { if (!c) return; this.draggable = c; }; refResizable = (c: Resizable | null) => { if (!c) return; this.resizable = c; this.resizableElement.current = c.resizable; }; render() { const { disableDragging, style, dragHandleClassName, position, onMouseDown, onMouseUp, dragAxis, dragGrid, bounds, enableUserSelectHack, cancel, children, onResizeStart, onResize, onResizeStop, onDragStart, onDrag, onDragStop, resizeHandleStyles, resizeHandleClasses, resizeHandleComponent, enableResizing, resizeGrid, resizeHandleWrapperClass, resizeHandleWrapperStyle, scale, allowAnyClick, ...resizableProps } = this.props; const defaultValue = this.props.default ? { ...this.props.default } : undefined; // Remove unknown props, see also https://reactjs.org/warnings/unknown-prop.html delete resizableProps.default; const cursorStyle = disableDragging || dragHandleClassName ? { cursor: "auto" } : { cursor: "move" }; const innerStyle = { ...resizableStyle, ...cursorStyle, ...style, }; const { left, top } = this.offsetFromParent; let draggablePosition; if (position) { draggablePosition = { x: position.x - left, y: position.y - top, }; } // INFO: Make uncontorolled component when resizing to control position by setPostion. const pos = this.state.resizing ? undefined : draggablePosition; const dragAxisOrUndefined = this.state.resizing ? "both" : dragAxis; return ( <Draggable ref={this.refDraggable} handle={dragHandleClassName ? `.${dragHandleClassName}` : undefined} defaultPosition={defaultValue} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onStart={this.onDragStart} onDrag={this.onDrag} onStop={this.onDragStop} axis={dragAxisOrUndefined} disabled={disableDragging} grid={dragGrid} bounds={bounds ? this.state.bounds : undefined} position={pos} enableUserSelectHack={enableUserSelectHack} cancel={cancel} scale={scale} allowAnyClick={allowAnyClick} nodeRef={this.resizableElement} > <Resizable {...resizableProps} ref={this.refResizable} defaultSize={defaultValue} size={this.props.size} enable={typeof enableResizing === "boolean" ? getEnableResizingByFlag(enableResizing) : enableResizing} onResizeStart={this.onResizeStart} onResize={this.onResize} onResizeStop={this.onResizeStop} style={innerStyle} minWidth={this.props.minWidth} minHeight={this.props.minHeight} maxWidth={this.state.resizing ? this.state.maxWidth : this.props.maxWidth} maxHeight={this.state.resizing ? this.state.maxHeight : this.props.maxHeight} grid={resizeGrid} handleWrapperClass={resizeHandleWrapperClass} handleWrapperStyle={resizeHandleWrapperStyle} lockAspectRatio={this.props.lockAspectRatio} lockAspectRatioExtraWidth={this.props.lockAspectRatioExtraWidth} lockAspectRatioExtraHeight={this.props.lockAspectRatioExtraHeight} handleStyles={resizeHandleStyles} handleClasses={resizeHandleClasses} handleComponent={resizeHandleComponent} scale={this.props.scale} > {children} </Resizable> </Draggable> ); } }
the_stack
import { AspidaClient, dataToURLString } from 'aspida' // prettier-ignore import { Methods as Methods0 } from './users/_user_id@string/orders' // prettier-ignore import { Methods as Methods1 } from './users/_user_id@string/orders/_order_id@string' // prettier-ignore import { Methods as Methods2 } from './users/_user_id@string/orders/purchase/invoice' // prettier-ignore import { Methods as Methods3 } from './users/_user_id@string/orders/purchase/wallet' // prettier-ignore import { Methods as Methods4 } from './users/_user_id@string/orders/unsubscribe' // prettier-ignore import { Methods as Methods5 } from './users/_user_id@string/orders/update/renew' // prettier-ignore import { Methods as Methods6 } from './users/_user_id@string/phone-numbers/_phone_number@string/orders' // prettier-ignore import { Methods as Methods7 } from './users/_user_id@string/phone-numbers/_phone_number@string/orders/purchase/invoice' // prettier-ignore import { Methods as Methods8 } from './users/_user_id@string/phone-numbers/_phone_number@string/orders/purchase/wallet' // prettier-ignore const api = <T>({ baseURL, fetch }: AspidaClient<T>) => { const prefix = (baseURL === undefined ? 'https://api.baikalplatform.com/product-management/v1' : baseURL).replace(/\/$/, '') const PATH0 = '/users' const PATH1 = '/orders' const PATH2 = '/orders/purchase/invoice' const PATH3 = '/orders/purchase/wallet' const PATH4 = '/orders/unsubscribe' const PATH5 = '/orders/update/renew' const PATH6 = '/phone-numbers' const GET = 'GET' const POST = 'POST' return { users: { _user_id: (val1: string) => { const prefix1 = `${PATH0}/${val1}` return { orders: { _order_id: (val3: string) => { const prefix3 = `${prefix1}${PATH1}/${val3}` return { /** * Get info of an order by order_id * @returns Ok */ get: (option?: { config?: T }) => fetch<Methods1['get']['resBody'], Methods1['get']['resHeaders'], Methods1['get']['status']>(prefix, prefix3, GET, option).json(), /** * Get info of an order by order_id * @returns Ok */ $get: (option?: { config?: T }) => fetch<Methods1['get']['resBody'], Methods1['get']['resHeaders'], Methods1['get']['status']>(prefix, prefix3, GET, option).json().then(r => r.body), $path: () => `${prefix}${prefix3}` } }, purchase: { invoice: { /** * Creates an purchase order for an offer by its offer_id and using invoice as payment method * @param option.body - Body to create a purchase order * @returns Created */ post: (option: { body: Methods2['post']['reqBody'], config?: T }) => fetch<Methods2['post']['resBody'], Methods2['post']['resHeaders'], Methods2['post']['status']>(prefix, `${prefix1}${PATH2}`, POST, option).json(), /** * Creates an purchase order for an offer by its offer_id and using invoice as payment method * @param option.body - Body to create a purchase order * @returns Created */ $post: (option: { body: Methods2['post']['reqBody'], config?: T }) => fetch<Methods2['post']['resBody'], Methods2['post']['resHeaders'], Methods2['post']['status']>(prefix, `${prefix1}${PATH2}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix1}${PATH2}` }, wallet: { /** * Creates an purchase order for an offer by its offer_id using wallet as payment method * @param option.body - Body to create a purchase order * @returns Created */ post: (option: { body: Methods3['post']['reqBody'], config?: T }) => fetch<Methods3['post']['resBody'], Methods3['post']['resHeaders'], Methods3['post']['status']>(prefix, `${prefix1}${PATH3}`, POST, option).json(), /** * Creates an purchase order for an offer by its offer_id using wallet as payment method * @param option.body - Body to create a purchase order * @returns Created */ $post: (option: { body: Methods3['post']['reqBody'], config?: T }) => fetch<Methods3['post']['resBody'], Methods3['post']['resHeaders'], Methods3['post']['status']>(prefix, `${prefix1}${PATH3}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix1}${PATH3}` } }, unsubscribe: { /** * Creates an unsubscribe order for a product_id * @param option.body - Body to create a purchase order * @returns Created */ post: (option: { body: Methods4['post']['reqBody'], config?: T }) => fetch<Methods4['post']['resBody'], Methods4['post']['resHeaders'], Methods4['post']['status']>(prefix, `${prefix1}${PATH4}`, POST, option).json(), /** * Creates an unsubscribe order for a product_id * @param option.body - Body to create a purchase order * @returns Created */ $post: (option: { body: Methods4['post']['reqBody'], config?: T }) => fetch<Methods4['post']['resBody'], Methods4['post']['resHeaders'], Methods4['post']['status']>(prefix, `${prefix1}${PATH4}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix1}${PATH4}` }, update: { renew: { /** * Creates an update order for a product_id * @param option.body - Body to create a update order * @returns Created */ post: (option: { body: Methods5['post']['reqBody'], config?: T }) => fetch<Methods5['post']['resBody'], Methods5['post']['resHeaders'], Methods5['post']['status']>(prefix, `${prefix1}${PATH5}`, POST, option).json(), /** * Creates an update order for a product_id * @param option.body - Body to create a update order * @returns Created */ $post: (option: { body: Methods5['post']['reqBody'], config?: T }) => fetch<Methods5['post']['resBody'], Methods5['post']['resHeaders'], Methods5['post']['status']>(prefix, `${prefix1}${PATH5}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix1}${PATH5}` } }, /** * List orders for a user * @returns Ok */ get: (option?: { query?: Methods0['get']['query'], config?: T }) => fetch<Methods0['get']['resBody'], Methods0['get']['resHeaders'], Methods0['get']['status']>(prefix, `${prefix1}${PATH1}`, GET, option).json(), /** * List orders for a user * @returns Ok */ $get: (option?: { query?: Methods0['get']['query'], config?: T }) => fetch<Methods0['get']['resBody'], Methods0['get']['resHeaders'], Methods0['get']['status']>(prefix, `${prefix1}${PATH1}`, GET, option).json().then(r => r.body), $path: (option?: { method?: 'get'; query: Methods0['get']['query'] }) => `${prefix}${prefix1}${PATH1}${option && option.query ? `?${dataToURLString(option.query)}` : ''}` }, phone_numbers: { _phone_number: (val3: string) => { const prefix3 = `${prefix1}${PATH6}/${val3}` return { orders: { purchase: { invoice: { /** * Creates an purchase order for an offer by its offer_id using invoice has payment method * @param option.body - Body to create a purchase order * @returns Created */ post: (option: { body: Methods7['post']['reqBody'], config?: T }) => fetch<Methods7['post']['resBody'], Methods7['post']['resHeaders'], Methods7['post']['status']>(prefix, `${prefix3}${PATH2}`, POST, option).json(), /** * Creates an purchase order for an offer by its offer_id using invoice has payment method * @param option.body - Body to create a purchase order * @returns Created */ $post: (option: { body: Methods7['post']['reqBody'], config?: T }) => fetch<Methods7['post']['resBody'], Methods7['post']['resHeaders'], Methods7['post']['status']>(prefix, `${prefix3}${PATH2}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix3}${PATH2}` }, wallet: { /** * Creates an purchase order for an offer by its offer_id using a wallet has payment method * @param option.body - Body to create a purchase order * @returns Created */ post: (option: { body: Methods8['post']['reqBody'], config?: T }) => fetch<Methods8['post']['resBody'], Methods8['post']['resHeaders'], Methods8['post']['status']>(prefix, `${prefix3}${PATH3}`, POST, option).json(), /** * Creates an purchase order for an offer by its offer_id using a wallet has payment method * @param option.body - Body to create a purchase order * @returns Created */ $post: (option: { body: Methods8['post']['reqBody'], config?: T }) => fetch<Methods8['post']['resBody'], Methods8['post']['resHeaders'], Methods8['post']['status']>(prefix, `${prefix3}${PATH3}`, POST, option).json().then(r => r.body), $path: () => `${prefix}${prefix3}${PATH3}` } }, /** * List orders for a phone number * @returns Ok */ get: (option?: { config?: T }) => fetch<Methods6['get']['resBody'], Methods6['get']['resHeaders'], Methods6['get']['status']>(prefix, `${prefix3}${PATH1}`, GET, option).json(), /** * List orders for a phone number * @returns Ok */ $get: (option?: { config?: T }) => fetch<Methods6['get']['resBody'], Methods6['get']['resHeaders'], Methods6['get']['status']>(prefix, `${prefix3}${PATH1}`, GET, option).json().then(r => r.body), $path: () => `${prefix}${prefix3}${PATH1}` } } } } } } } } } // prettier-ignore export type ApiInstance = ReturnType<typeof api> // prettier-ignore export default api
the_stack
import { APP_BASE_HREF } from '@angular/common'; import { HttpRequest } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { TranslateLoader, TranslateModule, TranslateParser, TranslateService } from '@ngx-translate/core'; import { Action } from 'app/model/action.model'; import { Parameter } from 'app/model/parameter.model'; import { Project } from 'app/model/project.model'; import { Requirement } from 'app/model/requirement.model'; import { ActionService } from 'app/service/action/action.service'; import { AuthenticationService } from 'app/service/authentication/authentication.service'; import { ParameterService } from 'app/service/parameter/parameter.service'; import { RepoManagerService } from 'app/service/repomanager/project.repomanager.service'; import { RequirementService } from 'app/service/requirement/requirement.service'; import { RequirementStore } from 'app/service/requirement/requirement.store'; import { ThemeStore } from 'app/service/theme/theme.store'; import { UserService } from 'app/service/user/user.service'; import { WorkerModelService } from 'app/service/worker-model/worker-model.service'; import { ParameterEvent } from '../parameter/parameter.event.model'; import { RequirementEvent } from '../requirements/requirement.event.model'; import { SharedModule } from '../shared.module'; import { SharedService } from '../shared.service'; import { ActionComponent } from './action.component'; import { ActionEvent } from './action.event.model'; import { StepEvent } from './step/step.event'; describe('CDS: Action Component', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [], providers: [ SharedService, TranslateService, RequirementStore, RequirementService, ParameterService, RepoManagerService, ActionService, WorkerModelService, TranslateLoader, TranslateParser, { provide: APP_BASE_HREF, useValue: '/' }, ThemeStore, UserService, AuthenticationService ], imports: [ RouterTestingModule.withRoutes([]), SharedModule, TranslateModule.forRoot(), HttpClientTestingModule ] }).compileComponents(); }); it('should create and then delete a requirement', fakeAsync(() => { // Create component let fixture = TestBed.createComponent(ActionComponent); let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); let action: Action = new Action(); action.name = 'FooAction'; action.requirements = new Array<Requirement>(); fixture.componentInstance.editableAction = action; fixture.componentInstance.edit = true; fixture.componentInstance.project = <Project>{ key: 'key' }; fixture.detectChanges(); tick(50); let r: Requirement = new Requirement('binary'); r.name = 'npm'; r.value = 'npm'; // Add a requirement let addRequirementEvent: RequirementEvent = new RequirementEvent('add', r); fixture.componentInstance.requirementEvent(addRequirementEvent); expect(fixture.componentInstance.editableAction.requirements.length).toBe(1, 'Action must have 1 requirement'); expect(fixture.componentInstance.editableAction.requirements[0]).toBe(r); // Not add twice fixture.componentInstance.requirementEvent(addRequirementEvent); expect(fixture.componentInstance.editableAction.requirements.length).toBe(1, 'Action must have 1 requirement'); expect(fixture.componentInstance.editableAction.requirements[0]).toBe(r); // Remove a requirement let removeRequiementEvent: RequirementEvent = new RequirementEvent('delete', r); fixture.componentInstance.requirementEvent(removeRequiementEvent); expect(fixture.componentInstance.editableAction.requirements.length).toBe(0, 'Action must have 0 requirement'); })); it('should create and then delete a parameter', fakeAsync(() => { // Create component let fixture = TestBed.createComponent(ActionComponent); let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); let action: Action = new Action(); action.name = 'FooAction'; action.requirements = new Array<Requirement>(); fixture.componentInstance.editableAction = action; fixture.componentInstance.edit = true; fixture.componentInstance.project = <Project>{ key: 'key' }; fixture.detectChanges(); tick(50); let p: Parameter = new Parameter(); p.name = 'gitUrl'; p.type = 'string'; p.description = 'git url of the repository'; // Add a parameter let addparamEvent: ParameterEvent = new ParameterEvent('add', p); fixture.componentInstance.parameterEvent(addparamEvent); expect(fixture.componentInstance.editableAction.parameters.length).toBe(1, 'Action must have 1 parameter'); expect(fixture.componentInstance.editableAction.parameters[0]).toBe(p); // Remove a parameter let removeParamEvent: ParameterEvent = new ParameterEvent('delete', p); fixture.componentInstance.parameterEvent(removeParamEvent); expect(fixture.componentInstance.editableAction.parameters.length).toBe(0, 'Action must have 0 parameter'); })); it('should send delete action event', fakeAsync(() => { // Create component let fixture = TestBed.createComponent(ActionComponent); let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); let action: Action = new Action(); action.name = 'FooAction'; action.requirements = new Array<Requirement>(); action.id = 1; fixture.componentInstance.editableAction = action; fixture.componentInstance.project = <Project>{ key: 'key' }; fixture.componentInstance._cd.detectChanges(); tick(50); // readonly , no button expect(fixture.debugElement.nativeElement.querySelector('.ui.red.button')).toBeFalsy(); expect(fixture.debugElement.nativeElement.querySelector('button[name="updatebtn"]')).toBeFalsy(); fixture.componentInstance.edit = true; fixture.componentInstance._cd.detectChanges(); tick(50); let compiled = fixture.debugElement.nativeElement; spyOn(fixture.componentInstance.actionEvent, 'emit'); compiled.querySelector('.ui.red.button').click(); fixture.componentInstance._cd.detectChanges(); tick(50); compiled.querySelector('.ui.red.button.active').click(); expect(compiled.querySelector('button[name="updatebtn"]')).toBeTruthy(); expect(fixture.componentInstance.actionEvent.emit).toHaveBeenCalledWith(new ActionEvent('delete', action)); })); it('should send insert action event', fakeAsync(() => { // Create component let fixture = TestBed.createComponent(ActionComponent); let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); let action: Action = new Action(); action.name = 'FooAction'; action.requirements = new Array<Requirement>(); fixture.componentInstance.editableAction = action; fixture.componentInstance.edit = true; fixture.componentInstance.project = <Project>{ key: 'key' }; fixture.detectChanges(); tick(50); let compiled = fixture.debugElement.nativeElement; spyOn(fixture.componentInstance.actionEvent, 'emit'); let inputName = compiled.querySelector('input[name="actionName"]'); inputName.dispatchEvent(new Event('keydown')); fixture.detectChanges(); tick(50); expect(compiled.querySelector('button[name="deletebtn"]')).toBeFalsy(); expect(compiled.querySelector('button[name="updatebtn"]')).toBeFalsy(); let btn = compiled.querySelector('button[name="addbtn"]'); btn.click(); expect(fixture.componentInstance.actionEvent.emit).toHaveBeenCalledWith(new ActionEvent('insert', action)); })); it('should add and then remove a step', fakeAsync(() => { const http = TestBed.get(HttpTestingController); let actionMock = <Action>{ name: 'action1' }; // Create component let fixture = TestBed.createComponent(ActionComponent); fixture.componentInstance.project = <Project>{ key: 'key' }; let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); // TODO // http.expectOne(((req: HttpRequest<any>) => { // return req.url === '/requirement/types'; // })).flush(actionMock); fixture.componentInstance.ngOnInit(); http.expectOne(((req: HttpRequest<any>) => req.url === '/project/key/action')).flush(actionMock); let action: Action = <Action>{ name: 'FooAction', requirements: new Array<Requirement>() }; fixture.componentInstance.editableAction = action; fixture.componentInstance.edit = true; fixture.detectChanges(); tick(50); let step = <Action>{ always_executed: false, name: 'action1' }; let event = new StepEvent('add', step); fixture.componentInstance.stepManagement(event); expect(fixture.componentInstance.steps.length).toBe(1, 'Action must have 1 step'); expect(fixture.componentInstance.steps[0].name).toBe('action1'); event.type = 'add'; step.always_executed = true; step.name = 'action2'; fixture.componentInstance.stepManagement(event); expect(fixture.componentInstance.steps.length).toBe(2, 'Action must have 2 steps'); expect(fixture.componentInstance.steps[1].name).toBe('action2'); })); it('should init step not always executed and step always executed', fakeAsync(() => { // Create component let fixture = TestBed.createComponent(ActionComponent); let component = fixture.debugElement.componentInstance; expect(component).toBeTruthy(); let action = new Action(); action.name = 'rootAction'; let step1 = new Action(); step1.always_executed = true; let step2 = new Action(); step2.always_executed = false; action.actions = new Array<Action>(); action.actions.push(step1, step2); fixture.componentInstance.action = action; expect(fixture.componentInstance.steps.length).toBe(2); })); });
the_stack
import {BaseGlShaderAssembler} from '../_Base'; import {ThreeToGl} from '../../../../../../core/ThreeToGl'; import {OutputGlNode} from '../../../Output'; import {AttributeGlNode} from '../../../Attribute'; import {ShaderName} from '../../../../utils/shaders/ShaderName'; import {GlobalsGlNode} from '../../../Globals'; import {BaseGLDefinition, UniformGLDefinition, VaryingGLDefinition} from '../../../utils/GLDefinition'; import {GlConnectionPointType} from '../../../../utils/io/connections/Gl'; import {MapUtils} from '../../../../../../core/MapUtils'; import {ShaderMaterialWithCustomMaterials} from '../../../../../../core/geometry/Material'; import {ShadersCollectionController} from '../../utils/ShadersCollectionController'; import {ShaderMaterial} from 'three/src/materials/ShaderMaterial'; import {GlNodeFinder} from '../../utils/NodeFinder'; import {IUniformsWithResolution, IUniformsWithTime} from '../../../../../scene/utils/UniformsController'; import {BaseGlNodeType} from '../../../_Base'; // import {BaseNodeType} from '../../_Base'; // import {GlobalsGeometryHandler} from './Globals/Geometry' export enum CustomMaterialName { DISTANCE = 'customDistanceMaterial', DEPTH = 'customDepthMaterial', DEPTH_DOF = 'customDepthDOFMaterial', } // export type ShaderAssemblerRenderDerivated = {new (node: BaseNodeType): ShaderAssemblerRender}; // type ShaderAssemblerRenderDerivatedClass = new (...args: any[]) => ShaderAssemblerRender; export type CustomAssemblerMap = Map<CustomMaterialName, typeof ShaderAssemblerMaterial>; export enum GlobalsOutput { TIME = 'time', RESOLUTION = 'resolution', MV_POSITION = 'mvPosition', GL_POSITION = 'gl_Position', GL_FRAGCOORD = 'gl_FragCoord', GL_POINTCOORD = 'gl_PointCoord', } const FRAGMENT_GLOBALS_OUTPUT = [ /*GlobalsOutput.GL_POSITION,*/ GlobalsOutput.GL_FRAGCOORD, GlobalsOutput.GL_POINTCOORD, ]; const COMPILE_CUSTOM_MATERIALS = true; interface HandleGlobalsOutputOptions { globals_node: GlobalsGlNode; shaders_collection_controller: ShadersCollectionController; output_name: string; globals_shader_name: ShaderName; definitions_by_shader_name: Map<ShaderName, BaseGLDefinition[]>; body_lines: string[]; var_name: string; shader_name: ShaderName; dependencies: ShaderName[]; body_lines_by_shader_name: Map<ShaderName, string[]>; } type FragmentShaderFilterCallback = (s: string) => string; export class ShaderAssemblerMaterial extends BaseGlShaderAssembler { private _assemblers_by_custom_name: Map<CustomMaterialName, ShaderAssemblerMaterial> = new Map(); createMaterial(): ShaderMaterial { return new ShaderMaterial(); } custom_assembler_class_by_custom_name(): CustomAssemblerMap | undefined { return undefined; } protected _addCustomMaterials(material: ShaderMaterial) { const class_by_custom_name = this.custom_assembler_class_by_custom_name(); if (class_by_custom_name) { class_by_custom_name.forEach( (assembler_class: typeof ShaderAssemblerMaterial, custom_name: CustomMaterialName) => { this._add_custom_material( material as ShaderMaterialWithCustomMaterials, custom_name, assembler_class ); } ); } } private _add_custom_material( material: ShaderMaterialWithCustomMaterials, custom_name: CustomMaterialName, assembler_class: typeof ShaderAssemblerMaterial ) { let custom_assembler: ShaderAssemblerMaterial | undefined = this._assemblers_by_custom_name.get(custom_name); if (!custom_assembler) { custom_assembler = new assembler_class(this.currentGlParentNode()); this._assemblers_by_custom_name.set(custom_name, custom_assembler); } material.customMaterials = material.customMaterials || {}; const mat = custom_assembler.createMaterial(); mat.name = custom_name; material.customMaterials[custom_name] = mat; } compileCustomMaterials(material: ShaderMaterialWithCustomMaterials) { // const custom_materials_by_name: Map<CustomMaterialName, ShaderMaterial> = new Map(); // this._assemblers_by_custom_name.clear(); const class_by_custom_name = this.custom_assembler_class_by_custom_name(); if (class_by_custom_name) { class_by_custom_name.forEach( (assembler_class: typeof ShaderAssemblerMaterial, custom_name: CustomMaterialName) => { if (this._code_builder) { let assembler: ShaderAssemblerMaterial | undefined = this._assemblers_by_custom_name.get( custom_name ); if (!assembler) { assembler = new assembler_class(this.currentGlParentNode()); this._assemblers_by_custom_name.set(custom_name, assembler); } assembler.set_root_nodes(this._root_nodes); assembler.set_param_configs_owner(this._code_builder); assembler.set_shader_configs(this.shaderConfigs()); assembler.set_variable_configs(this.variable_configs()); const custom_material = material.customMaterials[custom_name]; if (custom_material) { // the custom material will use the fragment filtering from the parent assembler assembler.setFilterFragmentShaderMethodOwner(this); assembler.compileMaterial(custom_material); assembler.setFilterFragmentShaderMethodOwner(undefined); } // if (material) { // // add needsUpdate = true, as we always get the same material // // material.needsUpdate = true; // custom_materials_by_name.set(custom_name, material); // } } } ); } // for (let custom_name of Object.keys(class_by_custom_name)) { // const assembler_class = class_by_custom_name[custom_name]; // // const assembler = new assembler_class(this.currentGlParentNode()) // } // return custom_materials_by_name; } private _filterFragmentShaderCallbacks: Map<string, FragmentShaderFilterCallback> = new Map(); protected _resetFilterFragmentShaderCallbacks() { this._filterFragmentShaderCallbacks.clear(); } _addFilterFragmentShaderCallback(callbackName: string, callback: (s: string) => string) { this._filterFragmentShaderCallbacks.set(callbackName, callback); } _removeFilterFragmentShaderCallback(callbackName: string) { this._filterFragmentShaderCallbacks.delete(callbackName); } private _filterFragmentShaderMethodOwner: ShaderAssemblerMaterial | undefined; setFilterFragmentShaderMethodOwner(owner: ShaderAssemblerMaterial | undefined) { this._filterFragmentShaderMethodOwner = owner; } filterFragmentShader(fragmentShader: string) { this._filterFragmentShaderCallbacks.forEach((callback, callbackName) => { fragmentShader = callback(fragmentShader); }); return fragmentShader; } processFilterFragmentShader(fragmentShader: string) { if (this._filterFragmentShaderMethodOwner) { return this._filterFragmentShaderMethodOwner.filterFragmentShader(fragmentShader); } else { return this.filterFragmentShader(fragmentShader); } } compileMaterial(material: ShaderMaterial) { // no need to compile if the globals handler has not been declared if (!this.compileAllowed()) { return; } const output_nodes: BaseGlNodeType[] = GlNodeFinder.findOutputNodes(this.currentGlParentNode()); if (output_nodes.length > 1) { this.currentGlParentNode().states.error.set('only one output node allowed'); } const varying_nodes = GlNodeFinder.findVaryingNodes(this.currentGlParentNode()); const root_nodes = output_nodes.concat(varying_nodes); this.set_root_nodes(root_nodes); this._update_shaders(); const new_vertex_shader = this._shaders_by_name.get(ShaderName.VERTEX); const new_fragment_shader = this._shaders_by_name.get(ShaderName.FRAGMENT); if (new_vertex_shader && new_fragment_shader) { material.vertexShader = new_vertex_shader; material.fragmentShader = this.processFilterFragmentShader(new_fragment_shader); this.addUniforms(material.uniforms); material.needsUpdate = true; } const scene = this.currentGlParentNode().scene(); if (this.uniformsTimeDependent()) { // make sure not to use this.currentGlParentNode().graphNodeId() as the id, // as we need several materials: // - the visible one // - the multiple shadow ones // - and possibly a depth one scene.uniformsController.addTimeDependentUniformOwner( material.uuid, material.uniforms as IUniformsWithTime ); } else { scene.uniformsController.removeTimeDependentUniformOwner(material.uuid); } if (this.uniforms_resolution_dependent()) { // make sure not to use this.currentGlParentNode().graphNodeId() as the id, // as we need several materials: // - the visible one // - the multiple shadow ones // - and possibly a depth one scene.uniformsController.addResolutionDependentUniformOwner( material.uuid, material.uniforms as IUniformsWithResolution ); } else { scene.uniformsController.removeResolutionDependentUniformOwner(material.uuid); } // const material = await this._assembler.get_material(); // if (material) { // this._shaders_by_name.set(ShaderName.VERTEX, this._template_shader!.vertexShader!); // this._shaders_by_name.set(ShaderName.FRAGMENT, this._template_shader!.fragmentShader!); // assign custom materials if (COMPILE_CUSTOM_MATERIALS) { if ((material as ShaderMaterialWithCustomMaterials).customMaterials) { this.compileCustomMaterials(material as ShaderMaterialWithCustomMaterials); } } // const custom_materials = await this.get_custom_materials(); // const material_with_custom_materials = material as ShaderMaterialWithCustomMaterials; // material_with_custom_materials.custom_materials = {}; // custom_materials.forEach((custom_material, shader_name) => { // material_with_custom_materials.custom_materials[shader_name] = custom_material; // }); // material.needsUpdate = true; // } // this.createSpareParameters(); } private _update_shaders() { this._shaders_by_name = new Map(); this._lines = new Map(); for (let shader_name of this.shaderNames()) { const template = this._template_shader_for_shader_name(shader_name); if (template) { this._lines.set(shader_name, template.split('\n')); } } if (this._root_nodes.length > 0) { // this._output_node.set_assembler(this) this.build_code_from_nodes(this._root_nodes); this._build_lines(); } // this._material.uniforms = this.build_uniforms(template_shader) for (let shader_name of this.shaderNames()) { const lines = this._lines.get(shader_name); if (lines) { this._shaders_by_name.set(shader_name, lines.join('\n')); } } } shadow_assembler_class_by_custom_name() { return {}; } add_output_body_line( output_node: OutputGlNode, shaders_collection_controller: ShadersCollectionController, input_name: string ) { const input = output_node.io.inputs.named_input(input_name); const var_input = output_node.variableForInput(input_name); const variable_config = this.variable_config(input_name); let new_var: string | null = null; if (input) { new_var = ThreeToGl.vector3(var_input); } else { if (variable_config.default_from_attribute()) { const connection_point = output_node.io.inputs.namedInputConnectionPointsByName(input_name); if (connection_point) { const gl_type = connection_point.type(); const attr_read = this.globals_handler?.read_attribute( output_node, gl_type, input_name, shaders_collection_controller ); if (attr_read) { new_var = attr_read; } } } else { const variable_config_default = variable_config.default(); if (variable_config_default) { new_var = variable_config_default; } } // const default_value = variable_config.default() // new_var = default_value // const definition_configs = variable_config.required_definitions() || [] // for(let definition_config of definition_configs){ // const definition = definition_config.create_definition(output_node) // output_node.addDefinitions([definition]) // } } if (new_var) { const prefix = variable_config.prefix(); const suffix = variable_config.suffix(); const if_condition = variable_config.if_condition(); if (if_condition) { shaders_collection_controller.addBodyLines(output_node, [`#if ${if_condition}`]); } shaders_collection_controller.addBodyLines(output_node, [`${prefix}${new_var}${suffix}`]); const postLines = variable_config.postLines(); if (postLines) { shaders_collection_controller.addBodyLines(output_node, postLines); } if (if_condition) { shaders_collection_controller.addBodyLines(output_node, [`#endif`]); } } } set_node_lines_output(output_node: OutputGlNode, shaders_collection_controller: ShadersCollectionController) { // const body_lines = []; const shader_name = shaders_collection_controller.current_shader_name; const input_names = this.shader_config(shader_name)?.input_names(); if (input_names) { // shaders_collection_controller.set_body_lines([], shader_name); for (let input_name of input_names) { if (output_node.io.inputs.has_named_input(input_name)) { this.add_output_body_line(output_node, shaders_collection_controller, input_name); } } } } set_node_lines_attribute( attribute_node: AttributeGlNode, shaders_collection_controller: ShadersCollectionController ) { // const named_output = attribute_node.connected_output() // const named_connection = attribute_node.connected_input() const gl_type = attribute_node.gl_type(); const new_var = this.globals_handler?.read_attribute( attribute_node, gl_type, attribute_node.attribute_name, shaders_collection_controller ); const var_name = attribute_node.glVarName(attribute_node.output_name); shaders_collection_controller.addBodyLines(attribute_node, [`${gl_type} ${var_name} = ${new_var}`]); // this.add_output_body_line( // attribute_node, // shader_name, // input_name // ) // const vertex_definitions = [] // const vertex_body_lines = [] // const fragment_definitions = [] // const named_output = attribute_node.named_outputs()[0] // const gl_type = named_output.type() // const var_name = attribute_node.glVarName(named_output.name()) // const attribute_name = attribute_node.attribute_name() // // TODO: I should probably raise an error in the node // // maybe when doint the initial eval of all nodes and check for errors? // if(!attribute_name){ // console.error(attribute_node.path()) // throw new Error("empty attr name") // } // if(GlobalsGeometryHandler.PRE_DEFINED_ATTRIBUTES.indexOf(attribute_name) < 0){ // vertex_definitions.push(new Definition.Attribute(attribute_node, gl_type, attribute_name)) // } // vertex_definitions.push(new Definition.Varying(attribute_node, gl_type, var_name)) // vertex_body_lines.push( `${var_name} = ${attribute_name}` ) // fragment_definitions.push(new Definition.Varying(attribute_node, gl_type, var_name)) // attribute_node.set_definitions(vertex_definitions, 'vertex') // attribute_node.set_definitions(fragment_definitions, 'fragment') // attribute_node.addBodyLines(vertex_body_lines, 'vertex') } handle_globals_output_name(options: HandleGlobalsOutputOptions) { switch (options.output_name) { case GlobalsOutput.TIME: this.handleTime(options); return; case GlobalsOutput.RESOLUTION: this.handle_resolution(options); return; case GlobalsOutput.MV_POSITION: this.handle_mvPosition(options); return; case GlobalsOutput.GL_POSITION: this.handle_gl_Position(options); return; case GlobalsOutput.GL_FRAGCOORD: this.handle_gl_FragCoord(options); return; case GlobalsOutput.GL_POINTCOORD: this.handle_gl_PointCoord(options); return; default: this.globals_handler?.handle_globals_node( options.globals_node, options.output_name, options.shaders_collection_controller // definitions_by_shader_name, // body_lines_by_shader_name, // body_lines, // dependencies, // shader_name ); } } handleTime(options: HandleGlobalsOutputOptions) { const definition = new UniformGLDefinition( options.globals_node, GlConnectionPointType.FLOAT, options.output_name ); if (options.globals_shader_name) { MapUtils.pushOnArrayAtEntry(options.definitions_by_shader_name, options.globals_shader_name, definition); } const body_line = `float ${options.var_name} = ${options.output_name}`; for (let dependency of options.dependencies) { MapUtils.pushOnArrayAtEntry(options.definitions_by_shader_name, dependency, definition); MapUtils.pushOnArrayAtEntry(options.body_lines_by_shader_name, dependency, body_line); } options.body_lines.push(body_line); this.setUniformsTimeDependent(); } handle_resolution(options: HandleGlobalsOutputOptions) { // if (options.shader_name == ShaderName.FRAGMENT) { options.body_lines.push(`vec2 ${options.var_name} = resolution`); // } const definition = new UniformGLDefinition( options.globals_node, GlConnectionPointType.VEC2, options.output_name ); if (options.globals_shader_name) { MapUtils.pushOnArrayAtEntry(options.definitions_by_shader_name, options.globals_shader_name, definition); } for (let dependency of options.dependencies) { MapUtils.pushOnArrayAtEntry(options.definitions_by_shader_name, dependency, definition); } this.set_uniforms_resolution_dependent(); } handle_mvPosition(options: HandleGlobalsOutputOptions) { if (options.shader_name == ShaderName.FRAGMENT) { const globals_node = options.globals_node; const shaders_collection_controller = options.shaders_collection_controller; const definition = new VaryingGLDefinition(globals_node, GlConnectionPointType.VEC4, options.var_name); const vertex_body_line = `${options.var_name} = modelViewMatrix * vec4(position, 1.0)`; shaders_collection_controller.addDefinitions(globals_node, [definition], ShaderName.VERTEX); shaders_collection_controller.addBodyLines(globals_node, [vertex_body_line], ShaderName.VERTEX); shaders_collection_controller.addDefinitions(globals_node, [definition]); } } handle_gl_Position(options: HandleGlobalsOutputOptions) { if (options.shader_name == ShaderName.FRAGMENT) { const globals_node = options.globals_node; const shaders_collection_controller = options.shaders_collection_controller; const definition = new VaryingGLDefinition(globals_node, GlConnectionPointType.VEC4, options.var_name); const vertex_body_line = `${options.var_name} = projectionMatrix * modelViewMatrix * vec4(position, 1.0)`; // const fragment_body_line = `vec4 ${options.var_name} = gl_FragCoord`; shaders_collection_controller.addDefinitions(globals_node, [definition], ShaderName.VERTEX); shaders_collection_controller.addBodyLines(globals_node, [vertex_body_line], ShaderName.VERTEX); shaders_collection_controller.addDefinitions(globals_node, [definition]); // shaders_collection_controller.addBodyLines(globals_node, [fragment_body_line]); } } handle_gl_FragCoord(options: HandleGlobalsOutputOptions) { if (options.shader_name == ShaderName.FRAGMENT) { options.body_lines.push(`vec4 ${options.var_name} = gl_FragCoord`); } } handle_gl_PointCoord(options: HandleGlobalsOutputOptions) { if (options.shader_name == ShaderName.FRAGMENT) { options.body_lines.push(`vec2 ${options.var_name} = gl_PointCoord`); } else { options.body_lines.push(`vec2 ${options.var_name} = vec2(0.0, 0.0)`); } } set_node_lines_globals(globals_node: GlobalsGlNode, shaders_collection_controller: ShadersCollectionController) { const body_lines: string[] = []; const shader_name = shaders_collection_controller.current_shader_name; const shader_config = this.shader_config(shader_name); if (!shader_config) { return; } const dependencies = shader_config.dependencies(); const definitions_by_shader_name: Map<ShaderName, BaseGLDefinition[]> = new Map(); const body_lines_by_shader_name: Map<ShaderName, string[]> = new Map(); const used_output_names = this.used_output_names_for_shader(globals_node, shader_name); for (let output_name of used_output_names) { const var_name = globals_node.glVarName(output_name); const globals_shader_name = shaders_collection_controller.current_shader_name; const options: HandleGlobalsOutputOptions = { globals_node, shaders_collection_controller, output_name, globals_shader_name, definitions_by_shader_name, body_lines, var_name, shader_name, dependencies, body_lines_by_shader_name, }; this.handle_globals_output_name(options); } definitions_by_shader_name.forEach((definitions, shader_name) => { shaders_collection_controller.addDefinitions(globals_node, definitions, shader_name); }); body_lines_by_shader_name.forEach((body_lines, shader_name) => { shaders_collection_controller.addBodyLines(globals_node, body_lines, shader_name); }); shaders_collection_controller.addBodyLines(globals_node, body_lines); } private used_output_names_for_shader(globals_node: GlobalsGlNode, shader_name: ShaderName) { const used_output_names = globals_node.io.outputs.used_output_names(); const filtered_names: string[] = []; for (let name of used_output_names) { if (shader_name == ShaderName.VERTEX) { if (!FRAGMENT_GLOBALS_OUTPUT.includes(name as GlobalsOutput)) { filtered_names.push(name); } } else { filtered_names.push(name); } } return filtered_names; } }
the_stack
import { utils as ethersUtils } from 'ethers'; import { AdvancedLogic } from '@requestnetwork/advanced-logic'; import { PaymentNetworkFactory } from '@requestnetwork/payment-detection'; import { RequestLogic } from '@requestnetwork/request-logic'; import { TransactionManager } from '@requestnetwork/transaction-manager'; import { AdvancedLogicTypes, DataAccessTypes, DecryptionProviderTypes, EncryptionTypes, IdentityTypes, PaymentTypes, RequestLogicTypes, SignatureProviderTypes, TransactionTypes, } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import { CurrencyInput, CurrencyManager, ICurrencyManager, UnsupportedCurrencyError, } from '@requestnetwork/currency'; import * as Types from '../types'; import ContentDataExtension from './content-data-extension'; import Request from './request'; import localUtils from './utils'; /** * Entry point of the request-client.js library. Create requests, get requests, manipulate requests. */ export default class RequestNetwork { public bitcoinDetectionProvider?: PaymentTypes.IBitcoinDetectionProvider; public supportedIdentities: IdentityTypes.TYPE[] = Utils.identity.supportedIdentities; private requestLogic: RequestLogicTypes.IRequestLogic; private transaction: TransactionTypes.ITransactionManager; private advancedLogic: AdvancedLogicTypes.IAdvancedLogic; private contentData: ContentDataExtension; private currencyManager: ICurrencyManager; /** * @param dataAccess instance of data-access layer * @param signatureProvider module in charge of the signatures * @param decryptionProvider module in charge of the decryption * @param bitcoinDetectionProvider bitcoin detection provider */ public constructor({ dataAccess, signatureProvider, decryptionProvider, bitcoinDetectionProvider, currencies, }: { dataAccess: DataAccessTypes.IDataAccess; signatureProvider?: SignatureProviderTypes.ISignatureProvider; decryptionProvider?: DecryptionProviderTypes.IDecryptionProvider; bitcoinDetectionProvider?: PaymentTypes.IBitcoinDetectionProvider; currencies?: CurrencyInput[]; }) { this.advancedLogic = new AdvancedLogic(); this.transaction = new TransactionManager(dataAccess, decryptionProvider); this.requestLogic = new RequestLogic(this.transaction, signatureProvider, this.advancedLogic); this.contentData = new ContentDataExtension(this.advancedLogic); this.bitcoinDetectionProvider = bitcoinDetectionProvider; this.currencyManager = new CurrencyManager(currencies || CurrencyManager.getDefaultList()); } /** * Creates a request. * * @param requestParameters Parameters to create a request * @returns The created request */ public async createRequest(parameters: Types.ICreateRequestParameters): Promise<Request> { const { requestParameters, topics, paymentNetwork } = await this.prepareRequestParameters( parameters, ); const requestLogicCreateResult = await this.requestLogic.createRequest( requestParameters, parameters.signer, topics, ); // create the request object const request = new Request( requestLogicCreateResult.result.requestId, this.requestLogic, this.currencyManager, { contentDataExtension: this.contentData, paymentNetwork, requestLogicCreateResult, skipPaymentDetection: parameters.disablePaymentDetection, disableEvents: parameters.disableEvents, }, ); // refresh the local request data await request.refresh(); return request; } /** * Creates an encrypted request. * * @param parameters Parameters to create a request * @param encryptionParams Request encryption parameters * @returns The created encrypted request */ public async _createEncryptedRequest( parameters: Types.ICreateRequestParameters, encryptionParams: EncryptionTypes.IEncryptionParameters[], ): Promise<Request> { const { requestParameters, topics, paymentNetwork } = await this.prepareRequestParameters( parameters, ); const requestLogicCreateResult = await this.requestLogic.createEncryptedRequest( requestParameters, parameters.signer, encryptionParams, topics, ); // create the request object const request = new Request( requestLogicCreateResult.result.requestId, this.requestLogic, this.currencyManager, { contentDataExtension: this.contentData, paymentNetwork, requestLogicCreateResult, skipPaymentDetection: parameters.disablePaymentDetection, disableEvents: parameters.disableEvents, }, ); // refresh the local request data await request.refresh(); return request; } /** * Gets the ID of a request without creating it. * * @param requestParameters Parameters to create a request * @returns The requestId */ public async computeRequestId( parameters: Types.ICreateRequestParameters, ): Promise<RequestLogicTypes.RequestId> { const { requestParameters } = await this.prepareRequestParameters(parameters); return this.requestLogic.computeRequestId(requestParameters, parameters.signer); } /** * Create a Request instance from an existing Request's ID * * @param requestId The ID of the Request * @param options options * @returns the Request */ public async fromRequestId( requestId: RequestLogicTypes.RequestId, options?: { disablePaymentDetection?: boolean; disableEvents?: boolean; explorerApiKeys?: Record<string, string>; }, ): Promise<Request> { const requestAndMeta: RequestLogicTypes.IReturnGetRequestFromId = await this.requestLogic.getRequestFromId( requestId, ); // if no request found, throw a human readable message: if (!requestAndMeta.result.request && !requestAndMeta.result.pending) { throw new Error(localUtils.formatGetRequestFromIdError(requestAndMeta)); } // get the request state. If the creation is not confirmed yet, get the pending state (useful for the payment network) const requestState: RequestLogicTypes.IRequest = requestAndMeta.result.request ? requestAndMeta.result.request : (requestAndMeta.result.pending as RequestLogicTypes.IRequest); const paymentNetwork: PaymentTypes.IPaymentNetwork | null = PaymentNetworkFactory.getPaymentNetworkFromRequest( { advancedLogic: this.advancedLogic, bitcoinDetectionProvider: this.bitcoinDetectionProvider, request: requestState, explorerApiKeys: options?.explorerApiKeys, currencyManager: this.currencyManager, }, ); // create the request object const request = new Request(requestId, this.requestLogic, this.currencyManager, { contentDataExtension: this.contentData, paymentNetwork, skipPaymentDetection: options?.disablePaymentDetection, disableEvents: options?.disableEvents, }); // refresh the local request data await request.refresh(requestAndMeta); return request; } /** * Create an array of request instances from an identity * * @param identity * @param updatedBetween filter the requests with time boundaries * @param options options * @returns the Requests */ public async fromIdentity( identity: IdentityTypes.IIdentity, updatedBetween?: Types.ITimestampBoundaries, options?: { disablePaymentDetection?: boolean; disableEvents?: boolean }, ): Promise<Request[]> { if (!this.supportedIdentities.includes(identity.type)) { throw new Error(`${identity.type} is not supported`); } return this.fromTopic(identity, updatedBetween, options); } /** * Create an array of request instances from multiple identities * * @param identities * @param updatedBetween filter the requests with time boundaries * @param disablePaymentDetection if true, skip the payment detection * @returns the requests */ public async fromMultipleIdentities( identities: IdentityTypes.IIdentity[], updatedBetween?: Types.ITimestampBoundaries, options?: { disablePaymentDetection?: boolean; disableEvents?: boolean }, ): Promise<Request[]> { const identityNotSupported = identities.find( (identity) => !this.supportedIdentities.includes(identity.type), ); if (identityNotSupported) { throw new Error(`${identityNotSupported.type} is not supported`); } return this.fromMultipleTopics(identities, updatedBetween, options); } /** * Create an array of request instances from a topic * * @param topic * @param updatedBetween filter the requests with time boundaries * @param options options * @returns the Requests */ public async fromTopic( topic: any, updatedBetween?: Types.ITimestampBoundaries, options?: { disablePaymentDetection?: boolean; disableEvents?: boolean }, ): Promise<Request[]> { // Gets all the requests indexed by the value of the identity const requestsAndMeta: RequestLogicTypes.IReturnGetRequestsByTopic = await this.requestLogic.getRequestsByTopic( topic, updatedBetween, ); // From the requests of the request-logic layer creates the request objects and gets the payment networks const requestPromises = requestsAndMeta.result.requests.map( async (requestFromLogic: { request: RequestLogicTypes.IRequest | null; pending: RequestLogicTypes.IPendingRequest | null; }): Promise<Request> => { // get the request state. If the creation is not confirmed yet, get the pending state (useful for the payment network) const requestState: RequestLogicTypes.IRequest = requestFromLogic.request ? requestFromLogic.request : (requestFromLogic.pending as RequestLogicTypes.IRequest); const paymentNetwork: PaymentTypes.IPaymentNetwork | null = PaymentNetworkFactory.getPaymentNetworkFromRequest( { advancedLogic: this.advancedLogic, bitcoinDetectionProvider: this.bitcoinDetectionProvider, request: requestState, currencyManager: this.currencyManager, }, ); // create the request object const request = new Request( requestState.requestId, this.requestLogic, this.currencyManager, { contentDataExtension: this.contentData, paymentNetwork, skipPaymentDetection: options?.disablePaymentDetection, disableEvents: options?.disableEvents, }, ); // refresh the local request data await request.refresh(); return request; }, ); return Promise.all(requestPromises); } /** * Create an array of request instances from a multiple topics * * @param topics * @param updatedBetween filter the requests with time boundaries * @param options options * @returns the Requests */ public async fromMultipleTopics( topics: any[], updatedBetween?: Types.ITimestampBoundaries, options?: { disablePaymentDetection?: boolean; disableEvents?: boolean }, ): Promise<Request[]> { // Gets all the requests indexed by the value of the identity const requestsAndMeta: RequestLogicTypes.IReturnGetRequestsByTopic = await this.requestLogic.getRequestsByMultipleTopics( topics, updatedBetween, ); // From the requests of the request-logic layer creates the request objects and gets the payment networks const requestPromises = requestsAndMeta.result.requests.map( async (requestFromLogic: { request: RequestLogicTypes.IRequest | null; pending: RequestLogicTypes.IPendingRequest | null; }): Promise<Request> => { // get the request state. If the creation is not confirmed yet, get the pending state (useful for the payment network) const requestState: RequestLogicTypes.IRequest = requestFromLogic.request ? requestFromLogic.request : (requestFromLogic.pending as RequestLogicTypes.IRequest); const paymentNetwork: PaymentTypes.IPaymentNetwork | null = PaymentNetworkFactory.getPaymentNetworkFromRequest( { advancedLogic: this.advancedLogic, bitcoinDetectionProvider: this.bitcoinDetectionProvider, request: requestState, currencyManager: this.currencyManager, }, ); // create the request object const request = new Request( requestState.requestId, this.requestLogic, this.currencyManager, { contentDataExtension: this.contentData, paymentNetwork, skipPaymentDetection: options?.disablePaymentDetection, disableEvents: options?.disableEvents, }, ); // refresh the local request data await request.refresh(); return request; }, ); return Promise.all(requestPromises); } /* * If request currency is a string, convert it to currency object */ private getCurrency(input: string | RequestLogicTypes.ICurrency): RequestLogicTypes.ICurrency { if (typeof input === 'string') { const currency = this.currencyManager.from(input); if (!currency) { throw new UnsupportedCurrencyError(input); } return CurrencyManager.toStorageCurrency(currency); } return input; } /** * A helper to validate and prepare the parameters of a request. * @param parameters Parameters to create a request * @returns the parameters, ready for request creation, the topics, and the paymentNetwork */ private async prepareRequestParameters( parameters: Types.ICreateRequestParameters, ): Promise<{ requestParameters: RequestLogicTypes.ICreateParameters; topics: any[]; paymentNetwork: PaymentTypes.IPaymentNetwork | null; }> { const currency = this.getCurrency(parameters.requestInfo.currency); const requestParameters = { ...parameters.requestInfo, currency, }; const paymentNetworkCreationParameters = parameters.paymentNetwork; const contentData = parameters.contentData; const topics = parameters.topics?.slice() || []; if (requestParameters.extensionsData) { throw new Error('extensionsData in request parameters must be empty'); } // If ERC20, validate that the value is a checksum address if (requestParameters.currency.type === RequestLogicTypes.CURRENCY.ERC20) { if (!this.validERC20Address(requestParameters.currency.value)) { throw new Error('The ERC20 currency address needs to be a valid Ethereum checksum address'); } } // avoid mutation of the parameters const copiedRequestParameters = Utils.deepCopy(requestParameters); copiedRequestParameters.extensionsData = []; let paymentNetwork: PaymentTypes.IPaymentNetwork | null = null; if (paymentNetworkCreationParameters) { paymentNetwork = PaymentNetworkFactory.createPaymentNetwork({ advancedLogic: this.advancedLogic, bitcoinDetectionProvider: this.bitcoinDetectionProvider, currency: requestParameters.currency, paymentNetworkCreationParameters, currencyManager: this.currencyManager, }); if (paymentNetwork) { // create the extensions data for the payment network copiedRequestParameters.extensionsData.push( await paymentNetwork.createExtensionsDataForCreation( paymentNetworkCreationParameters.parameters, ), ); } } if (contentData) { // create the extensions data for the content data copiedRequestParameters.extensionsData.push( this.contentData.createExtensionsDataForCreation(contentData), ); } // add identities as topics if (copiedRequestParameters.payee) { topics.push(copiedRequestParameters.payee); } if (copiedRequestParameters.payer) { topics.push(copiedRequestParameters.payer); } return { requestParameters: copiedRequestParameters, topics, paymentNetwork }; } /** * Returns true if the address is a valid checksum address * * @param address The address to validate * @returns If the address is valid or not */ private validERC20Address(address: string): boolean { return ethersUtils.getAddress(address) === address; } }
the_stack
import {Component, OnDestroy, OnInit} from '@angular/core'; import {ActivatedRoute} from '@angular/router'; import {EveboxSubscriptionService} from '../../subscription.service'; import {ElasticSearchService} from '../../elasticsearch.service'; import {TopNavService} from '../../topnav.service'; import {ReportsService} from '../reports.service'; import {AppEvent, AppEventCode, AppService} from '../../app.service'; import {loadingAnimation} from '../../animations'; import * as moment from 'moment'; import {humanizeFileSize} from '../../humanize.service'; import {ApiService} from '../../api.service'; @Component({ templateUrl: './ip-report.component.html', animations: [ loadingAnimation, ] }) export class IpReportComponent implements OnInit, OnDestroy { ip: string; loading = 0; alertsOverTime: any[]; flow: any = { ready: false, sourceFlowCount: 0, destFlowCount: 0, bytesToIp: 0, bytesFromIp: 0, packetsToIp: 0, packetsFromIp: 0, }; // DNS hostname lookups returning this IP. dnsHostnamesForAddress: any[]; // Top requested hostnames. dnsRequestedHostnames: any[]; userAgents: any[]; topHttpHostnames: any[]; tlsSni: any[]; topTlsSniRequests: any[]; tlsClientVersions: any[]; tlsServerVersions: any[]; topTlsSubjectRequests: any[]; topDestinationHttpHostnames: any[]; topSignatures: any[]; ssh: any = { sshInboundClientVersions: [], sshOutboundClientVersions: [], sshOutboundServerVersions: [], sshInboundServerVersions: [], sshOutboundClientProtoVersions: [], sshOutboundServerProtoVersions: [], sshInboundClientProtoVersions: [], sshInboundServerProtoVersions: [], }; sensors: Set<string> = new Set<string>(); // Empty string defaults to all sensors. sensorFilter = ''; queryString = ''; constructor(private route: ActivatedRoute, private elasticsearch: ElasticSearchService, private appService: AppService, private topNavService: TopNavService, private reportsService: ReportsService, private api: ApiService, private ss: EveboxSubscriptionService) { } ngOnInit() { this.ss.subscribe(this, this.route.params, (params: any) => { this.ip = params.ip; this.queryString = params.q; this.refresh(); this.buildRelated(this.ip); }); this.ss.subscribe(this, this.appService, (event: AppEvent) => { if (event.event == AppEventCode.TIME_RANGE_CHANGED) { this.refresh(); } }); } relatedAddresses: any[] = []; buildRelated(ip: any) { this.relatedAddresses = []; let sep = '.'; if (ip.indexOf(':') > -1) { // Looks like IPv6. sep = ':'; } let parts = ip.split(sep).filter((part: any) => { return part != ''; }); if (sep == ':') { while (parts.length > 1) { parts.splice(parts.length - 1, 1); this.relatedAddresses.push({ value: parts.join(sep) + sep, name: parts.join(sep) + sep, }); } } else { // The above generic loop could be used for IPv4 as well, but // this gives better use about with CIDR notation. if (parts.length > 3) { this.relatedAddresses.push({ value: `${parts[0]}.${parts[1]}.${parts[2]}.`, name: `${parts[0]}.${parts[1]}.${parts[2]}/24` }); } if (parts.length > 2) { this.relatedAddresses.push({ value: `${parts[0]}.${parts[1]}.`, name: `${parts[0]}.${parts[1]}/16` }); } if (parts.length > 1) { this.relatedAddresses.push({ value: `${parts[0]}.`, name: `${parts[0]}/8` }); } } } ngOnDestroy() { this.ss.unsubscribe(this); } keywordTermQuery(keyword: string, value: any): any { return this.elasticsearch.keywordTerm(keyword, value); } asKeyword(keyword: string): string { return this.elasticsearch.asKeyword(keyword); } queryDnsHostnamesForAddress(range: any, now: any) { this.loading++; let query = { query: { bool: { filter: [ {exists: {field: 'event_type'}}, {term: {'event_type': 'dns'}}, this.keywordTermQuery('dns.type', 'answer'), this.ipQuery('dns.rdata', this.ip), ] } }, size: 0, aggs: { uniqueHostnames: { terms: { field: this.asKeyword('dns.rrname'), size: 100, } } } }; if (this.sensorFilter != '') { this.elasticsearch.addSensorNameFilter(query, this.sensorFilter); } this.elasticsearch.addTimeRangeFilter(query, now, range); this.elasticsearch.search(query).then((response: any) => { this.dnsHostnamesForAddress = response.aggregations.uniqueHostnames.buckets.map((bucket: any) => { return { key: bucket.key, count: bucket.doc_count, }; }); this.loading--; }); } refresh() { let range = this.topNavService.getTimeRangeAsSeconds(); let now = moment(); this.queryDnsHostnamesForAddress(range, now); this.loading++; // Alert histogram. this.api.reportHistogram({ timeRange: range, interval: this.reportsService.histogramTimeInterval(range), addressFilter: this.ip, queryString: this.queryString, eventType: 'alert', sensorFilter: this.sensorFilter, }).then((response: any) => { this.alertsOverTime = response.data.map((x: any) => { return { date: moment(x.key).toDate(), value: x.count, }; }); }); let query = { query: { bool: { filter: [ {exists: {field: 'event_type'}}, ], should: [ this.ipQuery('src_ip', this.ip), this.ipQuery('dest_ip', this.ip), ], 'minimum_should_match': 1 } }, size: 0, sort: [ {'@timestamp': {order: 'desc'}} ], aggs: { sensors: { terms: { field: this.asKeyword('host'), size: 1000, }, }, alerts: { filter: { term: {event_type: 'alert'} }, aggs: { signatures: { terms: { field: this.asKeyword('alert.signature'), size: 10, } } } }, // Top DNS requests made by this IP. dnsRequests: { filter: { bool: { filter: [ {term: {'event_type': 'dns'}}, {term: {'dns.type': 'query'}}, this.ipQuery('src_ip', this.ip), ] }, }, aggs: { rrnames: { terms: { field: this.asKeyword('dns.rrname'), size: 10, } } } }, // HTTP user agents. httpRequests: { filter: { bool: { filter: [ {term: {'event_type': 'http'}}, this.ipQuery('src_ip', this.ip), ] } }, aggs: { userAgents: { terms: { field: this.asKeyword('http.http_user_agent'), size: 10, } }, hostnames: { terms: { field: this.asKeyword('http.hostname'), size: 10, } } } }, http: { filter: { term: {event_type: 'http'}, }, aggs: { dest: { filter: this.ipQuery('dest_ip', this.ip), aggs: { hostnames: { terms: { field: this.asKeyword('http.hostname'), size: 10, }, } } }, } }, // TLS SNI... tlsSni: { filter: { bool: { filter: [ {term: {'event_type': 'tls'}}, this.ipQuery('dest_ip', this.ip), ] } }, aggs: { sni: { terms: { field: this.asKeyword('tls.sni'), size: 100, } } } }, // TLS (Versions)... tls: { filter: { term: {event_type: 'tls'} }, aggs: { asSource: { filter: this.ipQuery('src_ip', this.ip), aggs: { versions: { terms: { field: this.asKeyword('tls.version'), size: 10, } }, sni: { terms: { field: this.asKeyword('tls.sni'), size: 10, } }, subjects: { terms: { field: this.asKeyword('tls.subject'), size: 10, } } } }, asDest: { filter: this.ipQuery('dest_ip', this.ip), aggs: { versions: { terms: { field: this.asKeyword('tls.version'), size: 10, } } } } } }, ssh: { filter: { term: {event_type: 'ssh'}, }, aggs: { // SSH connections as client. sources: { filter: this.ipQuery('src_ip', this.ip), aggs: { outboundClientProtoVersions: { terms: { field: this.asKeyword('ssh.client.proto_version'), size: 10, } }, outboundServerProtoVersions: { terms: { field: this.asKeyword('ssh.server.proto_version'), size: 10, } }, // Outbound server versions - that is, the server // versions connected to by this host. outboundServerVersions: { terms: { field: this.asKeyword('ssh.server.software_version'), size: 10, } }, // Outbound client versions. outboundClientVersions: { terms: { field: this.asKeyword('ssh.client.software_version'), size: 10, } } } }, // SSH connections as server. dests: { filter: this.ipQuery('dest_ip', this.ip), aggs: { inboundClientProtoVersions: { terms: { field: this.asKeyword('ssh.client.proto_version'), size: 10, } }, inboundServerProtoVersions: { terms: { field: this.asKeyword('ssh.server.proto_version'), size: 10, } }, // Inbound client versions. inboundClientVersions: { terms: { field: this.asKeyword('ssh.client.software_version'), size: 10, } }, // Inbound server versions. inboundServerVersions: { terms: { field: this.asKeyword('ssh.server.software_version'), size: 10, } } } } } }, // Number of flows as client. sourceFlows: { filter: { bool: { filter: [ {term: {'event_type': 'flow'}}, this.ipQuery("src_ip", this.ip), ] } }, aggs: { bytesToClient: { sum: { field: 'flow.bytes_toclient', } }, bytesToServer: { sum: { field: 'flow.bytes_toserver', } }, packetsToClient: { sum: { field: 'flow.pkts_toclient', } }, packetsToServer: { sum: { field: 'flow.pkts_toserver', } }, } }, // Number of flows as server. destFlows: { filter: { bool: { filter: [ {term: {'event_type': 'flow'}}, this.ipQuery("dest_ip", this.ip), ] } }, aggs: { bytesToClient: { sum: { field: 'flow.bytes_toclient', } }, bytesToServer: { sum: { field: 'flow.bytes_toserver', } }, packetsToClient: { sum: { field: 'flow.pkts_toclient', } }, packetsToServer: { sum: { field: 'flow.pkts_toserver', } } } }, } }; if (this.sensorFilter != '') { this.elasticsearch.addSensorNameFilter(query, this.sensorFilter); } this.elasticsearch.addTimeRangeFilter(query, now, range); this.elasticsearch.search(query).then((response) => { this.flow.bytesFromIp = response.aggregations.destFlows.bytesToClient.value + response.aggregations.sourceFlows.bytesToServer.value; this.flow.bytesFromIp = humanizeFileSize(this.flow.bytesFromIp); this.flow.bytesToIp = response.aggregations.destFlows.bytesToServer.value + response.aggregations.sourceFlows.bytesToClient.value; this.flow.bytesToIp = humanizeFileSize(this.flow.bytesToIp); this.flow.packetsFromIp = response.aggregations.destFlows.packetsToClient.value + response.aggregations.sourceFlows.packetsToServer.value; this.flow.packetsToIp = response.aggregations.destFlows.packetsToServer.value + response.aggregations.sourceFlows.packetsToClient.value; this.flow.sourceFlowCount = response.aggregations.sourceFlows.doc_count; this.flow.destFlowCount = response.aggregations.destFlows.doc_count; this.flow.ready = true; this.userAgents = this.mapTerms(response.aggregations.httpRequests.userAgents.buckets); this.topHttpHostnames = this.mapTerms(response.aggregations.httpRequests.hostnames.buckets); this.tlsSni = this.mapTerms(response.aggregations.tlsSni.sni.buckets); this.tlsClientVersions = this.mapTerms(response.aggregations.tls.asSource.versions.buckets); this.tlsServerVersions = this.mapTerms(response.aggregations.tls.asDest.versions.buckets); this.topTlsSniRequests = this.mapTerms(response.aggregations.tls.asSource.sni.buckets); this.topTlsSubjectRequests = this.mapTerms(response.aggregations.tls.asSource.subjects.buckets); this.topDestinationHttpHostnames = this.mapTerms(response.aggregations.http.dest.hostnames.buckets); this.topSignatures = this.mapTerms(response.aggregations.alerts.signatures.buckets); this.ssh.sshInboundClientVersions = this.mapTerms( response.aggregations.ssh.dests.inboundClientVersions.buckets); this.ssh.sshOutboundClientVersions = this.mapTerms( response.aggregations.ssh.sources.outboundClientVersions.buckets); this.ssh.sshOutboundServerVersions = this.mapTerms( response.aggregations.ssh.sources.outboundServerVersions.buckets); this.ssh.sshInboundServerVersions = this.mapTerms( response.aggregations.ssh.dests.inboundServerVersions.buckets); this.ssh.sshInboundClientProtoVersions = this.mapTerms( response.aggregations.ssh.dests.inboundClientProtoVersions.buckets); this.ssh.sshInboundServerProtoVersions = this.mapTerms( response.aggregations.ssh.dests.inboundServerProtoVersions.buckets); this.ssh.sshOutboundClientProtoVersions = this.mapTerms( response.aggregations.ssh.sources.outboundClientProtoVersions.buckets); this.ssh.sshOutboundServerProtoVersions = this.mapTerms( response.aggregations.ssh.sources.outboundServerProtoVersions.buckets); response.aggregations.sensors.buckets.forEach((bucket: any) => { this.sensors.add(bucket.key); }); this.dnsRequestedHostnames = this.mapTerms( response.aggregations.dnsRequests.rrnames.buckets); this.loading--; }); } /** * Helper function to map terms aggregations into the common format used * by Evebox. */ mapTerms(buckets: any): any[] { return buckets.map((bucket: any) => { return { key: bucket.key, count: bucket.doc_count, }; }); } ipQuery(field: string, value: string): any { let type = "term"; if (value[value.length - 1] == ".") { type = "prefix"; } field = this.asKeyword(field); let term = {}; term[type] = {}; term[type][field] = value; return term; } }
the_stack
* @title: GPU ParticleSystem * @description: * This sample demonstrates the capabilities and usage of the GPU ParticleSystem. */ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/floor.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/texturemanager.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/effectmanager.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/scenedebugging.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/forwardrendering.js") }}*/ /*{{ javascript("jslib/particlesystem.js") }}*/ /*{{ javascript("jslib/fontmanager.js") }}*/ /*{{ javascript("jslib/canvas.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*global CameraController: false */ /*global Camera: false */ /*global Canvas: false */ /*global EffectManager: false */ /*global Floor: false */ /*global FontManager: false */ /*global ForwardRendering: false */ /*global HTMLControls: false */ /*global ParticleBuilder: false */ /*global ParticleSystem: false */ /*global ParticleView: false */ /*global RequestHandler: false*/ /*global Scene: false */ /*global SceneNode: false */ /*global ShaderManager: false */ /*global TextureManager: false */ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global window: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; //========================================================================== // Turbulenz Initialization //========================================================================== var graphicsDevice = TurbulenzEngine.createGraphicsDevice({}); if (graphicsDevice.maxSupported("VERTEX_TEXTURE_UNITS") === 0) { errorCallback("Device does not support sampling of textures from vertex shaders " + "required by GPU particle system"); return; } var mathDevice = TurbulenzEngine.createMathDevice({}); var inputDevice = TurbulenzEngine.createInputDevice({}); var requestHandler = RequestHandler.create({}); var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var effectManager = EffectManager.create(); var fontManager = FontManager.create(graphicsDevice, requestHandler, null, errorCallback); // region of world where systems will be spawned. var sceneWidth = 1000; var sceneHeight = 1000; // speed of generation. var generationSpeed = 50; // generations per second. var lastGen = 0; // speed of simulation (log 1.3) var simulationSpeed = 0; var camera = Camera.create(mathDevice); var halfFOV = Math.tan(30 * Math.PI / 180); camera.recipViewWindowX = 1 / halfFOV; camera.recipViewWindowY = 1 / halfFOV; camera.lookAt(mathDevice.v3Build(0, 0, 0), mathDevice.v3BuildYAxis(), mathDevice.v3Build(sceneWidth / 2, 30, sceneHeight / 2)); camera.updateProjectionMatrix(); camera.updateViewMatrix(); var cameraController = CameraController.create(graphicsDevice, inputDevice, camera); var maxCameraSpeed = 200; var renderer; var clearColor = mathDevice.v4Build(0, 0, 0, 1); var scene = Scene.create(mathDevice); var floor = Floor.create(graphicsDevice, mathDevice); floor.color = mathDevice.v4Build(0, 0, 0.6, 1); floor.fadeToColor = clearColor; var drawRenderableExtents = false; function extraDrawCallback() { floor.render(graphicsDevice, camera); if (drawRenderableExtents) { (<any>scene).drawVisibleRenderablesExtents(graphicsDevice, shaderManager, camera, false, true); } } // Create canvas object for minimap. var canvas = Canvas.create(graphicsDevice); var ctx = canvas.getContext('2d'); // Scaling to use when drawing to minimap, targetting a size of (150,150) for minimap var scaleX = 150 / sceneWidth; var scaleY = 150 / sceneHeight; ctx.lineWidth = 0.1; var fontTechnique; var fontTechniqueParameters; var fpsElement = document.getElementById("fps"); var fpsText = ""; function displayFPS() { if (!fpsElement) { return; } var text = graphicsDevice.fps.toFixed(2) + " fps"; if (text !== fpsText) { fpsText = text; fpsElement.innerHTML = fpsText; } } //========================================================================== // Particle Systems //========================================================================== var particleManager = ParticleManager.create(graphicsDevice, textureManager, shaderManager); particleManager.registerParticleAnimation({ name: "fire", // Define a texture-size to normalize uv-coordinates with. // This avoids needing to use fractional values, especially if texture // may be changed in future. // // In this case the actual texture is 512x512, but we map the particle animation // to the top-half, so can pretend it is really 512x256. // // To simplify the uv-coordinates further, we can 'pretend' it is really 4x2 as // after normalization the resulting uv-coordinates would be equivalent. "texture0-size": [4, 2], texture0: [ // [x y w h] [0, 0, 1, 1], // frame 0 [1, 0, 1, 1], // [2, 0, 1, 1], // [3, 0, 1, 1], // [0, 1, 1, 1], // [1, 1, 1, 1], // [2, 1, 1, 1], // [3, 1, 1, 1], // frame 7 ], animation: [{ frame: 0 }, { // after 0.6 seconds, ensure colour is still [1,1,1,1] time: 0.6, color: [1, 1, 1, 1] }, { // after another 0.1 seconds time: 0.1, // want to be 'just past' the last frame. // so all frames of animation have equal screen presence. frame: 8, color: [1, 1, 1, 0] }] }); particleManager.registerParticleAnimation({ name: "smoke", // smoke is similarly mapped as "fire" particle above, but to bottom of packed texture. "texture0-size": [4, 2], texture0: [ // [x y w h] [0, 0, 1, 1], // frame 0 [1, 0, 1, 1], // [2, 0, 1, 1], // [3, 0, 1, 1], // [0, 1, 1, 1], // [1, 1, 1, 1], // [2, 1, 1, 1], // [3, 1, 1, 1], // frame 7 ], animation: [{ // these are values applied by default to the first snapshot in animation // we could omit them here if we wished. frame: 0, "frame-interpolation": "linear", color: [1, 1, 1, 1], "color-interpolation": "linear" }, { // after 0.8 seconds time: 0.8, color: [1, 0.5, 0.5, 1] }, { // after another 0.5 seconds, we fade out. time: 0.5, // want to be 'just past' the last frame. // so all frames of animation have equal screen presence. frame: 8, color: [0, 0, 0, 0] }] }); particleManager.registerParticleAnimation({ name: "portal", animation: [{ "scale-interpolation": "catmull", color: [0, 1, 0, 1] }, { // after 0.3 seconds time : 0.3, scale: [2, 2], color: [1, 1, 1, 1] }, { // after another 0.7 seconds time : 0.7, scale: [0.5, 0.5], color: [1, 0, 0, 0] }] }); var description1 = { system: { // define local system extents, particles will be clamped against these extents when reached. // // We make extents a little larger than necessary so that in movement of system // particles will not push up against the edges of extents so easily. center : [0, 6, 0], halfExtents : [7, 6, 7] }, updater: { // set noise texture to use for randomization, and allow acceleration (when enabled) // to be randomized to up to the given amounts. noiseTexture: "textures/noise.dds", randomizedAcceleration: [10, 10, 10] }, renderer: { // use default renderer with additive blend mode name: "additive", // set noise texture to use for randomizations. noiseTexture: "textures/noise.dds", // for particles that enable these options, we're going to allow particle alphas // if enabled on particles, allow particle orientation to be randomized up to these // spherical amounts (+/-), in this case, to rotate around y-axis by +/- 0.3*Math.PI // specify this variation should change over time randomizedOrientation: [0, 0.3 * Math.PI], animatedOrientation: true, // if enabled on particles, allow particle scale to be randomized up to these // amounts (+/-), and define that this variation should not change over time. randomizedScale: [3, 3], animatedScale : false }, // All particles make use of this single texture. packedTexture: "textures/flamesmokesequence.png", particles: { fire: { animation: "fire", // select sub-set of packed texture this particles animation should be mapped to. "texture-uv": [0, 0, 1, 0.5], // top-half // apply animation tweaks to increase size of animation (x5) tweaks: { "scale-scale": [5, 5] } }, ember: { animation: "fire", "texture-uv": [0, 0.0, 1, 0.5], // top-half // apply animation tweaks so that only the second half of flip-book is used. // and double the size. tweaks: { "scale-scale": [2, 2], // The animation we're using has 8 frames, we want to use the second // half of the flip-book animation, so we scale by 0.5 and offset by 4. "frame-scale": 0.5, "frame-offset": 4 } }, smoke: { animation: "smoke", // select sub-set of packed texture this particles animation should be mapped to. "texture-uv": [0, 0.5, 1, 0.5], // bottom-half // apply animation tweaks to increase size of animation (x3) tweaks: { "scale-scale": [3, 3] } } }, emitters: [{ particle: { name: "fire", // let life time of particle vary between 0.6 and 1.2 of animation life time. lifeTimeScaleMin: 0.6, lifeTimeScaleMax: 1.2, // set userData so that its orientation will be randomized, and will have a // also define scale should be randomized. renderUserData: { facing : "billboard", randomizeOrientation: true, randomizeScale : true } }, emittance: { // emit particles 10 times per second. With 0 - 2 particles emitted each time. rate: 10, burstMin: 0, burstMax: 2 }, position: { // position 2 units above system position position: [0, 2, 0], // and with a randomized radius in disc of up to 1 unit // with a normal (gaussian) distribution to focus on centre. radiusMax: 1, radiusDistribution: "normal" }, velocity: { // spherical angles defining direction to emit particles in. // the default 0, 0 means to emit particles straight up the y-axis. theta: 0, phi: 0 } }, { particle: { name: "ember", // override animation life times. lifeTimeMin: 0.2, lifeTimeMax: 0.6, // set userData so that acceleration will be randomized and also orientation. updateUserData: { randomizeAcceleration: true }, renderUserData: { randomizeOrientation: true } }, emittance: { // emit particles 3 times per second. With 0 - 15 particles emitted each time. rate: 3, burstMin: 0, burstMax: 15, // only start emitting after 0.25 seconds delay: 0.25 }, velocity: { // set velocity to a random direction in conical spread conicalSpread: Math.PI * 0.25, // and with speeds between these values. speedMin: 1, speedMax: 3 }, position: { // position 3 units above system position position: [0, 3, 0], // and in a random radius of this position in a sphere. spherical: true, radiusMin: 1, radiusMax: 2.5 } }, { particle: { name: "smoke", // set userData so that acceleration will be randomized. updateUserData: { randomizeAcceleration: true } }, emittance: { // emit particles 20 times per second, with 0 - 3 every time. rate: 20, burstMin: 0, burstMax: 3 }, velocity: { // set velocity to a random direction in conical spread conicalSpread: Math.PI * 0.25, // and with speeds between these values. speedMin: 2, speedMax: 6 }, position: { // position 2.5 units above system position position: [0, 2.5, 0], // and in a random radius of this position in a sphere. spherical: true, radiusMin: 0.5, radiusMax: 2.0 } }] }; var description2 = { system: { // define local system extents // as with first system these are defined to be a bit larger to account for // movements of the system. center : [0, 6, 0], halfExtents: [12, 6, 12] }, renderer: { // we're going to use the default renderer with the "additive" blend mode. name: "additive", // set noise texture to use for randomizations noiseTexture: "textures/noise.dds", // for particles that enable these options, we're going to allow particle alphas // to vary +/- 0.5, and this alpha variation will change over time. randomizedAlpha: 1.0, animatedAlpha: true, // for particles that enable these options, we're going to allow particle orientations // to vary by the given spherical angles (+/-), and this variation will change over time. randomizedOrientation: [Math.PI * 0.25, Math.PI * 0.25], animatedOrientation : true, // for particles that enable these options, we're going to allow particle rotations // to vary by the given angle (+/-), and this variation will change over time. randomizedRotation: Math.PI * 2, animatedRotation : true }, updater: { // In the absense of acceleration, set drag so that particles will come to a stop after // 1 second of simulation. drag: 1, // for particles that enable these options, we're going to allow acceleration applied to // particles to vary according to the noise texture, up to a defined maximum in each // coordinate (+/-) noiseTexture: "textures/noise.dds", randomizedAcceleration: [10, 0, 10] }, particles: { // Define two particles to be used in this system. // As these define their own textures, textures will be packed at runtime by the particleManager. spark: { animation: "portal", // define animation tweaks to be applied for this particle. tweaks: { // this defines that we're going to half the animated scale of the particle. // In effect, we're making this particle half the size the animation said it should be. "scale-scale": [0.5, 0.5] }, texture: "textures/particle_spark.png" }, smoke: { animation: "portal", tweaks: { // The effect of these parameters will be to invert the RGB colours of the particle as // defined by the animation, and particle texture. "color-scale" : [-1, -1, -1, 1], "color-offset": [ 1, 1, 1, 0] }, texture: "textures/smoke.dds" } }, emitters: [{ emittance: { // After 1 second from the start of the effect, we're going to emit particles 80 times per second. delay: 1, rate: 80, // Whenever we emit particles, we will emit exactly 4 particles. burstMin: 4, burstMax: 4 }, particle: { name: "spark", // Here we access functions of the updater and renderer that will be used, to set the userData // that will be applied to each particle emitted. // We define that we want particles emitted by this emitter to have their acceleration randomize // and also their alpha, orientation and rotation. We specify particle quad should be aligned // with the particles velocity vector. updateUserData: { randomizeAcceleration: true }, renderUserData: { facing : "velocity", randomizeAlpha : true, randomizeOrientation: true, randomizeRotation : true } }, velocity: { // Particles will be emitted with local speeds between these values. speedMin: 3, speedMax: 20, // And with a conical spread of the given angle about the default direction (y-axis). conicalSpread: Math.PI / 10 }, position: { // Particles will be generated at radii between these values. radiusMin: 4, radiusMax: 5, // And the distribution of the radius selected will be according to a normal (Gaussian) distribution // with the given sigma parameter. radiusDistribution: "normal", radiusSigma : 0.125 } }, { emittance: { // We will emit particles 20 times per second. rate: 20, // And whenever we emit particles, we'll emit between 0 and 6 particles. burstMin: 0, burstMax: 6 }, particle: { name: "smoke", // Particles of this emitter will have their quads billboarded to face camera. renderUserData: { facing: "billboard" }, // Particles will live for between these amounts of time in seconds. useAnimationLifeTime: false, lifeTimeMin: 0.5, lifeTimeMax: 1.5 }, velocity: { speedMin: 5, speedMax: 15 }, position: { spherical: false, radiusMin: 0, radiusMax: 2 } }] }; // Produce ParticleArchetype objects based on these descriptions. // These calls will verify the input descriptions for correctness, and fill in all missing parameters // with the default values defined by the individual components of a particle system. var archetype1 = particleManager.parseArchetype(description1); var archetype2 = particleManager.parseArchetype(description2); //========================================================================== // Main loop //========================================================================= var previousFrameTime; function init() { fontTechnique = shaderManager.get("shaders/font.cgfx").getTechnique('font'); fontTechniqueParameters = graphicsDevice.createTechniqueParameters({ clipSpace : mathDevice.v4BuildZero(), alphaRef : 0.01, color : mathDevice.v4BuildOne() }); renderer = ForwardRendering.create( graphicsDevice, mathDevice, shaderManager, effectManager, {} ); // particleManager is initialized with the Scene to be worked with. // and the transparent pass index of the renderer, so that particle systems // created will be sorted with other transparent renderable elements of the Scene. particleManager.initialize(scene, renderer.passIndex.transparent); previousFrameTime = TurbulenzEngine.time; } // All systems are added as children of this node so we can shuffle them around // in space, demonstrating trails. var particleNode = SceneNode.create({ name : "particleNode", dynamic: true }); scene.addRootNode(particleNode); var moveSystems = false; var movementTime = 0; // movement radius of particleNode. var radius = 50; function mainLoop() { var currentTime = TurbulenzEngine.time; var deltaTime = (currentTime - previousFrameTime); previousFrameTime = currentTime; displayFPS(); inputDevice.update(); cameraController.maxSpeed = (deltaTime * maxCameraSpeed); cameraController.update(); // Update the aspect ratio of the camera in case of window resizes var aspectRatio = (graphicsDevice.width / graphicsDevice.height); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); // alter deltaTime for simulation speed after camera maxSpeed was set to avoid // slowing down the camera movement. deltaTime *= Math.pow(1.3, simulationSpeed); // Update ParticleManager object with elapsed time. // This will add the deltaTime to the managers internal clock used by systems when synchronizing // and will also remove any expired ParticleInstance objects created in the particleManager. particleManager.update(deltaTime); // Create new ParticleInstances in particleManager. lastGen += deltaTime; var limit = 0; while (lastGen > 1 / generationSpeed && limit < 100) { limit += 1; lastGen -= 1 / generationSpeed; var instance, x, z, s, timeout; timeout = 2 + 2 * Math.random(); instance = particleManager.createInstance(archetype1, timeout); x = Math.random() * (sceneWidth - radius * 2) + radius; z = Math.random() * (sceneHeight - radius * 2) + radius; s = 1 + Math.random() * 2; // this local transform will be applied to the entire system // allowing us to re-use the same particle archetype around the // scene at different positions and scales. instance.renderable.setLocalTransform(mathDevice.m43Build( s, 0, 0, 0, s, 0, 0, 0, s, x, 0, z)); particleManager.addInstanceToScene(instance, particleNode); timeout = 2 + 2 * Math.random(); instance = particleManager.createInstance(archetype2, timeout); x = Math.random() * (sceneWidth - radius * 2) + radius; z = Math.random() * (sceneHeight - radius * 2) + radius; s = 1 + Math.random() * 2; instance.renderable.setLocalTransform(mathDevice.m43Build( s, 0, 0, 0, s, 0, 0, 0, s, x, 0, z)); particleManager.addInstanceToScene(instance, particleNode); } lastGen %= (1 / generationSpeed); // Shuffle node containing all particle systems around if (moveSystems) { movementTime += deltaTime; var time = movementTime / 5; var rad = radius * Math.sin(time); var transform = mathDevice.m43BuildTranslation( Math.sin(time) * rad, 0, Math.cos(time) * rad); particleNode.setLocalTransform(transform); } // Update scene scene.update(); if (!graphicsDevice.beginFrame()) { return; } // Update renderer, this will as a side-effect of particle instances becoming visible to the camera // cause particle systems if required to be lazily created along with any views onto a particle system // the low-level particle system will deal with this itself the way it is used by the particleManager. renderer.update(graphicsDevice, camera, scene, currentTime); // Render scene including all particle systems. renderer.draw(graphicsDevice, clearColor, extraDrawCallback); // Gather metrics about object usages in the particleManager, and display on the screen. graphicsDevice.setTechnique(fontTechnique); mathDevice.v4Build(2 / graphicsDevice.width, -2 / graphicsDevice.height, -1, 1, fontTechniqueParameters.clipSpace); graphicsDevice.setTechniqueParameters(fontTechniqueParameters); var metrics = particleManager.gatherMetrics(); var text = "ParticleManager Metrics:\n"; for (var f in metrics) { if (metrics.hasOwnProperty(f)) { text += f + ": " + metrics[f] + "\n"; } } var font = fontManager.get("fonts/hero.fnt"); var fontScale = 0.5; var dimensions = font.calculateTextDimensions(text, fontScale, 0); font.drawTextRect(text, { rect : mathDevice.v4Build(0, 0, dimensions.width, dimensions.height), scale: fontScale, alignment: 0 }); // Draw 2d mini-map displaying all particle instances, and whether they are: // A) Actively being synchronized, updated and renderer. // B) Have had particle systems/views and gpu texture space allocated, but are in-active. // C) Are in-active, and have not had any systems/views or texture space allocated. if (canvas.width !== graphicsDevice.width) { canvas.width = graphicsDevice.width; } if (canvas.height !== graphicsDevice.height) { canvas.height = graphicsDevice.height; } var width = sceneWidth * scaleX; var height = sceneHeight * scaleY; var viewport = mathDevice.v4Build( canvas.width - width - 2, canvas.height - 2, width, height ); viewport = null; ctx.beginFrame(null, viewport); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.translate(canvas.width - sceneWidth * scaleX - 2, 2); ctx.strokeStyle = "#ffffff"; ctx.strokeRect(0, 0, sceneWidth * scaleX, sceneHeight * scaleY); var instanceMetrics = particleManager.gatherInstanceMetrics(); var count = instanceMetrics.length; var invScaleX = 1.0 / 2 * scaleX; var invScaleY = 1.0 / 2 * scaleY; var i; // Active ctx.beginPath(); var numRectangles = 0; for (i = 0; i < count; i += 1) { var metric = instanceMetrics[i]; if (metric.active) { var extents = metric.instance.renderable.getWorldExtents(); x = (extents[0] + extents[3]) * invScaleX; z = (extents[2] + extents[5]) * invScaleY; ctx.rect(x - 0.5, z - 0.5, 2, 2); numRectangles += 1; } } if (numRectangles) { ctx.fillStyle = "#00ff00"; ctx.fill(); } // Allocated ctx.beginPath(); numRectangles = 0; for (i = 0; i < count; i += 1) { var metric = instanceMetrics[i]; if (!metric.active && metric.allocated) { var extents = metric.instance.renderable.getWorldExtents(); x = (extents[0] + extents[3]) * invScaleX; z = (extents[2] + extents[5]) * invScaleY; ctx.rect(x - 0.5, z - 0.5, 2, 2); numRectangles += 1; } } if (numRectangles) { ctx.fillStyle = "#ffff00"; ctx.fill(); } // Not active and not allocated ctx.beginPath(); numRectangles = 0; for (i = 0; i < count; i += 1) { var metric = instanceMetrics[i]; if (!metric.active && !metric.allocated) { var extents = metric.instance.renderable.getWorldExtents(); x = (extents[0] + extents[3]) * invScaleX; z = (extents[2] + extents[5]) * invScaleY; ctx.rect(x - 0.5, z - 0.5, 2, 2); numRectangles += 1; } } if (numRectangles) { ctx.fillStyle = "#ff0000"; ctx.fill(); } // Display camera (xz) position on minimap also. var pos = mathDevice.m43Pos(mathDevice.m43Inverse(camera.viewMatrix)); if (pos[0] >= 0 && pos[2] >= 0 && pos[0] <= sceneWidth && pos[2] <= sceneHeight) { ctx.strokeStyle = "#ffffff"; ctx.strokeRect(pos[0] * scaleX - 1.5, pos[2] * scaleY - 1.5, 3, 3); } ctx.endFrame(); graphicsDevice.endFrame(); } //========================================================================== // Asset and Mapping table loading //========================================================================= var intervalID; function loadingLoop() { if (graphicsDevice.beginFrame()) { graphicsDevice.clear(clearColor); graphicsDevice.endFrame(); } if (textureManager.getNumPendingTextures() === 0 && shaderManager.getNumPendingShaders() === 0) { TurbulenzEngine.clearInterval(intervalID); init(); intervalID = TurbulenzEngine.setInterval(mainLoop, 1000 / 60); } } function loadAssets() { // Load assets required to render renderable extents. shaderManager.load("shaders/debug.cgfx"); // Load assets required to render the fonts on screen. shaderManager.load("shaders/font.cgfx"); fontManager.load('fonts/hero.fnt'); // Load all assets required to create and work with the particle system archetypes we're using. particleManager.loadArchetype(archetype1); particleManager.loadArchetype(archetype2); intervalID = TurbulenzEngine.setInterval(loadingLoop, 10); } function mappingTableReceived(table) { textureManager.setPathRemapping(table.urlMapping, table.assetPrefix); shaderManager.setPathRemapping(table.urlMapping, table.assetPrefix); fontManager.setPathRemapping(table.urlMapping, table.assetPrefix); loadAssets(); } function sessionCreated(gameSession) { TurbulenzServices.createMappingTable( requestHandler, gameSession, mappingTableReceived ); } var gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated); //========================================================================== // Sample tear-down //========================================================================= TurbulenzEngine.onunload = function unloadFn() { TurbulenzEngine.clearInterval(intervalID); if (gameSession) { gameSession.destroy(); gameSession = null; } if (shaderManager) { shaderManager.destroy(); shaderManager = null; } if (textureManager) { textureManager.destroy(); textureManager = null; } if (fontManager) { fontManager.destroy(); fontManager = null; } if (renderer) { renderer.destroy(); renderer = null; } if (particleManager) { particleManager.destroy(); particleManager = null; } effectManager = null; requestHandler = null; cameraController = null; camera = null; floor = null; TurbulenzEngine.flush(); inputDevice = null; graphicsDevice = null; mathDevice = null; }; //========================================================================= // HTML Controls //========================================================================= var htmlControls = HTMLControls.create(); htmlControls.addSliderControl({ id: "speedSlider", value: (simulationSpeed), max: 6, min: -10, step: 1, fn: function () { simulationSpeed = this.value; htmlControls.updateSlider("speedSlider", simulationSpeed); } }); htmlControls.addSliderControl({ id: "instanceSlider", value: (generationSpeed), max: 200, min: 20, step: 20, fn: function () { generationSpeed = this.value; htmlControls.updateSlider("instanceSlider", generationSpeed); } }); var scaleOffset = 0; function refreshArchetype(description, archetype, scale) { var emitters = description.emitters; var count = emitters.length; var i; for (i = 0; i < count; i += 1) { var emitter = emitters[i]; emitter.emittance.burstMin *= scale; emitter.emittance.burstMax *= scale; } // build new archetype from modified description. // replacing all instances of old with new. // and destroying the old. var newArchetype = particleManager.parseArchetype(description); particleManager.replaceArchetype(archetype, newArchetype); particleManager.destroyArchetype(archetype); return newArchetype; } htmlControls.addButtonControl({ id: "button-decrease-particles", value: "-", fn: function () { if (scaleOffset > -5) { scaleOffset -= 1; archetype1 = refreshArchetype(description1, archetype1, 1 / 1.5); archetype2 = refreshArchetype(description2, archetype2, 1 / 1.5); } } }); htmlControls.addButtonControl({ id: "button-increase-particles", value: "+", fn: function () { if (scaleOffset < 4) { scaleOffset += 1; archetype1 = refreshArchetype(description1, archetype1, 1.5); archetype2 = refreshArchetype(description2, archetype2, 1.5); } } }); htmlControls.addCheckboxControl({ id : "move-systems", value : "moveSystems", isSelected : moveSystems, fn: function () { moveSystems = !moveSystems; return moveSystems; } }); htmlControls.addCheckboxControl({ id : "draw-extents", value : "drawRenderableExtents", isSelected : drawRenderableExtents, fn: function () { drawRenderableExtents = !drawRenderableExtents; return drawRenderableExtents; } }); htmlControls.addButtonControl({ id: "button-clear", value: "Clear", fn: function () { // remove all instances of both archetypes, retaining other state like object // pools and allocated memory on gpu. particleManager.clear(archetype1); particleManager.clear(archetype2); } }); htmlControls.addButtonControl({ id: "button-destroy-1", value: "Destroy 1", fn: function () { // destroy all state and instances associated with archetype1 (complete reset) particleManager.destroyArchetype(archetype1); } }); htmlControls.addButtonControl({ id: "button-destroy-2", value: "Destroy 2", fn: function () { // destroy all state and instances associated with archetype2 (complete reset) particleManager.destroyArchetype(archetype2); } }); htmlControls.addButtonControl({ id: "button-replace-1-2", value: "Replace 1 to 2", fn: function () { // replace all instances of archetype1 with ones of archetype2 in-place. particleManager.replaceArchetype(archetype1, archetype2); } }); htmlControls.addButtonControl({ id: "button-replace-2-1", value: "Replace 2 to 1", fn: function () { // replace all instances of archetype2 with ones of archetype1 in-place. particleManager.replaceArchetype(archetype2, archetype1); } }); htmlControls.register(); };
the_stack
* @module node-opcua-address-space */ // produce nodeset xml files import { assert } from "node-opcua-assert"; import { make_debugLog, make_errorLog } from "node-opcua-debug"; import { ExtensionObject } from "node-opcua-extension-object"; import { BrowseDirection, LocalizedText, makeNodeClassMask, makeResultMask, NodeClass, makeAccessLevelFlag, QualifiedName } from "node-opcua-data-model"; import { getStructuredTypeSchema, getStructureTypeConstructor, StructuredTypeField, StructuredTypeSchema, hasStructuredType } from "node-opcua-factory"; import { NodeId, resolveNodeId } from "node-opcua-nodeid"; import * as utils from "node-opcua-utils"; import { Variant, VariantArrayType, DataType } from "node-opcua-variant"; import { IAddressSpace, BaseNode, INamespace, UADataType, UAMethod, UAObject, UAReference, UAReferenceType, UAVariable, UAVariableType } from "node-opcua-address-space-base"; import { Int64, minOPCUADate } from "node-opcua-basic-types"; import { BrowseDescription, EnumDefinition, StructureDefinition, StructureField, StructureType } from "node-opcua-types"; import { AddressSpacePrivate } from "../address_space_private"; import { XmlWriter } from "../../source/xml_writer"; import { NamespacePrivate } from "../namespace_private"; import { ReferenceImpl } from "../reference_impl"; import { BaseNodeImpl, getReferenceType } from "../base_node_impl"; import { UAReferenceTypeImpl } from "../ua_reference_type_impl"; import { UAObjectTypeImpl } from "../ua_object_type_impl"; import { UAVariableImpl } from "../ua_variable_impl"; import { UAObjectImpl } from "../ua_object_impl"; import { UANamespace } from "../namespace_impl"; import { UAMethodImpl } from "../ua_method_impl"; import { UADataTypeImpl } from "../ua_data_type_impl"; import { UAVariableTypeImpl } from "../ua_variable_type_impl"; import { constructNamespaceDependency } from "./construct_namespace_dependency"; // tslint:disable:no-var-requires const XMLWriter = require("xml-writer"); const debugLog = make_debugLog(__filename); const errorLog = make_errorLog(__filename); function _hash(node: BaseNode | UAReference): string { return node.nodeId.toString(); } function _dumpDisplayName(xw: XmlWriter, node: BaseNode): void { if (node.displayName && node.displayName[0]) { xw.startElement("DisplayName").text(node.displayName[0].text!).endElement(); } } function _dumpDescription(xw: XmlWriter, node: BaseNode): void { if (node.description) { let desc = node.description.text; desc = desc || ""; xw.startElement("Description").text(desc).endElement(); } } function translateNodeId(xw: XmlWriter, nodeId: NodeId): NodeId { assert(nodeId instanceof NodeId); const nn = xw.translationTable[nodeId.namespace]; const translatedNode = new NodeId(nodeId.identifierType, nodeId.value, nn); return translatedNode; } function n(xw: XmlWriter, nodeId: NodeId): string { return translateNodeId(xw, nodeId).toString().replace("ns=0;", ""); } function translateBrowseName(xw: XmlWriter, browseName: QualifiedName): QualifiedName { assert(browseName instanceof QualifiedName); const nn = xw.translationTable[browseName.namespaceIndex]; const translatedBrowseName = new QualifiedName({ namespaceIndex: nn, name: browseName.name }); return translatedBrowseName; } function b(xw: XmlWriter, browseName: QualifiedName): string { return translateBrowseName(xw, browseName).toString().replace("ns=0;", ""); } function _dumpReferences(xw: XmlWriter, node: BaseNode) { xw.startElement("References"); const addressSpace = node.addressSpace; const aggregateReferenceType = addressSpace.findReferenceType("Aggregates")!; const hasChildReferenceType = addressSpace.findReferenceType("HasChild")!; const hasSubtypeReferenceType = addressSpace.findReferenceType("HasSubtype")!; const hasTypeDefinitionReferenceType = addressSpace.findReferenceType("HasTypeDefinition")!; const nonHierarchicalReferencesType = addressSpace.findReferenceType("NonHierarchicalReferences")!; const organizesReferencesType = addressSpace.findReferenceType("Organizes")!; const connectsToReferenceType = addressSpace.findReferenceType("ConnectsTo")!; const hasEventSourceReferenceType = addressSpace.findReferenceType("HasEventSource")!; function referenceToKeep(reference: UAReference): boolean { const referenceType = (reference as ReferenceImpl)._referenceType!; // get the direct backward reference to a external namespace if (referenceType.isSupertypeOf(aggregateReferenceType) && !reference.isForward) { if (reference.nodeId.namespace !== node.nodeId.namespace) { // todo: may be check that reference.nodeId.namespace is one of the namespace // on which our namespace is build and not a derived one ! // xx console.log("xxxxxxxxxxxxxx Keeping => ", referenceType.toString(), reference.node?.nodeId.toString()); return true; } } // only keep if (referenceType.isSupertypeOf(aggregateReferenceType) && reference.isForward) { return true; } else if (referenceType.isSupertypeOf(hasSubtypeReferenceType) && !reference.isForward) { return true; } else if (referenceType.isSupertypeOf(hasTypeDefinitionReferenceType) && reference.isForward) { return true; } else if (referenceType.isSupertypeOf(nonHierarchicalReferencesType) && reference.isForward) { return true; } else if (referenceType.isSupertypeOf(organizesReferencesType) && !reference.isForward) { return true; } else if (connectsToReferenceType && referenceType.isSupertypeOf(connectsToReferenceType) && reference.isForward) { return true; } else if (referenceType.isSupertypeOf(hasEventSourceReferenceType) && reference.isForward) { return true; } return false; } const references = node.allReferences().filter(referenceToKeep); for (const reference of references) { if (getReferenceType(reference).browseName.toString() === "HasSubtype" && reference.isForward) { continue; } // only output inverse Reference xw.startElement("Reference"); xw.writeAttribute("ReferenceType", b(xw, getReferenceType(reference).browseName)); if (!reference.isForward) { xw.writeAttribute("IsForward", reference.isForward ? "true" : "false"); } xw.text(n(xw, reference.nodeId)); xw.endElement(); } xw.endElement(); } function _dumpLocalizedText(xw: XmlWriter, v: LocalizedText) { xw.startElement("Locale"); if (v.locale) { xw.text(v.locale); } xw.endElement(); xw.startElement("Text"); if (v.text) { xw.text(v.text); } xw.endElement(); } function _dumpQualifiedName(xw: XmlWriter, v: QualifiedName) { const t = translateBrowseName(xw, v); if (t.name) { xw.startElement("Name"); xw.text(t.name); xw.endElement(); } if (t.namespaceIndex) { xw.startElement("NamespaceIndex"); xw.text(t.namespaceIndex.toString()); xw.endElement(); } } function _dumpXmlElement(xw: XmlWriter, v: string) { xw.text(v); } /* <uax:ExtensionObject> <uax:TypeId> <uax:Identifier>i=339</uax:Identifier> </uax:TypeId> <uax:Body> <BuildInfo xmlns="http://opcfoundation.org/UA/2008/02/Types.xsd"> <ProductUri></ProductUri> <ManufacturerName></ManufacturerName> <ProductName></ProductName> <SoftwareVersion></SoftwareVersion> <BuildNumber></BuildNumber> <BuildDate>1900-01-01T00:00:00Z</BuildDate> </BuildInfo> </uax:Body> </uax:ExtensionObject> */ function _dumpExtensionObject(xw: XmlWriter, v: ExtensionObject) { if (!v) { return; } xw.startElement("TypeId"); _dumpNodeId(xw, v.schema.encodingDefaultXml!); xw.endElement(); xw.startElement("Body"); xw.endElement(); } function _dumpNodeId(xw: XmlWriter, v: NodeId) { xw.startElement("Identifier"); xw.text(v.toString()); xw.endElement(); } // tslint:disable:no-console function _dumpVariantValue(xw: XmlWriter, dataType: DataType, value: any) { if (value === undefined || value === null) { return; } switch (dataType) { case DataType.Null: break; case DataType.LocalizedText: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); _dumpLocalizedText(xw, value as LocalizedText); xw.endElement(); break; case DataType.NodeId: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); _dumpNodeId(xw, value as NodeId); xw.endElement(); break; case DataType.DateTime: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); xw.text(value.toISOString()); xw.endElement(); break; case DataType.Int64: case DataType.UInt64: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); xw.text(value[1].toString()); xw.endElement(); break; case DataType.Boolean: case DataType.SByte: case DataType.Byte: case DataType.Float: case DataType.Double: case DataType.Int16: case DataType.Int32: case DataType.UInt16: case DataType.UInt32: case DataType.String: if (value !== undefined && value !== null) { xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); xw.text(value.toString()); xw.endElement(); } break; case DataType.ByteString: if (value !== undefined && value !== null) { xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); const base64 = value.toString("base64"); xw.text(base64.match(/.{0,80}/g).join("\n")); xw.endElement(); } break; case DataType.Guid: /* <uax:Guid> <uax:String>947c29a7-490d-4dc9-adda-1109e3e8fcb7</uax:String> </uax:Guid> */ if (value !== undefined && value !== null) { xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); xw.startElement("String"); xw.text(value.toString()); xw.endElement(); xw.endElement(); } break; case DataType.ExtensionObject: xw.startElement(DataType[dataType]); _dumpExtensionObject(xw, value as ExtensionObject); xw.endElement(); break; case DataType.QualifiedName: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); _dumpQualifiedName(xw, value as QualifiedName); xw.endElement(); break; case DataType.XmlElement: xw.startElement(DataType[dataType]); // xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); _dumpXmlElement(xw, value as string); xw.endElement(); break; case DataType.StatusCode: default: errorLog("_dumpVariantValue!! incomplete dataType=" + dataType + " - v=" + DataType[dataType] + " value = " + value); /* throw new Error( "_dumpVariantValue!! incomplete dataType=" + dataType + " - v=" + DataType[dataType] + " value = " + value ); */ } } // tslint:disable:no-console function _dumpVariantInnerValue(xw: XmlWriter, dataType: DataType, value: any) { switch (dataType) { case null: case DataType.Null: break; case DataType.LocalizedText: _dumpLocalizedText(xw, value as LocalizedText); break; case DataType.QualifiedName: _dumpQualifiedName(xw, value as QualifiedName); break; case DataType.NodeId: _dumpNodeId(xw, value as NodeId); break; case DataType.DateTime: xw.text(value.toISOString()); break; case DataType.Int64: case DataType.UInt64: xw.text(value[1].toString()); break; case DataType.Boolean: case DataType.Byte: case DataType.Float: case DataType.Double: case DataType.Int16: case DataType.Int32: case DataType.UInt16: case DataType.UInt32: case DataType.String: xw.text(value.toString()); break; case DataType.ByteString: case DataType.StatusCode: default: errorLog("_dumpVariantInnerValue incomplete " + value + " " + "DataType=" + dataType + "=" + DataType[dataType]); // throw new Error("_dumpVariantInnerValue incomplete " + value + " " + "DataType=" + dataType + "=" + DataType[dataType]); } } /** * * @param field */ function findBaseDataType(field: StructuredTypeField): DataType { if (field.fieldType === "UAString") { return DataType.String; } const result = (DataType as any)[field.fieldType] as DataType; if (!result) { throw new Error("cannot find baseDataType of " + field.name + "= " + field.fieldType); } return result; } /** * * @param xw * @param schema * @param value * @private */ function _dumpVariantExtensionObjectValue_Body(xw: XmlWriter, schema: StructuredTypeSchema, value: any) { if (value) { xw.startElement(schema.name); if (value) { for (const field of schema.fields) { const v = value[field.name]; if (v !== null && v !== undefined) { xw.startElement(utils.capitalizeFirstLetter(field.name)); try { const baseType = findBaseDataType(field); _dumpVariantInnerValue(xw, baseType, v); } catch (err) { // eslint-disable-next-line max-depth if (err instanceof Error) { console.log("Error in _dumpVariantExtensionObjectValue_Body !!!", err.message); } console.log(schema.name); console.log(field); // throw err; } xw.endElement(); } } } xw.endElement(); } } /* encode object as XML */ function _dumpVariantExtensionObjectValue(xw: XmlWriter, schema: StructuredTypeSchema, value: any) { xw.startElement("ExtensionObject"); { xw.startElement("TypeId"); { // find HasEncoding node const encodingDefaultXml = (getStructureTypeConstructor(schema.name) as any).encodingDefaultXml; if (!encodingDefaultXml) { console.log("?????"); } // xx var encodingDefaultXml = schema.encodingDefaultXml; xw.startElement("Identifier"); xw.text(encodingDefaultXml.toString()); xw.endElement(); } xw.endElement(); xw.startElement("Body"); _dumpVariantExtensionObjectValue_Body(xw, schema, value); xw.endElement(); } xw.endElement(); } function _isDefaultValue(value: Variant): boolean { // detect default value if (value.arrayType === VariantArrayType.Scalar) { switch (value.dataType) { case DataType.ExtensionObject: if (!value.value) { return true; } break; case DataType.DateTime: if (!value.value || value.value.getTime() === minOPCUADate) { return true; } break; case DataType.ByteString: if (!value.value || value.value.length === 0) { return true; } break; case DataType.Boolean: if (!value.value) { return true; } break; case DataType.SByte: case DataType.Byte: case DataType.UInt16: case DataType.UInt32: case DataType.Int16: case DataType.Int32: case DataType.Double: case DataType.Float: if (value.value === 0 || value.value === null) { return true; } break; case DataType.String: if (value.value === null || value.value === "") { return true; } break; case DataType.Int64: case DataType.UInt64: if (0 === coerceInt64ToInt32(value.value)) { return true; } break; case DataType.LocalizedText: if (!value.value) { return true; } { const l = value.value as LocalizedText; if (!l.locale && !l.text) { return true; } } break; } return false; } else { if (!value.value || value.value.length === 0) { return true; } return false; } } function _dumpValue(xw: XmlWriter, node: UAVariable | UAVariableType, value: Variant) { const addressSpace = node.addressSpace; // istanbul ignore next if (value === null || value === undefined) { return; } assert(value instanceof Variant); const dataTypeNode = addressSpace.findNode(node.dataType); if (!dataTypeNode) { console.log("Cannot find dataType:", node.dataType); return; } const dataTypeName = dataTypeNode.browseName.name!.toString(); const baseDataTypeName = DataType[value.dataType]; if (baseDataTypeName === "Null") { return; } assert(typeof baseDataTypeName === "string"); // determine if dataTypeName is a ExtensionObject const isExtensionObject = value.dataType === DataType.ExtensionObject; if (_isDefaultValue(value)) { return; } xw.startElement("Value"); if (isExtensionObject) { if (hasStructuredType(dataTypeName)) { const schema = getStructuredTypeSchema(dataTypeName); const encodeXml = _dumpVariantExtensionObjectValue.bind(null, xw, schema); if (value.arrayType === VariantArrayType.Array) { xw.startElement("ListOf" + baseDataTypeName); value.value.forEach(encodeXml); xw.endElement(); } else if (value.arrayType === VariantArrayType.Scalar) { encodeXml(value.value); } else { errorLog(node.toString()); errorLog("_dumpValue : unsupported case , Matrix of ExtensionObjects"); // throw new Error("Unsupported case"); } } } else { const encodeXml = _dumpVariantValue.bind(null, xw, value.dataType); if (value.arrayType === VariantArrayType.Matrix) { console.log("Warning _dumpValue : Matrix not supported yet"); xw.startElement("ListOf" + dataTypeName); xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); value.value.forEach(encodeXml); xw.endElement(); } else if (value.arrayType === VariantArrayType.Array) { xw.startElement("ListOf" + dataTypeName); xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2008/02/Types.xsd"); value.value.forEach(encodeXml); xw.endElement(); } else if (value.arrayType === VariantArrayType.Scalar) { encodeXml(value.value); } else { errorLog(node.toString()); errorLog("_dumpValue : unsupported case , Matrix"); // xx throw new Error("Unsupported case"); } } xw.endElement(); } function _dumpArrayDimensionsAttribute(xw: XmlWriter, node: UAVariableType | UAVariable) { if (node.arrayDimensions) { if (node.arrayDimensions.length === 1 && node.arrayDimensions[0] === 0) { return; } xw.writeAttribute("ArrayDimensions", node.arrayDimensions.join(",")); } } function visitUANode(node: BaseNode, options: any, forward: boolean) { assert(typeof forward === "boolean"); const addressSpace = node.addressSpace; options.elements = options.elements || []; options.index_el = options.index_el || {}; // visit references function process_reference(reference: UAReference) { // only backward or forward references if (reference.isForward !== forward) { return; } if (reference.nodeId.namespace === 0) { return; // skip OPCUA namespace } const k = _hash(reference); if (!options.index_el[k]) { options.index_el[k] = 1; const o = addressSpace.findNode(k)! as BaseNode; if (o) { visitUANode(o, options, forward); } } } (node as BaseNodeImpl).ownReferences().forEach(process_reference); options.elements.push(node); return node; } function dumpNodeInXml(xw: XmlWriter, node: BaseNode) { return (node as BaseNodeImpl).dumpXML(xw); } function dumpReferencedNodes(xw: XmlWriter, node: BaseNode, forward: boolean) { const addressSpace = node.addressSpace; if (!forward) { { const r = node.findReferencesEx("HasTypeDefinition"); if (r && r.length) { assert(r.length === 1); const typeDefinitionObj = ReferenceImpl.resolveReferenceNode(addressSpace, r[0])! as BaseNode; if (!typeDefinitionObj) { console.log(node.toString()); console.log("Warning : " + node.browseName.toString() + " unknown typeDefinition, ", r[0].toString()); } else { assert(typeDefinitionObj instanceof BaseNodeImpl); if (typeDefinitionObj.nodeId.namespace === node.nodeId.namespace) { // only output node if it is on the same namespace if (!xw.visitedNode[_hash(typeDefinitionObj)]) { dumpNodeInXml(xw, typeDefinitionObj); } } } } } // { const r = node.findReferencesEx("HasSubtype", BrowseDirection.Inverse); if (r && r.length) { const subTypeOf = ReferenceImpl.resolveReferenceNode(addressSpace, r[0])! as BaseNode; assert(r.length === 1); if (subTypeOf.nodeId.namespace === node.nodeId.namespace) { // only output node if it is on the same namespace if (!xw.visitedNode[_hash(subTypeOf)]) { dumpNodeInXml(xw, subTypeOf); } } } } } else { const r = node.findReferencesEx("Aggregates", BrowseDirection.Forward); for (const reference of r) { const nodeChild = ReferenceImpl.resolveReferenceNode(addressSpace, reference) as BaseNode; assert(nodeChild instanceof BaseNodeImpl); if (nodeChild.nodeId.namespace === node.nodeId.namespace) { if (!xw.visitedNode[_hash(nodeChild)]) { console.log( node.nodeId.toString(), " dumping child ", nodeChild.browseName.toString(), nodeChild.nodeId.toString() ); dumpNodeInXml(xw, nodeChild); } } } } } const currentReadFlag = makeAccessLevelFlag("CurrentRead"); function dumpCommonAttributes(xw: XmlWriter, node: BaseNode) { xw.writeAttribute("NodeId", n(xw, node.nodeId)); xw.writeAttribute("BrowseName", b(xw, node.browseName)); if (Object.prototype.hasOwnProperty.call(node, "symbolicName")) { xw.writeAttribute("SymbolicName", (node as any).symbolicName); } if (Object.prototype.hasOwnProperty.call(node, "isAbstract")) { if ((node as any).isAbstract) { xw.writeAttribute("IsAbstract", (node as any).isAbstract ? "true" : "false"); } } if (Object.prototype.hasOwnProperty.call(node, "accessLevel")) { // CurrentRead is by default if ((node as UAVariable).accessLevel !== currentReadFlag) { xw.writeAttribute("AccessLevel", (node as UAVariable).accessLevel.toString()); } } } function dumpCommonElements(xw: XmlWriter, node: BaseNode) { _dumpDisplayName(xw, node); _dumpDescription(xw, node); _dumpReferences(xw, node); } function coerceInt64ToInt32(int64: Int64): number { if (typeof int64 === "number") { return int64 as number; } if (int64[0] === 4294967295 && int64[1] === 4294967295) { return 0xffffffff; } if (int64[0] !== 0) { debugLog("coerceInt64ToInt32 , loosing high word in conversion"); } return int64[1]; } function _dumpEnumDefinition(xw: XmlWriter, enumDefinition: EnumDefinition) { enumDefinition.fields = enumDefinition.fields || []; for (const defItem of enumDefinition.fields!) { xw.startElement("Field"); xw.writeAttribute("Name", defItem.name as string); if (!utils.isNullOrUndefined(defItem.value)) { xw.writeAttribute("Value", coerceInt64ToInt32(defItem.value)); } if (defItem.description && defItem.description.text) { xw.startElement("Description"); xw.text(defItem.description.text.toString()); xw.endElement(); } xw.endElement(); } } function _dumpStructureDefinition(xw: XmlWriter, structureDefinition: StructureDefinition) { /* * note: baseDataType and defaultEncodingId are implicit and not stored in the XML file ?? * */ const baseDataType = structureDefinition.baseDataType; const defaultEncodingId = structureDefinition.defaultEncodingId; structureDefinition.fields = structureDefinition.fields || []; for (const defItem /*: StructureField*/ of structureDefinition.fields) { xw.startElement("Field"); xw.writeAttribute("Name", defItem.name!); if (defItem.arrayDimensions) { xw.writeAttribute("ArrayDimensions", defItem.arrayDimensions.map((x) => x.toString()).join(",")); } if (defItem.valueRank !== undefined && defItem.valueRank !== -1) { xw.writeAttribute("ValueRank", defItem.valueRank); } if (defItem.isOptional /* && defItem.isOptional !== false */) { xw.writeAttribute("IsOptional", defItem.isOptional.toString()); } if (defItem.maxStringLength !== undefined && defItem.maxStringLength !== 0) { xw.writeAttribute("MaxStringLength", defItem.maxStringLength); } // todo : SymbolicName ( see AutoId ) if (defItem.dataType) { // todo : namespace translation ! xw.writeAttribute("DataType", n(xw, defItem.dataType)); } if (defItem.description && defItem.description.text) { xw.startElement("Description"); xw.text(defItem.description.text.toString()); xw.endElement(); } xw.endElement(); } } function _dumpUADataTypeDefinition(xw: XmlWriter, node: UADataType) { // to do remove DataType from base class const definition = node.getDefinition(); if (!definition) { return; } if (definition instanceof EnumDefinition) { xw.startElement("Definition"); xw.writeAttribute("Name", node.browseName.name!); _dumpEnumDefinition(xw, definition); xw.endElement(); return; } if (definition instanceof StructureDefinition) { xw.startElement("Definition"); xw.writeAttribute("Name", node.browseName.name!); if (definition.structureType === StructureType.Union) { xw.writeAttribute("IsUnion", "true"); } _dumpStructureDefinition(xw, definition); xw.endElement(); return; } // throw new Error("_dumpUADataTypeDefinition: Should not get here !"); } function dumpUADataType(xw: XmlWriter, node: UADataType) { _markAsVisited(xw, node); xw.startElement("UADataType"); xw.writeAttribute("NodeId", n(xw, node.nodeId)); xw.writeAttribute("BrowseName", b(xw, node.browseName)); if (node.symbolicName !== node.browseName.name) { xw.writeAttribute("SymbolicName", node.symbolicName); } if (node.isAbstract) { xw.writeAttribute("IsAbstract", node.isAbstract ? "true" : "false"); } _dumpDisplayName(xw, node); _dumpReferences(xw, node); _dumpUADataTypeDefinition(xw, node); xw.endElement(); dumpAggregates(xw, node); } function _markAsVisited(xw: XmlWriter, node: BaseNode) { xw.visitedNode = xw.visitedNode || {}; assert(!xw.visitedNode[_hash(node)]); xw.visitedNode[_hash(node)] = 1; } function dumpUAVariable(xw: XmlWriter, node: UAVariable) { _markAsVisited(xw, node); dumpReferencedNodes(xw, node, false); const addressSpace = node.addressSpace; xw.startElement("UAVariable"); { // attributes dumpCommonAttributes(xw, node); if (node.valueRank !== -1) { // -1 = Scalar xw.writeAttribute("ValueRank", node.valueRank); } _dumpArrayDimensionsAttribute(xw, node); const dataTypeNode = addressSpace.findNode(node.dataType); if (dataTypeNode) { // verify that data Type is in alias // xx const dataTypeName = dataTypeNode.browseName.toString(); const dataTypeName = b(xw, resolveDataTypeName(addressSpace, dataTypeNode.nodeId)); xw.writeAttribute("DataType", dataTypeName); } } { // sub elements dumpCommonElements(xw, node); _dumpValue(xw, node, node.readValue().value); } xw.endElement(); dumpAggregates(xw, node); } function dumpUAVariableType(xw: XmlWriter, node: UAVariableType) { xw.visitedNode = xw.visitedNode || {}; assert(!xw.visitedNode[_hash(node)]); xw.visitedNode[_hash(node)] = 1; dumpReferencedNodes(xw, node, false); const addressSpace = node.addressSpace; xw.startElement("UAVariableType"); { // attributes dumpCommonAttributes(xw, node); if (node.valueRank !== -1) { xw.writeAttribute("ValueRank", node.valueRank); } const dataTypeNode = addressSpace.findNode(node.dataType); if (!dataTypeNode) { // throw new Error(" cannot find datatype " + node.dataType); console.log( " cannot find datatype " + node.dataType + " for node " + node.browseName.toString() + " id =" + node.nodeId.toString() ); } else { const dataTypeName = b(xw, resolveDataTypeName(addressSpace, dataTypeNode.nodeId)); xw.writeAttribute("DataType", dataTypeName); } } { _dumpArrayDimensionsAttribute(xw, node); // sub elements dumpCommonElements(xw, node); _dumpValue(xw, node, (node as any).value); } xw.endElement(); dumpAggregates(xw, node); } function dumpUAObject(xw: XmlWriter, node: UAObject) { xw.writeComment("Object - " + b(xw, node.browseName) + " {{{{ "); xw.visitedNode = xw.visitedNode || {}; assert(!xw.visitedNode[_hash(node)]); xw.visitedNode[_hash(node)] = 1; // dump SubTypeOf and HasTypeDefinition dumpReferencedNodes(xw, node, false); xw.startElement("UAObject"); dumpCommonAttributes(xw, node); dumpCommonElements(xw, node); xw.endElement(); // dump aggregates nodes ( Properties / components ) dumpAggregates(xw, node); dumpElementInFolder(xw, node as UAObjectImpl); xw.writeComment("Object - " + b(xw, node.browseName) + " }}}} "); } function dumpElementInFolder(xw: XmlWriter, node: BaseNodeImpl) { const aggregates = node .getFolderElements() .sort((x: BaseNode, y: BaseNode) => (x.browseName.name!.toString() > y.browseName.name!.toString() ? 1 : -1)); for (const aggregate of aggregates) { // do not export node that do not belong to our namespace if (node.nodeId.namespace !== aggregate.nodeId.namespace) { return; } if (!xw.visitedNode[_hash(aggregate)]) { aggregate.dumpXML(xw); } } } function dumpAggregates(xw: XmlWriter, node: BaseNode) { // Xx xw.writeComment("Aggregates {{ "); const aggregates = node .getAggregates() .sort((x: BaseNode, y: BaseNode) => (x.browseName.name!.toString() > y.browseName.name!.toString() ? 1 : -1)); for (const aggregate of aggregates) { // do not export node that do not belong to our namespace if (node.nodeId.namespace !== aggregate.nodeId.namespace) { return; } if (!xw.visitedNode[_hash(aggregate)]) { (<BaseNodeImpl>aggregate).dumpXML(xw); } } // Xx xw.writeComment("Aggregates }} "); } function dumpUAObjectType(xw: XmlWriter, node: UAObjectTypeImpl) { assert(node instanceof UAObjectTypeImpl); xw.writeComment("ObjectType - " + b(xw, node.browseName) + " {{{{ "); _markAsVisited(xw, node); // dump SubtypeOf and HasTypeDefinition dumpReferencedNodes(xw, node, false); xw.startElement("UAObjectType"); dumpCommonAttributes(xw, node); dumpCommonElements(xw, node); xw.endElement(); dumpAggregates(xw, node); xw.writeComment("ObjectType - " + b(xw, node.browseName) + " }}}}"); } function dumpUAMethod(xw: XmlWriter, node: UAMethod) { _markAsVisited(xw, node); dumpReferencedNodes(xw, node, false); xw.startElement("UAMethod"); dumpCommonAttributes(xw, node); if (node.methodDeclarationId) { xw.writeAttribute("MethodDeclarationId", n(xw, node.methodDeclarationId)); } dumpCommonElements(xw, node); xw.endElement(); dumpAggregates(xw, node); } function resolveDataTypeName(addressSpace: IAddressSpace, dataType: string | NodeId): QualifiedName { let dataTypeNode = null; // istanbul ignore next if (typeof dataType === "string") { dataTypeNode = addressSpace.findDataType(dataType); } else { assert(dataType instanceof NodeId); const o = addressSpace.findNode(dataType.toString()); dataTypeNode = o ? o : null; } if (!dataTypeNode) { throw new Error("Cannot find dataTypeName " + dataType); } return dataTypeNode.browseName; } function buildUpAliases(node: BaseNode, xw: XmlWriter, options: any) { const addressSpace = node.addressSpace; options.aliases = options.aliases || {}; options.aliases_visited = options.aliases_visited || {}; const k = _hash(node); // istanbul ignore next if (options.aliases_visited[k]) { return; } options.aliases_visited[k] = 1; // put datatype into aliases list if (node.nodeClass === NodeClass.Variable || node.nodeClass === NodeClass.VariableType) { const nodeV = node as UAVariableType | UAVariable; if (nodeV.dataType && nodeV.dataType.namespace === 0 && nodeV.dataType.value !== 0) { // name const dataTypeName = b(xw, resolveDataTypeName(addressSpace, nodeV.dataType)); if (dataTypeName) { if (!options.aliases[dataTypeName]) { options.aliases[dataTypeName] = n(xw, nodeV.dataType); } } } if (nodeV.dataType && nodeV.dataType.namespace !== 0 && nodeV.dataType.value !== 0) { // name const dataTypeName = b(xw, resolveDataTypeName(addressSpace, nodeV.dataType)); if (dataTypeName) { if (!options.aliases[dataTypeName]) { options.aliases[dataTypeName] = n(xw, nodeV.dataType); } } } } function collectReferenceNameInAlias(reference: UAReference) { // reference.referenceType const key = b(xw, getReferenceType(reference).browseName); if (!options.aliases.key) { if (reference.referenceType.namespace === 0) { options.aliases[key] = reference.referenceType.toString().replace("ns=0;", ""); } else { options.aliases[key] = n(xw, reference.referenceType); } } } node.allReferences().forEach(collectReferenceNameInAlias); } function writeAliases(xw: XmlWriter, aliases: any) { xw.startElement("Aliases"); if (aliases) { const keys = Object.keys(aliases).sort(); for (const key of keys) { xw.startElement("Alias"); xw.writeAttribute("Alias", key); xw.text(aliases[key].toString().replace(/ns=0;/, "")); xw.endElement(); } } xw.endElement(); } interface ITranslationTable { [key: number]: number; } function constructNamespaceTranslationTable(dependency: INamespace[]): ITranslationTable { const translationTable: ITranslationTable = {}; for (let i = 0; i < dependency.length; i++) { translationTable[dependency[i].index] = i; } return translationTable; } function dumpReferenceType(xw: XmlWriter, referenceType: UAReferenceType) { _markAsVisited(xw, referenceType); xw.startElement("UAReferenceType"); dumpCommonAttributes(xw, referenceType); dumpCommonElements(xw, referenceType); if (referenceType.inverseName /* LocalizedText*/) { xw.startElement("InverseName"); xw.text(referenceType.inverseName!.text || ""); xw.endElement(); } xw.endElement(); } function sortByBrowseName(x: BaseNode, y: BaseNode): number { const x_str = x.browseName.toString(); const y_str = y.browseName.toString(); if (x_str > y_str) { return -1; } else if (x_str < y_str) { return 1; } return 0; } export function dumpXml(node: BaseNode, options: any): void { const namespace = node.namespace as NamespacePrivate; // make a first visit so that we determine which node to output and in which order const nodesToVisit: any = {}; const dependency = constructNamespaceDependency(namespace); const translationTable = constructNamespaceTranslationTable(dependency); const xw = new XMLWriter(true); xw.translationTable = translationTable; visitUANode(node, nodesToVisit, false); xw.startDocument({ encoding: "utf-8" }); xw.startElement("UANodeSet"); xw.writeAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema-instance"); xw.writeAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); xw.writeAttribute("Version", "1.02"); xw.writeAttribute("LastModified", new Date().toISOString()); xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2011/03/UANodeSet.xsd"); buildUpAliases(node, xw, nodesToVisit); writeAliases(xw, nodesToVisit.aliases); for (const el of nodesToVisit.elements) { el.dumpXML(xw); } xw.endElement(); xw.endDocument(); return xw.toString(); } UAMethodImpl.prototype.dumpXML = function (xw) { dumpUAMethod(xw, this); }; UAObjectImpl.prototype.dumpXML = function (xw) { dumpUAObject(xw, this); }; UAVariableImpl.prototype.dumpXML = function (xw: XmlWriter) { dumpUAVariable(xw, this); }; UAVariableTypeImpl.prototype.dumpXML = function (xw) { dumpUAVariableType(xw, this); }; UAReferenceTypeImpl.prototype.dumpXML = function (xw: XmlWriter) { dumpReferenceType(xw, this); }; UAObjectTypeImpl.prototype.dumpXML = function (xw) { dumpUAObjectType(xw, this); }; UADataTypeImpl.prototype.dumpXML = function (xw: XmlWriter) { dumpUADataType(xw, this); }; UANamespace.prototype.toNodeset2XML = function (this: UANamespace) { const dependency = constructNamespaceDependency(this); const translationTable = constructNamespaceTranslationTable(dependency); const xw = new XMLWriter(true); xw.translationTable = translationTable; xw.startDocument({ encoding: "utf-8", version: "1.0" }); xw.startElement("UANodeSet"); xw.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xw.writeAttribute("xmlns:uax", "http://opcfoundation.org/UA/2008/02/Types.xsd"); xw.writeAttribute("xmlns", "http://opcfoundation.org/UA/2011/03/UANodeSet.xsd"); // xx xw.writeAttribute("Version", "1.02"); // xx xw.writeAttribute("LastModified", (new Date()).toISOString()); // ------------- INamespace Uris xw.startElement("NamespaceUris"); // xx const namespaceArray = namespace.addressSpace.getNamespaceArray(); for (const depend of dependency) { if (depend.index === 0) { continue; // ignore namespace 0 } xw.startElement("Uri"); xw.text(depend.namespaceUri); xw.endElement(); } xw.endElement(); // ------------- INamespace Uris xw.startElement("Models"); xw.endElement(); const s: any = {}; for (const node of this.nodeIterator()) { buildUpAliases(node, xw, s); } writeAliases(xw, s.aliases); xw.visitedNode = {}; // -------------- writeReferences xw.writeComment("ReferenceTypes"); const referenceTypes = [...this._referenceTypeIterator()].sort(sortByBrowseName); for (const referenceType of referenceTypes) { dumpReferenceType(xw, referenceType); } // -------------- Dictionaries const addressSpace = this.addressSpace; const opcBinaryTypeSystem = addressSpace.findNode("OPCBinarySchema_TypeSystem") as UAObject; if (opcBinaryTypeSystem) { // let find all DataType dictionary node corresponding to a given namespace // (have DataTypeDictionaryType) const nodeToBrowse = new BrowseDescription({ browseDirection: BrowseDirection.Forward, includeSubtypes: false, nodeClassMask: makeNodeClassMask("Variable"), nodeId: opcBinaryTypeSystem.nodeId, referenceTypeId: resolveNodeId("HasComponent"), resultMask: makeResultMask("ReferenceType | IsForward | BrowseName | NodeClass | TypeDefinition") }); const result = opcBinaryTypeSystem.browseNode(nodeToBrowse).filter((r) => r.nodeId.namespace === this.index); assert(result.length <= 1); if (result.length === 1) { xw.writeComment("DataSystem"); const dataSystemType = addressSpace.findNode(result[0].nodeId)! as UAVariable; dumpNodeInXml(xw, dataSystemType); } } // -------------- DataTypes const dataTypes = [...this._dataTypeIterator()].sort(sortByBrowseName); if (dataTypes.length) { xw.writeComment("DataTypes"); // xx xw.writeComment(" "+ objectTypes.map(x=>x.browseName.name.toString()).join(" ")); for (const dataType of dataTypes) { if (!xw.visitedNode[_hash(dataType)]) { dumpNodeInXml(xw, dataType); } } } // -------------- ObjectTypes xw.writeComment("ObjectTypes"); const objectTypes = [...this._objectTypeIterator()].sort(sortByBrowseName); // xx xw.writeComment(" "+ objectTypes.map(x=>x.browseName.name.toString()).join(" ")); for (const objectType of objectTypes) { if (!xw.visitedNode[_hash(objectType)]) { dumpNodeInXml(xw, objectType); } } // -------------- VariableTypes xw.writeComment("VariableTypes"); const variableTypes = [...this._variableTypeIterator()].sort(sortByBrowseName); // xx xw.writeComment("ObjectTypes "+ variableTypes.map(x=>x.browseName.name.toString()).join(" ")); for (const variableType of variableTypes) { if (!xw.visitedNode[_hash(variableType)]) { dumpNodeInXml(xw, variableType); } } // -------------- Any thing else xw.writeComment("Other Nodes"); const nodes = [...this.nodeIterator()].sort(sortByBrowseName); for (const node of nodes) { if (!xw.visitedNode[_hash(node)]) { dumpNodeInXml(xw, node); } } xw.endElement(); xw.endDocument(); return xw.toString(); };
the_stack
import { Player } from "./Player"; import WebSocket from "ws"; /** * The Lavalink Event * */ export interface LavalinkEvent { /** * The type of event from lavalink */ type: "TrackStartEvent" | "TrackEndEvent" | "TrackExceptionEvent" | "TrackStuckEvent" | "WebSocketClosedEvent"; /** * Why the event was sent, only used for TrackEndEvent */ reason?: "FINISHED" | "LOAD_FAILED" | "STOPPED" | "REPLACED" | "CLEANUP"; /** * The buffer threshold in milliseconds */ thresholdMs?: number; /** * the error for TrackExceptionEvent */ error?: string; } /** * Lavalink Player State */ export interface LavalinkPlayerState { /** * The current time in milliseconds */ time?: number; /** * The position of where the song is at in milliseconds */ position?: number; } /** * Player State */ export interface PlayerState extends LavalinkPlayerState { /** * The current volume of the Player, used for end user as lavalink doesn't provide this */ volume: number; /** * The current equalizer state of the Player, so end users can keep track if they need to */ equalizer: PlayerEqualizerBand[]; } /** * Player Play Options */ export interface PlayerPlayOptions { /** * Where to start the song fromm if you wanted to start from somewhere */ startTime?: number; /** * Where to end the song if you wanted to end the song early */ endTime?: number; /** * Whether to replace what is currently playing, aka skip the current song */ noReplace?: boolean; /** * Whether to pause it at the start */ pause?: boolean; /** * The volume to start playing at */ volume?: number; } /** * Player Equalizer Band */ export interface PlayerEqualizerBand { /** * There are 15 bands (0-14) that can be changed */ band: number; /** * Gain is the multiplier for the given band. The default value is 0. Valid values range from -0.25 to 1.0, where -0.25 means the given band is completely muted, and 0.25 means it is doubled. Modifying the gain could also change the volume of the output */ gain: number; } /** * Player Update Voice State */ export interface PlayerUpdateVoiceState { /** * The session id of the voice connection */ sessionId: string; /** * Event data */ event: { /** * The token for the voice session */ token: string; /** * The guild if of the voice connection */ guild_id: string; /** * The endpoint for lavalink to connect to, e.g us-west, sydney etc */ endpoint: string; }; } /** * Manager Options */ export interface ManagerOptions { /** * User id of the bot */ user?: string; /** * The amount of shards the bot is currently operating on, by default this is `1` */ shards?: number; /** * The Player class that the manager uses to create Players, so users can modify this */ player?: typeof Player; /** * The send function for end users to implement for their specific library */ send?: (packet: DiscordPacket) => unknown; } /** * Manager Join Data */ export interface JoinData { /** * The guild id of the guild the voice channel is in, that you want to join */ guild: string; /** * The voice channel you want to join */ channel: string; /** * The LavalinkNode ID you want to use */ node: string; } /** * Manager Join Options */ export interface JoinOptions { /** * Whether or not the bot will be self muted when it joins the voice channel */ selfmute?: boolean; /** * Whether or not the bot will be self deafen when it joins the voice channel */ selfdeaf?: boolean; } /** * Voice Server Update */ export interface VoiceServerUpdate { /** * The token for the session */ token: string; /** * Guild if of the voice connection */ guild_id: string; /** * The endpoint lavalink will connect to */ endpoint: string; } /** * Voice State Update */ export interface VoiceStateUpdate { /** * Guild id */ guild_id: string; /** * channel id */ channel_id?: string; /** * User id */ user_id: string; /** * Session id */ session_id: string; /** * Whether the user is deafened or not */ deaf?: boolean; /** * Whether the user is muted or not */ mute?: boolean; /** * Whether the user is self-deafened or not */ self_deaf?: boolean; /** * Whether the user is self-muted or not */ self_mute?: boolean; /** * Whether the user is suppressed */ suppress?: boolean; } /** * Discord Packet */ export interface DiscordPacket { /** * opcode for the payload */ op: number; /** * event data */ d: any; /** * sequence number, used for resuming sessions and heartbeats */ s?: number; /** * the event name for this payload */ t?: string; } /** * Lavalink Node Options */ export interface LavalinkNodeOptions { /** * The id of the LavalinkNode so Nodes are better organized */ id: string; /** * The host of the LavalinkNode, this could be a ip or domain. */ host: string; /** * The port of the LavalinkNode */ port?: number | string; /** * The password of the lavalink node */ password?: string; /** * The interval that the node will try to reconnect to lavalink at in milliseconds */ reconnectInterval?: number; /** * The resume key to send to the LavalinkNode so you can resume properly */ resumeKey?: string; /** * Resume timeout */ resumeTimeout?: number; /** * Extra info attached to your node, not required and is not sent to lavalink, purely for you. */ state?: any; } /** * Lavalink Statistics */ export interface LavalinkStats { /** * The amount of players the node is handling */ players: number; /** * The amount of players that are playing something */ playingPlayers: number; /** * How long the LavalinkNode has been up for in milliseconds */ uptime: number; /** * memory information */ memory: { /** * The amount of memory that is free */ free: number; /** * the amount of memory that is used */ used: number; /** * The amount of allocated memory */ allocated: number; /** * The amount of reservable memory */ reservable: number; }; /** * CPU Data */ cpu: { /** * The amount of cores the server has where lavalink is hosted */ cores: number; /** * System load of the server lavalink is on */ systemLoad: number; /** * The amount of load that lavalink is using */ lavalinkLoad: number; }; /** * Frame statistics */ frameStats?: { /** * The amount of frames sent */ sent?: number; /** * The amount of frames nullified */ nulled?: number; /** * The amount of deficit frames */ deficit?: number; }; } /** * Queue Data */ export interface QueueData { /** * The data to actually send from the queue */ data: string; /** * The resolve function for the promise */ resolve: (value?: boolean | PromiseLike<boolean> | undefined) => void; /** * The reject function for the promise */ reject: (reason?: any) => void; } /** * Websocket Close Event */ export interface WebsocketCloseEvent { /** * If the close was clean or not */ wasClean: boolean; /** * The code that was sent for the close */ code: number; /** * The reason of the closure */ reason: string; /** * The target */ target: WebSocket; } /** * Track Response */ export interface TrackResponse { /** * Load Type */ loadType: LoadType; /** * Playlist Info */ playlistInfo: PlaylistInfo; /** * All the Tracks in an array */ tracks: TrackData[]; } /** * LoadType ENUM */ export enum LoadType { TRACK_LOADED = "TRACK_LOADED", PLAYLIST_LOADED = "PLAYLIST_LOADED", SEARCH_RESULT = "SEARCH_RESULT", NO_MATCHES = "NO_MATCHES", LOAD_FAILED = "LOAD_FAILED" } /** * Playlist Info */ export interface PlaylistInfo { /** * Playlist Name */ name?: string; /** * Selected track from playlist */ selectedTrack?: number; } /** * Lavalink Track */ export interface TrackData { /** * The track base64 string */ track: string; /** * All the meta data on the track */ info: { /** * The id of the track, depends on the source */ identifier: string; /** * Whether you can use seek with this track */ isSeekable: boolean; /** * The author of the track */ author: string; /** * The length of the track */ length: number; /** * Whether or not the track is a stream */ isStream: boolean; /** * The position of the song */ position: number; /** * The title of the track */ title: string; /** * The URI of the track */ uri: string; }; } /** * The 3 types of Route Planner Statuses */ export type RoutePlannerStatus = RotatingIpRoutePlanner | NanoIpRoutePlanner | RotatingIpRoutePlanner; /** * Base Route Planner Status Data */ export interface BaseRoutePlannerStatusData { /** * The IP Block */ ipBlock: { /** * The IP block type */ type: string; /** * IP Block size */ size: string; }; /** * Failing Addresses */ failingAddresses: { /** * The address */ address: string; /** * Failing Timestamp */ failingTimestamp: number; /** * Failing Time */ failingTime: string; }[]; } /** * Rotating Ip Route Planner */ export interface RotatingIpRoutePlanner { /** * Class name */ class: "RotatingIpRoutePlanner"; /** * Details */ details: BaseRoutePlannerStatusData & { /** * Rotate index */ rotateIndex: string; /** * Ip index */ ipIndex: string; /** * The current address */ currentAddress: string; }; } /** * Nano IP Route Planner */ export interface NanoIpRoutePlanner { /** * Class name */ class: "NanoIpRoutePlanner"; /** * Details */ details: BaseRoutePlannerStatusData & { /** * Current Address Index */ currentAddressIndex: number; }; } /** * Rotating Nano IP Route Planner */ export interface RotatingNanoIpRoutePlanner { /** * Class name */ class: "RotatingNanoIpRoutePlanner"; /** Details */ details: BaseRoutePlannerStatusData & { /** * Block Index */ blockIndex: string; /** * Current Address Index */ currentAddressIndex: number; }; }
the_stack
import type { Box, Connection, CoordinateExtent, DefaultEdgeOptions, Dimensions, Edge, EdgeMarkerType, Elements, FlowElement, Getters, GraphEdge, GraphNode, Node, Rect, Viewport, XYPosition, XYZPosition, } from '~/types' import { useWindow } from '~/composables' const isHTMLElement = (el: EventTarget): el is HTMLElement => ('nodeName' || 'hasAttribute') in el export const isInputDOMNode = (e: KeyboardEvent | MouseEvent): boolean => { const target = e.target if (target && isHTMLElement(target)) { return ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON'].includes(target.nodeName) || target.hasAttribute('contentEditable') } return false } export const getDimensions = (node: HTMLElement): Dimensions => ({ width: node.offsetWidth, height: node.offsetHeight, }) export const clamp = (val: number, min = 0, max = 1): number => Math.min(Math.max(val, min), max) export const clampPosition = (position: XYPosition, extent: CoordinateExtent): XYPosition => ({ x: clamp(position.x, extent[0][0], extent[1][0]), y: clamp(position.y, extent[0][1], extent[1][1]), }) export const getHostForElement = (element: HTMLElement): Document => { const doc = element.getRootNode() as Document const window = useWindow() if ('getElementFromPoint' in doc) return doc else return window.document } type MaybeElement = Node | Edge | Connection | FlowElement export const isEdge = (element: MaybeElement): element is Edge => 'id' in element && 'source' in element && 'target' in element export const isGraphEdge = (element: MaybeElement): element is GraphEdge => isEdge(element) && 'sourceNode' in element && 'targetNode' in element export const isNode = (element: MaybeElement): element is Node => 'id' in element && !isEdge(element) export const isGraphNode = (element: MaybeElement): element is GraphNode => isNode(element) && 'computedPosition' in element export const parseNode = (node: Node, nodeExtent: CoordinateExtent, defaults?: Partial<GraphNode>): GraphNode => { let defaultValues = defaults if (!isGraphNode(node)) { defaultValues = { type: node.type ?? 'default', dimensions: markRaw({ width: 0, height: 0, }), handleBounds: { source: [], target: [], }, computedPosition: markRaw({ z: 0, ...node.position, }), draggable: undefined, selectable: undefined, connectable: undefined, ...defaults, } } return { ...defaultValues, ...(node as GraphNode), id: node.id.toString(), } } export const parseEdge = (edge: Edge, defaults?: Partial<GraphEdge>): GraphEdge => { defaults = !isGraphEdge(edge) ? ({ sourceHandle: edge.sourceHandle ? edge.sourceHandle.toString() : undefined, targetHandle: edge.targetHandle ? edge.targetHandle.toString() : undefined, type: edge.type, source: edge.source.toString(), target: edge.target.toString(), z: 0, sourceX: 0, sourceY: 0, targetX: 0, targetY: 0, updatable: edge.updatable, selectable: edge.selectable, data: edge.data, ...defaults, } as GraphEdge) : defaults return Object.assign({ id: edge.id.toString() }, edge, defaults) as GraphEdge } const getConnectedElements = (node: GraphNode, elements: Elements, dir: 'source' | 'target') => { if (!isNode(node)) return [] const ids = elements.filter((e) => isEdge(e) && e.source === node.id).map((e) => isEdge(e) && e[dir]) return elements.filter((e) => ids.includes(e.id)) } export const getOutgoers = (node: GraphNode, elements: Elements) => getConnectedElements(node, elements, 'target') export const getIncomers = (node: GraphNode, elements: Elements) => getConnectedElements(node, elements, 'source') export const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection) => `vueflow__edge-${source}${sourceHandle ?? ''}-${target}${targetHandle ?? ''}` export const connectionExists = (edge: Edge | Connection, elements: Elements) => elements.some( (el) => isEdge(el) && el.source === edge.source && el.target === edge.target && (el.sourceHandle === edge.sourceHandle || (!el.sourceHandle && !edge.sourceHandle)) && (el.targetHandle === edge.targetHandle || (!el.targetHandle && !edge.targetHandle)), ) /** * Intended for options API * In composition API you can access utilities from `useVueFlow` */ export const addEdge = (edgeParams: Edge | Connection, elements: Elements, defaults?: DefaultEdgeOptions) => { if (!edgeParams.source || !edgeParams.target) { console.warn("[vueflow]: Can't create edge. An edge needs a source and a target.") return elements } let edge if (isEdge(edgeParams)) { edge = { ...edgeParams } } else { edge = { ...edgeParams, id: getEdgeId(edgeParams), } as Edge } edge = parseEdge(edge, defaults) if (connectionExists(edge, elements)) return elements elements.push(edge) return [...elements, edge] } /** * Intended for options API * In composition API you can access utilities from `useVueFlow` */ export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: Elements) => { if (!newConnection.source || !newConnection.target) { console.warn("[vueflow]: Can't create new edge. An edge needs a source and a target.") return elements } const foundEdge = elements.find((e) => isEdge(e) && e.id === oldEdge.id) if (!foundEdge) { console.warn(`[vueflow]: The old edge with id=${oldEdge.id} does not exist.`) return elements } // Remove old edge and create the new edge with parameters of old edge. const edge: Edge = { ...oldEdge, id: getEdgeId(newConnection), source: newConnection.source, target: newConnection.target, sourceHandle: newConnection.sourceHandle, targetHandle: newConnection.targetHandle, } elements.splice(elements.indexOf(foundEdge), 1, edge) return elements.filter((e) => e.id !== oldEdge.id) } export const pointToRendererPoint = ( { x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: Viewport, snapToGrid: boolean, [snapX, snapY]: [number, number], ) => { const position: XYPosition = { x: (x - tx) / tScale, y: (y - ty) / tScale, } if (snapToGrid) { return { x: snapX * Math.round(position.x / snapX), y: snapY * Math.round(position.y / snapY), } } return position } const getBoundsOfBoxes = (box1: Box, box2: Box): Box => ({ x: Math.min(box1.x, box2.x), y: Math.min(box1.y, box2.y), x2: Math.max(box1.x2, box2.x2), y2: Math.max(box1.y2, box2.y2), }) export const rectToBox = ({ x, y, width, height }: Rect): Box => ({ x, y, x2: x + width, y2: y + height, }) export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({ x, y, width: x2 - x, height: y2 - y, }) export const getBoundsofRects = (rect1: Rect, rect2: Rect) => boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2))) export const getRectOfNodes = (nodes: GraphNode[]) => { const box = nodes.reduce( (currBox, { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = {} as any) => getBoundsOfBoxes( currBox, rectToBox({ ...computedPosition, ...dimensions, } as Rect), ), { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }, ) return boxToRect(box) } export const graphPosToZoomedPos = ({ x, y }: XYPosition, { x: tx, y: ty, zoom: tScale }: Viewport): XYPosition => ({ x: x * tScale + tx, y: y * tScale + ty, }) export const getNodesInside = ( nodes: GraphNode[], rect: Rect, { x: tx, y: ty, zoom: tScale }: Viewport = { x: 0, y: 0, zoom: 1 }, partially = false, ) => { const rBox = rectToBox({ x: (rect.x - tx) / tScale, y: (rect.y - ty) / tScale, width: rect.width / tScale, height: rect.height / tScale, }) return nodes.filter((node) => { if (!node || node.selectable === false) return false const { computedPosition = { x: 0, y: 0 }, dimensions = { width: 0, height: 0 } } = node const nBox = rectToBox({ ...computedPosition, ...dimensions }) const xOverlap = Math.max(0, Math.min(rBox.x2, nBox.x2) - Math.max(rBox.x, nBox.x)) const yOverlap = Math.max(0, Math.min(rBox.y2, nBox.y2) - Math.max(rBox.y, nBox.y)) const overlappingArea = Math.ceil(xOverlap * yOverlap) const notInitialized = typeof dimensions.width === 'undefined' || typeof dimensions.height === 'undefined' || dimensions.width === 0 || dimensions.height === 0 const partiallyVisible = partially && overlappingArea > 0 const area = dimensions.width * dimensions.height return notInitialized || partiallyVisible || overlappingArea >= area }) } export const getConnectedEdges = (nodes: GraphNode[], edges: GraphEdge[]) => { const nodeIds = nodes.map((node) => node.id) return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target)) } export const getTransformForBounds = ( bounds: Rect, width: number, height: number, minZoom: number, maxZoom: number, padding = 0.1, offset: { x?: number y?: number } = { x: 0, y: 0 }, ): Viewport => { const xZoom = width / (bounds.width * (1 + padding)) const yZoom = height / (bounds.height * (1 + padding)) const zoom = Math.min(xZoom, yZoom) const clampedZoom = clamp(zoom, minZoom, maxZoom) const boundsCenterX = bounds.x + bounds.width / 2 const boundsCenterY = bounds.y + bounds.height / 2 const x = width / 2 - boundsCenterX * clampedZoom + (offset.x ?? 0) const y = height / 2 - boundsCenterY * clampedZoom + (offset.y ?? 0) return { x, y, zoom: clampedZoom } } export const getXYZPos = (parentPos: XYZPosition, computedPosition: XYZPosition): XYZPosition => { return { x: computedPosition.x + parentPos.x, y: computedPosition.y + parentPos.y, z: parentPos.z > computedPosition.z ? parentPos.z : computedPosition.z, } } export const isParentSelected = (node: GraphNode, getNode: Getters['getNode']): boolean => { if (!node.parentNode) return false const parent = getNode(node.parentNode) if (!parent) return false if (parent.selected) return true return isParentSelected(parent, getNode) } export const getMarkerId = (marker: EdgeMarkerType | undefined): string => { if (typeof marker === 'undefined') return '' if (typeof marker === 'string') return marker return Object.keys(marker) .sort() .map((key) => `${key}=${marker[<keyof EdgeMarkerType>key]}`) .join('&') }
the_stack
import {BoundingBox, LineXY, PointXY} from "@jsplumb/util" export type Curve = Array<PointXY> export type PointOnPath = { point:PointXY, location:number } export type DistanceFromCurve = { location:number, distance:number } export type AxisCoefficients = [ number, number, number, number ] type CubicRoots = [ number, number, number] /** * @internal */ const Vectors = { subtract : (v1:PointXY, v2:PointXY):PointXY => { return {x:v1.x - v2.x, y:v1.y - v2.y }; }, dotProduct: (v1:PointXY, v2:PointXY):number => { return (v1.x * v2.x) + (v1.y * v2.y); }, square:(v:PointXY):number => { return Math.sqrt((v.x * v.x) + (v.y * v.y)); }, scale:(v:PointXY, s:number) => { return {x:v.x * s, y:v.y * s }; } } const maxRecursion = 64 const flatnessTolerance = Math.pow(2.0,-maxRecursion-1) /** * Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier, * so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values * of the curve and the point - it will most likely be pixels. * * @param point - a point in the form {x:567, y:3342} * @param curve - a Bezier curve: an Array of PointXY objects. Note that this is currently * hardcoded to assume cubix beziers, but would be better off supporting any degree. * @returns a JS object literal containing location and distance. Location is analogous to the location * argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from * the point to the curve. * @public */ export function distanceFromCurve (point:PointXY, curve:Curve):DistanceFromCurve { let candidates:Array<any> = [], w = _convertToBezier(point, curve), degree = curve.length - 1, higherDegree = (2 * degree) - 1, numSolutions = _findRoots(w, higherDegree, candidates, 0), v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0, newDist for (let i = 0; i < numSolutions; i++) { v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null)) newDist = Vectors.square(v) if (newDist < dist) { dist = newDist t = candidates[i] } } v = Vectors.subtract(point, curve[degree]) newDist = Vectors.square(v) if (newDist < dist) { dist = newDist t = 1.0 } return {location:t, distance:dist} } /** * Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the * point's coordinates and also the 'location' of the point (see above). * @public */ export function nearestPointOnCurve(point:PointXY, curve:Curve):{point:PointXY, location:number} { const td = distanceFromCurve(point, curve) return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location} } /** * @internal * @param point * @param curve */ function _convertToBezier (point:PointXY, curve:Curve):any { let degree = curve.length - 1, higherDegree = (2 * degree) - 1, c = [], d = [], cdTable:Array<Array<any>> = [], w:Array<any> = [], z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ] for (let i = 0; i <= degree; i++) { c[i] = Vectors.subtract(curve[i], point) } for (let i = 0; i <= degree - 1; i++) { d[i] = Vectors.subtract(curve[i+1], curve[i]) d[i] = Vectors.scale(d[i], 3.0) } for (let row = 0; row <= degree - 1; row++) { for (let column = 0; column <= degree; column++) { if (!cdTable[row]) cdTable[row] = [] cdTable[row][column] = Vectors.dotProduct(d[row], c[column]) } } for (let i = 0; i <= higherDegree; i++) { if (!w[i]) { w[i] = [] } w[i].y = 0.0 w[i].x = parseFloat("" + i) / higherDegree } let n = degree, m = degree-1 for (let k = 0; k <= n + m; k++) { const lb = Math.max(0, k - m), ub = Math.min(k, n) for (let i = lb; i <= ub; i++) { const j = k - i w[i+j].y += cdTable[j][i] * z[j][i] } } return w } /** * counts how many roots there are. */ function _findRoots (w:any, degree:number, t:any, depth:number):any { let left:Array<any> = [], right:Array<any> = [], left_count, right_count, left_t:Array<any> = [], right_t:Array<any> = [] switch (_getCrossingCount(w, degree)) { case 0 : { return 0 } case 1 : { if (depth >= maxRecursion) { t[0] = (w[0].x + w[degree].x) / 2.0 return 1 } if (_isFlatEnough(w, degree)) { t[0] = _computeXIntercept(w, degree) return 1 } break } } _bezier(w, degree, 0.5, left, right) left_count = _findRoots(left, degree, left_t, depth+1) right_count = _findRoots(right, degree, right_t, depth+1) for (let i = 0; i < left_count; i++) { t[i] = left_t[i] } for (let i = 0; i < right_count; i++) { t[i+left_count] = right_t[i] } return (left_count+right_count) } function _getCrossingCount (curve:Curve, degree:number):number { let n_crossings = 0, sign, old_sign sign = old_sign = sgn(curve[0].y) for (let i = 1; i <= degree; i++) { sign = sgn(curve[i].y) if (sign != old_sign) n_crossings++ old_sign = sign } return n_crossings } function _isFlatEnough (curve:Curve, degree:number):1|0 { let error, intercept_1, intercept_2, left_intercept, right_intercept, a, b, c, det, dInv, a1, b1, c1, a2, b2, c2 a = curve[0].y - curve[degree].y b = curve[degree].x - curve[0].x c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y let max_distance_above, max_distance_below max_distance_above = max_distance_below = 0.0 for (let i = 1; i < degree; i++) { let value = a * curve[i].x + b * curve[i].y + c if (value > max_distance_above) { max_distance_above = value } else if (value < max_distance_below) { max_distance_below = value } } a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b c2 = c - max_distance_above det = a1 * b2 - a2 * b1 dInv = 1.0/det intercept_1 = (b1 * c2 - b2 * c1) * dInv a2 = a; b2 = b; c2 = c - max_distance_below det = a1 * b2 - a2 * b1 dInv = 1.0/det intercept_2 = (b1 * c2 - b2 * c1) * dInv left_intercept = Math.min(intercept_1, intercept_2) right_intercept = Math.max(intercept_1, intercept_2) error = right_intercept - left_intercept return (error < flatnessTolerance)? 1 : 0 } function _computeXIntercept (curve:Curve, degree:number):number { let XLK = 1.0, YLK = 0.0, XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y, XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0, det = XNM*YLK - YNM*XLK, detInv = 1.0/det, S = (XNM*YMK - YNM*XMK) * detInv return 0.0 + XLK * S } function _bezier (curve:Curve, degree:number, t:any, left:any, right:any):any { let temp:Array<any> = [[]] for (let j =0; j <= degree; j++) { temp[0][j] = curve[j] } for (let i = 1; i <= degree; i++) { for (let j =0 ; j <= degree - i; j++) { if (!temp[i]) temp[i] = [] if (!temp[i][j]) temp[i][j] = {} temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y } } if (left != null) { for (let j = 0; j <= degree; j++) { left[j] = temp[j][0] } } if (right != null) { for (let j = 0; j <= degree; j++) { right[j] = temp[degree - j][j] } } return (temp[degree][0]) } function _getLUT(steps:number, curve:Curve): Array<PointXY> { const out: Array<PointXY> = [] steps-- for (let n = 0; n <= steps; n++) { out.push(_computeLookup(n / steps, curve)) } return out } function _computeLookup(e:number, curve:Curve):PointXY { const EMPTY_POINT:PointXY = {x:0, y:0} if (e === 0) { return curve[0] } let degree = curve.length - 1 if (e === 1) { return curve[degree] } let o = curve let s = 1 - e if (degree === 0) { return curve[0] } if (degree === 1) { return { x: s * o[0].x + e * o[1].x, y: s * o[0].y + e * o[1].y } } if (4 > degree) { let l = s * s, h = e * e, u = 0, m, g, f if (degree === 2) { o = [o[0], o[1], o[2], EMPTY_POINT] m = l g = 2 * (s * e) f = h } else if (degree === 3) { m = l * s g = 3 * (l * e) f = 3 * (s * h) u = e * h } return { x: m * o[0].x + g * o[1].x + f * o[2].x + u * o[3].x, y: m * o[0].y + g * o[1].y + f * o[2].y + u * o[3].y } } else { return EMPTY_POINT; // not supported. } } export function computeBezierLength(curve:Curve):number { let length = 0 if (!isPoint(curve)) { const steps = 16 const lut = _getLUT(steps, curve) for (let i = 0; i < steps - 1; i++) { let a = lut[i], b = lut[i + 1] length += dist(a, b) } } return length } const _curveFunctionCache:Map<number, Array<TermFunc>> = new Map() type TermFunc = (t:number) => number function _getCurveFunctions (order:number):Array<TermFunc> { let fns:Array<TermFunc> = _curveFunctionCache.get(order) if (!fns) { fns = [] const f_term = ():TermFunc => { return (t:number) => { return Math.pow(t, order); }; }, l_term = ():TermFunc => { return (t:number) => { return Math.pow((1-t), order); }; }, c_term = (c:number):TermFunc => { return (t:number) => { return c; }; }, t_term = ():TermFunc => { return (t:number) => { return t; }; }, one_minus_t_term = ():TermFunc => { return (t:number) => { return 1-t; }; }, _termFunc = (terms:any):TermFunc => { return (t:number) => { let p = 1 for (let i = 0; i < terms.length; i++) { p = p * terms[i](t) } return p } } fns.push(f_term()); // first is t to the power of the curve order for (let i = 1; i < order; i++) { let terms = [c_term(order)] for (let j = 0 ; j < (order - i); j++) terms.push(t_term()) for (let j = 0 ; j < i; j++) terms.push(one_minus_t_term()) fns.push(_termFunc(terms)) } fns.push(l_term()); // last is (1-t) to the power of the curve order _curveFunctionCache.set(order, fns) } return fns } /** * calculates a point on the curve, for a Bezier of arbitrary order. * @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points. * @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive. */ export function pointOnCurve (curve:Curve, location:number):PointXY { let cc = _getCurveFunctions(curve.length - 1), _x = 0, _y = 0 for (let i = 0; i < curve.length ; i++) { _x = _x + (curve[i].x * cc[i](location)) _y = _y + (curve[i].y * cc[i](location)) } return {x:_x, y:_y} } export function dist (p1:PointXY,p2:PointXY):number { return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)) } export function isPoint (curve:Curve):boolean { return curve[0].x === curve[1].x && curve[0].y === curve[1].y } /** * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also * its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the * point. * * TODO The compute length functionality was made much faster recently, using a lookup table. is it possible to use that lookup table find * a value for the point some distance along the curve from somewhere? */ export function pointAlongPath (curve:Curve, location:number, distance:number):PointOnPath { if (isPoint(curve)) { return { point:curve[0], location:location } } let prev = pointOnCurve(curve, location), tally = 0, curLoc = location, direction = distance > 0 ? 1 : -1, cur = null while (tally < Math.abs(distance)) { curLoc += (0.005 * direction) cur = pointOnCurve(curve, curLoc) tally += dist(cur, prev) prev = cur } return {point:cur, location:curLoc} } /** * finds the point that is 'distance' along the path from 'location'. * @publix */ export function pointAlongCurveFrom (curve:Curve, location:number, distance:number):PointXY { return pointAlongPath(curve, location, distance).point } /** * finds the location that is 'distance' along the path from 'location'. * @public */ export function locationAlongCurveFrom (curve:Curve, location:number, distance:number):number { return pointAlongPath(curve, location, distance).location } /** * Calculates the gradient at the point on the given curve at the given location * @returns a decimal between 0 and 1 inclusive. * @public */ export function gradientAtPoint (curve:Curve, location:number):number { let p1 = pointOnCurve(curve, location), p2 = pointOnCurve(curve.slice(0, curve.length - 1), location), dy = p2.y - p1.y, dx = p2.x - p1.x return dy === 0 ? Infinity : Math.atan(dy / dx) } /** * Returns the gradient of the curve at the point which is 'distance' from the given location. * if this point is greater than location 1, the gradient at location 1 is returned. * if this point is less than location 0, the gradient at location 0 is returned. * @returns a decimal between 0 and 1 inclusive. * @public */ export function gradientAtPointAlongPathFrom (curve:Curve, location:number, distance:number):number { const p = pointAlongPath(curve, location, distance) if (p.location > 1) p.location = 1 if (p.location < 0) p.location = 0 return gradientAtPoint(curve, p.location) } /** * calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location. * if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero). * @public */ export function perpendicularToPathAt (curve:Curve, location:number, length:number, distance:number):LineXY { distance = distance == null ? 0 : distance const p = pointAlongPath(curve, location, distance), m = gradientAtPoint(curve, p.location), _theta2 = Math.atan(-1 / m), y = length / 2 * Math.sin(_theta2), x = length / 2 * Math.cos(_theta2) return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}] } /** * Calculates all intersections of the given line with the given curve. * @param x1 * @param y1 * @param x2 * @param y2 * @param curve * @returns Array of intersecting points. */ export function bezierLineIntersection (x1:number, y1:number, x2:number, y2:number, curve:Curve):Array<PointXY> { let a = y2 - y1, b = x1 - x2, c = (x1 * (y1 - y2)) + (y1 * (x2-x1)), coeffs = _computeCoefficients(curve), p = [ (a*coeffs[0][0]) + (b * coeffs[1][0]), (a*coeffs[0][1])+(b*coeffs[1][1]), (a*coeffs[0][2])+(b*coeffs[1][2]), (a*coeffs[0][3])+(b*coeffs[1][3]) + c ], r = _cubicRoots.apply(null, p), intersections:Array<PointXY> = [] if (r != null) { for (let i = 0; i < 3; i++) { let t = r[i], t2 = Math.pow(t, 2), t3 = Math.pow(t, 3), x:PointXY = { x: (coeffs[0][0] * t3) + (coeffs[0][1] * t2) + (coeffs[0][2] * t) + coeffs[0][3], y: (coeffs[1][0] * t3) + (coeffs[1][1] * t2) + (coeffs[1][2] * t) + coeffs[1][3] } // check bounds of the line let s if ((x2 - x1) !== 0) { s = (x[0] - x1) / (x2 - x1) } else { s = (x[1] - y1) / (y2 - y1) } if (t >= 0 && t <= 1.0 && s >= 0 && s <= 1.0) { intersections.push(x) } } } return intersections } /** * Calculates all intersections of the given box with the given curve. * @param x X position of top left corner of box * @param y Y position of top left corner of box * @param w width of box * @param h height of box * @param curve * @returns Array of intersecting points. * @public */ export function boxIntersection (x:number, y:number, w:number, h:number, curve:Curve):Array<PointXY> { let i:Array<PointXY> = [] i.push.apply(i, bezierLineIntersection(x, y, x + w, y, curve)) i.push.apply(i, bezierLineIntersection(x + w, y, x + w, y + h, curve)) i.push.apply(i, bezierLineIntersection(x + w, y + h, x, y + h, curve)) i.push.apply(i, bezierLineIntersection(x, y + h, x, y, curve)) return i } /** * Calculates all intersections of the given bounding box with the given curve. * @param boundingBox Bounding box to test for intersections. * @param curve * @returns Array of intersecting points. * @public */ export function boundingBoxIntersection (boundingBox:BoundingBox, curve:Curve):Array<PointXY> { let i:Array<PointXY> = [] i.push.apply(i, bezierLineIntersection(boundingBox.x, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y, curve)) i.push.apply(i, bezierLineIntersection(boundingBox.x + boundingBox.w, boundingBox.y, boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, curve)) i.push.apply(i, bezierLineIntersection(boundingBox.x + boundingBox.w, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y + boundingBox.h, curve)) i.push.apply(i, bezierLineIntersection(boundingBox.x, boundingBox.y + boundingBox.h, boundingBox.x, boundingBox.y, curve)) return i } /** * @internal * @param curve * @param axis */ function _computeCoefficientsForAxis(curve:Curve, axis:string):AxisCoefficients { return [ -(curve[0][axis]) + (3*curve[1][axis]) + (-3 * curve[2][axis]) + curve[3][axis], (3*(curve[0][axis])) - (6*(curve[1][axis])) + (3*(curve[2][axis])), -3*curve[0][axis] + 3*curve[1][axis], curve[0][axis] ] } /** * @internal * @param curve */ function _computeCoefficients(curve:Curve):[ AxisCoefficients, AxisCoefficients ] { return [ _computeCoefficientsForAxis(curve, "x"), _computeCoefficientsForAxis(curve, "y") ] } /** * @internal * @param x */ function sgn(x:number):-1|0|1 { return x < 0 ? -1 : x > 0 ? 1 : 0 } /** * @internal * @param a * @param b * @param c * @param d */ function _cubicRoots(a:number, b:number, c:number, d:number):CubicRoots{ let A = b / a, B = c / a, C = d / a, Q = (3*B - Math.pow(A, 2))/9, R = (9*A*B - 27*C - 2*Math.pow(A, 3))/54, D = Math.pow(Q, 3) + Math.pow(R, 2), S, T, t:CubicRoots = [0,0,0] if (D >= 0) // complex or duplicate roots { S = sgn(R + Math.sqrt(D))*Math.pow(Math.abs(R + Math.sqrt(D)),(1/3)) T = sgn(R - Math.sqrt(D))*Math.pow(Math.abs(R - Math.sqrt(D)),(1/3)) t[0] = -A/3 + (S + T) t[1] = -A/3 - (S + T)/2 t[2] = -A/3 - (S + T)/2 /*discard complex roots*/ if (Math.abs(Math.sqrt(3)*(S - T)/2) !== 0) { t[1] = -1 t[2] = -1 } } else // distinct real roots { let th = Math.acos(R/Math.sqrt(-Math.pow(Q, 3))) t[0] = 2*Math.sqrt(-Q)*Math.cos(th/3) - A/3 t[1] = 2*Math.sqrt(-Q)*Math.cos((th + 2*Math.PI)/3) - A/3 t[2] = 2*Math.sqrt(-Q)*Math.cos((th + 4*Math.PI)/3) - A/3 } // discard out of spec roots for (let i = 0; i < 3; i++) { if (t[i] < 0 || t[i] > 1.0) { t[i] = -1 } } return t }
the_stack
import { Component, AfterViewInit, Input, ViewChildren } from "@angular/core"; // Components import { FileFolderComponent } from "../../components/file-folder/file-folder.component"; import { PopUpComponent } from "../../components/pop-up/pop-up.component"; // data models import sortType from "../../../model/sortType"; import keyBoardStatus from "../../../model/keyBoardStatus"; import dragDimension from "../../../model/dragDimension"; import { fs } from "../../../model/fs"; // file folder operations list import AVAILABLE_FILE_ICONS from "../../../default-values/AVAILABLE_FILE_ICONS"; import AVAILABLE_POP_UP_ICONS from "../../../default-values/AVAILABLE_POP_UP_ICONS"; import config from "../../config/config"; let dynamic_port = localStorage.getItem("USED_PORT") || config.server.PORT; let domain: string = `http://${config.server.HOST}:${dynamic_port}`; let socket: any = new WebSocket(`ws://localhost:${dynamic_port}`); let isSocketOpen: boolean = false; // Custom Functions const _ = (s: string): any => document.querySelector(s); const $ = (s: string): any => document.querySelectorAll(s); declare global { // extending window to contain main attribute (for attaching electron's functions) interface Window { main: any; } } let keyState = { ctrl: false, shift: false, alt: false, caps: false }; @Component({ selector: "app-file-manager", templateUrl: "./file-manager.component.html", styleUrls: ["./file-manager.component.css"] }) export class FileManagerComponent implements AfterViewInit { @Input() theme: string = "light"; // theme @ViewChildren(FileFolderComponent) filesAndFolders: any; @ViewChildren(PopUpComponent) popUpElement: any; dragging: boolean = false; // currently dragging or not drag: dragDimension = new dragDimension(); path: string[] = []; // directory path contents: any[] = []; // directory contents search: any = null; // search element editPathInput: any = null; sort: sortType = new sortType("type", "asc"); // sort by type and arrange as ascending noItems: boolean = false; error_loading: string = ""; // "" for no error else error message loading: boolean = false; INITIAL_PATH: string = "/"; editingPath: boolean = false; // currently editing path default_icon_size_index: number = 2; // default 2 iconSizes: string[] = ["ex-sm", "sm", "md", "lg", "ex-lg", "hg"]; iconSizeIndex: any = this.default_icon_size_index; // medium by default connections: any[] = []; popUp: any = this.initialPopUpState(); contextMenu: any = null; paste: any = null; inBrowser: boolean = false; process_id: number = 0; // id to keep track of background tast netween server and client using socket background_processes: any = []; // accessed with process_id (number), not with array index keyboard: keyBoardStatus = keyState; isProgressActive: boolean = false; online: boolean = navigator.onLine; current_server: string | null = null; current_test_connection: string | null = null; isWin: boolean | null = null; finished_loaded_init_contents: boolean = false; finished_setting_up_socket: boolean = false; max_spash_visibility_over: boolean = false; minimum_splash_visibility: number = 0; // default 2000 for visual effects and 0 for performance isDriveListing: boolean = false; // if loading a list of drives or not (only in local) constructor() { // web socket this.setUpSocket(); // set theme this.theme = localStorage.getItem("theme") || "light"; document.body.setAttribute("data-theme", this.theme); // dark or light mode // default light // hide close and minimize if in browser this.inBrowser = typeof window?.main == "undefined"; // set icon size this.setIconSizeIndex( localStorage.getItem("icon-size") ?? this.default_icon_size_index ); // default is medium // set connections this.connections = this.getConnections(); // Connect and load contents this.connectToFileSystem(null, true); // loading from local file system // offline listener window.addEventListener("offline", event => { this.online = false; this.toast("error", "You are offline"); }); // online listener window.addEventListener("online", event => { this.online = true; this.toast("success", "Back online"); }); setTimeout(() => { this.max_spash_visibility_over = true; }, this.minimum_splash_visibility); } ngAfterViewInit(): void { this.search = _("#search"); this.editPathInput = _("#editable-path"); this.arrange(); } closeProgress() { this.isProgressActive = false; } toggleProgressState() { this.isProgressActive = !this.isProgressActive; } getProcessTitle(type: string, status: string) { if (type == fs.DELETE) { return status == "in-progress" ? "Deleting" : "Delete"; } else if (type == fs.NEW_FOLDER) { return status == "in-progress" ? "Creating New Folder" : "New Folder"; } else if (type == fs.NEW_FILE) { return status == "in-progress" ? "Creating New File" : "New File"; } else if (type == fs.RENAME) { return status == "in-progress" ? "Renaming" : "Rename"; } else if (type == fs.CUT_PASTE) { return status == "in-progress" ? "Moving" : "Move"; } else if (type == fs.COPY_PASTE) { return status == "in-progress" ? "Copying" : "Copy"; } else if (type == fs.OPEN_FILE) { return status == "in-progress" ? "Opening" : "Opened"; } return "In progress"; } setUpSocket() { socket.startBackgroundProcess = ( type: fs, data: any, progressIndefinite: boolean = true ) => { let process = { process_id: this.process_id, type, data, progressIndefinite, // progress calculatable 0 to 100 - false, unknown amount of time - true progress: 0, status: "in-progress" }; socket.send(JSON.stringify(process)); this.background_processes[this.process_id] = process; return this.process_id++; }; socket.onopen = (event: any) => { //connected isSocketOpen = true; socket.send( JSON.stringify({ type: "settings", data: { ///// settings_config:"etc." } }) ); }; socket.onmessage = (event: any) => { try { let data = JSON.parse(event.data); console.log(data); if (data.type == "progress") { this.background_processes[data.process_id].progress = data.progress; } else if (data.type == "completed") { this.background_processes[data.process_id].status = "completed"; if (data.reload) { this.loadDirContents(this.getCWD()); } this.toast("success", data.message); } else if (data.type == "failed") { console.error(data); this.background_processes[data.process_id].status = "failed"; this.toast("error", data.message); } else if (data.type == "partial-success") { this.background_processes[data.process_id].status = "failed"; // partial is also fail if (data.reload) { this.loadDirContents(this.getCWD()); } this.toast("warning", data.message); } else if (data.type == "open-short-folder") { this.background_processes[data.process_id].status = "completed"; this.loadDirContents(data.extra_data.path); // opening the shortcut file path } else if (data.type == "settings") { // loaded settings configured in server this.isWin = data.data.isWin; this.finished_setting_up_socket = true; } } catch (error) { console.error(error.message); console.warn(event.data); } }; socket.onclose = () => { socket = { // socket is cleared and function returns null; startBackgroundProcess: (a: any = {}, b: any = {}, c: any = {}) => null }; isSocketOpen = false; }; } openDir(data: any, fallback = false) { let name = fallback ? data.name : data.folder; if (data.readable || data.isDrive) { this.loadDirContents(this.getCWD(name)); } else { this.toast("error", `Directory "${name}" is not accessible`); } } moveToDir(event: any) { let index = event.currentTarget.getAttribute("data-index"); let temp = this.path.slice(0, index).join("/") || "/"; temp = this.normalize_path(temp); this.loadDirContents(temp); } goBackOneDir() { if (this.path.length < 1) { return; } let path = [...this.path]; path.pop(); this.loadDirContents(this.normalize_path(path.join("/")) || "/"); } refresh() { this.loadDirContents(this.getCWD()); } normalize_path(path: string): string { path = path .replace("://", ":") .replace(":/", ":") .replace(":", "://"); // if collon(:) is present then it should be :// return path.includes(":") ? path : path.startsWith("/") ? path : `/${path}`; // adds slash in front if linux path (identified by colon : (only present in windows, but not present in root path of windows)) } getCWD(extra_path: string = "") { let temp = `${this.path.join("/")}/`; temp = temp != "/" ? temp : ""; // temp=temp.includes(":")?temp:(temp.startsWith("/")?temp:(this.isWin?temp:`/${temp}`)); // adds slash in front if linux path (identified by colon : (only present in windows, but not present in root path of windows)) temp = `${temp}${extra_path}`; temp = this.normalize_path(temp); return temp || "/"; } toast(type: string = "info", message: string, delay: number = 4000) { let delayOffset = 800; let box = document.createElement("div"); box.classList.add("toast"); box.classList.add(`toast-${type}`); box.innerHTML = message; _(".toast-container")?.appendChild(box); setTimeout(() => { box.classList.add("toast-fade"); }, delay); setTimeout(() => { box?.parentNode?.removeChild(box); }, delay + delayOffset); } loadDirContents(path: string, fromSplash: boolean = false) { if (this.loading) { this.toast("warning", "Please wait while loading is completed."); return; } if (this.search != null) { this.search.value = ""; // clear search input if text exists } this.loading = true; this.contents = []; let protocol, body; if (this.current_server == null) { protocol = "local"; body = JSON.stringify({ path }); } else { protocol = "ssh"; body = JSON.stringify({ server_id: this.current_server, path }); } fetch(`${domain}/fs/${protocol}/dir-contents/`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body }) .then(resp => { if (resp.status === 200) { return resp.json(); } throw new Error("status error"); }) .then(data => { // console.log(data); if (data.status) { this.isDriveListing = data.type == "drive"; this.path = this.parsePath(data.path); this.contents = data.contents.map((item: any) => { let mime_type = item.mime_type; if (AVAILABLE_FILE_ICONS.includes(mime_type)) { item.file_icon = `file-${mime_type}`; } else { item.file_icon = "file-default"; } item.selected = false; // file selected (for cut/copy etc) status item.isDrive = this.isDriveListing; return item; }); this.noItems = this.contents.length < 1; this.error_loading = ""; this.arrange(); // sort } else { console.log(`%c${data.message}`, "color:#FC0"); console.log(`%c${data.error_log}`, "color:#F00"); if (data.customError) { throw { name: "customError", message: data.message }; } throw new Error("Some Error occured"); } }) .catch(err => { console.log(err.message); let err_msg = err.name === "customError" ? err.message : "Something went wrong"; this.toast("error", err_msg); this.error_loading = err_msg; this.path = this.parsePath("/"); this.contents = []; this.noItems = true; }) .finally(() => { this.loading = false; this.editingPath = false; if (fromSplash) { this.finished_loaded_init_contents = true; } }); } switchTheme() { let body = document.body; this.theme = body.getAttribute("data-theme") == "dark" ? "light" : "dark"; body.setAttribute("data-theme", this.theme); localStorage.setItem("theme", this.theme); } mouseDown(event: any) { let isRightClick = event.button === 2; if (!(this.keyboard.ctrl || this.keyboard.shift || isRightClick)) { this.clearSelection(); } let { clientX: x, clientY: y } = event; this.drag.initY = y; this.drag.initX = x; this.setSelectDimensions(x, y, 0, 0); this.dragging = true; } mouseMoving(event: any) { if (!this.dragging) { return; } let { clientX: x, clientY: y } = event; // bottom right drag selection if (this.drag.initY < y && this.drag.initX < x) { this.setSelectDimensions( this.drag.initX, this.drag.initY, x - this.drag.initX, y - this.drag.initY ); } // bottom left drag selection else if (this.drag.initY < y && this.drag.initX >= x) { this.setSelectDimensions( x, this.drag.initY, this.drag.initX - x, y - this.drag.initY ); } // top right drag selection else if (this.drag.initY >= y && this.drag.initX < x) { this.setSelectDimensions( this.drag.initX, y, x - this.drag.initX, this.drag.initY - y ); } // top left drag selectiong else if (this.drag.initY >= y && this.drag.initX >= x) { this.setSelectDimensions(x, y, this.drag.initX - x, this.drag.initY - y); } this.selectItemsInDragBox(); } mouseUp() { this.dragging = false; } selectItemsInDragBox() { this.filesAndFolders?._results?.forEach((item: any) => { // exit, already selected and ctrl is pressed if (this.keyboard.ctrl && item.content.selected) { return; } let i = item.getDimensions(), d: any = this.drag; d.right = d.left + d.width; d.bottom = d.top + d.height; let item_left_in_drag_x = i.left > d.left && i.left < d.right; let item_right_in_drag_x = i.right > d.left && i.right < d.right; let item_x_in_drag_x = item_left_in_drag_x || item_right_in_drag_x; let item_top_in_drag_y = i.top > d.top && i.top < d.bottom; let item_bottom_in_drag_y = i.bottom > d.top && i.bottom < d.bottom; let item_y_in_drag_y = item_top_in_drag_y || item_bottom_in_drag_y; let item_in_drag = item_x_in_drag_x && item_y_in_drag_y; let drag_left_in_item_x = d.left > i.left && d.left < i.right; let drag_right_in_item_x = d.right > i.left && d.right < i.right; let drag_x_in_item_x = drag_left_in_item_x || drag_right_in_item_x; let drag_top_in_item_y = d.top > i.top && d.top < i.bottom; let drag_bottom_in_item_y = d.bottom > i.top && d.bottom < i.bottom; let drag_y_in_item_y = drag_top_in_item_y || drag_bottom_in_item_y; let drag_in_item = drag_x_in_item_x && drag_y_in_item_y; let drag_x_between_item_x = drag_x_in_item_x && item_y_in_drag_y; let drag_y_between_item_y = drag_y_in_item_y && item_x_in_drag_x; let drag_between_item = drag_x_between_item_x || drag_y_between_item_y; let select = item_in_drag || drag_in_item || drag_between_item; item.setItemSelection(select); }); } // clear file/folder selection clearSelection() { this.contents = this.contents.map(content => { content.selected = false; return content; }); } // set dragging box setSelectDimensions(x: number, y: number, w: number, h: number) { this.drag.top = y; this.drag.left = x; this.drag.width = w; this.drag.height = h; } preventDefault(event: any) { event.preventDefault(); } updateKeyBoardState(event: any) { this.keyboard.ctrl = event.ctrlKey; this.keyboard.shift = event.shiftKey; this.keyboard.alt = event.altKey; this.keyboard.caps = event.getModifierState("CapsLock"); } shortcut(event: any) { let key = event.keyCode; this.updateKeyBoardState(event); let ctrl = this.keyboard.ctrl; let shift = this.keyboard.shift; let alt = this.keyboard.alt; let caps = this.keyboard.caps; // console.log(key); if (ctrl || shift || alt) { //Control Key was also pressing if (ctrl) { // Select all if (key === 65) { // key: a event.preventDefault(); this.selectAll(); } // find/search if (key === 70) { // key: f event.preventDefault(); _("#search")?.focus(); } // invert selection if (key === 73) { // key: i event.preventDefault(); this.invertAllItemSelections(); } // refresh if (key == 82) { // key: r event.preventDefault(); this.refresh(); } // increase icon size if (key == 107 || key == 187) { // key: + event.preventDefault(); this.setIconSizeIndex(this.iconSizeIndex + 1); } // decrease icon size if (key == 109 || key == 189) { // key: - event.preventDefault(); this.setIconSizeIndex(this.iconSizeIndex - 1); } // reset icon size to medium if (key == 96 || key == 48) { // key 0 event.preventDefault(); this.setIconSizeIndex(this.default_icon_size_index); } // ctrl + shift + [any number] if (shift) { let k_start = 49, k_end = 54, t_n = this.iconSizes.length; if (key >= k_start && key <= k_end) { event.preventDefault(); this.setIconSizeIndex(t_n - 1 - ((key - (k_start - t_n)) % t_n)); } } } } else if (key === 114) { // F3 : search event.preventDefault(); _("#search")?.focus(); } else if (key === 115) { // F4 : Edit Path this.editThePath(); } else if (key === 116) { // F5 : Refresh event.preventDefault(); this.refresh(); } else if (key === 8) { // backspace event.preventDefault(); this.goBackOneDir(); } } editThePath() { this.editPathInput.value = this.getCWD() || "/"; this.editingPath = true; this.editPathInput.selectionStart = 0; this.editPathInput.selectionEnd = this.editPathInput.value.length - 1; _("#editable-path")?.focus(); } //split url path to array of drirectory path parsePath(url: string): string[] { // replaces different types of slashes like ( :// , \ , / ) to one type to ( / ) before spliting return url ?.replace(/(:\/\/|\\)/g, "/") ?.split("/") ?.filter(dir => dir != ""); } stopPropagation(event: any) { event?.stopPropagation(); this.updateKeyBoardState(event); this.closeMenu(); } // typing in search box searching(event: any) { event?.stopPropagation(); this.updateKeyBoardState(event); this.closeMenu(); let key = this.search.value, i = 0; this.filesAndFolders?._results?.forEach((item: any) => { if ( item .getData() .name.toLowerCase() .indexOf(key.toLowerCase()) == -1 ) { item.hide(); // not a match } else { item.show(); i++; } }); this.noItems = i < 1; } strcmp(a: any, b: any): 1 | -1 | 0 { let x = a.name.toLowerCase(), y = b.name.toLowerCase(); //ignore case return x < y ? -1 : x > y ? 1 : 0; } //sort arrange() { let { key, order } = this.sort; if (key == "type") { // sort by file/folder type let temp_files: any[] = [], temp_folders: any[] = []; this.contents.forEach(content => { // console.log(content); if (content.folder) { temp_folders.push(content); } else { temp_files.push(content); } }); temp_files = this.alphabeticalSort(temp_files) || []; temp_folders = this.alphabeticalSort(temp_folders) || []; this.contents = [...temp_folders, ...temp_files]; } if (key == "name") { // sort by file/folder name this.contents = this.alphabeticalSort(this.contents) || []; } else if (key == "size") { // sort by file size // incorrect size is returned from ssh plugin console.error("sort by size not implemented"); // this.contents.sort((a,b)=>a.properties.size-b.properties.size); } else if (key == "date") { // sort by date // incorrect date is returned from ssh plugin console.error("sort by date not implemented"); // this.contents.sort((a,b)=>b.properties.mtime-a.properties.mtime); } if (order == "desc") { // descending order this.contents.reverse(); } } alphabeticalSort(data: any[] = []) { let temp = [...data]; temp.sort(this.strcmp); return temp; } getSelectorStyle() { return { top: this.drag.top + "px", left: this.drag.left + "px", width: this.drag.width + "px", height: this.drag.height + "px" }; } toggleEditPath() { this.editPathInput.value = this.getCWD() || "/"; this.editingPath = !this.editingPath; _("#editable-path")?.focus(); } typingPath(event: any) { event?.stopPropagation(); this.updateKeyBoardState(event); this.closeMenu(); let key = event.keyCode; if (key === 13) { // enter this.goToPath(); } else if (key === 27) { // escape // reset path this.editingPath = false; } } goToPath(): void { this.loadDirContents(this.editPathInput.value || "/"); } updateIconSize(offset: number): void { this.setIconSizeIndex(this.iconSizeIndex + offset); } selectAll(): void { this.contents = this.contents.map(content => { content.selected = true; return content; }); } invertAllItemSelections(): void { this.contents = this.contents.map(content => { content.selected = !content.selected; return content; }); } setIconSizeIndex(index: any): void { this.iconSizeIndex = Math.min( this.iconSizes.length - 1, Math.max(0, index) ); localStorage.setItem("icon-size", this.iconSizeIndex); } shiftSelection(current: number) { let start = this.getFirstSelectedItem(); if (start != null) { this.selectFileFolderFromIndex(start, current); } else { this.contents[current].selected = true; } } selectFileFolderFromIndex(a: number, b: number) { let start = Math.min(a, b), end = Math.max(a, b); for (let i = 0, n = this.contents.length; i < n; i++) { this.contents[i].selected = i >= start && i <= end; } } getFirstSelectedItem(): number | null { for (let i = 0, n = this.contents.length; i < n; i++) { if (this.contents[i].selected) { return i; } } return null; } setConnections(connections: any[]) { localStorage.setItem("connections", btoa(JSON.stringify(connections))); } getConnections(): any[] { return ( JSON.parse(atob(localStorage.getItem("connections") ?? "") || "[]") || [] ); } getNumberOfSelectedItems() { let count = 0; this.contents.forEach((item: any) => { if (item.selected) { count++; } }); return count; } deleteConnection(event: any, index: number) { event?.stopPropagation(); this.closeMenu(); this.showPopUp( "confirm", "Delete Connection", `Are you sure you want to delete the connection : "${this.connections[index].name}"?`, "delete", "Delete", (data: any) => { let deleting_server_id = `${this.connections[index]["user"]}@${this.connections[index]["server"]}`; this.connections = [ ...this.connections.slice(0, index), ...this.connections.slice(index + 1) ]; this.setConnections(this.connections); this.closePopUp(); if (this.current_server == deleting_server_id) { this.connectToFileSystem(null); } }, "Cancel", (data: any) => { this.closePopUp(); }, true ); } connectToFileSystem(id: any, fromSplash: boolean = false) { if (this.loading) { this.toast("warning", "Please wait while loading is completed."); return; } if (id == null) { this.current_server = null; this.loadDirContents(this.INITIAL_PATH, fromSplash); return; } this.loading = true; this.contents = []; let connection = this.connections[id]; this.current_server = `${connection.user}@${connection.server}`; fetch(`${domain}/fs/ssh/connect`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ server: connection.server, user: connection.user, password: connection.password, force: false }) }) .then(resp => { return resp.json(); }) .then(data => { this.loading = false; if (data.status) { this.loadDirContents(this.INITIAL_PATH); } else { throw data; // to display data in error to view status } }) .catch(error => { console.error(error); this.loading = false; this.noItems = true; this.error_loading = "Connection failed"; }); } testConnection(server: string, user: string, password: string) { let testing_connection = `${user}@${server}`; this.current_test_connection = testing_connection; this.popUp.test_connection = "loading"; fetch(`${domain}/fs/ssh/connect`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ server, user, password, force: true }) }) .then(resp => { return resp.json(); }) .then(data => { if (data.status) { if (data.data == this.current_test_connection) { // if not it is from old request this.popUp.test_connection = "success"; } // old test status, no need to update } else { throw new Error("Connection Failed"); } }) .catch(error => { if (testing_connection == this.current_test_connection) { // if not it is from old request this.popUp.test_connection = "failed"; } }); } initialPopUpState() { return { active: false, // visible or not type: "confirm", // normal popup with ok and cancel icon: "", // icon type title: "", // title body: "", // content ok: null, // ok event cancel: null, // cancel event misk: null, // additional event test_connection: null, // testing status backgroundCancellation: true // cancel event when clicked on background }; } // // Example showPopUp // // this.showPopUp("confirm","Title",`Message`,"default","Ok",(data:any)=>{},"Cancel",(data:any)=>{ // this.closePopUp(); // },true,"Misk",(data:any)=>{}); // showPopUp( type: string = "confirm", title: string | null, body: string | null, icon: string | null, ok: string | null, okHandler: any, cancel: string | null, cancelHandler: any, backgroundCancellation: boolean = true, misk: string | null = null, miskHandler: any = null ) { icon = AVAILABLE_POP_UP_ICONS.includes(icon ?? "default") ? icon : "default"; this.popUp = { active: true, type, icon, title, body, ok: ok == null ? null : { text: ok, handler: okHandler }, cancel: cancel == null ? null : { text: cancel, handler: cancelHandler }, misk: misk == null ? null : { text: misk, handler: miskHandler }, test_connection: null, // testing status // tick, loading, failed backgroundCancellation }; } closePopUp() { this.popUp = this.initialPopUpState(); } handlePopUpEvent(type: string, data: any) { this.popUp[type].handler(data); } addConnection() { this.showPopUp( "connection-properties", "New Connection", null, "default", "Add", (data: any) => { let connection: any = {}; connection.protocol = "ssh"; connection.name = data["connection-name"]; connection.description = data["connection-description"]; connection.server = data["connection-server"]; connection.user = data["connection-user"]; connection.password = data["connection-password"]; this.connections.push(connection); this.setConnections(this.connections); this.closePopUp(); }, "Cancel", (data: any) => { this.closePopUp(); }, false, "Test", (data: any) => { this.testConnection( data["connection-server"], data["connection-user"], data["connection-password"] ); } ); } editConnection(event: any, id: number) { event.stopPropagation(); this.closeMenu(); let connection = this.connections[id]; this.popUpElement._results[0].editConnectionData = { "connection-name": connection.name, "connection-description": connection.description, "connection-server": connection.server, "connection-user": connection.user, "connection-password": connection.password }; this.showPopUp( "connection-properties", "Edit Connection", null, "default", "Save", (data: any) => { let connection: any = {}; connection.protocol = "ssh"; connection.name = data["connection-name"]; connection.description = data["connection-description"]; connection.server = data["connection-server"]; connection.user = data["connection-user"]; connection.password = data["connection-password"]; this.connections[id] = connection; this.setConnections(this.connections); this.closePopUp(); }, "Cancel", (data: any) => { this.closePopUp(); }, false, "Test", (data: any) => { this.testConnection( data["connection-server"], data["connection-user"], data["connection-password"] ); } ); } rightClick( event: any, fromMain: boolean = true, isFolder: boolean = false, multipleSelected: boolean = false ): void { event?.preventDefault(); let menu = _(".context-menu")?.getBoundingClientRect(); let screen = document.body.getBoundingClientRect(); let w = menu.width, h = menu.height; let offsetX = screen.width - w, offsetY = screen.height - h; let x = event.clientX, y = event.clientY; let left = x < offsetX ? x : x - w, top = y < offsetY ? y : y - h; let selectedItems = null, visibleOptions: any = []; if (!fromMain) { selectedItems = this.contents.filter((item: any) => item.selected); if (this.isDriveListing) { if (selectedItems.length == 1) { visibleOptions = ["open"]; } } else { visibleOptions = ["delete", "cut", "copy", "rename", "properties"]; if (selectedItems.length == 1) { if (selectedItems[0].folder) { visibleOptions.push(`open`); } } } } else { visibleOptions = ["back", "refresh", "paste", "new-folder", "new-file"]; } this.contextMenu = { visibility: "hidden", fromMain, isFolder, multipleSelected, top: top + "px", left: left + "px", x, y, selectedItems, visibleOptions }; } getContextMenuStyle() { return { visibility: this.contextMenu?.visibility ?? "hidden", top: this.contextMenu?.top || 0, left: this.contextMenu?.left || 0 }; } closeMenu() { this.contextMenu = null; } fileFolderRightClick(event: any, isFolder: boolean, index: number) { event?.preventDefault(); event?.stopPropagation(); this.closePopUp(); let multipleSelected = this.getNumberOfSelectedItems() > 0; this.contents[index].selected = true; // select currently right clicked also this.rightClick(event, false, isFolder, multipleSelected); setTimeout(this.setMenuStyle, 0); } setMenuStyle() { if (this.contextMenu != null) { let menu = _(".context-menu")?.getBoundingClientRect(); let screen = document.body.getBoundingClientRect(); let w = menu.width; let h = menu.height; let offsetX = screen.width - w; let offsetY = screen.height - h; let x = this.contextMenu.x; let y = this.contextMenu.y; let left = x < offsetX ? x : x - w; let top = y < offsetY ? y : y - h; this.contextMenu.top = top + "px"; this.contextMenu.left = left + "px"; this.contextMenu.visibility = "visible"; } return false; } newFileFolder(type: string) { let max_n = 0; let isFolder = type == "folder"; let pattern = isFolder ? /^New Folder [0-9]+$/ : /^Text Document [0-9]+\.txt$/; let operation = isFolder ? fs.NEW_FOLDER : fs.NEW_FILE; this.contents.forEach((item: any) => { if (isFolder == item.folder && pattern.test(item.name)) { max_n = Math.max(max_n, parseInt(item.name.split(" ").pop())); } }); let status = socket.startBackgroundProcess(operation, { source: { server: this.current_server, baseFolder: this.getCWD() }, files: [ isFolder ? `New Folder ${++max_n}` : `Text Document ${++max_n}.txt` ] }); if (status === null) { this.toast("error", "Not Connected to Server, Reconnect"); } } deleteFileFolder() { let operation = fs.DELETE; let list = this.contextMenu.selectedItems.map((item: any) => { return { name: item.name, isFolder: item.folder }; }); this.showPopUp( "confirm", "Delete", `Are you sure you want to delete ${list .map((item: any) => `"${item.name}"`) .join(", ")}`, "delete", "Delete", (data: any) => { let status = socket.startBackgroundProcess(operation, { source: { server: this.current_server, baseFolder: this.getCWD() }, files: list }); if (status === null) { this.toast("error", "Not Connected to Server, Reconnect"); } this.closePopUp(); }, "Cancel", (data: any) => { this.closePopUp(); }, true ); } hideBackgroundProcess(id: number) { delete this.background_processes[id]; } isBackgroundProssessesRunning() { return this.background_processes.some((process: any) => { return process.status == "in-progress"; }); } getContentContainerStyle() { let classList = ["contents", "scroller"]; if (!this.isProgressActive) { classList.push("wide"); } if (this.isDriveListing) { classList.push("drive-container"); } return classList.join(" "); } printSourceFiles(list: any) { if (typeof list[0] == "string") { return list?.join(", "); } if (typeof list[0] == "object") { return list?.map((item: any) => item.name)?.join(", "); } return ""; } isItemCutForPaste(index: number): boolean { let element = this.contents[index]; return this.paste?.type != "cut-paste" || this.paste?.source?.baseFolder != this.getCWD() || this.paste?.source?.server != this.current_server ? false : this.paste?.files?.some((item: any) => { return item.name == element.name && item.isFolder == element.folder; }); } cutCopy(type: any) { let list = this.contextMenu.selectedItems.map((item: any) => { return { name: item.name, isFolder: item.folder }; }); this.paste = { type: type == "cut" ? fs.CUT_PASTE : fs.COPY_PASTE, source: { server: this.current_server, baseFolder: this.getCWD() }, files: list }; } isValidPaste(src_base: string, target_base: string, files: any[]) { src_base = this.parsePath(src_base).join("/"); target_base = this.parsePath(target_base).join("/"); if (src_base == target_base) { return { status: "warning", message: "You cannot paste in same folder" }; } let isInSourceFolder = files .filter(item => item.isFolder) .map(item => this.parsePath(`${src_base}/${item.name}`).join("/")) .some(new_path => target_base.startsWith(new_path)); if (isInSourceFolder) { return { status: "warning", message: "You cannot paste inside copied folder" }; } let list: any = { files: [], folders: [] }; this.contents.forEach(item => { list[item.folder ? "folders" : "files"].push(item.name); }); let doesAlreadyExist = files.some(item => { return list[item.isFolder ? "folders" : "files"].includes(item.name); }); if (doesAlreadyExist) { return { status: "confirm", message: "Some Files/Folders already exists" }; } return { status: "success" }; } getNonExistingItemsForPaste(files: any[]) { let list: any = { files: [], folders: [] }; this.contents.forEach(item => { list[item.folder ? "folders" : "files"].push(item.name); }); files = files.filter(item => { return !list[item.isFolder ? "folders" : "files"].includes(item.name); }); return files; } pasteIt() { let paste_data = this.paste; let targetBaseFolder = this.getCWD(); let isValid = this.isValidPaste( paste_data.source.baseFolder, targetBaseFolder, paste_data.files ); if (isValid.status == "warning") { this.toast("warning", isValid.message || "Something went wrong"); return; } if (isValid.status == "confirm") { this.showPopUp( "confirm", "Paste Conflict", isValid.message || "Some Files/Folders already exists", "paste", "Skip", (data: any) => { paste_data.files = this.getNonExistingItemsForPaste(paste_data.files); this.forcePaste(paste_data.files); this.closePopUp(); }, "Cancel", (data: any) => { this.closePopUp(); }, true, "Overwrite", (data: any) => { this.forcePaste(paste_data.files); this.closePopUp(); } ); } else { this.forcePaste(paste_data.files); } } forcePaste(files: any[]) { let paste_data = this.paste; let status = socket.startBackgroundProcess(paste_data.type, { source: paste_data.source, target: { server: this.current_server, baseFolder: this.getCWD() }, files: files }); if (status === null) { this.toast("error", "Not Connected to Server, Reconnect"); } else if (paste_data.type == "cut-paste") { this.paste = null; } } rename() { let item = this.contextMenu?.selectedItems[0]; this.popUpElement._results[0].renameData = item.name; this.showPopUp( "rename", `Rename ${item.folder ? "Folder" : "File"}`, null, "rename", "Rename", (data: any) => { if (data != null) { if (data != item.name) { // not same name if (this.contents.some(existing => existing.name == data)) { // already another file/folder exists with same name this.toast("error", `A file/folder exists with same name`); } else { let status = socket.startBackgroundProcess(fs.RENAME, { source: { server: this.current_server, baseFolder: this.getCWD() }, files: [item.name, data] // original name, new name }); if (status === null) { this.toast("error", "Not Connected to Server, Reconnect"); } } } this.closePopUp(); } }, "Cancel", (data: any) => { this.closePopUp(); }, false ); } showSourceGit() { window.open("https://github.com/27px/Remote-File-Manager", "_blank"); } showMyDevProfile() { window.open("https://www.linkedin.com/in/27px/", "_blank"); } openFileInDefaultApp(filename: any) { if (this.current_server != null) { // if not local system this.toast( "warning", "You cannot open a file in server, copy it and paste it to your local system to open" ); } else if (this.inBrowser) { this.toast( "warning", "Opening a file feature is not available in browser, try in the executable version" ); } else { let status = socket.startBackgroundProcess(fs.OPEN_FILE, { source: { server: this.current_server, baseFolder: this.getCWD() }, files: [filename] // file to open }); if (status === null) { this.toast("error", "Not Connected to Server, Reconnect"); } } } }
the_stack
import { IonicNativePlugin } from '@ionic-native/core'; /** * @name jmessage * @description * This plugin does something * * @usage * ```typescript * import { jmessage } from '@ionic-native/jmessage'; * * * constructor(private jmessage: jmessage) { } * * ... * * * this.jmessage.functionName('Hello', 123) * .then((res: any) => console.log(res)) * .catch((error: any) => console.error(error)); * * ``` */ export interface JMSingleType { type: 'single'; username: string; appKey?: string; } export interface JMGroupType { type: 'group'; groupId: string; } export interface JMChatRoomType { type: 'chatRoom'; roomId: string; } export declare type JMAllType = (JMSingleType | JMGroupType | JMChatRoomType); export interface JMMessageOptions { extras?: { [key: string]: string; }; messageSendingOptions?: JMMessageSendOptions; } export interface JMConfig { isOpenMessageRoaming: boolean; } export interface JMError { code: string; description: string; } /** * Message type */ export interface JMNormalMessage { id: string; serverMessageId: string; isSend: boolean; from: JMUserInfo; target: (JMUserInfo | JMGroupInfo); createTime: number; extras?: { [key: string]: string; }; } export declare type JMTextMessage = JMNormalMessage & { type: 'text'; text: string; }; export declare type JMVoiceMessage = JMNormalMessage & { type: 'voice'; path?: string; duration: number; }; export declare type JMImageMessage = JMNormalMessage & { type: 'image'; thumbPath?: string; }; export declare type JMFileMessage = JMNormalMessage & { type: 'file'; fileName: string; }; export declare type JMLocationMessage = JMNormalMessage & { type: 'location'; longitude: number; latitude: number; scale: number; address?: string; }; export declare type JMCustomMessage = JMNormalMessage & { type: 'custom'; customObject: { [key: string]: string; }; }; export interface JMEventMessage { type: 'event'; eventType: 'group_member_added' | 'group_member_removed' | 'group_member_exit'; usernames: string[]; } export declare type JMAllMessage = JMTextMessage | JMVoiceMessage | JMImageMessage | JMFileMessage | JMEventMessage | JMCustomMessage; export declare type JMMessageEventListener = (message: JMAllMessage) => void; export declare type JMSyncOfflineMessageListener = (event: { conversation: JMConversationInfo; messageArray: JMAllMessage[]; }) => void; export declare type JMSyncRoamingMessageListener = (event: { conversation: JMConversationInfo; }) => void; export declare type JMLoginStateChangedListener = (event: { type: 'user_password_change' | 'user_logout' | 'user_deleted' | 'user_login_status_unexpected'; }) => void; export declare type JMContactNotifyListener = (event: { type: 'invite_received' | 'invite_accepted' | 'invite_declined' | 'contact_deleted'; reason: string; fromUsername: string; fromUserAppKey?: string; }) => void; export declare type JMMessageRetractListener = (event: { conversation: JMConversationInfo; retractedMessage: JMAllMessage; }) => void; export declare type JMReceiveTransCommandListener = (event: { message: string; sender: JMUserInfo; receiver: JMUserInfo | JMGroupInfo; receiverType: 'single' | 'group'; }) => void; export declare type JMReceiveChatRoomMessageListener = (event: { messageArray: JMAllMessage[]; }) => void; export declare type JMReceiveApplyJoinGroupApprovalListener = (event: { eventId: string; groupId: string; isInitiativeApply: boolean; sendApplyUser: JMUserInfo; joinGroupUsers?: JMUserInfo[]; reason?: string; }) => void; export declare type JMReceiveGroupAdminRejectListener = (event: { groupId: string; groupManager: JMUserInfo; reason?: string; }) => void; export declare type JMReceiveGroupAdminApprovalListener = (event: { isAgree: boolean; applyEventId: string; groupId: string; groupAdmin: JMUserInfo; users: JMUserInfo[]; }) => void; /** * User Type */ export interface JMUserInfo { type: 'user'; username: string; appKey?: string; nickname?: string; gender: 'male' | 'female' | 'unknown'; avatarThumbPath: string; birthday?: number; region?: string; signature?: string; address?: string; noteName?: string; noteText?: string; isNoDisturb: boolean; isInBlackList: boolean; isFriend: boolean; extras?: { [key: string]: string; }; } export interface JMGroupMemberInfo { user: JMUserInfo; groupNickname: string; memberType: 'owner' | 'admin' | 'ordinary'; joinGroupTime: number; } export interface JMGroupInfo { type: 'group'; id: string; name?: string; desc?: string; level: number; owner: string; ownerAppKey?: string; maxMemberCount: number; isNoDisturb: boolean; isBlocked: boolean; } export interface JMChatRoomInfo { type: 'chatRoom'; roomId: string; name: string; appKey?: string; description?: string; createTime: number; maxMemberCount?: number; memberCount: number; } export declare type JMConversationInfo = ({ conversationType: 'single'; target: JMUserInfo; } | { conversationType: 'group'; target: JMGroupInfo; }) & { title: string; latestMessage: JMAllMessage; unreadCount: number; }; export interface JMMessageSendOptions { /** * 接收方是否针对此次消息发送展示通知栏通知。 * @type {boolean} * @defaultvalue */ isShowNotification?: boolean; /** * 是否让后台在对方不在线时保存这条离线消息,等到对方上线后再推送给对方。 * @type {boolean} * @defaultvalue */ isRetainOffline?: boolean; /** * 是否开启了自定义接收方通知栏功能。 * @type {?boolean} */ isCustomNotificationEnabled?: boolean; /** * 设置此条消息在接收方通知栏所展示通知的标题。 * @type {?string} */ notificationTitle?: string; /** * 设置此条消息在接收方通知栏所展示通知的内容。 * @type {?string} */ notificationText?: string; } export declare class JMChatRoom { getChatRoomInfoListOfApp(params: { start: number; count: number; }, success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void; getChatRoomInfoListOfUser(success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void; getChatRoomInfoListById(params: { roomId: string; }, success: (chatroomList: JMChatRoomInfo[]) => void, fail: (error: JMError) => void): void; getChatRoomOwner(params: { roomId: string; }, success: (chatroomList: JMUserInfo) => void, fail: (error: JMError) => void): void; enterChatRoom(obj: { roomId: string; }, success: (conversation: JMConversationInfo) => void, fail: (error: JMError) => void): void; exitChatRoom(params: { roomId: string; }, success: () => void, fail: (error: JMError) => void): void; getChatRoomConversation(params: { roomId: string; }, success: () => void, fail: (error: JMError) => void): void; getChatRoomConversationList(success: (conversationList: JMConversationInfo[]) => void, fail: (error: JMError) => void): void; } export declare class JMessagePlugin extends IonicNativePlugin { /** * This function does something * @param arg1 {string} Some param to configure something * @param arg2 {number} Another param to configure something * @return {Promise<any>} Returns a promise that resolves when something happens */ functionName(arg1: string, arg2: number): Promise<any>; init(params: JMConfig): void; setDebugMode(params: { enable: boolean; }): void; register(params: { username: string; password: string; nickname: string; }): Promise<void>; login(params: { username: string; password: string; }): Promise<void>; logout(): void; setBadge(params: { badge: number; }): void; getMyInfo(): Promise<JMUserInfo | {}>; getUserInfo(params: { username: string; appKey?: string; }): Promise<JMUserInfo>; updateMyPassword(params: { oldPwd: string; newPwd: string; }): Promise<void>; /** * 更新当前用户头像。 * @param {object} params = { * imgPath: string // 本地图片绝对路径。 * } * 注意 Android 与 iOS 的文件路径是不同的: * - Android 类似:/storage/emulated/0/DCIM/Camera/IMG_20160526_130223.jpg * - iOS 类似:/var/mobile/Containers/Data/Application/7DC5CDFF-6581-4AD3-B165-B604EBAB1250/tmp/photo.jpg */ updateMyAvatar(params: { imgPath: string; }): Promise<any>; updateMyInfo(params: { birthday?: number; gender?: 'male' | 'female' | 'unknown'; extras?: { [key: string]: string; }; }): Promise<any>; updateGroupAvatar(params: { id: string; imgPath: string; }): Promise<any>; downloadThumbGroupAvatar(params: { id: string; }): Promise<any>; downloadOriginalGroupAvatar(params: { id: string; }): Promise<any>; setConversationExtras(params: JMAllType & { extras: { [key: string]: string; }; }): Promise<any>; sendTextMessage(params: JMAllType & JMMessageOptions & { text: string; }): Promise<any>; sendImageMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any>; sendVoiceMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any>; sendCustomMessage(params: JMAllType & JMMessageOptions & { customObject: { [key: string]: string; }; }): Promise<any>; sendLocationMessage(params: JMAllType & JMMessageOptions & { latitude: number; longitude: number; scale: number; address: string; }): Promise<any>; sendFileMessage(params: JMAllType & JMMessageOptions & { path: string; }): Promise<any>; retractMessage(params: JMAllType & { messageId: string; }): Promise<any>; getHistoryMessages(params: (JMSingleType | JMGroupType) & { from: number; limit: number; }): Promise<any>; getMessageById(params: JMAllType & { messageId: string; }): Promise<any>; deleteMessageById(params: JMAllType & { messageId: string; }): Promise<any>; sendInvitationRequest(params: { username: string; reason: string; appKey?: string; }): Promise<any>; acceptInvitation(params: { username: string; appKey?: string; }): Promise<any>; declineInvitation(params: { username: string; reason: string; appKey?: string; }): Promise<any>; removeFromFriendList(params: { username: string; appKey?: string; }): Promise<any>; updateFriendNoteName(params: { username: string; noteName: string; appKey?: string; }): Promise<any>; updateFriendNoteText(params: { username: string; noteText: string; appKey?: string; }): Promise<any>; getFriends(): Promise<any>; createGroup(params: { groupType?: 'public' | 'private'; name?: string; desc?: string; }): Promise<string>; getGroupIds(): Promise<any>; getGroupInfo(params: { id: string; }): Promise<any>; updateGroupInfo(params: { id: string; newName: string; newDesc?: string; } | { id: string; newDesc: string; }): Promise<any>; addGroupMembers(params: { id: string; usernameArray: string[]; appKey?: string; }): Promise<any>; removeGroupMembers(params: { id: string; usernameArray: string[]; appKey?: string; }): Promise<any>; exitGroup(params: { id: string; }): Promise<any>; getGroupMembers(params: { id: string; }): Promise<JMGroupMemberInfo[]>; addUsersToBlacklist(params: { usernameArray: string[]; appKey?: string; }): Promise<any>; removeUsersFromBlacklist(params: { usernameArray: string[]; appKey?: string; }): Promise<any>; getBlacklist(): Promise<any>; setNoDisturb(params: (JMSingleType | JMGroupType) & { isNoDisturb: boolean; }): Promise<any>; getNoDisturbList(): Promise<any>; setNoDisturbGlobal(params: { isNoDisturb: boolean; }): Promise<any>; isNoDisturbGlobal(): Promise<any>; blockGroupMessage(params: { id: string; isBlock: boolean; }): Promise<any>; isGroupBlocked(params: { id: string; }): Promise<any>; getBlockedGroupList(): Promise<any>; downloadThumbUserAvatar(params: { username: string; appKey?: string; }): Promise<any>; downloadOriginalUserAvatar(params: { username: string; appKey?: string; }): Promise<any>; downloadThumbImage(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any>; downloadOriginalImage(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any>; downloadVoiceFile(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any>; downloadFile(params: (JMSingleType | JMGroupType) & { messageId: string; }): Promise<any>; createConversation(params: JMAllType): Promise<any>; deleteConversation(params: JMAllType): Promise<any>; enterConversation(params: JMSingleType | JMGroupType): Promise<any>; exitConversation(params: JMSingleType | JMGroupType): void; getConversation(params: JMAllType): Promise<any>; getConversations(): Promise<any>; resetUnreadMessageCount(params: JMAllType): Promise<any>; transferGroupOwner(params: { groupId: string; username: string; appKey?: string; }): Promise<any>; setGroupMemberSilence(params: { groupId: string; isSilence: boolean; username: string; appKey?: string; }): Promise<any>; isSilenceMember(params: { groupId: string; username: string; appKey?: string; }): Promise<any>; groupSilenceMembers(params: { groupId: string; }): Promise<any>; setGroupNickname(params: { groupId: string; nickName: string; username: string; appKey?: string; }): Promise<any>; /** * TODO: * * chatRoom internal api. */ ChatRoom: JMChatRoom; enterChatRoom(params: { roomId: string; }): Promise<any>; exitChatRoom(params: { roomId: string; }): Promise<any>; getChatRoomConversation(params: { roomId: string; }): Promise<any>; getChatRoomConversationList(): Promise<any>; getAllUnreadCount(): Promise<{ count: number; }>; addGroupAdmins(params: { groupId: string; usernames: string[]; appKey?: string; }): Promise<any>; removeGroupAdmins(params: { groupId: string; usernames: string[]; appKey?: string; }): Promise<any>; changeGroupType(params: { groupId: string; type: 'public' | 'private'; }): Promise<any>; getPublicGroupInfos(params: { appKey: string; start: number; count: number; }): Promise<any>; applyJoinGroup(params: { groupId: string; reason?: string; }): Promise<any>; processApplyJoinGroup(params: { events: string[]; isAgree: boolean; isRespondInviter: boolean; reason?: string; }): Promise<any>; dissolveGroup(params: { groupId: string; }): Promise<any>; addReceiveMessageListener(params: JMMessageEventListener): void; removeReceiveMessageListener(params: JMMessageEventListener): void; addClickMessageNotificationListener(params: JMMessageEventListener): void; removeClickMessageNotificationListener(params: JMMessageEventListener): void; addSyncOfflineMessageListener(params: JMSyncOfflineMessageListener): void; removeSyncOfflineMessageListener(params: JMSyncOfflineMessageListener): void; addSyncRoamingMessageListener(params: JMSyncRoamingMessageListener): void; removeSyncRoamingMessageListener(params: JMSyncRoamingMessageListener): void; addLoginStateChangedListener(params: JMLoginStateChangedListener): void; removeLoginStateChangedListener(params: JMLoginStateChangedListener): void; addContactNotifyListener(params: JMContactNotifyListener): void; removeContactNotifyListener(params: JMContactNotifyListener): void; addMessageRetractListener(params: JMMessageRetractListener): void; removeMessageRetractListener(params: JMMessageRetractListener): void; addReceiveTransCommandListener(params: JMReceiveTransCommandListener): void; removeReceiveTransCommandListener(params: JMReceiveTransCommandListener): void; addReceiveChatRoomMessageListener(params: JMReceiveChatRoomMessageListener): void; removeReceiveChatRoomMessageListener(params: JMReceiveChatRoomMessageListener): void; addReceiveApplyJoinGroupApprovalListener(params: JMReceiveApplyJoinGroupApprovalListener): void; removeReceiveApplyJoinGroupApprovalListener(params: JMReceiveApplyJoinGroupApprovalListener): void; addReceiveGroupAdminRejectListener(params: JMReceiveGroupAdminRejectListener): void; removeReceiveGroupAdminRejectListener(params: JMReceiveGroupAdminRejectListener): void; addReceiveGroupAdminApprovalListener(params: JMReceiveGroupAdminApprovalListener): void; removeReceiveGroupAdminApprovalListener(params: JMReceiveGroupAdminApprovalListener): void; }
the_stack
namespace egret { /** * @private */ export class ScrollEase { /** * @version Egret 2.4 * @platform Web,Native */ constructor() { egret.$error(1014); } /** * * @param amount * @returns * @version Egret 2.4 * @platform Web,Native */ public static get(amount):Function { if (amount < -1) { amount = -1; } if (amount > 1) { amount = 1; } return function (t) { if (amount == 0) { return t; } if (amount < 0) { return t * (t * -amount + 1 + amount); } return t * ((2 - t) * amount + (1 - amount)); } } /** * @version Egret 2.4 * @platform Web,Native */ public static quintOut = ScrollEase.getPowOut(5); /** * * @param pow * @returns * @version Egret 2.4 * @platform Web,Native */ public static getPowOut(pow):Function { return function (t) { return 1 - Math.pow(1 - t, pow); } } /** * @version Egret 2.4 * @platform Web,Native */ public static quartOut = ScrollEase.getPowOut(4); } /** * @private */ export class ScrollTween extends EventDispatcher { /** * @private */ private static _tweens:ScrollTween[] = []; /** * @private */ private static IGNORE = {}; /** * @private */ private static _plugins = {}; /** * @private */ private static _inited = false; /** * @private */ private _target:any = null; /** * @private */ private _useTicks:boolean = false; /** * @private */ private ignoreGlobalPause:boolean = false; /** * @private */ private loop:boolean = false; /** * @private */ private pluginData = null; /** * @private */ private _curQueueProps; /** * @private */ private _initQueueProps; /** * @private */ private _steps:any[] = null; /** * @private */ private _actions:any[] = null; /** * @private */ private paused:boolean = false; /** * @private */ private duration:number = 0; /** * @private */ private _prevPos:number = -1; /** * @private */ private position:number = null; /** * @private */ private _prevPosition:number = 0; /** * @private */ private _stepPosition:number = 0; /** * @private */ private passive:boolean = false; /** * Activate an object and add a ScrollTween animation to the object * @param target {any} The object to be activated * @param props {any} Parameters, support loop onChange onChangeObj * @param pluginData {any} Write realized * @param override {boolean} Whether to remove the object before adding a tween, the default value false * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 激活一个对象,对其添加 ScrollTween 动画 * @param target {any} 要激活 ScrollTween 的对象 * @param props {any} 参数,支持loop(循环播放) onChange(变化函数) onChangeObj(变化函数作用域) * @param pluginData {any} 暂未实现 * @param override {boolean} 是否移除对象之前添加的tween,默认值false * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static get(target:any, props:any = null, pluginData:any = null, override:boolean = false):ScrollTween { if (override) { ScrollTween.removeTweens(target); } return new ScrollTween(target, props, pluginData); } /** * Delete all ScrollTween animations from an object * @param target The object whose ScrollTween to be deleted * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 删除一个对象上的全部 ScrollTween 动画 * @param target 需要移除 ScrollTween 的对象 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static removeTweens(target:any):void { if (!target.tween_count) { return; } let tweens:ScrollTween[] = ScrollTween._tweens; for (let i = tweens.length - 1; i >= 0; i--) { if (tweens[i]._target == target) { tweens[i].paused = true; tweens.splice(i, 1); } } target.tween_count = 0; } /** * @private * * @param delta * @param paused */ private static tick(timeStamp:number, paused = false):boolean { let delta = timeStamp - ScrollTween._lastTime; ScrollTween._lastTime = timeStamp; let tweens:ScrollTween[] = ScrollTween._tweens.concat(); for (let i = tweens.length - 1; i >= 0; i--) { let tween:ScrollTween = tweens[i]; if ((paused && !tween.ignoreGlobalPause) || tween.paused) { continue; } tween.tick(tween._useTicks ? 1 : delta); } return false; } private static _lastTime:number = 0; /** * @private * * @param tween * @param value */ private static _register(tween:ScrollTween, value:boolean):void { let target:any = tween._target; let tweens:ScrollTween[] = ScrollTween._tweens; if (value) { if (target) { target.tween_count = target.tween_count > 0 ? target.tween_count + 1 : 1; } tweens.push(tween); if (!ScrollTween._inited) { ScrollTween._lastTime = egret.getTimer(); ticker.$startTick(ScrollTween.tick, null); ScrollTween._inited = true; } } else { if (target) { target.tween_count--; } let i = tweens.length; while (i--) { if (tweens[i] == tween) { tweens.splice(i, 1); return; } } } } /** * 创建一个 egret.ScrollTween 对象 * @private * @version Egret 2.4 * @platform Web,Native */ constructor(target:any, props:any, pluginData:any) { super(); this.initialize(target, props, pluginData); } /** * @private * * @param target * @param props * @param pluginData */ private initialize(target:any, props:any, pluginData:any):void { this._target = target; if (props) { this._useTicks = props.useTicks; this.ignoreGlobalPause = props.ignoreGlobalPause; this.loop = props.loop; props.onChange && this.addEventListener("change", props.onChange, props.onChangeObj); if (props.override) { ScrollTween.removeTweens(target); } } this.pluginData = pluginData || {}; this._curQueueProps = {}; this._initQueueProps = {}; this._steps = []; this._actions = []; if (props && props.paused) { this.paused = true; } else { ScrollTween._register(this, true); } if (props && props.position != null) { this.setPosition(props.position); } } /** * @private * * @param value * @param actionsMode * @returns */ private setPosition(value:number, actionsMode:number = 1):boolean { if (value < 0) { value = 0; } //正常化位置 let t:number = value; let end:boolean = false; if (t >= this.duration) { if (this.loop) { t = t % this.duration; } else { t = this.duration; end = true; } } if (t == this._prevPos) { return end; } let prevPos = this._prevPos; this.position = this._prevPos = t; this._prevPosition = value; if (this._target) { if (end) { //结束 this._updateTargetProps(null, 1); } else if (this._steps.length > 0) { // 找到新的tween let i:number; let l = this._steps.length; for (i = 0; i < l; i++) { if (this._steps[i].t > t) { break; } } let step = this._steps[i - 1]; this._updateTargetProps(step, (this._stepPosition = t - step.t) / step.d); } } if (end) { this.setPaused(true); } //执行actions if (actionsMode != 0 && this._actions.length > 0) { if (this._useTicks) { this._runActions(t, t); } else if (actionsMode == 1 && t < prevPos) { if (prevPos != this.duration) { this._runActions(prevPos, this.duration); } this._runActions(0, t, true); } else { this._runActions(prevPos, t); } } this.dispatchEventWith("change"); return end; } /** * @private * * @param startPos * @param endPos * @param includeStart */ private _runActions(startPos:number, endPos:number, includeStart:boolean = false) { let sPos:number = startPos; let ePos:number = endPos; let i:number = -1; let j:number = this._actions.length; let k:number = 1; if (startPos > endPos) { //把所有的倒置 sPos = endPos; ePos = startPos; i = j; j = k = -1; } while ((i += k) != j) { let action = this._actions[i]; let pos = action.t; if (pos == ePos || (pos > sPos && pos < ePos) || (includeStart && pos == startPos)) { action.f.apply(action.o, action.p); } } } /** * @private * * @param step * @param ratio */ private _updateTargetProps(step:any, ratio:number) { let p0, p1, v, v0, v1, arr; if (!step && ratio == 1) { this.passive = false; p0 = p1 = this._curQueueProps; } else { this.passive = !!step.v; //不更新props. if (this.passive) { return; } //使用ease if (step.e) { ratio = step.e(ratio, 0, 1, 1); } p0 = step.p0; p1 = step.p1; } for (let n in this._initQueueProps) { if ((v0 = p0[n]) == null) { p0[n] = v0 = this._initQueueProps[n]; } if ((v1 = p1[n]) == null) { p1[n] = v1 = v0; } if (v0 == v1 || ratio == 0 || ratio == 1 || (typeof(v0) != "number")) { v = ratio == 1 ? v1 : v0; } else { v = v0 + (v1 - v0) * ratio; } let ignore = false; if (arr = ScrollTween._plugins[n]) { for (let i = 0, l = arr.length; i < l; i++) { let v2 = arr[i].tween(this, n, v, p0, p1, ratio, !!step && p0 == p1, !step); if (v2 == ScrollTween.IGNORE) { ignore = true; } else { v = v2; } } } if (!ignore) { this._target[n] = v; } } } /** * Whether setting is paused * @param value {boolean} Whether to pause * @returns ScrollTween object itself * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 设置是否暂停 * @param value {boolean} 是否暂停 * @returns Tween对象本身 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public setPaused(value:boolean):ScrollTween { this.paused = value; ScrollTween._register(this, !value); return this; } /** * @private * * @param props * @returns */ private _cloneProps(props):any { let o = {}; for (let n in props) { o[n] = props[n]; } return o; } /** * @private * * @param o * @returns */ private _addStep(o):ScrollTween { if (o.d > 0) { this._steps.push(o); o.t = this.duration; this.duration += o.d; } return this; } /** * @private * * @param o * @returns */ private _appendQueueProps(o):any { let arr, oldValue, i, l, injectProps; for (let n in o) { if (this._initQueueProps[n] === undefined) { oldValue = this._target[n]; //设置plugins if (arr = ScrollTween._plugins[n]) { for (i = 0, l = arr.length; i < l; i++) { oldValue = arr[i].init(this, n, oldValue); } } this._initQueueProps[n] = this._curQueueProps[n] = (oldValue === undefined) ? null : oldValue; } else { oldValue = this._curQueueProps[n]; } } for (let n in o) { oldValue = this._curQueueProps[n]; if (arr = ScrollTween._plugins[n]) { injectProps = injectProps || {}; for (i = 0, l = arr.length; i < l; i++) { if (arr[i].step) { arr[i].step(this, n, oldValue, o[n], injectProps); } } } this._curQueueProps[n] = o[n]; } if (injectProps) { this._appendQueueProps(injectProps); } return this._curQueueProps; } /** * @private * * @param o * @returns */ private _addAction(o):ScrollTween { o.t = this.duration; this._actions.push(o); return this; } /** * Modify the property of the specified display object to a specified value * @param props {Object} Property set of an object * @param duration {number} Duration * @param ease {egret.ScrollEase} Easing algorithm * @returns {egret.ScrollTween} ScrollTween object itself * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 将指定显示对象的属性修改为指定值 * @param props {Object} 对象的属性集合 * @param duration {number} 持续时间 * @param ease {egret.ScrollEase} 缓动算法 * @returns {egret.ScrollTween} Tween对象本身 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public to(props, duration?:number, ease:Function = undefined):ScrollTween { if (isNaN(duration) || duration < 0) { duration = 0; } return this._addStep({d: duration || 0, p0: this._cloneProps(this._curQueueProps), e: ease, p1: this._cloneProps(this._appendQueueProps(props))}); } /** * Execute callback function * @param callback {Function} Callback method * @param thisObj {any} this action scope of the callback method * @param params {any[]} Parameter of the callback method * @returns {egret.ScrollTween} ScrollTween object itself * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 执行回调函数 * @param callback {Function} 回调方法 * @param thisObj {any} 回调方法this作用域 * @param params {any[]} 回调方法参数 * @returns {egret.ScrollTween} Tween对象本身 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public call(callback:Function, thisObj:any = undefined, params:any[] = undefined):ScrollTween { return this._addAction({f: callback, p: params ? params : [], o: thisObj ? thisObj : this._target}); } /** * @method egret.ScrollTween#tick * @param delta {number} * @private * @version Egret 2.4 * @platform Web,Native */ public tick(delta:number):void { if (this.paused) { return; } this.setPosition(this._prevPosition + delta); } } }
the_stack
import React from 'react' import { expect, match, mount, stub } from '@instructure/ui-test-utils' import { PaginationPageInput } from '../index' import { PaginationPageInputLocator } from '../PaginationPageInputLocator' const defaultSRLabel = (currentPage: number, numberOfPages: number) => `Select page (${currentPage} of ${numberOfPages})` describe('<PaginationPageInput />', async () => { const defaultOnChange = stub() it('should render', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={0} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} /> ) const pageInput = await PaginationPageInputLocator.find() expect(pageInput).to.exist() }) it('should display the current page number', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() expect(input.getDOMNode().value).to.equal('4') }) it('should correctly update page number', async () => { const subject = await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() expect(input.getDOMNode().value).to.equal('4') await subject.setProps({ currentPageIndex: 6 }) expect(input.getDOMNode().value).to.equal('7') }) it("shouldn't display the arrow keys of NumberInput", async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} /> ) const pageInput = await PaginationPageInputLocator.find() const arrowKeys = await pageInput.findNumberInputArrows({ expectEmpty: true }) expect(arrowKeys.length).to.equal(0) }) it("should disable the input on 'disabled'", async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} disabled /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() expect(input.getDOMNode().disabled).to.true() }) it('should set the ScreenReaderLabel for the input', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} /> ) const pageInput = await PaginationPageInputLocator.find() const label = await pageInput.find(':contains(Select page (4 of 10))') expect(label).to.exist() }) it('should display the number of pages in the label', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const label = await pageInput.find(':contains(of 10)') expect(label).to.exist() }) describe('on typing', async () => { it('a number, should update the number in the input', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '6' } }) expect(input.getDOMNode().value).to.equal('6') }) it('a letter, should not update the input', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: 'a' } }) expect(input.getDOMNode().value).to.equal('') }) it("shouldn't call onChange on input", async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() input.change({ target: { value: '6' } }) expect(onChange).to.not.have.been.called() }) }) describe('on input and Enter', async () => { it('should keep the number in the input', async () => { await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={defaultOnChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '6' } }) expect(input.getDOMNode().value).to.equal('6') await input.keyDown('enter') expect(input.getDOMNode().value).to.equal('6') }) it('should call onChange on successful update', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '6' } }) await input.keyDown('enter') expect(onChange).to.have.been.calledWithMatch(match.object, 5) }) it('should set MAX value on too big number', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '20' } }) await input.keyDown('enter') expect(input.getDOMNode().value).to.equal('10') expect(onChange).to.have.been.calledWithMatch(match.object, 9) }) it('should set MIN value on too small number', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '0' } }) await input.keyDown('enter') expect(input.getDOMNode().value).to.equal('1') expect(onChange).to.have.been.calledWithMatch(match.object, 0) }) it('should reset current value and not call onChange on empty string', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.change({ target: { value: '' } }) await input.keyDown('enter') expect(input.getDOMNode().value).to.equal('4') expect(onChange).to.have.not.been.called() }) }) describe('on up arrow', async () => { it('should increment value and call onChange', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.keyDown('up') expect(input.getDOMNode().value).to.equal('5') expect(onChange).to.have.been.calledWithMatch(match.object, 4) }) }) describe('on down arrow', async () => { it('should decrement value and call onChange', async () => { const onChange = stub() await mount( <PaginationPageInput numberOfPages={10} currentPageIndex={3} onChange={onChange} screenReaderLabel={defaultSRLabel} label={(numberOfPages) => `of ${numberOfPages}`} /> ) const pageInput = await PaginationPageInputLocator.find() const input = await pageInput.findInput() await input.keyDown('down') expect(input.getDOMNode().value).to.equal('3') expect(onChange).to.have.been.calledWithMatch(match.object, 2) }) }) })
the_stack
import { Compiler } from '@0x/sol-compiler'; import { NameResolver } from '@0x/sol-resolver'; import { PackageJSON } from '@0x/types'; import { logUtils } from '@0x/utils'; import { CompilerOptions } from 'ethereum-types'; import * as fs from 'fs'; import * as _ from 'lodash'; import * as mkdirp from 'mkdirp'; import * as path from 'path'; import * as prettier from 'prettier'; import toSnakeCase = require('to-snake-case'); const SOLIDITY_EXTENSION = '.sol'; const DEFAULT_ARTIFACTS_DIR = 'test/artifacts'; const DEFAULT_CONTRACTS_DIR = 'contracts'; const DEFAULT_WRAPPERS_DIR = 'test/generated-wrappers'; const SRC_ARTIFACTS_TS_FILE_PATH = 'src/artifacts.ts'; const TEST_ARTIFACTS_TS_FILE_PATH = 'test/artifacts.ts'; const SRC_WRAPPERS_TS_FILE_PATH = 'src/wrappers.ts'; const TEST_WRAPPERS_TS_FILE_PATH = 'test/wrappers.ts'; const AUTO_GENERATED_BANNER = `/* * ----------------------------------------------------------------------------- * Warning: This file is auto-generated by contracts-gen. Don't edit manually. * ----------------------------------------------------------------------------- */`; const AUTO_GENERATED_BANNER_FOR_LISTS = `This list is auto-generated by contracts-gen. Don't edit manually.`; const ALL_CONTRACTS_IDENTIFIER = '*'; const GENERATE = 'generate'; const COPY = 'copy'; (async () => { const command = process.argv.pop(); if (command !== GENERATE && command !== COPY) { throw new Error(`Unknown command found: ${command}`); } const compilerJSON = readJSONFile<CompilerOptions>('compiler.json'); const compiler = new Compiler(compilerJSON); const testContracts = compiler.getContractNamesToCompile(); if (!_.isArray(testContracts)) { throw new Error('Unable to run the generator bacause contracts key in compiler.json is not of type array'); } let srcContracts = testContracts; const packageJSON = readJSONFile<PackageJSON>('package.json'); if (packageJSON.config !== undefined && (packageJSON.config as any).publicInterfaceContracts !== undefined) { srcContracts = (packageJSON.config as any).publicInterfaceContracts.split(','); } if (!_.isArray(testContracts)) { throw new Error('Unable to run the generator bacause contracts key in compiler.json is not of type array'); } const testArtifactsDir = compilerJSON.artifactsDir || DEFAULT_ARTIFACTS_DIR; const srcArtifactsDir = convertToTopLevelDir('testArtifactsDir', testArtifactsDir); const testWrappersDir = DEFAULT_WRAPPERS_DIR; const srcWrappersDir = convertToTopLevelDir('testWrappersDir', testWrappersDir); // Make sure all dirs exist, if not, create them mkdirp.sync(testArtifactsDir); mkdirp.sync(srcArtifactsDir); mkdirp.sync(testWrappersDir); mkdirp.sync(srcWrappersDir); if (command === GENERATE) { await regenerateContractPackageAsync( testContracts, srcContracts, testArtifactsDir, srcArtifactsDir, testWrappersDir, srcWrappersDir, ); } else if (command === COPY) { copyOverTestArtifactsAndWrappersToSrc( srcContracts, testArtifactsDir, srcArtifactsDir, testWrappersDir, srcWrappersDir, ); } process.exit(0); })().catch(err => { logUtils.log(err); process.exit(1); }); function copyOverTestArtifactsAndWrappersToSrc( srcContracts: string[], testArtifactsDir: string, srcArtifactsDir: string, testWrappersDir: string, srcWrappersDir: string, ): void { // Copy over artifacts srcContracts.forEach(contract => { const srcPath = `${srcArtifactsDir}/${contract}.json`; mkdirp.sync(srcArtifactsDir); fs.copyFileSync(`${testArtifactsDir}/${contract}.json`, srcPath); }); // Copy over wrappers srcContracts.forEach(contract => { const wrapperFileName = makeOutputFileName(contract); const srcPath = `${srcWrappersDir}/${wrapperFileName}.ts`; mkdirp.sync(srcWrappersDir); fs.copyFileSync(`${testWrappersDir}/${wrapperFileName}.ts`, srcPath); }); } async function regenerateContractPackageAsync( testContracts: string[], srcContracts: string[], testArtifactsDir: string, srcArtifactsDir: string, testWrappersDir: string, srcWrappersDir: string, ): Promise<void> { const compilerJSON = readJSONFile<CompilerOptions>('compiler.json'); const packageDir = process.cwd(); const testContractsDir = compilerJSON.contractsDir || DEFAULT_CONTRACTS_DIR; const prettierConfig = await prettier.resolveConfig(packageDir); generateCompilerJSONContractsList(testContracts, testContractsDir, prettierConfig); generateArtifactsTs(testContracts, testArtifactsDir, TEST_ARTIFACTS_TS_FILE_PATH, prettierConfig); generateArtifactsTs(srcContracts, srcArtifactsDir, SRC_ARTIFACTS_TS_FILE_PATH, prettierConfig); generateWrappersTs(testContracts, testWrappersDir, TEST_WRAPPERS_TS_FILE_PATH, prettierConfig); generateWrappersTs(srcContracts, srcWrappersDir, SRC_WRAPPERS_TS_FILE_PATH, prettierConfig); generateTsConfigJSONFilesList(testContracts, testArtifactsDir, srcContracts, srcArtifactsDir, prettierConfig); generatePackageJSONABIConfig(testContracts, 'abis', testArtifactsDir, prettierConfig); } function convertToTopLevelDir(name: string, aPath: string): string { let finalPath = aPath; const hasDotPrefix = aPath.startsWith('./'); if (hasDotPrefix) { finalPath = aPath.substr(2); } const segments = finalPath.split('/'); if (segments.length === 0) { throw new Error(`Cannot have empty path for ${name}`); } if (segments.length === 1) { return aPath; } segments.shift(); return `${hasDotPrefix ? './' : ''}${segments.join('/')}`; } function generateCompilerJSONContractsList( contracts: string[], contractsDir: string, prettierConfig: prettier.Options | null, ): void { const COMPILER_JSON_FILE_PATH = 'compiler.json'; const compilerJSON = readJSONFile<CompilerOptions>(COMPILER_JSON_FILE_PATH); if (compilerJSON.contracts !== undefined && compilerJSON.contracts !== ALL_CONTRACTS_IDENTIFIER) { compilerJSON.contracts = _.map(contracts, contract => { if (contract.endsWith(SOLIDITY_EXTENSION)) { // If it's already a relative path - NO-OP. return contract; } else { // If it's just a contract name - resolve it and rewrite. return new NameResolver(contractsDir).resolve(contract).path; } }); compilerJSON.contracts = _.sortBy(compilerJSON.contracts); } const compilerJSONString = JSON.stringify(compilerJSON); const formattedCompilerJSON = prettier.format(compilerJSONString, { ...prettierConfig, filepath: COMPILER_JSON_FILE_PATH, }); fs.writeFileSync(COMPILER_JSON_FILE_PATH, formattedCompilerJSON); } function generateArtifactsTs( contracts: string[], artifactsDir: string, artifactsTsFilePath: string, prettierConfig: prettier.Options | null, ): void { const imports = _.map(contracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); const importPath = path.join('..', artifactsDir, `${contractName}.json`); return `import * as ${contractName} from '${importPath}';`; }); const sortedImports = _.sortBy(imports, _import => _import.toLowerCase()); const artifacts = _.map(contracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); if (contractName === 'ZRXToken') { // HACK(albrow): "as any" hack still required here because ZRXToken does not // conform to the v2 artifact type. return `${contractName}: (${contractName} as any) as ContractArtifact,`; } else { return `${contractName}: ${contractName} as ContractArtifact,`; } }); const artifactsTs = ` ${AUTO_GENERATED_BANNER} import { ContractArtifact } from 'ethereum-types'; ${sortedImports.join('\n')} export const artifacts = {${artifacts.join('\n')}}; `; const formattedArtifactsTs = prettier.format(artifactsTs, { ...prettierConfig, filepath: artifactsTsFilePath }); fs.writeFileSync(artifactsTsFilePath, formattedArtifactsTs); } function generateWrappersTs( contracts: string[], wrappersDir: string, wrappersTsFilePath: string, prettierConfig: prettier.Options | null, ): void { const imports = _.map(contracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); const outputFileName = makeOutputFileName(contractName); const exportPath = path.join('..', wrappersDir, outputFileName); return `export * from '${exportPath}';`; }); const sortedImports = _.sortBy(imports); const wrappersTs = ` ${AUTO_GENERATED_BANNER} ${sortedImports.join('\n')} `; const formattedArtifactsTs = prettier.format(wrappersTs, { ...prettierConfig, filepath: wrappersTsFilePath }); fs.writeFileSync(wrappersTsFilePath, formattedArtifactsTs); } function generateTsConfigJSONFilesList( testContracts: string[], testArtifactsDir: string, srcContracts: string[], srcArtifactsDir: string, prettierConfig: prettier.Options | null, ): void { const TS_CONFIG_FILE_PATH = 'tsconfig.json'; const tsConfig = readJSONFile<any>(TS_CONFIG_FILE_PATH); const testFiles = _.map(testContracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); const artifactPath = path.join(testArtifactsDir, `${contractName}.json`); return artifactPath; }); const srcFiles = _.map(srcContracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); const artifactPath = path.join(srcArtifactsDir, `${contractName}.json`); return artifactPath; }); tsConfig.files = [...testFiles, ...srcFiles]; tsConfig.files = _.sortBy(tsConfig.files); const tsConfigString = JSON.stringify(tsConfig); const formattedTsConfig = prettier.format(tsConfigString, { ...prettierConfig, filepath: TS_CONFIG_FILE_PATH }); fs.writeFileSync(TS_CONFIG_FILE_PATH, formattedTsConfig); } function generatePackageJSONABIConfig( contracts: string[], configName: string, artifactsDir: string, prettierConfig: prettier.Options | null, ): void { let packageJSON = readJSONFile<PackageJSON>('package.json'); const contractNames = _.map(contracts, contract => { const contractName = path.basename(contract, SOLIDITY_EXTENSION); return contractName; }); const sortedContractNames = _.sortBy(contractNames); packageJSON = { ...packageJSON, config: { ...packageJSON.config, [`${configName}:comment`]: AUTO_GENERATED_BANNER_FOR_LISTS, [configName]: `${artifactsDir}/@(${sortedContractNames.join('|')}).json`, }, }; const PACKAGE_JSON_FILE_PATH = 'package.json'; const packageJSONString = JSON.stringify(packageJSON); const formattedPackageJSON = prettier.format(packageJSONString, { ...prettierConfig, filepath: PACKAGE_JSON_FILE_PATH, }); fs.writeFileSync(PACKAGE_JSON_FILE_PATH, formattedPackageJSON); } function makeOutputFileName(name: string): string { let fileName = toSnakeCase(name); // HACK: Snake case doesn't make a lot of sense for abbreviated names but we can't reliably detect abbreviations // so we special-case the abbreviations we use. fileName = fileName.replace('z_r_x', 'zrx').replace('e_r_c', 'erc'); return fileName; } function readJSONFile<T>(filePath: string): T { const JSONString = fs.readFileSync(filePath, 'utf8'); const parsed: T = JSON.parse(JSONString); return parsed; }
the_stack
import assert from "assert" import last from "lodash/last" import type { ErrorCode, HasLocation, Namespace, Token, VAttribute, } from "../ast" import { ParseError } from "../ast" import { debug } from "../common/debug" import type { Tokenizer, TokenizerState, TokenType } from "./tokenizer" const DUMMY_PARENT: any = Object.freeze({}) /** * Concatenate token values. * @param text Concatenated text. * @param token The token to concatenate. */ function concat(text: string, token: Token): string { return text + token.value } /** * The type of intermediate tokens. */ export type IntermediateToken = StartTag | EndTag | Text | Mustache /** * The type of start tags. */ export interface StartTag extends HasLocation { type: "StartTag" name: string rawName: string selfClosing: boolean attributes: VAttribute[] } /** * The type of end tags. */ export interface EndTag extends HasLocation { type: "EndTag" name: string } /** * The type of text chunks. */ export interface Text extends HasLocation { type: "Text" value: string } /** * The type of text chunks of an expression container. */ export interface Mustache extends HasLocation { type: "Mustache" value: string startToken: Token endToken: Token } /** * The class to create HTML tokens from ESTree-like tokens which are created by a Tokenizer. */ export class IntermediateTokenizer { private tokenizer: Tokenizer private currentToken: IntermediateToken | null private attribute: VAttribute | null private attributeNames: Set<string> private expressionStartToken: Token | null private expressionTokens: Token[] public readonly tokens: Token[] public readonly comments: Token[] /** * The source code text. */ public get text(): string { return this.tokenizer.text } /** * The parse errors. */ public get errors(): ParseError[] { return this.tokenizer.errors } /** * The current state. */ public get state(): TokenizerState { return this.tokenizer.state } public set state(value: TokenizerState) { this.tokenizer.state = value } /** * The current namespace. */ public get namespace(): Namespace { return this.tokenizer.namespace } public set namespace(value: Namespace) { this.tokenizer.namespace = value } /** * The current flag of expression enabled. */ public get expressionEnabled(): boolean { return this.tokenizer.expressionEnabled } public set expressionEnabled(value: boolean) { this.tokenizer.expressionEnabled = value } /** * Initialize this intermediate tokenizer. * @param tokenizer The tokenizer. */ public constructor(tokenizer: Tokenizer) { this.tokenizer = tokenizer this.currentToken = null this.attribute = null this.attributeNames = new Set<string>() this.expressionStartToken = null this.expressionTokens = [] this.tokens = [] this.comments = [] } /** * Get the next intermediate token. * @returns The intermediate token or null. */ public nextToken(): IntermediateToken | null { let token: Token | null = null let result: IntermediateToken | null = null while (result == null && (token = this.tokenizer.nextToken()) != null) { result = this[token.type as TokenType](token) } if (result == null && token == null && this.currentToken != null) { result = this.commit() } return result } /** * Commit the current token. */ private commit(): IntermediateToken { assert(this.currentToken != null || this.expressionStartToken != null) let token = this.currentToken this.currentToken = null this.attribute = null if (this.expressionStartToken != null) { // VExpressionEnd was not found. // Concatenate the deferred tokens to the committed token. const start = this.expressionStartToken const end = last(this.expressionTokens) || start const value = this.expressionTokens.reduce(concat, start.value) this.expressionStartToken = null this.expressionTokens = [] if (token == null) { token = { type: "Text", range: [start.range[0], end.range[1]], loc: { start: start.loc.start, end: end.loc.end }, value, } } else if (token.type === "Text") { token.range[1] = end.range[1] token.loc.end = end.loc.end token.value += value } else { throw new Error("unreachable") } } return token as IntermediateToken } /** * Report an invalid character error. * @param code The error code. */ private reportParseError(token: HasLocation, code: ErrorCode): void { const error = ParseError.fromCode( code, token.range[0], token.loc.start.line, token.loc.start.column, ) this.errors.push(error) debug("[html] syntax error:", error.message) } /** * Process the given comment token. * @param token The comment token to process. */ private processComment(token: Token): IntermediateToken | null { this.comments.push(token) if (this.currentToken != null && this.currentToken.type === "Text") { return this.commit() } return null } /** * Process the given text token. * @param token The text token to process. */ private processText(token: Token): IntermediateToken | null { this.tokens.push(token) let result: IntermediateToken | null = null if (this.expressionStartToken != null) { // Defer this token until a VExpressionEnd token or a non-text token appear. const lastToken = last(this.expressionTokens) || this.expressionStartToken if (lastToken.range[1] === token.range[0]) { this.expressionTokens.push(token) return null } result = this.commit() } else if (this.currentToken != null) { // Concatenate this token to the current text token. if ( this.currentToken.type === "Text" && this.currentToken.range[1] === token.range[0] ) { this.currentToken.value += token.value this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end return null } result = this.commit() } assert(this.currentToken == null) this.currentToken = { type: "Text", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, value: token.value, } return result } /** * Process a HTMLAssociation token. * @param token The token to process. */ protected HTMLAssociation(token: Token): IntermediateToken | null { this.tokens.push(token) if (this.attribute != null) { this.attribute.range[1] = token.range[1] this.attribute.loc.end = token.loc.end if ( this.currentToken == null || this.currentToken.type !== "StartTag" ) { throw new Error("unreachable") } this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end } return null } /** * Process a HTMLBogusComment token. * @param token The token to process. */ protected HTMLBogusComment(token: Token): IntermediateToken | null { return this.processComment(token) } /** * Process a HTMLCDataText token. * @param token The token to process. */ protected HTMLCDataText(token: Token): IntermediateToken | null { return this.processText(token) } /** * Process a HTMLComment token. * @param token The token to process. */ protected HTMLComment(token: Token): IntermediateToken | null { return this.processComment(token) } /** * Process a HTMLEndTagOpen token. * @param token The token to process. */ protected HTMLEndTagOpen(token: Token): IntermediateToken | null { this.tokens.push(token) let result: IntermediateToken | null = null if (this.currentToken != null || this.expressionStartToken != null) { result = this.commit() } this.currentToken = { type: "EndTag", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, name: token.value, } return result } /** * Process a HTMLIdentifier token. * @param token The token to process. */ protected HTMLIdentifier(token: Token): IntermediateToken | null { this.tokens.push(token) if ( this.currentToken == null || this.currentToken.type === "Text" || this.currentToken.type === "Mustache" ) { throw new Error("unreachable") } if (this.currentToken.type === "EndTag") { this.reportParseError(token, "end-tag-with-attributes") return null } if (this.attributeNames.has(token.value)) { this.reportParseError(token, "duplicate-attribute") } this.attributeNames.add(token.value) this.attribute = { type: "VAttribute", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, parent: DUMMY_PARENT, directive: false, key: { type: "VIdentifier", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, parent: DUMMY_PARENT, name: token.value, rawName: this.text.slice(token.range[0], token.range[1]), }, value: null, } this.attribute.key.parent = this.attribute this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end this.currentToken.attributes.push(this.attribute) return null } /** * Process a HTMLLiteral token. * @param token The token to process. */ protected HTMLLiteral(token: Token): IntermediateToken | null { this.tokens.push(token) if (this.attribute != null) { this.attribute.range[1] = token.range[1] this.attribute.loc.end = token.loc.end this.attribute.value = { type: "VLiteral", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, parent: this.attribute, value: token.value, } if ( this.currentToken == null || this.currentToken.type !== "StartTag" ) { throw new Error("unreachable") } this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end } return null } /** * Process a HTMLRCDataText token. * @param token The token to process. */ protected HTMLRCDataText(token: Token): IntermediateToken | null { return this.processText(token) } /** * Process a HTMLRawText token. * @param token The token to process. */ protected HTMLRawText(token: Token): IntermediateToken | null { return this.processText(token) } /** * Process a HTMLSelfClosingTagClose token. * @param token The token to process. */ protected HTMLSelfClosingTagClose(token: Token): IntermediateToken | null { this.tokens.push(token) if (this.currentToken == null || this.currentToken.type === "Text") { throw new Error("unreachable") } if (this.currentToken.type === "StartTag") { this.currentToken.selfClosing = true } else { this.reportParseError(token, "end-tag-with-trailing-solidus") } this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end return this.commit() } /** * Process a HTMLTagClose token. * @param token The token to process. */ protected HTMLTagClose(token: Token): IntermediateToken | null { this.tokens.push(token) if (this.currentToken == null || this.currentToken.type === "Text") { throw new Error("unreachable") } this.currentToken.range[1] = token.range[1] this.currentToken.loc.end = token.loc.end return this.commit() } /** * Process a HTMLTagOpen token. * @param token The token to process. */ protected HTMLTagOpen(token: Token): IntermediateToken | null { this.tokens.push(token) let result: IntermediateToken | null = null if (this.currentToken != null || this.expressionStartToken != null) { result = this.commit() } this.currentToken = { type: "StartTag", range: [token.range[0], token.range[1]], loc: { start: token.loc.start, end: token.loc.end }, name: token.value, rawName: this.text.slice(token.range[0] + 1, token.range[1]), selfClosing: false, attributes: [], } this.attribute = null this.attributeNames.clear() return result } /** * Process a HTMLText token. * @param token The token to process. */ protected HTMLText(token: Token): IntermediateToken | null { return this.processText(token) } /** * Process a HTMLWhitespace token. * @param token The token to process. */ protected HTMLWhitespace(token: Token): IntermediateToken | null { return this.processText(token) } /** * Process a VExpressionStart token. * @param token The token to process. */ protected VExpressionStart(token: Token): IntermediateToken | null { if (this.expressionStartToken != null) { return this.processText(token) } const separated = this.currentToken != null && this.currentToken.range[1] !== token.range[0] const result = separated ? this.commit() : null this.tokens.push(token) this.expressionStartToken = token return result } /** * Process a VExpressionEnd token. * @param token The token to process. */ protected VExpressionEnd(token: Token): IntermediateToken | null { if (this.expressionStartToken == null) { return this.processText(token) } const start = this.expressionStartToken const end = last(this.expressionTokens) || start // If it's '{{}}', it's handled as a text. if (token.range[0] === start.range[1]) { this.tokens.pop() this.expressionStartToken = null const result = this.processText(start) this.processText(token) return result } // If invalid notation `</>` exists directly before this token, separate it. if (end.range[1] !== token.range[0]) { const result = this.commit() this.processText(token) return result } // Clear state. const value = this.expressionTokens.reduce(concat, "") this.tokens.push(token) this.expressionStartToken = null this.expressionTokens = [] // Create token. const result = this.currentToken != null ? this.commit() : null this.currentToken = { type: "Mustache", range: [start.range[0], token.range[1]], loc: { start: start.loc.start, end: token.loc.end }, value, startToken: start, endToken: token, } return result || this.commit() } }
the_stack
import XGraph from './graph_class'; import { Rule, EventMap } from './rule_class'; import { Metric } from './metric_class'; import { TooltipHandler } from './tooltipHandler'; import { $GF, GFVariables } from 'globals_class'; /** * Class for state of one cell * * @export * @class State */ export class State { mxcell: mxCell; // mxCell State cellId: string; // cell ID in mxcell newcellId: string | undefined; // for inspect mode previousId: string | undefined; // for inspect mode edited: boolean | undefined; // if modified in inspector edit: boolean | undefined; // if modified in inspector xgraph: XGraph; changed = false; matched = false; shapeState: ShapeState; tooltipState: TooltipState; iconState: IconState; eventState: EventState; textState: TextState; linkState: LinkState; variables: GFVariables; status: Map<string, any>; globalLevel = -1; tooltipHandler: TooltipHandler | null = null; originalText: string; /** * Creates an instance of State. * @param {mxCell} mxcell * @param {XGraph} xgraph * @memberof State */ constructor(mxcell: mxCell, xgraph: XGraph) { const trc = $GF.trace.before(this.constructor.name + '.' + 'constructor()'); this.mxcell = mxcell; this.cellId = mxcell.id; this.xgraph = xgraph; this.shapeState = new ShapeState(xgraph, mxcell); this.tooltipState = new TooltipState(xgraph, mxcell); this.iconState = new IconState(xgraph, mxcell); this.eventState = new EventState(xgraph, mxcell); this.textState = new TextState(xgraph, mxcell); this.linkState = new LinkState(xgraph, mxcell); this.variables = $GF.createLocalVars(); this.status = new Map(); this.tooltipHandler = null; this.mxcell.GF_tooltipHandler = null; this.originalText = this.xgraph.getLabelCell(mxcell); trc.after(); } /** * Reset/empty/clear/destroy it * * @returns {this} * @memberof State */ clear(): this { return this; } /** * Call applyState() asynchronously * * @memberof State */ async async_applyState() { // new Promise (this.applyState.bind(this)); this.applyState(); } /** * Define state according to 1 rule and 1 serie without apply display * * @returns {this} * @param {Rule} rule * @param {Metric} metric * @memberof State */ setState(rule: Rule, metric: Metric): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'setState()'); if (!rule.isHidden() && rule.matchMetric(metric)) { let beginPerf = Date.now(); const shapeMaps = rule.getShapeMaps(); const textMaps = rule.getTextMaps(); const linkMaps = rule.getLinkMaps(); const eventMaps = rule.getEventMaps(); const value = rule.getValueForMetric(metric); const FormattedValue = rule.getFormattedValue(value); const level = rule.getThresholdLevel(value); const color = rule.data.gradient && rule.data.type === 'number' ? rule.getColorForValue(value) : rule.getColorForLevel(level); this.variables.set($GF.CONSTANTS.VAR_STR_RULENAME, rule.data.alias); this.variables.set($GF.CONSTANTS.VAR_NUM_VALUE, value); this.variables.set($GF.CONSTANTS.VAR_STR_FORMATED, FormattedValue); this.variables.set($GF.CONSTANTS.VAR_NUM_LEVEL, level); this.variables.set($GF.CONSTANTS.VAR_STR_COLOR, color); // SHAPE let cellProp = this.getCellProp(rule.data.shapeProp); shapeMaps.forEach(shape => { let k = shape.data.style; if (!shape.isHidden() && shape.match(cellProp, rule.data.shapeRegEx)) { let v: any = color; this.matched = true; this.globalLevel = level > this.globalLevel ? level : this.globalLevel; if (shape.toColorize(level)) { this.shapeState.set(k, v, level) && this.status.set(k, v); } // TOOLTIP if (rule.toTooltipize(level)) { k = 'tooltip'; v = true; this.tooltipState.set('tooltip', true, level) && this.status.set(k, v); this.tooltipState.setTooltip(rule, metric, color, FormattedValue); } // ICONS if (rule.toIconize(level)) { k = 'icon'; v = true; this.iconState.set('icon', true, level) && this.status.set(k, v); } } }); // TEXT cellProp = this.getCellProp(rule.data.textProp); textMaps.forEach(text => { const k = 'label'; if (!text.isHidden() && text.match(cellProp, rule.data.textRegEx) && text.toLabelize(level)) { if (text.toLabelize(level)) { this.matched = true; this.globalLevel = level > this.globalLevel ? level : this.globalLevel; const textScoped = this.variables.replaceText(FormattedValue); const v = text.getReplaceText(this.textState.getMatchValue(k), textScoped); this.textState.set(k, v, level) && this.status.set(k, v); } } }); // EVENTS cellProp = this.getCellProp(rule.data.eventProp); eventMaps.forEach(event => { const k = event.data.style; if (!event.isHidden() && event.match(cellProp, rule.data.eventRegEx) && event.toEventable(level)) { if (event.toEventable(level)) { this.matched = true; this.globalLevel = level > this.globalLevel ? level : this.globalLevel; const v = this.variables.eval(event.data.value); this.eventState.set(k, v, level) && this.status.set(k, v); } } }); // LINK cellProp = this.getCellProp(rule.data.linkProp); linkMaps.forEach(link => { const k = 'link'; if (!link.isHidden() && link.match(cellProp, rule.data.linkRegEx)) { if (link.toLinkable(level)) { this.matched = true; this.globalLevel = level > this.globalLevel ? level : this.globalLevel; const v = this.variables.replaceText(link.getLink()); this.linkState.set(k, v, level) && this.status.set(k, v); } } }); if (level >= rule.highestLevel && this.matched) { rule.highestLevel = level; rule.highestValue = value; rule.highestFormattedValue = FormattedValue; rule.highestColor = color; } let endPerf = Date.now(); rule.execTimes += endPerf - beginPerf; } trc.after(); return this; } /** * Restore initial status of state without apply display. * Use applyState() to apply on graph (color, level and text) * * @returns {this} * @memberof State */ unsetState(): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'unsetState()'); this.eventState.unset(); this.textState.unset(); this.linkState.unset(); this.tooltipState.unset(); this.iconState.unset(); this.matched = false; trc.after(); return this; } /** * * * @param {string} prop - id|value * @returns {string|null} return original value of id or label of cell * @memberof State */ getCellProp(prop: gf.TPropertieKey): string | null { if (prop === 'id') { return this.cellId; } if (prop === 'value') { return this.originalText; } return null; } /** * Get the highest/global level * * @returns {number} * @memberof State */ getLevel(): number { return this.globalLevel; } /** * Get Level in text * * @returns {number} * @memberof State */ getTextLevel(): string { return this.globalLevel === -1 ? '' : this.globalLevel.toString(); } /** * Give value of status * * @param {string} key * @returns {string} * @memberof State */ getStatus(key: string): string { let style: string | null | undefined = this.status.get(key); if (style !== undefined && style !== null) { return style; } style = this.xgraph.getStyleCell(this.mxcell, key); if (style === null) { style = ''; } this.status.set(key, style); return style; } /** * Indicate if have a status for this key * * @param {string} key * @memberof State */ haveStatus(key: string): boolean { return this.status.has(key); } /** * Return true if is a shape/vertex * * @returns * @memberof State */ isShape(): boolean { return this.mxcell.isVertex(); } /** * Return true if is a arrow/connector * * @returns * @memberof State */ isConnector(): boolean { return this.mxcell.isEdge(); } /** * Apply new state * * @returns {this} * @memberof State */ applyState(): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'applyState()'); if (this.matched || this.changed) { this.changed = true; this.shapeState.apply(); this.tooltipState.apply(); this.iconState.apply(); this.textState.apply(); this.eventState.apply(); this.linkState.apply(); } trc.after(); return this; } /** * Reset and restore state * * @returns {this} * @memberof State */ reset(): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'reset()'); this.shapeState.reset(); this.tooltipState.reset(); this.iconState.reset(); this.textState.reset(); this.eventState.reset(); this.linkState.reset(); this.variables.clear(); this.status.clear(); this.globalLevel = -1; this.changed = false; trc.after(); return this; } /** * Prepare state for a new rule and serie * * @returns {this} * @memberof State */ prepare(): this { const trc = $GF.trace.before(this.constructor.name + '.' + 'prepare()'); if (this.changed) { this.shapeState.prepare(); this.tooltipState.prepare(); this.iconState.prepare(); this.textState.prepare(); this.eventState.prepare(); this.linkState.prepare(); this.variables.clear(); this.status.clear(); this.globalLevel = -1; this.matched = false; } trc.after(); return this; } /** * Highlight mxcell * * @returns {this} * @memberof State */ highlightCell(): this { this.xgraph.highlightCell(this.mxcell); return this; } /** * Unhighlight mxcell * * @returns {this} * @memberof State */ unhighlightCell(): this { this.xgraph.unhighlightCell(this.mxcell); return this; } } /** * Mother of sub states * * @class GFState */ export class GFState { xgraph: XGraph; mxcell: mxCell; keys: string[] = []; matchedKey: Map<string, boolean> = new Map(); changedKey: Map<string, boolean> = new Map(); originalValue: Map<string, any> = new Map(); matchValue: Map<string, any> = new Map(); static DEFAULTLEVEL: number = -1; // lastValue: Map<string, any> = new Map(); To not apply the same value matchLevel: Map<string, number> = new Map(); constructor(xgraph: XGraph, mxcell: mxCell) { this.xgraph = xgraph; this.mxcell = mxcell; this.init_core(); } /** * Reset/clear/empty/destroy * * @memberof GFState */ clear() { this.keys = []; this.matchedKey.clear(); this.changedKey.clear(); this.originalValue.clear(); this.matchValue.clear(); this.matchLevel.clear(); } init_core() {} addValue(key: string, value: any) { if (!this.hasKey(key)) { // _GF.log.warn('GFState.addValue()', key, 'not found'); this.keys.push(key); } this.originalValue.set(key, value); this.matchValue.set(key, value); // this.lastValue.set(key, value); To not apply the same value this.matchLevel.set(key, GFState.DEFAULTLEVEL); this.matchedKey.set(key, false); this.changedKey.set(key, false); // $GF.log.debug( // 'GFState.addValue from ' + this.constructor.name + ' [' + this.mxcell.id + '] KEY=' + key + ' VALUE=' + value // ); } hasKey(key: string): boolean { return this.keys.includes(key); } getOriginalValue(key: string): any | undefined { if (!this.hasKey(key)) { this.originalValue.set(key, this.default_core(key)); } return this.originalValue.get(key); } getMatchValue(key: string): any | undefined { if (!this.hasKey(key)) { this.matchValue.set(key, this.getOriginalValue(key)); } return this.matchValue.get(key); } /** * Insert key and value if >= level * * @param {string} key * @param {*} value * @param {number} level * @returns {boolean} true if applied * @memberof GFState */ set(key: string, value: any, level: number): boolean { let matchLevel = this.matchLevel.get(key); if (matchLevel === undefined) { const defaultValue = this.default_core(key); this.addValue(key, defaultValue); return this.set(key, value, level); } if (matchLevel <= level) { this.matchLevel.set(key, level); this.matchedKey.set(key, true); this.matchValue.set(key, value); return true; } return false; } apply(key?: string): this { if (key !== undefined) { if (this.isMatched(key)) { $GF.log.debug('GFState.apply from ' + this.constructor.name + ' [' + this.mxcell.id + '] MATCHED KEY=' + key); let value = this.getMatchValue(key); try { this.apply_core(key, value); } catch (error) { $GF.log.error('Error on reset for key ' + key, error); } this.changedKey.set(key, true); this.matchedKey.set(key, false); } else if (this.isChanged(key)) { $GF.log.debug('GFState.apply from ' + this.constructor.name + ' [' + this.mxcell.id + '] CHANGED KEY=' + key); this.reset(key); } } else { this.keys.forEach(key => { this.apply(key); }); } return this; } default_core(key: any): any { return null; } apply_core(key: any, value: any) {} isMatched(key?: string): boolean { if (key !== undefined) { return this.matchedKey.get(key) === true; } let matched = false; this.keys.forEach(key => { matched = this.isMatched(key) || matched; }); return matched; } isChanged(key?: string): boolean { if (key !== undefined) { return this.changedKey.get(key) === true; } let changed = false; this.keys.forEach(key => { changed = this.isChanged(key) ? true : changed; }); return changed; } getLevel(key?: string): number { if (key !== undefined) { let level = this.matchLevel.get(key); return level !== undefined ? level : GFState.DEFAULTLEVEL; } let level = GFState.DEFAULTLEVEL; this.keys.forEach(key => (level = Math.max(this.getLevel(key)))); return level; } unset(key?: string): this { if (key !== undefined) { this.matchValue.set(key, this.originalValue.get(key)); this.matchedKey.set(key, false); this.matchLevel.set(key, -1); } else { this.keys.forEach(key => { this.unset(key); }); } return this; } reset(key?: string): this { if (key !== undefined) { $GF.log.debug('GFState.reset from ' + this.constructor.name + ' [' + this.mxcell.id + '] KEY=' + key); this.unset(key); let value = this.getOriginalValue(key); try { this.reset_core(key, value); } catch (error) { $GF.log.error('Error on reset for key ' + key, error); } this.changedKey.set(key, false); this.matchedKey.set(key, false); } else { this.keys.forEach(key => { this.reset(key); }); } return this; } reset_core(key: any, value: any) {} prepare(): this { if (this.isChanged()) { this.unset(); } return this; } } /** * Event SubState * * @class EventState * @extends {GFState} */ class EventState extends GFState { keys: gf.TStyleEventKeys[] = []; geo: | { x: number; y: number; width: number; height: number; } | undefined = undefined; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init_core(); } init_core() { // this.keys = $GF.CONSTANTS.EVENTMETHODS.map(x => x.value); this.geo = this.xgraph.getSizeCell(this.mxcell); // this.keys.forEach(key => { // const value = this._get(key); // this.addValue(key, value); // }); } default_core(key: gf.TStyleEventKeys): any { return this._get(key); } async apply_core(key: gf.TStyleEventKeys, value: any) { if (value === undefined) { value = null; } this._set(key, value); } async reset_core(key: gf.TStyleEventKeys, value: any) { if (value === undefined) { value = null; } this._set(key, value); } _set(key: gf.TStyleEventKeys, value: any) { if (value === undefined) { value = null; } let beginValue: any = undefined; const toUnset: boolean = this.isChanged(key) && !this.isMatched(key); let className = ''; let newkey: gf.TStyleEventKeys | 'class' = key; if (key.startsWith('class_')) { newkey = 'class'; className = key.substring(6); } switch (newkey) { case 'class': if (toUnset) { this.xgraph.unsetClassCell(this.mxcell, className); } else { this.xgraph.setClassCell(this.mxcell, className); } break; case 'text': value = String(value); this.xgraph.setLabelCell(this.mxcell, value); break; case 'visibility': value = String(value); if (value === '0') { this.xgraph.hideCell(this.mxcell); } else if (value === '1') { this.xgraph.showCell(this.mxcell); } break; case 'fold': value = String(value); if (value === '0') { this.xgraph.collapseCell(this.mxcell); } else if (value === '1') { this.xgraph.expandCell(this.mxcell); } break; case 'height': if (this.geo !== undefined) { let height = Number(value); if (this.isMatched('height')) { let width = this.isMatched('width') ? Number(this.getMatchValue('width')) : undefined; this.xgraph.changeSizeCell(this.mxcell, width, height, this.geo); this.unset('width'); } else { if (!this.isMatched('width')) { this.xgraph.resetSizeCell(this.mxcell, this.geo); this.unset('width'); } } } break; case 'width': if (this.geo !== undefined) { let width = Number(value); if (this.isMatched('width')) { let height = this.isMatched('height') ? Number(this.getMatchValue('height')) : undefined; this.xgraph.changeSizeCell(this.mxcell, width, height, this.geo); this.unset('width'); } else { if (!this.isMatched('height')) { this.xgraph.resetSizeCell(this.mxcell, this.geo); this.unset('height'); } } } break; case 'size': if (this.geo !== undefined) { let percent = Number(value); this.xgraph.resizeCell(this.mxcell, percent, this.geo); } break; case 'barPos': case 'fontSize': case 'opacity': case 'textOpacity': case 'rotation': beginValue = this._get(key); beginValue = beginValue === undefined ? EventMap.getDefaultValue(key) : beginValue; this.xgraph.setStyleAnimCell(this.mxcell, key, value, beginValue); break; case 'blink': if (!!value) { this.xgraph.blinkCell(this.mxcell, value); } else { this.xgraph.unblinkCell(this.mxcell); } break; default: this.xgraph.setStyleCell(this.mxcell, key, value); break; } } _get(key: gf.TStyleEventKeys): any { switch (key) { case 'text': return this.xgraph.getLabelCell(this.mxcell); break; case 'visibility': return this.xgraph.isVisibleCell(this.mxcell) === false ? '0' : '1'; break; case 'height': return this.geo !== undefined ? this.geo.height : undefined; break; case 'width': return this.geo !== undefined ? this.geo.width : undefined; break; case 'size': return 100; break; case 'fold': return this.xgraph.isCollapsedCell(this.mxcell) === true ? '0' : '1'; break; case 'blink': return this.xgraph.geBlinkMxCell(this.mxcell); break; default: return this.xgraph.getStyleCell(this.mxcell, key); break; } } } class TextState extends GFState { // keys: string[] = ['label']; keys: string[] = []; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init_core(); } init_core() { // const value = this.xgraph.getLabelCell(this.mxcell); // this.addValue('label', value); } default_core(key: any): string | null { return this.xgraph.getLabelCell(this.mxcell); } async apply_core(key: string, value: any) { this.xgraph.setLabelCell(this.mxcell, value); } async reset_core(key: string, value: any) { this.xgraph.setLabelCell(this.mxcell, value); } } class LinkState extends GFState { // keys: string[] = ['link']; keys: string[] = []; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init_core(); } init_core() { // const value = this.xgraph.getLink(this.mxcell); // this.addValue('link', value); } default_core(key: any): string | null { return this.xgraph.getLink(this.mxcell); } async apply_core(key: string, value: any) { this.xgraph.addLink(this.mxcell, value); } async reset_core(key: string, value: any) { if (value === undefined || value === null || value.length === 0) { this.xgraph.removeLink(this.mxcell); } else { this.xgraph.addLink(this.mxcell, value); } } } /** * State for shape color * * @class ShapeState * @extends {GFState} */ class ShapeState extends GFState { keys: gf.TStyleColorKeys[] = []; fullStylesString: string | undefined; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init_core(); } init_core() { //$GF.log.info('ShapeState [' + this.mxcell.id + ']'); // this.keys = $GF.CONSTANTS.COLORMETHODS.map(x => x.value); // this.fullStylesString = this.mxcell.getStyle(); // this.keys.forEach(key => { // const value = this.xgraph.getStyleCell(this.mxcell, key); // this.addValue(key, value); // $GF.log.debug('ShapeState [' + this.mxcell.id + '] Add value : ' + key, value); // }); this.mxcell.GF_tooltipHandler = null; } default_core(key: any): string | null { return this.xgraph.getStyleCell(this.mxcell, key); } async apply_core(key: gf.TStyleColorKeys, value: any) { if (value === undefined) { value = null; } this.xgraph.setColorAnimCell(this.mxcell, key, value); } async reset_core(key: gf.TStyleColorKeys, value: any) { if (value === undefined) { value = null; } this.xgraph.setColorAnimCell(this.mxcell, key, value); } } class TooltipState extends GFState { keys: string[] = ['tooltip']; tooltipHandler: TooltipHandler | undefined; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init_core(); } init_core() { this.addValue('tooltip', false); this.tooltipHandler = undefined; this.mxcell.GF_tooltipHandler = null; } async setTooltip(rule: Rule, metric: Metric, color: string, value: string) { let tpColor: string | null = null; let label: string = rule.data.tooltipLabel; if (this.tooltipHandler === null || this.tooltipHandler === undefined) { this.tooltipHandler = new TooltipHandler(this.mxcell); } if (label === null || label.length === 0) { if (rule.data.metricType === 'serie') { label = metric.getName(); } if (rule.data.metricType === 'table') { label = rule.data.column; } } if (rule.data.tooltipColors) { tpColor = color; } // METRIC const metricToolip = this.tooltipHandler .addMetric() .setLabel(label) .setValue(value) .setColor(tpColor) .setDirection(rule.data.tpDirection); // GRAPH if (rule.data.tpGraph) { const graph = metricToolip.addGraph(rule.data.tpGraphType); graph .setColor(tpColor) .setColumn(rule.data.column) .setMetric(metric) .setSize(rule.data.tpGraphSize) .setScaling(rule.data.tpGraphLow, rule.data.tpGraphHigh) .setScale(rule.data.tpGraphScale); } // Date this.tooltipHandler.updateDate(); } apply(key?: string): this { if (key !== undefined && key === 'tooltip') { if (this.isMatched(key) && this.getMatchValue(key) === true) { if (this.tooltipHandler != null && this.tooltipHandler.isChecked()) { this.mxcell.GF_tooltipHandler = this.tooltipHandler; } super.apply(key); } } else { this.keys.forEach(key => { this.apply(key); }); } return this; } prepare(): this { super.prepare(); this.reset(); return this; } reset(key?: string): this { if (key !== undefined && key === 'tooltip') { this.mxcell.GF_tooltipHandler = null; if (this.tooltipHandler) { this.tooltipHandler.destroy(); } this.tooltipHandler = undefined; super.reset(key); } else { this.keys.forEach(key => { this.reset(key); }); } return this; } } class IconState extends GFState { // keys: string[] = ['icon']; keys: string[] = []; constructor(xgraph: XGraph, mxcell: mxCell) { super(xgraph, mxcell); this.init(); } init() { // this.addValue('icon', false); } default_core(key: string): any { return false; } apply_core(key?: string): this { if (key !== undefined && key === 'icon') { if (this.isMatched(key) && this.getMatchValue(key) === true) { if (!this.isChanged(key)) { this.xgraph.addOverlay(`WARNING/ERROR`, this.mxcell); } // super.apply(key); } else if (this.isChanged(key)) { this.reset_core(key); } } else { this.keys.forEach(key => { this.apply_core(key); }); } return this; } reset_core(key?: string): this { if (key !== undefined && key === 'icon') { this.xgraph.removeOverlay(this.mxcell); // super.reset(key); } else { this.keys.forEach(key => { this.reset_core(key); }); } return this; } }
the_stack
import * as Restler from "restler"; import * as http from "http"; export {}; interface RestlerResult { on(eventName: string, listener: (data?: any, response?: http.ServerResponse) => void): RestlerResult; } export type SailthruError = { statusCode: string, error: string, errormsg: string } | null; export interface PurchaseItem { qty: number; title: string; price: number; id: string | number; url: string; tags?: string[] | undefined; vars?: object | undefined; images?: { full?: { url: string } | undefined, thumb?: { url: string } | undefined } | undefined; } export type SailthruResponse = object | string; export type SailthruCallback = (err: SailthruError, response: SailthruResponse) => void; /** * API client version */ export const VERSION: string; export function createSailthruClient(apiKey: string, apiSecret: string, apiUrl?: string): SailthruClient; export function createClient(apiKey: string, apiSecret: string, apiUrl?: string): SailthruClient; export interface SailthruClient { logging: boolean; /** * Enable Logging */ enableLogging(): void; /** * Disable Logging */ disableLogging(): void; /** * Perform an arbitrary API GET request to Sailthru. * @param action the API endpoint to send a request to * @param data provide the API options, as outlined in the GET section of the documentation for that endpoint * @param callback a standard callback function which will be invoked after the API server responds */ apiGet( action: string, data: object, callback: SailthruCallback ): void; /** * Perform an arbitrary API DELETE request to Sailthru. * @param action the API endpoint to send a request to * @param data provide the API options, as outlined in the DELETE section of the documentation for that endpoint * @param callback a standard callback function which will be invoked after the API server responds */ apiDelete( action: string, data: object, callback?: SailthruCallback ): void; /** * Perform an arbitrary API POST request to Sailthru. * @param action the API endpoint to send a request to * @param data provide the API options, as outlined in the POST section of the documentation for that endpoint * @param callback a standard callback function which will be invoked after the API server responds */ apiPost( action: string, data: object, callback: SailthruCallback ): void; /** * Perform an arbitrary API POST request to Sailthru. * @param action the API endpoint to send a request to * @param data provide the API options, as outlined in the POST section of the documentation for that endpoint * @param binary_data_params used to specify file upload details. Should be an array which includes strings, corresponding to fields in the “options” parameter that should be read in as files * @param callback a standard callback function which will be invoked after the API server responds */ apiPost( action: string, data: object, binary_data_params: string[], callback: SailthruCallback ): void | RestlerResult; /** * Perform multipart API POST request to Sailthru * @param action the API endpoint to send a request to * @param data provide the API options, as outlined in the POST section of the documentation for that endpoint * @param binary_data_params used to specify file upload details. Should be an array which includes strings, corresponding to fields in the “options” parameter that should be read in as files * @param callback a standard callback function which will be invoked after the API server responds */ apiPostMultiPart( action: string, data: object, binary_data_param: string[], callback: SailthruCallback ): RestlerResult; /** * Send a single message to email, using the given template. * @param template Name of the template to use as the basis for the message content * @param email valid email address to send the message to * @param callback a standard callback function which will be invoked after the API server responds */ send( template: string, email: string, callback: SailthruCallback ): void; /** * Send a single message to email, using the given template. * @param template Name of the template to use as the basis for the message content * @param email valid email address to send the message to * @param options a Javascript object that can be used to specify any other valid API parameters for the send POST, * the full list is available https://getstarted.sailthru.com/new-for-developers-overview/email-and-user-profiles/send/ * @param callback a standard callback function which will be invoked after the API server responds */ send( template: string, email: string, options: object, callback: SailthruCallback ): void; /** * Send a message to each of the “emails” specified, using the given “template”. * @param template Name of the template to use as the basis for the message content * @param emails valid email addresses to send the message to. This can be either a comma-separated String, or a Javascript Array. * @param callback a standard callback function which will be invoked after the API server responds */ multiSend( template: string, emails: string | string[], callback: SailthruCallback ): void; /** * Send a message to each of the “emails” specified, using the given “template”. * @param template Name of the template to use as the basis for the message content * @param emails valid email addresses to send the message to. This can be either a comma-separated String, or a Javascript Array. * @param options a Javascript object that can be used to specify any other valid API parameters for the send POST, * the full list is available https://getstarted.sailthru.com/new-for-developers-overview/email-and-user-profiles/send/ * @param callback a standard callback function which will be invoked after the API server responds */ multiSend( template: string, emails: string[], options: object, callback: SailthruCallback ): void; /** * Looks up the delivery status of a particular send, by its “send_id”. * @param send_id the send ID which was in the response of a previous send call * @param callback a standard callback function which will be invoked after the API server responds */ getSend( send_id: string, callback: SailthruCallback ): void; /** * Cancels the scheduled send which is identified by “send_id”. Note that you can only cancel sends which were scheduled in the future with the “schedule_time” parameters. * @param send_id the send ID which was in the response of a previous send call * @param callback a standard callback function which will be invoked after the API server responds */ cancelSend( send_id: string, callback: SailthruCallback ): void; /** * Return a user profile by looking up via a Sailthru ID (sid). * @param sid the sailthru id for a given user * @param callback a standard callback function which will be invoked after the API server responds */ getUserBySid( sid: string, callback: SailthruCallback ): void; /** * Return a user profile by looking up via a given key and ID. * @param id the id for a given user * @param key specify which type of key was provided in the “id” parameter * @param callback a standard callback function which will be invoked after the API server responds */ getUserByKey( id: string, key: string, callback: SailthruCallback ): void; /** * Return a user profile by looking up via a given key and ID. * @param id the id for a given user * @param key specify which type of key was provided in the “id” parameter * @param fields specify which fields to return. Options are documented here https://getstarted.sailthru.com/new-for-developers-overview/email-and-user-profiles/user/#fieldstype * @param callback a standard callback function which will be invoked after the API server responds */ getUserByKey( id: string, key: string, fields: object, callback: SailthruCallback ): void; /** * Update a user profile. * @param sid the sailthru id for a given user * @param options provide user API options, as outlined in the user POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ saveUserBySid( sid: string, options: object, callback: SailthruCallback ): void | RestlerResult; /** * Update a user profile. * @param id the id for a given user * @param key specify which type of key was provided in the “id” parameter * @param options provide user API options, as outlined in the user POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ saveUserByKey( id: string, key: string, options: object, callback: SailthruCallback ): void | RestlerResult; /** * Looks up the details about a particular campaign, using blast ID. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ getBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Delete a previously created campaign, by blast ID. This cannot be undone. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ deleteBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Unschedule a previously scheduled campaign, by blast ID. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ unscheduleBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Pause a currently sending created campaign, by blast ID. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ pauseBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Resume a previously paused campaign, by blast ID. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ resumeBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Cancel a campaign which is currently sending, by blast ID. This cannot be undone. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ cancelBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Modify an existing campaign by setting any field. * @param blastId the blast ID which was in the response of a previous blast call * @param callback a standard callback function which will be invoked after the API server responds */ updateBlast( blastId: string | number, callback: SailthruCallback ): void; /** * Modify an existing campaign by setting any field. * @param blastId the blast ID which was in the response of a previous blast call * @param options provide additional blast API options, as outlined in the blast POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ updateBlast( blastId: string | number, options: object, callback: SailthruCallback ): void; /** * Modify an existing campaign by copying data into it from a Template, and then scheduling it. * @param blastId the blast ID which was in the response of a previous blast call * @param template the name of a template to copy from, as the basis for this campaign * @param list the target list for the campaign * @param scheduleTime when the campaign should be sent * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlastFromTemplate( blastId: string | number, template: string, list: string, scheduleTime: string, callback: SailthruCallback ): void; /** * Modify an existing campaign by copying data into it from a Template, and then scheduling it. * @param blastId the blast ID which was in the response of a previous blast call * @param template the name of a template to copy from, as the basis for this campaign * @param list the target list for the campaign * @param scheduleTime when the campaign should be sent * @param options provide additional blast API options, as outlined in the blast POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlastFromTemplate( blastId: string | number, template: string, list: string, scheduleTime: string, options: object, callback: SailthruCallback ): void; /** * Modify an existing campaign by setting any field. * @param blastId the blast ID which was in the response of a previous blast call * @param scheduleTime when the campaign should be sent * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlastFromBlast( blastId: string | number, scheduleTime: string, callback: SailthruCallback ): void; /** * Modify an existing campaign by setting any field. * @param blastId the blast ID which was in the response of a previous blast call * @param scheduleTime when the campaign should be sent * @param options provide additional blast API options, as outlined in the blast POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlastFromBlast( blastId: string | number, scheduleTime: string, options: object, callback: SailthruCallback ): void; /** * Schedule a new campaign. * @param name the name for the campaign, which will be used to identify it in Campaign Reporting * @param list the target list for the campaign * @param scheduleTime when the campaign should be sent * @param fromName the from name for the email campaign * @param fromEmail the from email for the email campaign * @param subject the email subject line for the campaign * @param contentHtml the content of the email body, for the HTML version of the campaign * @param contentText the content of the email body, for the Text version of the campaign * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlast( name: string, list: string, scheduleTime: string, fromName: string, fromEmail: string, subject: string, contentHtml: string, contentText: string, callback: SailthruCallback ): void; /** * Schedule a new campaign. * @param name the name for the campaign, which will be used to identify it in Campaign Reporting * @param list the target list for the campaign * @param scheduleTime when the campaign should be sent * @param fromName the from name for the email campaign * @param fromEmail the from email for the email campaign * @param subject the email subject line for the campaign * @param contentHtml the content of the email body, for the HTML version of the campaign * @param contentText the content of the email body, for the Text version of the campaign * @param options provide additional blast API options, as outlined in the blast POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ scheduleBlast( name: string, list: string, scheduleTime: string, fromName: string, fromEmail: string, subject: string, contentHtml: string, contentText: string, options: object, callback: SailthruCallback ): void; /** * Create or update a template with the given name * @param template the name of the template * @param options any template API options, as outlined in the template POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ saveTemplate( template: string, options: object, callback: SailthruCallback ): void; /** * Revert a template to one of its previous revisions. * @param template the name of the template * @param revision_id a revision_id of the template * @param callback a standard callback function which will be invoked after the API server responds */ saveTemplateFromRevision( template: string, revision_id: string, callback: SailthruCallback ): void; /** * Delete a template from your account. This cannot be undone. * @param template the name of the template * @param callbacka standard callback function which will be invoked after the API server responds */ deleteTemplate( template: string, callback: SailthruCallback ): void; /** * Return a list of all the lists in your account. * @param callback a standard callback function which will be invoked after the API server responds */ getLists( callback: SailthruCallback ): void; /** * Delete a list from your account, and remove all record of it from your user profiles. This cannot be undone. * @param list the name of an existing list in your account * @param callback a standard callback function which will be invoked after the API server responds */ deleteList( list: string, callback: SailthruCallback ): void; /** * Create a new content item. * @param title the name of the content item being created * @param url the URL of the content item, which will be used as its unique identifier * @param callback a standard callback function which will be invoked after the API server responds */ pushContent( title: string, url: string, callback: SailthruCallback ): void; /** * Create a new content item. * @param title the name of the content item being created * @param url the URL of the content item, which will be used as its unique identifier * @param options provide additional content API options, as outlined in the content POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ pushContent( title: string, url: string, options: object, callback: SailthruCallback ): void; /** * Record a purchase into the Sailthru system. * @param email the email of the user who made the purchase * @param items a description of what items the user purchased. See the examples on the main Purchase API page * @param callback a standard callback function which will be invoked after the API server responds */ purchase( email: string, items: PurchaseItem[], callback: SailthruCallback ): void; /** * Record a purchase into the Sailthru system. * @param email the email of the user who made the purchase * @param items a description of what items the user purchased. See the examples on the main Purchase API page * @param options provide additional purchase API options, as outlined in the purchase POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ purchase( email: string, items: PurchaseItem[], options: object, callback: SailthruCallback ): void; /** * Fetch stats for any part of Sailthru. * @param data provide stats API options, as outlined in the stats GET documentation * @param callback a standard callback function which will be invoked after the API server responds */ stats( data: object, callback: SailthruCallback ): void; /** * Fetch stats for a List within Sailthru. * @param options provide stats API options, as outlined in the stats GET documentation * @param callback a standard callback function which will be invoked after the API server responds */ statsList( options: object, callback: SailthruCallback ): void; /** * Fetch stats for a campaign send, or aggregate campaign data over a time period. * @param options provide stats API options, as outlined in the stats GET documentation * @param callback a standard callback function which will be invoked after the API server responds */ statsBlast( options: object, callback: SailthruCallback ): void; /** * Fetch the status of a job * @param job the job ID which was returned from a previous job POST * @param callback a standard callback function which will be invoked after the API server responds */ getJobStatus( job: string, callback: SailthruCallback ): void; /** * Create a new job with specific options. * @param job the name of the job to create * @param callback a standard callback function which will be invoked after the API server responds */ processJob( job: string, callback: SailthruCallback ): void; /** * Create a new job with specific options. * @param job the name of the job to create * @param options provide additional job API options, as outlined in the job POST documentation * @param callback a standard callback function which will be invoked after the API server responds */ processJob( job: string, options: object, callback: SailthruCallback ): void; /** * Create a new job with specific options. * @param job the name of the job to create * @param options provide additional job API options, as outlined in the job POST documentation * @param report_email the email address that will be emailed when the job completes or fails * @param callback a standard callback function which will be invoked after the API server responds */ processJob( job: string, options: object, report_email: string, callback: SailthruCallback ): void; /** * Create a new job with specific options. * @param job the name of the job to create * @param options provide additional job API options, as outlined in the job POST documentation * @param report_email the email address that will be emailed when the job completes or fails * @param postback_url the URL which will receive postback data when the job completes or fails * @param callback a standard callback function which will be invoked after the API server responds */ processJob( job: string, options: object, report_email: string, postback_url: string, callback: SailthruCallback ): void; /** * Create a new job with specific options. * @param job the name of the job to create * @param options provide additional job API options, as outlined in the job POST documentation * @param report_email the email address that will be emailed when the job completes or fails * @param postback_url the URL which will receive postback data when the job completes or fails * @param binary_data_params used to specify file upload details. Should be an array which includes strings, corresponding to fields in the “options” parameter that should be read in as files. * @param callback a standard callback function which will be invoked after the API server responds */ processJob( job: string, options: object, report_email: string, postback_url: string, binary_data_params: string[], callback: SailthruCallback ): void; receiveOptoutPost(): void; /** * Retrieve the last known rate limit information for the given action / method combination * @param action API action to get rate limit information * @param method API method to get rate limit information */ getLastRateLimitInfo(action: string, method: string): { limit: number, remaining: number, reset: number }; }
the_stack
import * as fs from "fs-extra"; import path = require("path"); import glob = require("glob"); import { promisify } from "util"; import { WorkspaceConfig } from "./../../../global-types.js"; import { WorkspaceConfigProvider } from "./workspace-config-provider.js"; import * as contentFormats from "./../../content-formats"; import formatProviderResolver from "../../format-provider-resolver.js"; const workspaceConfigProvider = new WorkspaceConfigProvider(); import { globJob, createThumbnailJob } from "./../../jobs"; import HugoBuilder from "../../hugo/hugo-builder.js"; import pathHelper from "../../path-helper.js"; import HugoServer from "../../hugo/hugo-server.js"; import { appEventEmitter } from "../../app-event-emmiter.js"; import { hugoDownloader } from "../../hugo/hugo-downloader.js"; class WorkspaceService { workspacePath: string; workspaceKey: string; siteKey: string; constructor(workspacePath: string, workspaceKey: string, siteKey: string) { this.workspacePath = workspacePath; this.workspaceKey = workspaceKey; this.siteKey = siteKey; } //Get the workspace configurations data to be used by the client getConfigurationsData(): Promise<WorkspaceConfig> { return workspaceConfigProvider.getConfig(this.workspacePath, this.workspaceKey); } async _smartResolveFormatProvider(filePath: string, fallbacks: Array<string>) { let formatProvider; if (contentFormats.isContentFile(filePath)) { if (fs.existsSync(filePath)) formatProvider = await formatProviderResolver.resolveForMdFilePromise(filePath); } else formatProvider = formatProviderResolver.resolveForFilePath(filePath); if (formatProvider) return formatProvider; if (fallbacks) { for (let i = 0; i < fallbacks.length; i++) { if (fallbacks[i]) { formatProvider = formatProviderResolver.resolveForExtension(fallbacks[i]); if (formatProvider) return formatProvider; } } } return undefined; } async _smartDump(filePath: string, formatFallbacks: Array<string>, obj: any) { let formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks); if (formatProvider === undefined) formatProvider = formatProviderResolver.getDefaultFormat(); if (contentFormats.isContentFile(filePath)) { return formatProvider.dumpContent(obj); } else { return formatProvider.dump(obj); } } async _smartParse(filePath: string, formatFallbacks: Array<string>, str: string) { if (str === undefined || str === null || str.length === 0 || !/\S$/gi) { return {}; } let formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks); if (formatProvider === undefined) throw new Error("Could not resolve a FormatProvider to parse."); if (contentFormats.isContentFile(filePath)) { return formatProvider.parseFromMdFileString(str); } else { return formatProvider.parse(str); } } async getSingle(singleKey: string) { let config = await this.getConfigurationsData(); let single = config.singles.find(x => x.key === singleKey); if (single == null) throw new Error("Could not find single."); let filePath = path.join(this.workspacePath, single.file); let doc: any; if (fs.existsSync(filePath)) { const dataStr = fs.readFileSync(filePath, "utf8"); doc = await this._smartParse(filePath, [path.extname(single.file).replace(".", "")], dataStr); } else { doc = {}; } if (contentFormats.isContentFile(filePath)) { doc.resources = await this.getResourcesFromContent(filePath, doc.resources); } return doc; } //Update the single async updateSingle(singleKey: string, document: any) { let config = await this.getConfigurationsData(); let single = config.singles.find(x => x.key === singleKey); if (single == null) throw new Error("Could not find single."); let filePath = path.join(this.workspacePath, single.file); let directory = path.dirname(filePath); if (!fs.existsSync(directory)) fs.mkdirSync(directory); //ensure directory existence let documentClone = JSON.parse(JSON.stringify(document)); this._stripNonDocumentData(documentClone); let stringData = await this._smartDump(filePath, [path.extname(single.file).replace(".", "")], documentClone); fs.writeFileSync(filePath, stringData); appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: [filePath] }); //preparing return if (document.resources) { for (let r = 0; r < document.resources.length; r++) { let resource = document.resources[r]; if (resource.$_deleted) { let fullSrc = path.join(directory, resource.src); await fs.remove(fullSrc); } } document.resources = document.resources.filter((x: any) => x.$_deleted !== true); } return document; } async getResourcesFromContent(filePath: string, currentResources: Array<any> = []) { filePath = path.normalize(filePath); let directory = path.dirname(filePath); let globExp = "**/*"; let allFiles = await promisify(glob)(globExp, { nodir: true, absolute: false, root: directory, cwd: directory }); let expression = `_?index[.](${contentFormats.SUPPORTED_CONTENT_EXTENSIONS.join("|")})$`; let pageOrSectionIndexReg = new RegExp(expression); allFiles = allFiles.filter((x: any) => !pageOrSectionIndexReg.test(x)); let merged = allFiles.map((src: any) => { return Object.assign( { src }, currentResources.find(r => r.src === src) ); }); return merged; } async getCollectionItem(collectionKey: string, collectionItemKey: string) { let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let filePath = path.join(this.workspacePath, collection.folder, collectionItemKey); if (fs.existsSync(filePath)) { let data = await fs.readFile(filePath, { encoding: "utf8" }); let obj = await this._smartParse(filePath, [collection.extension], data); if (contentFormats.isContentFile(filePath)) { obj.resources = await this.getResourcesFromContent(filePath, obj.resources); } return obj; } else { return undefined; } } async createCollectionItemKey(collectionKey: string, collectionItemKey: string) { let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let filePath; let returnedKey; const isContentFile = collection.folder.startsWith("content"); if (isContentFile) { returnedKey = path.join(collectionItemKey, "index." + collection.extension); filePath = path.join(this.workspacePath, collection.folder, returnedKey); } else { returnedKey = collectionItemKey + "." + collection.extension; filePath = path.join(this.workspacePath, collection.folder, returnedKey); } if (fs.existsSync(filePath)) return { unavailableReason: "already-exists" }; await fs.ensureDir(path.dirname(filePath)); const initialContent = isContentFile ? { draft: true } : {}; let stringData = await this._smartDump(filePath, [collection.dataformat], initialContent); await fs.writeFile(filePath, stringData, { encoding: "utf8" }); appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: [filePath] }); return { key: returnedKey.replace(/\\/g, "/") }; } async listCollectionItems(collectionKey: string) { let collection = (await this.getConfigurationsData()).collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let folder = path.join(this.workspacePath, collection.folder).replace(/\\/g, "/"); // TODO: make it more flexible! This should not be handled with IF ELSE. // But is good enough for now. let supportedContentExt = ["md", "html", "markdown"]; if (collection.folder.startsWith("content") || supportedContentExt.indexOf(collection.extension) !== -1) { let globExpression = path.join(folder, `**/index.{${supportedContentExt.join(",")}}`); let files = await globJob(globExpression, {}); return files.map((item: any) => { let key = item.replace(folder, "").replace(/^\//, ""); let label = key.replace(/^\/?(.+)\/[^\/]+$/, "$1"); return { key, label }; }); } else { //data folder and everything else let globExpression = path.join(folder, `**/*.{${formatProviderResolver.allFormatsExt().join(",")}}`); let files = await globJob(globExpression, {}); return files.map((item: any) => { let key = item.replace(folder, ""); return { key, label: key }; }); } } _stripNonDocumentData(document: any) { for (var key in document) { if (key.startsWith("$_")) { delete document[key]; } if (document.resources) { document.resources = document.resources.filter((x: any) => x.$_deleted == true); document.resources.forEach((x: any) => delete x.$_deleted); } } } async renameCollectionItem(collectionKey: string, collectionItemKey: string, collectionItemNewKey: string) { let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let filePath; let newFilePath; let newFileKey; if (collection.folder.startsWith("content")) { filePath = path.join(this.workspacePath, collection.folder, collectionItemKey); newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey); newFileKey = path.join(collectionItemNewKey, "index." + collection.extension); } else { filePath = path.join(this.workspacePath, collection.folder, collectionItemKey + collection.extension); newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey + collection.extension); newFileKey = path.join(collectionItemNewKey + "." + collection.extension); } if (!fs.existsSync(filePath)) { return { renamed: false }; } if (fs.existsSync(newFilePath)) { return { renamed: false }; } fs.renameSync(filePath, newFilePath); appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: [filePath, newFilePath] }); return { renamed: true, item: { key: newFileKey.replace(/\\/g, "/"), label: collectionItemNewKey } }; } async deleteCollectionItem(collectionKey: string, collectionItemKey: string) { //TODO: only work with "label" of a collection item let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let filePath = path.join(this.workspacePath, collection.folder, collectionItemKey); if (fs.existsSync(filePath)) { //TODO: use async await with a promise to test if deletion succeded fs.unlink(filePath); appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: [filePath] }); return true; } return false; } async updateCollectionItem(collectionKey: string, collectionItemKey: string, document: any) { //TODO: only work with "label" of a collection item let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let filePath = path.join(this.workspacePath, collection.folder, collectionItemKey); let directory = path.dirname(filePath); if (!fs.existsSync(directory)) fs.mkdirSync(directory); //ensure directory existence let documentClone = JSON.parse(JSON.stringify(document)); this._stripNonDocumentData(documentClone); let stringData = await this._smartDump(filePath, [collection.dataformat], documentClone); fs.writeFileSync(filePath, stringData); appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: [filePath] }); //preparing return if (document.resources) { for (let r = 0; r < document.resources.length; r++) { let resource = document.resources[r]; if (resource.$_deleted) { let fullSrc = path.join(directory, resource.src); await fs.remove(fullSrc); } } document.resources = document.resources.filter((x: any) => x.$_deleted !== true); } return document; } async getWorkspaceConfig(): Promise<any> { let globExpression = path.join(this.workspacePath, `/hokus.{${formatProviderResolver.allFormatsExt().join(",")}}`); const files = glob.sync(globExpression); if (files.length) { const file = files[0]; const configStr = await fs.readFile(file, "utf-8"); const data = formatProviderResolver.resolveForFilePath(file)?.parse(configStr); const { collections, singles, hugover } = data; return { collections, singles, hugover }; } return {}; } async setWorkspaceConfig(data: any): Promise<void> { const globExpression = path.join( this.workspacePath, `/hokus.{${formatProviderResolver.allFormatsExt().join(",")}}` ); const files = glob.sync(globExpression); let configFile = "hugo.toml"; let existentData = {}; if (files.length) { configFile = files[0]; const configStr = await fs.readFile(configFile, "utf-8"); existentData = formatProviderResolver.resolveForFilePath(configFile)?.parse(configStr); } const { collections, singles, hugover } = data; const updatedData = { ...existentData, hugover: hugover, collections: collections, singles: singles }; const dump = formatProviderResolver.resolveForFilePath(configFile)?.dump(updatedData); fs.writeFile(configFile, dump, "utf-8"); } async copyFilesIntoSingle(singleKey: string, targetPath: string, files: Array<string>) { let config = await this.getConfigurationsData(); let single = config.singles.find(x => x.key === singleKey); if (single == null) throw new Error("Could not find single."); const indexMatcher = /\/_?index[.](md|markdown|html)$/; if (!indexMatcher.test(single.file)) { throw new Error("The current single does not support bundling."); } let filesBasePath = path.join(this.workspacePath, single.file.replace(indexMatcher, ""), targetPath); for (let i = 0; i < files.length; i++) { let file = files[i]; let from = file; let to = path.join(filesBasePath, path.basename(file)); let toExists = fs.existsSync(to); if (toExists) { fs.unlinkSync(to); } await fs.copy(from, to); } if (files.length > 0) { appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: files }); } return files.map(x => { return path.join(targetPath, path.basename(x)).replace(/\\/g, "/"); }); } async copyFilesIntoCollectionItem( collectionKey: string, collectionItemKey: string, targetPath: string, files: Array<string> ) { let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let pathFromItemRoot = path.join(collectionItemKey.replace(/\/[^\/]+$/, ""), targetPath); let filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot); for (let i = 0; i < files.length; i++) { let file = files[i]; let from = file; let to = path.join(filesBasePath, path.basename(file)); let toExists = fs.existsSync(to); if (toExists) { fs.unlinkSync(to); } await fs.copy(from, to); } if (files.length > 0) { appEventEmitter.emit("onWorkspaceFileChanged", { siteKey: this.siteKey, workspaceKey: this.workspaceKey, files: files }); } return files.map(x => { return path.join(targetPath, path.basename(x)).replace(/\\/g, "/"); }); } existsPromise(src: string) { return new Promise(resolve => { fs.exists(src, (exists: boolean) => { resolve(exists); }); }); } async getThumbnailForCollectionItemImage(collectionKey: string, collectionItemKey: string, targetPath: string) { let config = await this.getConfigurationsData(); let collection = config.collections.find(x => x.key === collectionKey); if (collection == null) throw new Error("Could not find collection."); let itemPath = collectionItemKey.replace(/\/[^\/]+$/, ""); let src = path.join(this.workspacePath, collection.folder, itemPath, targetPath); let srcExists = await this.existsPromise(src); if (!srcExists) { return "NOT_FOUND"; } let thumbSrc = path.join(this.workspacePath, ".hokus/thumbs", collection.folder, itemPath, targetPath); let thumbSrcExists = await this.existsPromise(thumbSrc); if (!thumbSrcExists) { try { await createThumbnailJob(src, thumbSrc); } catch (e) { return "NOT_FOUND"; } } let ext = path.extname(thumbSrc).replace(".", ""); let mime = `image/${ext}`; let buffer: any = await promisify(fs.readFile)(thumbSrc); let base64 = buffer.toString("base64"); return `data:${mime};base64,${base64}`; } async getThumbnailForSingleImage(singleKey: string, targetPath: string) { let config = await this.getConfigurationsData(); let single = config.singles.find(x => x.key === singleKey); if (single == null) throw new Error("Could not find collection."); const indexMatcher = /\/_?index[.](md|markdown|html)$/; if (!indexMatcher.test(single.file)) { throw new Error("The current single does not support bundling."); } const singleFolder = single.file.replace(indexMatcher, ""); let src = path.join(this.workspacePath, singleFolder, targetPath); let srcExists = await this.existsPromise(src); if (!srcExists) { return "NOT_FOUND"; } let thumbSrc = path.join(this.workspacePath, ".hokus/thumbs", singleFolder, targetPath); let thumbSrcExists = await this.existsPromise(thumbSrc); if (!thumbSrcExists) { try { await createThumbnailJob(src, thumbSrc); } catch (e) { return "NOT_FOUND"; } } let ext = path.extname(thumbSrc).replace(".", ""); let mime = `image/${ext}`; let buffer: any = await promisify(fs.readFile)(thumbSrc); let base64 = buffer.toString("base64"); return `data:${mime};base64,${base64}`; } _findFirstMatchOrDefault<T extends any>(arr: Array<T>, key: string): T { let result; if (key) { result = (arr || []).find(x => x.key === key); if (result) return result; } result = (arr || []).find(x => x.key === "default" || x.key === "" || x.key == null); if (result) return result; if (arr !== undefined && arr.length === 1) return arr[0]; if (key) { throw new Error(`Could not find a config for key "${key}" and a default value was not available.`); } else { throw new Error(`Could not find a default config.`); } } async serve(serveKey: string): Promise<void> { let workspaceDetails = await this.getConfigurationsData(); await hugoDownloader.download(workspaceDetails.hugover); let serveConfig; if (workspaceDetails.serve && workspaceDetails.serve.length) { serveConfig = this._findFirstMatchOrDefault(workspaceDetails.serve, ""); } else serveConfig = { config: "" }; let hugoServerConfig = { config: serveConfig.config, workspacePath: this.workspacePath, hugover: workspaceDetails.hugover }; let hugoServer = new HugoServer(JSON.parse(JSON.stringify(hugoServerConfig))); await hugoServer.serve(); } async build(buildKey: string): Promise<void> { let workspaceDetails = await this.getConfigurationsData(); return new Promise((resolve, reject) => { let buildConfig; if (workspaceDetails.build && workspaceDetails.build.length) { buildConfig = this._findFirstMatchOrDefault(workspaceDetails.build, buildKey); } else buildConfig = { config: "" }; let destination = pathHelper.getBuildDir(this.siteKey, this.workspaceKey, buildKey); let hugoBuilderConfig = { config: buildConfig.config, workspacePath: this.workspacePath, hugover: workspaceDetails.hugover, destination: destination }; let hugoBuilder = new HugoBuilder(hugoBuilderConfig); hugoBuilder.build().then( () => resolve(), (err: any) => reject(err) ); }); } } export default WorkspaceService;
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a Load Balancer Rule. * * > **NOTE** When using this resource, the Load Balancer needs to have a FrontEnd IP Configuration Attached * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const examplePublicIp = new azure.network.PublicIp("examplePublicIp", { * location: "West US", * resourceGroupName: exampleResourceGroup.name, * allocationMethod: "Static", * }); * const exampleLoadBalancer = new azure.lb.LoadBalancer("exampleLoadBalancer", { * location: "West US", * resourceGroupName: exampleResourceGroup.name, * frontendIpConfigurations: [{ * name: "PublicIPAddress", * publicIpAddressId: examplePublicIp.id, * }], * }); * const exampleRule = new azure.lb.Rule("exampleRule", { * resourceGroupName: exampleResourceGroup.name, * loadbalancerId: exampleLoadBalancer.id, * protocol: "Tcp", * frontendPort: 3389, * backendPort: 3389, * frontendIpConfigurationName: "PublicIPAddress", * }); * ``` * * ## Import * * Load Balancer Rules can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:lb/rule:Rule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Network/loadBalancers/lb1/loadBalancingRules/rule1 * ``` */ export class Rule extends pulumi.CustomResource { /** * Get an existing Rule resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: RuleState, opts?: pulumi.CustomResourceOptions): Rule { return new Rule(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:lb/rule:Rule'; /** * Returns true if the given object is an instance of Rule. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Rule { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Rule.__pulumiType; } /** * @deprecated This property has been deprecated by `backend_address_pool_ids` and will be removed in the next major version of the provider */ public readonly backendAddressPoolId!: pulumi.Output<string>; /** * A list of reference to a Backend Address Pool over which this Load Balancing Rule operates. */ public readonly backendAddressPoolIds!: pulumi.Output<string[]>; /** * The port used for internal connections on the endpoint. Possible values range between 0 and 65535, inclusive. */ public readonly backendPort!: pulumi.Output<number>; /** * Is snat enabled for this Load Balancer Rule? Default `false`. */ public readonly disableOutboundSnat!: pulumi.Output<boolean | undefined>; /** * Are the Floating IPs enabled for this Load Balncer Rule? A "floating” IP is reassigned to a secondary server in case the primary server fails. Required to configure a SQL AlwaysOn Availability Group. Defaults to `false`. */ public readonly enableFloatingIp!: pulumi.Output<boolean | undefined>; /** * Is TCP Reset enabled for this Load Balancer Rule? Defaults to `false`. */ public readonly enableTcpReset!: pulumi.Output<boolean | undefined>; public /*out*/ readonly frontendIpConfigurationId!: pulumi.Output<string>; /** * The name of the frontend IP configuration to which the rule is associated. */ public readonly frontendIpConfigurationName!: pulumi.Output<string>; /** * The port for the external endpoint. Port numbers for each Rule must be unique within the Load Balancer. Possible values range between 0 and 65534, inclusive. */ public readonly frontendPort!: pulumi.Output<number>; /** * Specifies the idle timeout in minutes for TCP connections. Valid values are between `4` and `30` minutes. Defaults to `4` minutes. */ public readonly idleTimeoutInMinutes!: pulumi.Output<number>; /** * Specifies the load balancing distribution type to be used by the Load Balancer. Possible values are: `Default` – The load balancer is configured to use a 5 tuple hash to map traffic to available servers. `SourceIP` – The load balancer is configured to use a 2 tuple hash to map traffic to available servers. `SourceIPProtocol` – The load balancer is configured to use a 3 tuple hash to map traffic to available servers. Also known as Session Persistence, where the options are called `None`, `Client IP` and `Client IP and Protocol` respectively. */ public readonly loadDistribution!: pulumi.Output<string>; /** * The ID of the Load Balancer in which to create the Rule. */ public readonly loadbalancerId!: pulumi.Output<string>; /** * Specifies the name of the LB Rule. */ public readonly name!: pulumi.Output<string>; /** * A reference to a Probe used by this Load Balancing Rule. */ public readonly probeId!: pulumi.Output<string>; /** * The transport protocol for the external endpoint. Possible values are `Tcp`, `Udp` or `All`. */ public readonly protocol!: pulumi.Output<string>; /** * The name of the resource group in which to create the resource. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * Create a Rule resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: RuleArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: RuleArgs | RuleState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as RuleState | undefined; inputs["backendAddressPoolId"] = state ? state.backendAddressPoolId : undefined; inputs["backendAddressPoolIds"] = state ? state.backendAddressPoolIds : undefined; inputs["backendPort"] = state ? state.backendPort : undefined; inputs["disableOutboundSnat"] = state ? state.disableOutboundSnat : undefined; inputs["enableFloatingIp"] = state ? state.enableFloatingIp : undefined; inputs["enableTcpReset"] = state ? state.enableTcpReset : undefined; inputs["frontendIpConfigurationId"] = state ? state.frontendIpConfigurationId : undefined; inputs["frontendIpConfigurationName"] = state ? state.frontendIpConfigurationName : undefined; inputs["frontendPort"] = state ? state.frontendPort : undefined; inputs["idleTimeoutInMinutes"] = state ? state.idleTimeoutInMinutes : undefined; inputs["loadDistribution"] = state ? state.loadDistribution : undefined; inputs["loadbalancerId"] = state ? state.loadbalancerId : undefined; inputs["name"] = state ? state.name : undefined; inputs["probeId"] = state ? state.probeId : undefined; inputs["protocol"] = state ? state.protocol : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; } else { const args = argsOrState as RuleArgs | undefined; if ((!args || args.backendPort === undefined) && !opts.urn) { throw new Error("Missing required property 'backendPort'"); } if ((!args || args.frontendIpConfigurationName === undefined) && !opts.urn) { throw new Error("Missing required property 'frontendIpConfigurationName'"); } if ((!args || args.frontendPort === undefined) && !opts.urn) { throw new Error("Missing required property 'frontendPort'"); } if ((!args || args.loadbalancerId === undefined) && !opts.urn) { throw new Error("Missing required property 'loadbalancerId'"); } if ((!args || args.protocol === undefined) && !opts.urn) { throw new Error("Missing required property 'protocol'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["backendAddressPoolId"] = args ? args.backendAddressPoolId : undefined; inputs["backendAddressPoolIds"] = args ? args.backendAddressPoolIds : undefined; inputs["backendPort"] = args ? args.backendPort : undefined; inputs["disableOutboundSnat"] = args ? args.disableOutboundSnat : undefined; inputs["enableFloatingIp"] = args ? args.enableFloatingIp : undefined; inputs["enableTcpReset"] = args ? args.enableTcpReset : undefined; inputs["frontendIpConfigurationName"] = args ? args.frontendIpConfigurationName : undefined; inputs["frontendPort"] = args ? args.frontendPort : undefined; inputs["idleTimeoutInMinutes"] = args ? args.idleTimeoutInMinutes : undefined; inputs["loadDistribution"] = args ? args.loadDistribution : undefined; inputs["loadbalancerId"] = args ? args.loadbalancerId : undefined; inputs["name"] = args ? args.name : undefined; inputs["probeId"] = args ? args.probeId : undefined; inputs["protocol"] = args ? args.protocol : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["frontendIpConfigurationId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Rule.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Rule resources. */ export interface RuleState { /** * @deprecated This property has been deprecated by `backend_address_pool_ids` and will be removed in the next major version of the provider */ backendAddressPoolId?: pulumi.Input<string>; /** * A list of reference to a Backend Address Pool over which this Load Balancing Rule operates. */ backendAddressPoolIds?: pulumi.Input<pulumi.Input<string>[]>; /** * The port used for internal connections on the endpoint. Possible values range between 0 and 65535, inclusive. */ backendPort?: pulumi.Input<number>; /** * Is snat enabled for this Load Balancer Rule? Default `false`. */ disableOutboundSnat?: pulumi.Input<boolean>; /** * Are the Floating IPs enabled for this Load Balncer Rule? A "floating” IP is reassigned to a secondary server in case the primary server fails. Required to configure a SQL AlwaysOn Availability Group. Defaults to `false`. */ enableFloatingIp?: pulumi.Input<boolean>; /** * Is TCP Reset enabled for this Load Balancer Rule? Defaults to `false`. */ enableTcpReset?: pulumi.Input<boolean>; frontendIpConfigurationId?: pulumi.Input<string>; /** * The name of the frontend IP configuration to which the rule is associated. */ frontendIpConfigurationName?: pulumi.Input<string>; /** * The port for the external endpoint. Port numbers for each Rule must be unique within the Load Balancer. Possible values range between 0 and 65534, inclusive. */ frontendPort?: pulumi.Input<number>; /** * Specifies the idle timeout in minutes for TCP connections. Valid values are between `4` and `30` minutes. Defaults to `4` minutes. */ idleTimeoutInMinutes?: pulumi.Input<number>; /** * Specifies the load balancing distribution type to be used by the Load Balancer. Possible values are: `Default` – The load balancer is configured to use a 5 tuple hash to map traffic to available servers. `SourceIP` – The load balancer is configured to use a 2 tuple hash to map traffic to available servers. `SourceIPProtocol` – The load balancer is configured to use a 3 tuple hash to map traffic to available servers. Also known as Session Persistence, where the options are called `None`, `Client IP` and `Client IP and Protocol` respectively. */ loadDistribution?: pulumi.Input<string>; /** * The ID of the Load Balancer in which to create the Rule. */ loadbalancerId?: pulumi.Input<string>; /** * Specifies the name of the LB Rule. */ name?: pulumi.Input<string>; /** * A reference to a Probe used by this Load Balancing Rule. */ probeId?: pulumi.Input<string>; /** * The transport protocol for the external endpoint. Possible values are `Tcp`, `Udp` or `All`. */ protocol?: pulumi.Input<string>; /** * The name of the resource group in which to create the resource. */ resourceGroupName?: pulumi.Input<string>; } /** * The set of arguments for constructing a Rule resource. */ export interface RuleArgs { /** * @deprecated This property has been deprecated by `backend_address_pool_ids` and will be removed in the next major version of the provider */ backendAddressPoolId?: pulumi.Input<string>; /** * A list of reference to a Backend Address Pool over which this Load Balancing Rule operates. */ backendAddressPoolIds?: pulumi.Input<pulumi.Input<string>[]>; /** * The port used for internal connections on the endpoint. Possible values range between 0 and 65535, inclusive. */ backendPort: pulumi.Input<number>; /** * Is snat enabled for this Load Balancer Rule? Default `false`. */ disableOutboundSnat?: pulumi.Input<boolean>; /** * Are the Floating IPs enabled for this Load Balncer Rule? A "floating” IP is reassigned to a secondary server in case the primary server fails. Required to configure a SQL AlwaysOn Availability Group. Defaults to `false`. */ enableFloatingIp?: pulumi.Input<boolean>; /** * Is TCP Reset enabled for this Load Balancer Rule? Defaults to `false`. */ enableTcpReset?: pulumi.Input<boolean>; /** * The name of the frontend IP configuration to which the rule is associated. */ frontendIpConfigurationName: pulumi.Input<string>; /** * The port for the external endpoint. Port numbers for each Rule must be unique within the Load Balancer. Possible values range between 0 and 65534, inclusive. */ frontendPort: pulumi.Input<number>; /** * Specifies the idle timeout in minutes for TCP connections. Valid values are between `4` and `30` minutes. Defaults to `4` minutes. */ idleTimeoutInMinutes?: pulumi.Input<number>; /** * Specifies the load balancing distribution type to be used by the Load Balancer. Possible values are: `Default` – The load balancer is configured to use a 5 tuple hash to map traffic to available servers. `SourceIP` – The load balancer is configured to use a 2 tuple hash to map traffic to available servers. `SourceIPProtocol` – The load balancer is configured to use a 3 tuple hash to map traffic to available servers. Also known as Session Persistence, where the options are called `None`, `Client IP` and `Client IP and Protocol` respectively. */ loadDistribution?: pulumi.Input<string>; /** * The ID of the Load Balancer in which to create the Rule. */ loadbalancerId: pulumi.Input<string>; /** * Specifies the name of the LB Rule. */ name?: pulumi.Input<string>; /** * A reference to a Probe used by this Load Balancing Rule. */ probeId?: pulumi.Input<string>; /** * The transport protocol for the external endpoint. Possible values are `Tcp`, `Udp` or `All`. */ protocol: pulumi.Input<string>; /** * The name of the resource group in which to create the resource. */ resourceGroupName: pulumi.Input<string>; }
the_stack
import type { PosixFilePath } from '@contentlayer/utils' import { filePathJoin, unknownToPosixFilePath } from '@contentlayer/utils' import * as utils from '@contentlayer/utils' import type { E, HasClock, HasConsole } from '@contentlayer/utils/effect' import { Array, Chunk, flow, OT, pipe, S, T } from '@contentlayer/utils/effect' import { fs } from '@contentlayer/utils/node' import { camelCase } from 'camel-case' import type { PackageJson } from 'type-fest' import { ArtifactsDir } from '../ArtifactsDir.js' import type { HasCwd } from '../cwd.js' import type { DataCache } from '../DataCache.js' import type { SourceProvideSchemaError } from '../errors.js' import type { Config } from '../getConfig/index.js' import type { SourceFetchDataError } from '../index.js' import type { PluginOptions, SourcePluginType } from '../plugin.js' import type { DocumentTypeDef, SchemaDef } from '../schema/index.js' import { autogeneratedNote } from './common.js' import { renderTypes } from './generate-types.js' /** * Used to track which files already have been written. * Gets re-initialized per `generateDotpkg` invocation therefore only "works" during dev mode. */ type FilePath = string type DocumentHash = string type WrittenFilesCache = Record<FilePath, DocumentHash> export type GenerationOptions = { sourcePluginType: SourcePluginType options: PluginOptions } type GenerateDotpkgError = | fs.WriteFileError | fs.JsonStringifyError | fs.MkdirError | fs.RmError | SourceProvideSchemaError | SourceFetchDataError export type GenerateInfo = { documentCount: number } export const logGenerateInfo = (info: GenerateInfo): T.Effect<HasConsole, never, void> => T.log(`Generated ${info.documentCount} documents in .contentlayer`) export const generateDotpkg = ({ config, verbose, }: { config: Config verbose: boolean }): T.Effect<OT.HasTracer & HasClock & HasCwd & HasConsole, GenerateDotpkgError, GenerateInfo> => pipe( generateDotpkgStream({ config, verbose, isDev: false }), S.take(1), S.runCollect, T.map(Chunk.unsafeHead), T.rightOrFail, OT.withSpan('@contentlayer/core/generation:generateDotpkg', { attributes: { verbose } }), ) // TODO make sure unused old generated files are removed export const generateDotpkgStream = ({ config, verbose, isDev, }: { config: Config verbose: boolean isDev: boolean }): S.Stream<OT.HasTracer & HasClock & HasCwd & HasConsole, never, E.Either<GenerateDotpkgError, GenerateInfo>> => { const writtenFilesCache = {} const generationOptions = { sourcePluginType: config.source.type, options: config.source.options } const resolveParams = pipe( T.structPar({ schemaDef: config.source.provideSchema(config.esbuildHash), targetPath: ArtifactsDir.mkdir, }), T.either, ) // .pipe( // tap((artifactsDir) => watchData && errorIfArtifactsDirIsDeleted({ artifactsDir })) // ), return pipe( S.fromEffect(resolveParams), S.chainMapEitherRight(({ schemaDef, targetPath }) => pipe( config.source.fetchData({ schemaDef, verbose }), S.mapEffectEitherRight((cache) => pipe( writeFilesForCache({ schemaDef, targetPath, cache, generationOptions, writtenFilesCache, isDev }), T.eitherMap(() => ({ documentCount: Object.keys(cache.cacheItemsMap).length })), ), ), ), ), ) } const writeFilesForCache = ({ cache, schemaDef, targetPath, generationOptions, writtenFilesCache, isDev, }: { schemaDef: SchemaDef cache: DataCache.Cache targetPath: PosixFilePath generationOptions: GenerationOptions writtenFilesCache: WrittenFilesCache isDev: boolean }): T.Effect< OT.HasTracer, never, E.Either<fs.WriteFileError | fs.MkdirError | fs.RmError | fs.JsonStringifyError, void> > => pipe( T.gen(function* ($) { const withPrefix = (...path_: string[]) => filePathJoin(targetPath, ...path_.map(unknownToPosixFilePath)) if (process.env['CL_DEBUG']) { yield* $(fs.mkdirp(withPrefix('.cache'))) yield* $( T.collectAllPar([ fs.writeFileJson({ filePath: withPrefix('.cache', 'schema.json'), content: schemaDef as any }), fs.writeFileJson({ filePath: withPrefix('.cache', 'data-cache.json'), content: cache }), ]), ) } const allCacheItems = Object.values(cache.cacheItemsMap) const allDocuments = allCacheItems.map((_) => _.document) const documentDefs = Object.values(schemaDef.documentTypeDefMap) const [nodeVersionMajor, nodeVersionMinor] = yield* $( T.succeedWith(() => process.versions.node.split('.').map((_) => parseInt(_, 10)) as [number, number, number]), ) // NOTE Type assert statements for `.json` files are neccessary from Node v16.14 onwards const needsJsonAssertStatement = nodeVersionMajor > 16 || (nodeVersionMajor === 16 && nodeVersionMinor >= 14) const assertStatement = needsJsonAssertStatement ? ` assert { type: 'json' }` : '' const typeNameField = generationOptions.options.fieldOptions.typeFieldName const dataBarrelFiles = documentDefs.map((docDef) => ({ content: makeDataExportFile({ docDef, documentIds: allDocuments.filter((_) => _[typeNameField] === docDef.name).map((_) => _._id), assertStatement, }), filePath: withPrefix('generated', docDef.name, `_index.mjs`), })) const individualDataJsonFiles = allCacheItems.map(({ document, documentHash }) => ({ content: JSON.stringify(document, null, 2), filePath: withPrefix('generated', document[typeNameField], `${idToFileName(document._id)}.json`), documentHash, })) const collectionDataJsonFiles = pipe( documentDefs, Array.map((documentDef) => { const documents = allDocuments.filter((_) => _[typeNameField] === documentDef.name) const jsonData = documentDef.isSingleton ? documents[0]! : documents return { content: JSON.stringify(jsonData, null, 2), filePath: withPrefix('generated', documentDef.name, `_index.json`), documentHash: documents.map((_) => _.documentHash).join(''), } }), ) const dataDirPaths = documentDefs.map((_) => withPrefix('generated', _.name)) yield* $(T.forEachPar_([withPrefix('generated'), ...dataDirPaths], fs.mkdirp)) const writeFile = writeFileWithWrittenFilesCache({ writtenFilesCache }) yield* $( T.collectAllPar([ writeFile({ filePath: withPrefix('package.json'), content: makePackageJson(schemaDef.hash) }), writeFile({ filePath: withPrefix('generated', 'types.d.ts'), content: renderTypes({ schemaDef, generationOptions }), rmBeforeWrite: true, }), writeFile({ filePath: withPrefix('generated', 'index.d.ts'), content: makeDataTypes({ schemaDef }), rmBeforeWrite: true, }), writeFile({ filePath: withPrefix('generated', 'index.mjs'), content: makeIndexMjs({ schemaDef, assertStatement, isDev }), }), ...dataBarrelFiles.map(writeFile), ...individualDataJsonFiles.map(writeFile), ...collectionDataJsonFiles.map(writeFile), // TODO generate readme file ]), ) }), OT.withSpan('@contentlayer/core/generation/generate-dotpkg:writeFilesForCache', { attributes: { targetPath, cacheKeys: Object.keys(cache.cacheItemsMap), }, }), T.either, ) const makePackageJson = (schemaHash: string): string => { const packageJson: PackageJson & { typesVersions: any } = { name: 'dot-contentlayer', description: 'This package is auto-generated by Contentlayer', // TODO generate more meaningful version (e.g. by using Contentlayer version and schema hash) version: `0.0.0-${schemaHash}`, exports: { './generated': { import: './generated/index.mjs', }, }, typesVersions: { '*': { generated: ['./generated'], }, }, } return JSON.stringify(packageJson, null, 2) } /** * Remembers which files already have been written to disk. * If no `documentHash` was provided, the writes won't be cached. * * TODO maybe rewrite with effect-cache */ const writeFileWithWrittenFilesCache = ({ writtenFilesCache }: { writtenFilesCache: WrittenFilesCache }) => ({ filePath, content, documentHash, rmBeforeWrite = true, }: { filePath: PosixFilePath content: string documentHash?: string /** In order for VSC to pick up changes in generated files, it's currently needed to delete the file before re-creating it */ rmBeforeWrite?: boolean }) => T.gen(function* ($) { // TODO also consider schema hash const fileIsUpToDate = documentHash !== undefined && writtenFilesCache[filePath] === documentHash if (!rmBeforeWrite && fileIsUpToDate) { return } if (rmBeforeWrite) { yield* $(fs.rm(filePath, { force: true })) } yield* $(fs.writeFile(filePath, content)) if (documentHash) { writtenFilesCache[filePath] = documentHash } }) const makeDataExportFile = ({ docDef, documentIds, assertStatement, }: { docDef: DocumentTypeDef documentIds: string[] assertStatement: string }): string => { const dataVariableName = getDataVariableName({ docDef }) if (docDef.isSingleton) { const documentId = documentIds[0]! return `\ // ${autogeneratedNote} export { default as ${dataVariableName} } from './${idToFileName(documentId)}.json'${assertStatement} ` } const makeVariableName = flow(idToFileName, (_) => camelCase(_, { stripRegexp: /[^A-Z0-9\_]/gi })) const docImports = documentIds .map((_) => `import ${makeVariableName(_)} from './${idToFileName(_)}.json'${assertStatement}`) .join('\n') return `\ // ${autogeneratedNote} ${docImports} export const ${dataVariableName} = [${documentIds.map((_) => makeVariableName(_)).join(', ')}] ` } const makeIndexMjs = ({ schemaDef, assertStatement, isDev, }: { schemaDef: SchemaDef assertStatement: string isDev: boolean }): string => { const dataVariableNames = Object.values(schemaDef.documentTypeDefMap).map((docDef) => ({ isSingleton: docDef.isSingleton, documentDefName: docDef.name, dataVariableName: getDataVariableName({ docDef }), })) const constExports = 'export { ' + dataVariableNames.map((_) => _.dataVariableName).join(', ') + ' }' const constImportsForAllDocuments = dataVariableNames .map(({ documentDefName, dataVariableName }) => isDev ? `import { ${dataVariableName} } from './${documentDefName}/_index.mjs'` : `import ${dataVariableName} from './${documentDefName}/_index.json'${assertStatement}`, ) .join('\n') const allDocuments = dataVariableNames .map(({ isSingleton, dataVariableName }) => (isSingleton ? dataVariableName : `...${dataVariableName}`)) .join(', ') return `\ // ${autogeneratedNote} export { isType } from 'contentlayer/client' // NOTE During development Contentlayer imports from \`.mjs\` files to improve HMR speeds. // During (production) builds Contentlayer it imports from \`.json\` files to improve build performance. ${constImportsForAllDocuments} ${constExports} export const allDocuments = [${allDocuments}] ` } export const makeDataTypes = ({ schemaDef }: { schemaDef: SchemaDef }): string => { const dataConsts = Object.values(schemaDef.documentTypeDefMap) .map((docDef) => [docDef, docDef.name, getDataVariableName({ docDef })] as const) .map( ([docDef, typeName, dataVariableName]) => `export declare const ${dataVariableName}: ${typeName}${docDef.isSingleton ? '' : '[]'}`, ) .join('\n') const documentTypeNames = Object.values(schemaDef.documentTypeDefMap) .map((docDef) => docDef.name) .join(', ') return `\ // ${autogeneratedNote} import { ${documentTypeNames}, DocumentTypes } from './types' export type * from './types' ${dataConsts} export declare const allDocuments: DocumentTypes[] ` } const getDataVariableName = ({ docDef }: { docDef: DocumentTypeDef }): string => { if (docDef.isSingleton) { return utils.lowercaseFirstChar(utils.inflection.singularize(docDef.name)) } else { return 'all' + utils.uppercaseFirstChar(utils.inflection.pluralize(docDef.name)) } } const idToFileName = (id: string): string => leftPadWithUnderscoreIfStartsWithNumber(id).replace(/\//g, '__') const leftPadWithUnderscoreIfStartsWithNumber = (str: string): string => { if (/^[0-9]/.test(str)) { return '_' + str } return str } // const errorIfArtifactsDirIsDeleted = ({ artifactsDir }: { artifactsDir: string }) => { // watch(artifactsDir, async (event) => { // if (event === 'rename' && !(await fileOrDirExists(artifactsDir))) { // console.error(`Seems like the target directory (${artifactsDir}) was deleted. Please restart the command.`) // process.exit(1) // } // }) // }
the_stack
import * as React from "react"; import { fireEvent, render, waitFor } from "@testing-library/react"; import { login, logout, handleIncomingRedirect, getDefaultSession, onSessionRestore, } from "@inrupt/solid-client-authn-browser"; import { SessionContext, SessionProvider } from "./index"; jest.mock("@inrupt/solid-client-authn-browser"); jest.mock("@inrupt/solid-client"); function ChildComponent(): React.ReactElement { const { session, sessionRequestInProgress, login: sessionLogin, logout: sessionLogout, profile, } = React.useContext(SessionContext); return ( <div> {sessionRequestInProgress && ( <div data-testid="sessionRequestInProgress"> sessionRequestInProgress </div> )} <div data-testid="session">{JSON.stringify(session)}</div> <button type="button" onClick={() => sessionLogin({})}> Login </button> <button type="button" onClick={sessionLogout} data-testid="logout"> Logout </button> <p data-testid="profile"> {profile ? `${profile.altProfileAll.length} alt profiles found` : "No profile found"} </p> </div> ); } describe("Testing SessionContext", () => { it("matches snapshot", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const documentBody = render( <SessionProvider sessionId="key"> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); const { baseElement } = documentBody; expect(baseElement).toMatchSnapshot(); }); it("matches snapshot without optional sessionId", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const documentBody = render( <SessionProvider> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); const { baseElement } = documentBody; expect(baseElement).toMatchSnapshot(); }); it("calls onError if handleIncomingRedirect fails", async () => { (handleIncomingRedirect as jest.Mock).mockRejectedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const onError = jest.fn(); render( <SessionProvider sessionId="key" onError={onError}> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(onError).toHaveBeenCalled(); }); }); }); describe("SessionContext functionality", () => { it("attempts to handle an incoming redirect", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); render( <SessionProvider sessionId="key"> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); }); it("fetches the user's profile if logging in succeeds", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce({ webId: "https://some.webid", }); const mockedClientModule = jest.requireMock("@inrupt/solid-client"); const actualClientModule = jest.requireActual("@inrupt/solid-client"); mockedClientModule.getProfileAll = jest.fn().mockResolvedValue({ webIdProfile: actualClientModule.mockSolidDatasetFrom("https://some.webid"), altProfileAll: [ actualClientModule.mockSolidDatasetFrom("https://some.profile"), ], }); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const screen = render( <SessionProvider sessionId="key"> <ChildComponent /> </SessionProvider> ); await waitFor(async () => { expect(screen.getByTestId("profile").textContent).toBe( "1 alt profiles found" ); }); fireEvent.click(screen.getByTestId("logout")); await waitFor(async () => { expect(screen.getByTestId("profile").textContent).toBe( "No profile found" ); }); expect(mockedClientModule.getProfileAll).toHaveBeenCalled(); }); it("uses the login and logout functions from session", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const { getByText } = render( <SessionProvider sessionId="key"> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); expect(login).not.toHaveBeenCalled(); expect(logout).not.toHaveBeenCalled(); fireEvent.click(getByText("Login")); await waitFor(() => { expect(login).toHaveBeenCalledTimes(1); }); fireEvent.click(getByText("Logout")); await waitFor(() => { expect(logout).toHaveBeenCalledTimes(1); }); }); it("calls onError if there is an error logging in", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); (login as jest.Mock).mockRejectedValueOnce(null); const onError = jest.fn(); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const { getByText } = render( <SessionProvider sessionId="key" onError={onError}> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); fireEvent.click(getByText("Login")); await waitFor(() => expect(onError).toHaveBeenCalledTimes(1)); }); it("calls onError if there is an error logging out", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); (logout as jest.Mock).mockRejectedValueOnce(null); const onError = jest.fn(); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const { getByText } = render( <SessionProvider sessionId="key" onError={onError}> <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); fireEvent.click(getByText("Logout")); await waitFor(() => expect(onError).toHaveBeenCalledTimes(1)); }); it("registers a session restore callback if one is provided", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const sessionRestoreCallback = jest.fn(); render( <SessionProvider sessionId="key" onSessionRestore={sessionRestoreCallback} > <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); expect(onSessionRestore).toHaveBeenCalledWith(sessionRestoreCallback); }); it("does not register a session restore callback on every render unless it changes", async () => { (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const session = { info: { isLoggedIn: true, webId: "https://fakeurl.com/me", }, on: jest.fn(), } as any; (getDefaultSession as jest.Mock).mockReturnValue(session); const sessionRestoreCallback = jest.fn(); const differentSessionRestoreCallback = jest.fn(); (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); const { rerender } = render( <SessionProvider sessionId="key" onSessionRestore={sessionRestoreCallback} > <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); (handleIncomingRedirect as jest.Mock).mockResolvedValueOnce(null); rerender( <SessionProvider sessionId="key" onSessionRestore={sessionRestoreCallback} > <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); rerender( <SessionProvider sessionId="key" onSessionRestore={differentSessionRestoreCallback} > <ChildComponent /> </SessionProvider> ); await waitFor(() => { expect(handleIncomingRedirect).toHaveBeenCalled(); }); expect(onSessionRestore).toHaveBeenCalledTimes(2); expect(onSessionRestore).toHaveBeenCalledWith(sessionRestoreCallback); expect(onSessionRestore).toHaveBeenCalledWith( differentSessionRestoreCallback ); }); });
the_stack
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { assert, expect } from "chai"; import { BigNumber, ethers } from "ethers"; import { createSnapshot, PayloadToSign721withQuantity, SignatureDrop, Token, } from "../src"; import { expectError, sdk, signers, storage } from "./before-setup"; import { SignedPayload721WithQuantitySignature } from "../src/schema/contracts/common/signature"; import { NATIVE_TOKEN_ADDRESS } from "../src/constants/currency"; import invariant from "tiny-invariant"; import { MerkleTree } from "merkletreejs"; import { keccak256 } from "ethers/lib/utils"; global.fetch = require("cross-fetch"); describe("Signature drop tests", async () => { let signatureDropContract: SignatureDrop; let customTokenContract: Token; let tokenAddress: string; let adminWallet: SignerWithAddress, samWallet: SignerWithAddress, abbyWallet: SignerWithAddress, bobWallet: SignerWithAddress, w1: SignerWithAddress, w2: SignerWithAddress, w3: SignerWithAddress, w4: SignerWithAddress; let meta: PayloadToSign721withQuantity; before(() => { [adminWallet, samWallet, bobWallet, abbyWallet, w1, w2, w3, w4] = signers; }); beforeEach(async () => { sdk.updateSignerOrProvider(adminWallet); signatureDropContract = sdk.getSignatureDrop( await sdk.deployer.deployBuiltInContract(SignatureDrop.contractType, { name: "OUCH VOUCH", symbol: "VOUCH", primary_sale_recipient: adminWallet.address, seller_fee_basis_points: 0, }), ); meta = { currencyAddress: NATIVE_TOKEN_ADDRESS, metadata: { name: "OUCH VOUCH", }, price: "1", quantity: 1, to: samWallet.address, }; customTokenContract = sdk.getToken( await sdk.deployer.deployBuiltInContract(Token.contractType, { name: "Test", symbol: "TEST", primary_sale_recipient: adminWallet.address, }), ); await customTokenContract.mintBatchTo([ { toAddress: samWallet.address, amount: 1000, }, { toAddress: adminWallet.address, amount: 1000, }, ]); tokenAddress = customTokenContract.getAddress(); }); describe("Generating Signatures", () => { let goodPayload: SignedPayload721WithQuantitySignature; let badPayload: SignedPayload721WithQuantitySignature; beforeEach(async () => { goodPayload = await signatureDropContract.signature.generate(meta); badPayload = await signatureDropContract.signature.generate(meta); badPayload.payload.price = "0"; }); it("should generate a valid signature", async () => { const valid = await signatureDropContract.signature.verify(goodPayload); assert.isTrue(valid, "This voucher should be valid"); }); it("should reject invalid signatures", async () => { const invalid = await signatureDropContract.signature.verify(badPayload); assert.isFalse( invalid, "This voucher should be invalid because the signature is invalid", ); }); it("should reject invalid vouchers", async () => { goodPayload.payload.price = "0"; const invalidModified = await signatureDropContract.signature.verify( goodPayload, ); assert.isFalse( invalidModified, "This voucher should be invalid because the price was changed", ); }); it("should generate a valid batch of signatures", async () => { const input = [ { ...meta, metadata: { name: "OUCH VOUCH 0", }, }, { ...meta, metadata: { name: "OUCH VOUCH 1", }, }, { ...meta, metadata: { name: "OUCH VOUCH 2", }, }, ]; await signatureDropContract.createBatch([ { name: "OUCH VOUCH 0", }, { name: "OUCH VOUCH 1", }, { name: "OUCH VOUCH 2", }, ]); const batch = await signatureDropContract.signature.generateBatch(input); for (let i = 0; i < batch.length; i++) { const entry = batch[i]; const tx = await signatureDropContract.signature.mint(entry); const mintedId = (await signatureDropContract.get(tx.id)).metadata.id; const nft = await signatureDropContract.get(mintedId); assert.equal(input[i].metadata.name, nft.metadata.name); } }); }); describe("Claiming", async () => { let v1: SignedPayload721WithQuantitySignature, v2: SignedPayload721WithQuantitySignature; beforeEach(async () => { v1 = await signatureDropContract.signature.generate(meta); v2 = await signatureDropContract.signature.generate(meta); await signatureDropContract.createBatch([ { name: "Test1", }, { name: "Test2", }, ]); }); it("should mint with URI", async () => { const uri = await storage.uploadMetadata({ name: "Test1", }); const toSign = { metadata: uri, quantity: 1, }; const payload = await signatureDropContract.signature.generate(toSign); const tx = await signatureDropContract.signature.mint(payload); const nft = await signatureDropContract.get(tx.id); assert.equal(nft.metadata.name, "Test1"); }); it("should mint batch with URI", async () => { const uri1 = await storage.uploadMetadata({ name: "Test1", }); const uri2 = await storage.uploadMetadata({ name: "Test2", }); const toSign1 = { metadata: uri1, quantity: 1, }; const toSign2 = { metadata: uri2, quantity: 1, }; const payloads = await signatureDropContract.signature.generateBatch([ toSign1, toSign2, ]); const tx = await signatureDropContract.signature.mintBatch(payloads); const nft1 = await signatureDropContract.get(tx[0].id); assert.equal(nft1.metadata.name, "Test1"); const nft2 = await signatureDropContract.get(tx[1].id); assert.equal(nft2.metadata.name, "Test2"); }); it("should allow a valid voucher to mint", async () => { await sdk.updateSignerOrProvider(samWallet); const tx = await signatureDropContract.signature.mint(v1); const newId = (await signatureDropContract.get(tx.id)).metadata.id; assert.equal(newId.toString(), "0"); await sdk.updateSignerOrProvider(samWallet); const tx2 = await signatureDropContract.signature.mint(v2); const newId2 = (await signatureDropContract.get(tx2.id)).metadata.id; assert.equal(newId2.toString(), "1"); }); it("should mint the right metadata", async () => { const tx = await signatureDropContract.signature.mint(v1); const nft = await signatureDropContract.get(tx.id); assert.equal(nft.metadata.name, "Test1"); const tx2 = await signatureDropContract.signature.mint(v2); const nft2 = await signatureDropContract.get(tx2.id); assert.equal(nft2.metadata.name, "Test2"); }); it("should mint the right custom token price", async () => { const oldBalance = await samWallet.getBalance(); const payload = await signatureDropContract.signature.generate({ price: 1, currencyAddress: tokenAddress, metadata: { name: "custom token test", }, quantity: 1, mintEndTime: new Date(Date.now() + 60 * 60 * 24 * 1000 * 1000), mintStartTime: new Date(), }); await sdk.updateSignerOrProvider(samWallet); await signatureDropContract.signature.mint(payload); const newBalance = await samWallet.getBalance(); assert( oldBalance.sub(newBalance).gte(BigNumber.from(1)), "balance doesn't match", ); }); it("should mint the right native price", async () => { const oldBalance = await samWallet.getBalance(); const payload = await signatureDropContract.signature.generate({ price: 1, metadata: { name: "native token test", }, quantity: 1, mintEndTime: new Date(Date.now() + 60 * 60 * 24 * 1000 * 1000), mintStartTime: new Date(), }); await sdk.updateSignerOrProvider(samWallet); await signatureDropContract.signature.mint(payload); const newBalance = await samWallet.getBalance(); assert( oldBalance.sub(newBalance).gte(BigNumber.from(1)), "balance doesn't match", ); }); it("should mint the right native price with multiple tokens", async () => { const oldBalance = await samWallet.getBalance(); const payload = await signatureDropContract.signature.generate({ price: 1, metadata: { name: "native token test with quantity", }, quantity: 2, mintEndTime: new Date(Date.now() + 60 * 60 * 24 * 1000 * 1000), mintStartTime: new Date(), }); await sdk.updateSignerOrProvider(samWallet); await signatureDropContract.signature.mint(payload); const newBalance = await samWallet.getBalance(); assert( oldBalance.sub(newBalance).gte(BigNumber.from(2)), "balance doesn't match", ); }); }); describe("Delay Reveal", () => { it("metadata should reveal correctly", async () => { await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [{ name: "NFT #1" }, { name: "NFT #2" }], "my secret password", ); expect((await signatureDropContract.get("0")).metadata.name).to.be.equal( "Placeholder #1", ); await signatureDropContract.revealer.reveal(0, "my secret password"); expect((await signatureDropContract.get("0")).metadata.name).to.be.equal( "NFT #1", ); }); it("different reveal order and should return correct unreveal list", async () => { await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [ { name: "NFT #1", }, { name: "NFT #2", }, ], "my secret key", ); await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #2", }, [ { name: "NFT #3", }, { name: "NFT #4", }, ], "my secret key", ); await signatureDropContract.createBatch([ { name: "NFT #00", }, { name: "NFT #01", }, ]); await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #3", }, [ { name: "NFT #5", }, { name: "NFT #6", }, { name: "NFT #7", }, ], "my secret key", ); let unrevealList = await signatureDropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(3); expect(unrevealList[0].batchId.toNumber()).to.be.equal(0); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #1", ); expect(unrevealList[1].batchId.toNumber()).to.be.equal(1); expect(unrevealList[1].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); // skipped 2 because it is a revealed batch expect(unrevealList[2].batchId.toNumber()).to.be.equal(3); expect(unrevealList[2].placeholderMetadata.name).to.be.equal( "Placeholder #3", ); await signatureDropContract.revealer.reveal( unrevealList[0].batchId, "my secret key", ); unrevealList = await signatureDropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(2); expect(unrevealList[0].batchId.toNumber()).to.be.equal(1); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); expect(unrevealList[1].batchId.toNumber()).to.be.equal(3); expect(unrevealList[1].placeholderMetadata.name).to.be.equal( "Placeholder #3", ); await signatureDropContract.revealer.reveal( unrevealList[unrevealList.length - 1].batchId, "my secret key", ); unrevealList = await signatureDropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(1); expect(unrevealList[0].batchId.toNumber()).to.be.equal(1); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); }); it("should not be able to re-used published password for next batch", async () => { await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [{ name: "NFT #1" }, { name: "NFT #2" }], "my secret password", ); await signatureDropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #2", }, [{ name: "NFT #3" }, { name: "NFT #4" }], "my secret password", ); await signatureDropContract.revealer.reveal(0, "my secret password"); const transactions = (await adminWallet.provider?.getBlockWithTransactions("latest")) ?.transactions ?? []; const { _index, _key } = signatureDropContract.encoder.decode( "reveal", transactions[0].data, ); // re-using broadcasted _key to decode :) try { await signatureDropContract.revealer.reveal(_index.add(1), _key); assert.fail("should not be able to re-used published password"); } catch (e) { expect((e as Error).message).to.be.equal("invalid password"); } // original password should work await signatureDropContract.revealer.reveal(1, "my secret password"); }); }); describe("Claim Conditions", () => { it("should allow a snapshot to be set", async () => { await signatureDropContract.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); await signatureDropContract.claimCondition.set({ snapshot: [samWallet.address], }); const conditions = await signatureDropContract.claimCondition.get(); invariant(conditions.snapshot); expect(conditions.snapshot[0].address).to.eq(samWallet.address); }); it("should remove merkles from the metadata when claim conditions are removed", async () => { await signatureDropContract.claimCondition.set({ startTime: new Date(), waitInSeconds: 10, snapshot: [bobWallet.address, samWallet.address, abbyWallet.address], }); const metadata = await signatureDropContract.metadata.get(); const merkles = metadata.merkle; expect(merkles).have.property( "0xb1a60ad68b77609a455696695fbdd02b850d03ec285e7fe1f4c4093797457b24", ); const roots = await signatureDropContract.claimCondition.get(); expect(roots.merkleRootHash.length > 0); await signatureDropContract.claimCondition.set({}); const newMetadata = await signatureDropContract.metadata.get(); const newMerkles = newMetadata.merkle; expect(JSON.stringify(newMerkles)).to.eq("{}"); }); it("allow all addresses in the merkle tree to claim", async () => { const testWallets: SignerWithAddress[] = [ bobWallet, samWallet, abbyWallet, w1, w2, w3, w4, ]; const members = testWallets.map((w, i) => i % 3 === 0 ? w.address.toLowerCase() : i % 3 === 1 ? w.address.toUpperCase().replace("0X", "0x") : w.address, ); await signatureDropContract.claimCondition.set({ snapshot: members, }); const metadata = []; for (let i = 0; i < 10; i++) { metadata.push({ name: `test ${i}`, }); } await signatureDropContract.createBatch(metadata); /** * Claiming 1 tokens with proofs: 0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9,0xb1a5bda84b83f7f014abcf0cf69cab5a4de1c3ececa8123a5e4aaacb01f63f83 */ for (const member of testWallets) { await sdk.updateSignerOrProvider(member); await signatureDropContract.claim(1); } }); it("allow one address in the merkle tree to claim", async () => { const testWallets: SignerWithAddress[] = [bobWallet]; const members = testWallets.map((w) => w.address); await signatureDropContract.claimCondition.set({ snapshot: members, }); const metadata = []; for (let i = 0; i < 2; i++) { metadata.push({ name: `test ${i}`, }); } await signatureDropContract.createBatch(metadata); /** * Claiming 1 tokens with proofs: 0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9,0xb1a5bda84b83f7f014abcf0cf69cab5a4de1c3ececa8123a5e4aaacb01f63f83 */ for (const member of testWallets) { await sdk.updateSignerOrProvider(member); await signatureDropContract.claim(1); } try { await sdk.updateSignerOrProvider(samWallet); await signatureDropContract.claim(1); assert.fail("should have thrown"); } catch (e) { // expected } }); it("should correctly upload metadata for each nft", async () => { const metadatas = []; for (let i = 0; i < 100; i++) { metadatas.push({ name: `test ${i}`, }); } await signatureDropContract.createBatch(metadatas); const all = await signatureDropContract.getAll(); expect(all.length).to.eq(100); await signatureDropContract.claimCondition.set({}); await signatureDropContract.claim(1); const claimed = await signatureDropContract.totalClaimedSupply(); const unclaimed = await signatureDropContract.totalUnclaimedSupply(); expect(claimed.toNumber()).to.eq(1); expect(unclaimed.toNumber()).to.eq(99); }); it("should correctly update total supply after burning", async () => { const metadatas = []; for (let i = 0; i < 20; i++) { metadatas.push({ name: `test ${i}`, }); } await signatureDropContract.createBatch(metadatas); await signatureDropContract.claimCondition.set({}); await signatureDropContract.claim(10); const ts = await signatureDropContract.totalSupply(); expect(ts.toNumber()).to.eq(20); await signatureDropContract.burn(0); const ts2 = await signatureDropContract.totalSupply(); expect(ts2.toNumber()).to.eq(20); }); it("should not allow claiming to someone not in the merkle tree", async () => { await signatureDropContract.claimCondition.set({ snapshot: [bobWallet.address, samWallet.address, abbyWallet.address], }); await signatureDropContract.createBatch([ { name: "name", description: "description" }, ]); await sdk.updateSignerOrProvider(w1); try { await signatureDropContract.claim(1); } catch (err: any) { expect(err).to.have.property( "message", "No claim found for this address", "", ); return; } assert.fail("should not reach this point, claim should have failed"); }); it("should allow claims with default settings", async () => { await signatureDropContract.createBatch([ { name: "name", description: "description" }, ]); await signatureDropContract.claimCondition.set({}); await signatureDropContract.claim(1); }); it("should allow setting max claims per wallet", async () => { await signatureDropContract.createBatch([ { name: "name", description: "description" }, { name: "name2", description: "description" }, { name: "name3", description: "description" }, { name: "name4", description: "description" }, ]); await signatureDropContract.claimCondition.set({ snapshot: [ { address: w1.address, maxClaimable: 2 }, { address: w2.address, maxClaimable: 1 }, ], }); await sdk.updateSignerOrProvider(w1); const tx = await signatureDropContract.claim(2); expect(tx.length).to.eq(2); try { await sdk.updateSignerOrProvider(w2); await signatureDropContract.claim(2); } catch (e) { expectError(e, "invalid quantity proof"); } }); it("should generate valid proofs", async () => { const members = [ bobWallet.address, samWallet.address, abbyWallet.address, w1.address, w2.address, w3.address, w4.address, ]; const hashedLeafs = members.map((l) => ethers.utils.solidityKeccak256(["address", "uint256"], [l, 0]), ); const tree = new MerkleTree(hashedLeafs, keccak256, { sort: true, sortLeaves: true, sortPairs: true, }); const input = members.map((address) => ({ address, maxClaimable: 0, })); const snapshot = await createSnapshot(input, 0, storage); for (const leaf of members) { const expectedProof = tree.getHexProof( ethers.utils.solidityKeccak256(["address", "uint256"], [leaf, 0]), ); const actualProof = snapshot.snapshot.claims.find( (c) => c.address === leaf, ); assert.isDefined(actualProof); expect(actualProof?.proof).to.include.ordered.members(expectedProof); const verified = tree.verify( actualProof?.proof as string[], ethers.utils.solidityKeccak256(["address", "uint256"], [leaf, 0]), tree.getHexRoot(), ); expect(verified).to.eq(true); } }); it("should return the newly claimed token", async () => { await signatureDropContract.claimCondition.set({}); await signatureDropContract.createBatch([ { name: "test 0", }, { name: "test 1", }, { name: "test 2", }, ]); try { await signatureDropContract.createBatch([ { name: "test 0", }, { name: "test 1", }, { name: "test 2", }, ]); } catch (err) { expect(err).to.have.property("message", "Batch already created!", ""); } const token = await signatureDropContract.claim(2); assert.lengthOf(token, 2); }); }); });
the_stack
import React from 'react'; import { useSelector } from './useSelector'; import { createReducer, BaseStore } from '../..'; type IsNumber<P> = P extends number ? 1 : 0; type IsString<P> = P extends string ? 1 : 0; type IsBoolean<P> = P extends boolean ? 1 : 0; type IsArray<P> = P extends [] ? 1 : 0; type IsAny<P> = P extends never ? 1 : 0; // // Для проверки на точное значение, и что оно не является не any, // необходимо проверять и на IsAny, и на конкретный тип. // Если значение верное - оно пройдет обе проверки. // Если значение не верное - упадет проверка на конкретный тип. // Если значение any - упадет IsAny. // class MockStore extends BaseStore<{ id: number }> { static storeName = 'test' as const; state = { id: 1 }; inc() { // eslint-disable-next-line react/no-access-state-in-setstate this.setState({ id: this.state.id + 1 }); } } // eslint-disable-next-line max-statements describe('useSelector type infer', () => { it('infer right result type from single store argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result = useSelector(store, (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); it('infer right store name from single store argument, initialState has type', () => { const Component = () => { type State = { id: number }; const initialState: State = { id: 1 }; const store = createReducer('test', initialState); const result = useSelector(store, (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); it('UNTYPED CASE! infer any result type from single store name argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result = useSelector('test', (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; const isAny: IsAny<typeof result> = 1; return null; }; }); it('infer right result type from single optional store argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result = useSelector({ store, optional: true }, (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); it('UNTYPED CASE! infer any result type from single optional store name argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result = useSelector( { store: 'test', optional: true }, (something) => something.test.id ); const isNumber: IsNumber<typeof result> = 1; const isAny: IsAny<typeof result> = 1; return null; }; }); it('infer right result type from array of stores argument, with and without const', () => { const Component = () => { const store1 = createReducer('test1', { id: 1 }); const store2 = createReducer('test2', { id: '2' }); const result1 = useSelector([store1], (something) => something.test1.id); const result2 = useSelector([store2], (something) => something.test2.id); const result3 = useSelector([store1] as const, (something) => something.test1.id); const result4 = useSelector([store2] as const, (something) => something.test2.id); const isNumber1: IsNumber<typeof result1> = 1; // @ts-expect-error const isAny1: IsAny<typeof result1> = 1; const isString2: IsString<typeof result2> = 1; // @ts-expect-error const isAny2: IsAny<typeof result2> = 1; const isNumber3: IsNumber<typeof result3> = 1; // @ts-expect-error const isAny3: IsAny<typeof result3> = 1; const isString4: IsString<typeof result4> = 1; // @ts-expect-error const isAny4: IsAny<typeof result4> = 1; return null; }; }); it('UNTYPED CASE! infer any result type from array of stores names argument, with and without const', () => { const Component = () => { const store1 = createReducer('test1', { id: 1 }); const store2 = createReducer('test2', { id: '2' }); const result1 = useSelector(['test1'], (something) => something.test1.id); const result2 = useSelector(['test2'], (something) => something.test2.id); const result3 = useSelector(['test1'] as const, (something) => something.test1.id); const result4 = useSelector(['test2'] as const, (something) => something.test2.id); const isNumber1: IsNumber<typeof result1> = 1; const isAny1: IsAny<typeof result1> = 1; const isString2: IsString<typeof result2> = 1; const isAny2: IsAny<typeof result2> = 1; const isNumber3: IsNumber<typeof result3> = 1; const isAny3: IsAny<typeof result3> = 1; const isString4: IsString<typeof result4> = 1; const isAny4: IsAny<typeof result4> = 1; return null; }; }); it('infer right result type from array of optional stores argument, only with const', () => { const store1 = createReducer('test1', { id: 1 }); const store2 = createReducer('test2', { id: '2' }); const result1 = useSelector( [{ store: store1, optional: true }], (something) => something.test1.id ); const result2 = useSelector( [{ store: store2, optional: true }], (something) => something.test2.id ); const result3 = useSelector( [{ store: store1, optional: true }] as const, (something) => something.test1.id ); const result4 = useSelector( [{ store: store2, optional: true }] as const, (something) => something.test2.id ); const isNumber1: IsNumber<typeof result1> = 1; const isAny1: IsAny<typeof result1> = 1; const isString2: IsString<typeof result2> = 1; const isAny2: IsAny<typeof result2> = 1; const isNumber3: IsNumber<typeof result3> = 1; // @ts-expect-error const isAny3: IsAny<typeof result3> = 1; const isString4: IsString<typeof result4> = 1; // @ts-expect-error const isAny4: IsAny<typeof result4> = 1; return null; }); it('UNTYPED CASE! infer any result type from single array of optional stores names argument, with and without const', () => { const Component = () => { const store1 = createReducer('test1', { id: 1 }); const store2 = createReducer('test2', { id: '2' }); const result1 = useSelector( [{ store: 'test1', optional: true }], (something) => something.test1.id ); const result2 = useSelector( [{ store: 'test2', optional: true }], (something) => something.test2.id ); const result3 = useSelector( [{ store: 'test1', optional: true }] as const, (something) => something.test1.id ); const result4 = useSelector( [{ store: 'test2', optional: true }] as const, (something) => something.test2.id ); const isNumber1: IsNumber<typeof result1> = 1; const isAny1: IsAny<typeof result1> = 1; const isString2: IsString<typeof result2> = 1; const isAny2: IsAny<typeof result2> = 1; const isNumber3: IsNumber<typeof result3> = 1; const isAny3: IsAny<typeof result3> = 1; const isString4: IsString<typeof result4> = 1; const isAny4: IsAny<typeof result4> = 1; return null; }; }); it('infer right store name from single store argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); // @ts-expect-error const result = useSelector(store, (something) => something.WRONG.id); return null; }; }); it('UNTYPED CASE! infer right store name from single store argument, store has generic state only', () => { const Component = () => { const store = createReducer<{ id: number }>('test', { id: 1 }); const result = useSelector(store, (something) => something.WRONG.id); return null; }; }); it('infer right store name from single store argument, store has generic state and name', () => { const Component = () => { const store = createReducer<{ id: number }, 'test'>('test', { id: 1 }); // @ts-expect-error const result = useSelector(store, (something) => something.WRONG.id); return null; }; }); it('infer right store name from single store name argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); // @ts-expect-error const result = useSelector('test', (something) => something.WRONG.id); return null; }; }); it('infer right store name from single optional store argument', () => { const Component = () => { const store = createReducer('test', { id: 1 }); // @ts-expect-error const result = useSelector({ store, optional: true }, (something) => something.WRONG.id); return null; }; }); it('infer right store name from single optional store name argument, if name is const', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result1 = useSelector( { store: 'test', optional: true }, (something) => something.WRONG.id ); const result2 = useSelector( { store: 'test' as const, optional: true }, // @ts-expect-error (something) => something.WRONG.id ); return null; }; }); it('infer right store name from array of stores argument, with and without const', () => { const Component = () => { const store = createReducer('test', { id: 1 }); // @ts-expect-error const result1 = useSelector([store], (something) => something.WRONG.id); // @ts-expect-error const result2 = useSelector([store] as const, (something) => something.WRONG.id); return null; }; }); it('infer right store name from array of stores names argument, if array is const', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result1 = useSelector(['test'], (something) => something.WRONG.id); // @ts-expect-error const result2 = useSelector(['test'] as const, (something) => something.WRONG.id); return null; }; }); it('infer right store name from array of optional stores argument, only with const', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result1 = useSelector([{ store, optional: true }], (something) => something.WRONG.id); const result2 = useSelector( [{ store, optional: true }] as const, // @ts-expect-error (something) => something.WRONG.id ); return null; }; }); it('UNTYPED CASE! infer any store name from array of optional stores names argument, with and without const', () => { const Component = () => { const store = createReducer('test', { id: 1 }); const result1 = useSelector( [{ store: 'test', optional: true }], (something) => something.WRONG.id ); const result2 = useSelector( [{ store: 'test', optional: true }] as const, (something) => something.WRONG.id ); return null; }; }); it('infer right type from array of different arguments only for stores or optional stores, only for const array', () => { const store1 = createReducer('test1', { id: 1 }); const store2 = createReducer('test2', { id: '2' }); const store3 = createReducer('test3', { id: true }); const store4 = createReducer('test4', { id: [] }); const result1 = useSelector( ['test1', store2, { store: store3, optional: true }, { store: 'store4', optional: true }], (something) => { return { 1: something.test1.id, 2: something.test2.id, 3: something.test3.id, 4: something.test4.id, 5: something.WRONG.id, }; } ); const result2 = useSelector( [ 'test1', store2, { store: store3, optional: true }, { store: 'store4', optional: true }, ] as const, (something) => { return { 1: something.test1.id, 2: something.test2.id, 3: something.test3.id, 4: something.test4.id, 5: something.WRONG.id, }; } ); const isNumber11: IsNumber<typeof result1[1]> = 1; const isAny11: IsAny<typeof result1[1]> = 1; const isString12: IsString<typeof result1[2]> = 1; const isAny12: IsAny<typeof result1[2]> = 1; const isBoolean13: IsBoolean<typeof result1[3]> = 1; const isAny13: IsAny<typeof result1[3]> = 1; const isArray14: IsArray<typeof result1[4]> = 1; const isAny14: IsAny<typeof result1[4]> = 1; const isNumber21: IsNumber<typeof result2[1]> = 1; const isAny21: IsAny<typeof result2[1]> = 1; const isString22: IsString<typeof result2[2]> = 1; // @ts-expect-error const isAny22: IsAny<typeof result2[2]> = 1; const isBoolean23: IsBoolean<typeof result2[3]> = 1; // @ts-expect-error const isAny23: IsAny<typeof result2[3]> = 1; const isArray24: IsArray<typeof result2[4]> = 1; const isAny24: IsAny<typeof result2[4]> = 1; return null; }); it('infer right store name from single legacy BaseStore argument', () => { const Component = () => { // @ts-expect-error const result = useSelector(MockStore, (something) => something.WRONG.id); return null; }; }); it('infer right result type from single legacy BaseStore argument', () => { const Component = () => { const result = useSelector(MockStore, (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); it('infer right store name from list of legacy BaseStore arguments', () => { const Component = () => { // @ts-expect-error const result = useSelector([MockStore], (something) => something.WRONG.id); return null; }; }); it('infer right result type from list of legacy BaseStore arguments', () => { const Component = () => { const result = useSelector([MockStore], (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); it('infer right store name from const list of legacy BaseStore arguments', () => { const Component = () => { // @ts-expect-error const result = useSelector([MockStore] as const, (something) => something.WRONG.id); return null; }; }); it('infer right result type from const list of legacy BaseStore arguments', () => { const Component = () => { const result = useSelector([MockStore] as const, (something) => something.test.id); const isNumber: IsNumber<typeof result> = 1; // @ts-expect-error const isAny: IsAny<typeof result> = 1; return null; }; }); }); /* eslint-enable jest/expect-expect */
the_stack
import 'mocha' import * as assert from 'assert' import BitArray from './../../../../core/common/BitArray' import ByteMatrix from './../../../../core/qrcode/encoder/ByteMatrix' import MatrixUtil from './../../../../core/qrcode/encoder/MatrixUtil' import ErrorCorrectionLevel from './../../../../core/qrcode/decoder/ErrorCorrectionLevel' import Version from './../../../../core/qrcode/decoder/Version' /** * @author satorux@google.com (Satoru Takabayashi) - creator * @author mysen@google.com (Chris Mysen) - ported from C++ */ describe("MatrixUtilTestCase", () => { it("testToString", () => { const array = new ByteMatrix(3, 3) array.setNumber(0, 0, 0) array.setNumber(1, 0, 1) array.setNumber(2, 0, 0) array.setNumber(0, 1, 1) array.setNumber(1, 1, 0) array.setNumber(2, 1, 1) array.setNumber(0, 2, -1) array.setNumber(1, 2, -1) array.setNumber(2, 2, -1) const expected: string = " 0 1 0\n" + " 1 0 1\n" + " \n" assert.strictEqual(array.toString(), expected) }) it("testClearMatrix", () => { const matrix = new ByteMatrix(2, 2) MatrixUtil.clearMatrix(matrix) // TYPESCRIPTPORT: we use UintArray se changed here from -1 to 255 assert.strictEqual(matrix.get(0, 0), 255) assert.strictEqual(matrix.get(1, 0), 255) assert.strictEqual(matrix.get(0, 1), 255) assert.strictEqual(matrix.get(1, 1), 255) }) it("testEmbedBasicPatterns1", () => { // Version 1. const matrix = new ByteMatrix(21, 21) MatrixUtil.clearMatrix(matrix) MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(1), matrix) const expected: string = " 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 0 0 0 0 0 0 0 1 \n" + " 1 1 1 1 1 1 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 1 1 1 1 1 1 0 \n" assert.strictEqual(matrix.toString(), expected) }) it("testEmbedBasicPatterns2", () => { // Version 2. Position adjustment pattern should apppear at right // bottom corner. const matrix = new ByteMatrix(25, 25) MatrixUtil.clearMatrix(matrix) MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(2), matrix) const expected: string = " 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 \n" + " 0 \n" + " 1 1 1 1 1 1 \n" + " 0 0 0 0 0 0 0 0 1 1 0 0 0 1 \n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 \n" + " 1 0 0 0 0 0 1 0 1 0 0 0 1 \n" + " 1 0 1 1 1 0 1 0 1 1 1 1 1 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 1 1 1 0 1 0 \n" + " 1 0 0 0 0 0 1 0 \n" + " 1 1 1 1 1 1 1 0 \n" assert.strictEqual(matrix.toString(), expected) }) it("testEmbedTypeInfo", () => { // Type info bits = 100000011001110. const matrix = new ByteMatrix(21, 21) MatrixUtil.clearMatrix(matrix) MatrixUtil.embedTypeInfo(ErrorCorrectionLevel.M, 5, matrix) const expected: string = " 0 \n" + " 1 \n" + " 1 \n" + " 1 \n" + " 0 \n" + " 0 \n" + " \n" + " 1 \n" + " 1 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 0 \n" + " 1 \n" assert.strictEqual(matrix.toString(), expected) }) it("testEmbedVersionInfo", () => { // Version info bits = 000111 110010 010100 // Actually, version 7 QR Code has 45x45 matrix but we use 21x21 here // since 45x45 matrix is too big to depict. const matrix = new ByteMatrix(21, 21) MatrixUtil.clearMatrix(matrix) MatrixUtil.maybeEmbedVersionInfo(Version.getVersionForNumber(7), matrix) const expected: string = " 0 0 1 \n" + " 0 1 0 \n" + " 0 1 0 \n" + " 0 1 1 \n" + " 1 1 1 \n" + " 0 0 0 \n" + " \n" + " \n" + " \n" + " \n" + " 0 0 0 0 1 0 \n" + " 0 1 1 1 1 0 \n" + " 1 0 0 1 1 0 \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" assert.strictEqual(matrix.toString(), expected) }) it("testEmbedDataBits", () => { // Cells other than basic patterns should be filled with zero. const matrix = new ByteMatrix(21, 21) MatrixUtil.clearMatrix(matrix) MatrixUtil.embedBasicPatterns(Version.getVersionForNumber(1), matrix) const bits = new BitArray() MatrixUtil.embedDataBits(bits, 255, matrix) const expected: string = " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n" assert.strictEqual(matrix.toString(), expected) }) it("testBuildMatrix", () => { // From http://www.swetake.com/qr/qr7.html const bytes = Uint16Array.from([32, 65, 205, 69, 41, 220, 46, 128, 236, 42, 159, 74, 221, 244, 169, 239, 150, 138, 70, 237, 85, 224, 96, 74, 219 , 61]) const bits = new BitArray() for (let i = 0, length = bytes.length; i != length; i++) { const c = bytes[i] bits.appendBits(c, 8) } const matrix = new ByteMatrix(21, 21) MatrixUtil.buildMatrix(bits, ErrorCorrectionLevel.H, Version.getVersionForNumber(1), // Version 1 3, // Mask pattern 3 matrix) const expected: string = " 1 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1\n" + " 1 0 1 1 1 0 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 0 1 1 0 0 0 1 0 1 1 1 0 1\n" + " 1 0 1 1 1 0 1 0 1 1 0 0 1 0 1 0 1 1 1 0 1\n" + " 1 0 0 0 0 0 1 0 0 0 1 1 1 0 1 0 0 0 0 0 1\n" + " 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0\n" + " 0 0 1 1 0 0 1 1 1 0 0 1 1 1 1 0 1 0 0 0 0\n" + " 1 0 1 0 1 0 0 0 0 0 1 1 1 0 0 1 0 1 1 1 0\n" + " 1 1 1 1 0 1 1 0 1 0 1 1 1 0 0 1 1 1 0 1 0\n" + " 1 0 1 0 1 1 0 1 1 1 0 0 1 1 1 0 0 1 0 1 0\n" + " 0 0 1 0 0 1 1 1 0 0 0 0 0 0 1 0 1 1 1 1 1\n" + " 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 1 0 1 1\n" + " 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 0 1 0 1 1 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 1 0 1 1 1 0 0 0 0 0\n" + " 1 0 1 1 1 0 1 0 0 1 0 0 1 1 0 0 1 0 0 1 1\n" + " 1 0 1 1 1 0 1 0 1 1 0 1 0 0 0 0 0 1 1 1 0\n" + " 1 0 1 1 1 0 1 0 1 1 1 1 0 0 0 0 1 1 1 0 0\n" + " 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0\n" + " 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 1 0 0 1 0\n" assert.strictEqual(matrix.toString(), expected) }) it("testFindMSBSet", () => { assert.strictEqual(MatrixUtil.findMSBSet(0), 0) assert.strictEqual(MatrixUtil.findMSBSet(1), 1) assert.strictEqual(MatrixUtil.findMSBSet(0x80), 8) assert.strictEqual(MatrixUtil.findMSBSet(0x80000000), 32) }) it("testCalculateBCHCode", () => { // Encoding of type information. // From Appendix C in JISX0510:2004 (p 65) assert.strictEqual(MatrixUtil.calculateBCHCode(5, 0x537), 0xdc) // From http://www.swetake.com/qr/qr6.html assert.strictEqual(MatrixUtil.calculateBCHCode(0x13, 0x537), 0x1c2) // From http://www.swetake.com/qr/qr11.html assert.strictEqual(MatrixUtil.calculateBCHCode(0x1b, 0x537), 0x214) // Encoding of version information. // From Appendix D in JISX0510:2004 (p 68) assert.strictEqual(MatrixUtil.calculateBCHCode(7, 0x1f25), 0xc94) assert.strictEqual(MatrixUtil.calculateBCHCode(8, 0x1f25), 0x5bc) assert.strictEqual(MatrixUtil.calculateBCHCode(9, 0x1f25), 0xa99) assert.strictEqual(MatrixUtil.calculateBCHCode(10, 0x1f25), 0x4d3) assert.strictEqual(MatrixUtil.calculateBCHCode(20, 0x1f25), 0x9a6) assert.strictEqual(MatrixUtil.calculateBCHCode(30, 0x1f25), 0xd75) assert.strictEqual(MatrixUtil.calculateBCHCode(40, 0x1f25), 0xc69) }) // We don't test a lot of cases in this function since we've already // tested them in TEST(calculateBCHCode). it("testMakeVersionInfoBits", () => { // From Appendix D in JISX0510:2004 (p 68) const bits = new BitArray() MatrixUtil.makeVersionInfoBits(Version.getVersionForNumber(7), bits) assert.strictEqual(bits.toString(), " ...XXXXX ..X..X.X ..") }) // We don't test a lot of cases in this function since we've already // tested them in TEST(calculateBCHCode). it("testMakeTypeInfoInfoBits", () => { // From Appendix C in JISX0510:2004 (p 65) const bits = new BitArray() MatrixUtil.makeTypeInfoBits(ErrorCorrectionLevel.M, 5, bits) assert.strictEqual(bits.toString(), " X......X X..XXX.") }) })
the_stack
import { CompilerOptionsContainer, createHosts, createModuleResolutionHost, errors, FileSystemHost, FileUtils, InMemoryFileSystemHost, Memoize, RealFileSystemHost, ResolutionHostFactory, runtime, StandardizedFilePath, TransactionalFileSystem, ts, TsConfigResolver, } from "@ts-morph/common"; import { SourceFileCache } from "./SourceFileCache"; /** Options for creating a project. */ export interface ProjectOptions { /** Compiler options */ compilerOptions?: ts.CompilerOptions; /** File path to the tsconfig.json file. */ tsConfigFilePath?: string; /** Whether to skip adding source files from the specified tsconfig.json. @default false */ skipAddingFilesFromTsConfig?: boolean; /** Skip resolving file dependencies when providing a ts config file path and adding the files from tsconfig. @default false */ skipFileDependencyResolution?: boolean; /** * Skip loading the lib files. Unlike the compiler API, ts-morph does not load these * from the node_modules folder, but instead loads them from some other JS code * and uses a fake path for their existence. If you want to use a custom lib files * folder path, then provide one using the libFolderPath options. * @default false */ skipLoadingLibFiles?: boolean; /** The folder to use for loading lib files. */ libFolderPath?: string; /** Whether to use an in-memory file system. */ useInMemoryFileSystem?: boolean; /** * Optional file system host. Useful for mocking access to the file system. * @remarks Consider using `useInMemoryFileSystem` instead. */ fileSystem?: FileSystemHost; /** Creates a resolution host for specifying custom module and/or type reference directive resolution. */ resolutionHost?: ResolutionHostFactory; /** * Unstable and will probably be removed in the future. * I believe this option should be internal to the library and if you know how to achieve * that then please consider submitting a PR. */ isKnownTypesPackageName?: ts.LanguageServiceHost["isKnownTypesPackageName"]; } /** * Asynchronously creates a new collection of source files to analyze. * @param options Options for creating the project. */ export async function createProject(options: ProjectOptions = {}): Promise<Project> { const { project, tsConfigResolver } = createProjectCommon(options); // add any file paths from the tsconfig if necessary if (tsConfigResolver != null && options.skipAddingFilesFromTsConfig !== true) { await project._addSourceFilesForTsConfigResolver(tsConfigResolver, project.compilerOptions.get()); if (!options.skipFileDependencyResolution) project.resolveSourceFileDependencies(); } return project; } /** * Synchronously creates a new collection of source files to analyze. * @param options Options for creating the project. */ export function createProjectSync(options: ProjectOptions = {}): Project { const { project, tsConfigResolver } = createProjectCommon(options); // add any file paths from the tsconfig if necessary if (tsConfigResolver != null && options.skipAddingFilesFromTsConfig !== true) { project._addSourceFilesForTsConfigResolverSync(tsConfigResolver, project.compilerOptions.get()); if (!options.skipFileDependencyResolution) project.resolveSourceFileDependencies(); } return project; } function createProjectCommon(options: ProjectOptions) { verifyOptions(); const fileSystem = getFileSystem(); const fileSystemWrapper = new TransactionalFileSystem(fileSystem); // get tsconfig info const tsConfigResolver = options.tsConfigFilePath == null ? undefined : new TsConfigResolver( fileSystemWrapper, fileSystemWrapper.getStandardizedAbsolutePath(options.tsConfigFilePath), getEncodingFromProvidedOptions(), ); const project = new Project({ fileSystem, fileSystemWrapper, tsConfigResolver, }, options); return { project, tsConfigResolver }; function verifyOptions() { if (options.fileSystem != null && options.useInMemoryFileSystem) throw new errors.InvalidOperationError("Cannot provide a file system when specifying to use an in-memory file system."); } function getFileSystem() { if (options.useInMemoryFileSystem) return new InMemoryFileSystemHost(); return options.fileSystem ?? new RealFileSystemHost(); } function getEncodingFromProvidedOptions() { const defaultEncoding = "utf-8"; if (options.compilerOptions != null) return options.compilerOptions.charset || defaultEncoding; return defaultEncoding; } } /** Project that holds source files. */ export class Project { /** @internal */ private readonly _sourceFileCache: SourceFileCache; /** @internal */ private readonly _fileSystemWrapper: TransactionalFileSystem; /** @internal */ private readonly languageServiceHost: ts.LanguageServiceHost; /** @internal */ private readonly compilerHost: ts.CompilerHost; /** @internal */ private readonly configFileParsingDiagnostics: ts.Diagnostic[]; /** @private */ constructor(objs: { fileSystem: FileSystemHost; fileSystemWrapper: TransactionalFileSystem; tsConfigResolver: TsConfigResolver | undefined; }, options: ProjectOptions) { const { tsConfigResolver } = objs; this.fileSystem = objs.fileSystem; this._fileSystemWrapper = objs.fileSystemWrapper; // initialize the compiler options const tsCompilerOptions = getCompilerOptions(); this.compilerOptions = new CompilerOptionsContainer(); this.compilerOptions.set(tsCompilerOptions); // initialize the source file cache this._sourceFileCache = new SourceFileCache(this._fileSystemWrapper, this.compilerOptions); // initialize the compiler resolution host const resolutionHost = !options.resolutionHost ? undefined : options.resolutionHost(this.getModuleResolutionHost(), () => this.compilerOptions.get()); // setup context const newLineKind = "\n"; const { languageServiceHost, compilerHost } = createHosts({ transactionalFileSystem: this._fileSystemWrapper, sourceFileContainer: this._sourceFileCache, compilerOptions: this.compilerOptions, getNewLine: () => newLineKind, resolutionHost: resolutionHost || {}, getProjectVersion: () => this._sourceFileCache.getProjectVersion().toString(), isKnownTypesPackageName: options.isKnownTypesPackageName, libFolderPath: options.libFolderPath, skipLoadingLibFiles: options.skipLoadingLibFiles, }); this.languageServiceHost = languageServiceHost; this.compilerHost = compilerHost; this.configFileParsingDiagnostics = tsConfigResolver?.getErrors() ?? []; function getCompilerOptions(): ts.CompilerOptions { return { ...getTsConfigCompilerOptions(), ...(options.compilerOptions || {}) as ts.CompilerOptions, }; } function getTsConfigCompilerOptions() { if (tsConfigResolver == null) return {}; return tsConfigResolver.getCompilerOptions(); } } /** Gets the compiler options for modification. */ readonly compilerOptions: CompilerOptionsContainer; /** Gets the file system host used for this project. */ readonly fileSystem: FileSystemHost; /** * Asynchronously adds an existing source file from a file path or throws if it doesn't exist. * * Will return the source file if it was already added. * @param filePath - File path to get the file from. * @param options - Options for adding the file. * @throws FileNotFoundError when the file is not found. */ async addSourceFileAtPath(filePath: string, options?: { scriptKind?: ts.ScriptKind }): Promise<ts.SourceFile> { const sourceFile = await this.addSourceFileAtPathIfExists(filePath, options); if (sourceFile == null) throw new errors.FileNotFoundError(this._fileSystemWrapper.getStandardizedAbsolutePath(filePath)); return sourceFile; } /** * Synchronously adds an existing source file from a file path or throws if it doesn't exist. * * Will return the source file if it was already added. * @param filePath - File path to get the file from. * @param options - Options for adding the file. * @throws FileNotFoundError when the file is not found. */ addSourceFileAtPathSync(filePath: string, options?: { scriptKind?: ts.ScriptKind }): ts.SourceFile { const sourceFile = this.addSourceFileAtPathIfExistsSync(filePath, options); if (sourceFile == null) throw new errors.FileNotFoundError(this._fileSystemWrapper.getStandardizedAbsolutePath(filePath)); return sourceFile; } /** * Asynchronously adds a source file from a file path if it exists or returns undefined. * * Will return the source file if it was already added. * @param filePath - File path to get the file from. * @param options - Options for adding the file. * @skipOrThrowCheck */ addSourceFileAtPathIfExists(filePath: string, options?: { scriptKind?: ts.ScriptKind }): Promise<ts.SourceFile | undefined> { return this._sourceFileCache.addOrGetSourceFileFromFilePath(this._fileSystemWrapper.getStandardizedAbsolutePath(filePath), { scriptKind: options && options.scriptKind, }); } /** * Synchronously adds a source file from a file path if it exists or returns undefined. * * Will return the source file if it was already added. * @param filePath - File path to get the file from. * @param options - Options for adding the file. * @skipOrThrowCheck */ addSourceFileAtPathIfExistsSync(filePath: string, options?: { scriptKind?: ts.ScriptKind }): ts.SourceFile | undefined { return this._sourceFileCache.addOrGetSourceFileFromFilePathSync(this._fileSystemWrapper.getStandardizedAbsolutePath(filePath), { scriptKind: options && options.scriptKind, }); } /** * Asynchronously adds source files based on file globs. * @param fileGlobs - File glob or globs to add files based on. * @returns The matched source files. */ async addSourceFilesByPaths(fileGlobs: string | ReadonlyArray<string>): Promise<ts.SourceFile[]> { if (typeof fileGlobs === "string") fileGlobs = [fileGlobs]; const sourceFilePromises: Promise<void>[] = []; const sourceFiles: ts.SourceFile[] = []; for await (const filePath of this._fileSystemWrapper.glob(fileGlobs)) { sourceFilePromises.push( this.addSourceFileAtPathIfExists(filePath).then(sourceFile => { if (sourceFile != null) sourceFiles.push(sourceFile); }), ); } await Promise.all(sourceFilePromises); return sourceFiles; } /** * Synchronously adds source files based on file globs. * @param fileGlobs - File glob or globs to add files based on. * @returns The matched source files. * @remarks This is much slower than the asynchronous version. */ addSourceFilesByPathsSync(fileGlobs: string | ReadonlyArray<string>): ts.SourceFile[] { if (typeof fileGlobs === "string") fileGlobs = [fileGlobs]; const sourceFiles: ts.SourceFile[] = []; for (const filePath of this._fileSystemWrapper.globSync(fileGlobs)) { const sourceFile = this.addSourceFileAtPathIfExistsSync(filePath); if (sourceFile != null) sourceFiles.push(sourceFile); } return sourceFiles; } /** * Asynchronously adds all the source files from the specified tsconfig.json. * * Note that this is done by default when specifying a tsconfig file in the constructor and not explicitly setting the * `skipAddingSourceFilesFromTsConfig` option to `true`. * @param tsConfigFilePath - File path to the tsconfig.json file. */ addSourceFilesFromTsConfig(tsConfigFilePath: string): Promise<ts.SourceFile[]> { const resolver = this._getTsConfigResolover(tsConfigFilePath); return this._addSourceFilesForTsConfigResolver(resolver, resolver.getCompilerOptions()); } /** * Synchronously adds all the source files from the specified tsconfig.json. * * Note that this is done by default when specifying a tsconfig file in the constructor and not explicitly setting the * `skipAddingSourceFilesFromTsConfig` option to `true`. * @param tsConfigFilePath - File path to the tsconfig.json file. */ addSourceFilesFromTsConfigSync(tsConfigFilePath: string): ts.SourceFile[] { const resolver = this._getTsConfigResolover(tsConfigFilePath); return this._addSourceFilesForTsConfigResolverSync(resolver, resolver.getCompilerOptions()); } /** @internal */ private _getTsConfigResolover(tsConfigFilePath: string) { const standardizedFilePath = this._fileSystemWrapper.getStandardizedAbsolutePath(tsConfigFilePath); return new TsConfigResolver(this._fileSystemWrapper, standardizedFilePath, this.compilerOptions.getEncoding()); } /** * Creates a source file at the specified file path with the specified text. * * Note: The file will not be created and saved to the file system until .save() is called on the source file. * @param filePath - File path of the source file. * @param sourceFileText - Text to use for the source file. * @param options - Options. * @throws - InvalidOperationError if a source file already exists at the provided file path. */ createSourceFile( filePath: string, sourceFileText?: string, options?: { scriptKind?: ts.ScriptKind }, ): ts.SourceFile { return this._sourceFileCache.createSourceFileFromText( this._fileSystemWrapper.getStandardizedAbsolutePath(filePath), sourceFileText || "", { scriptKind: options && options.scriptKind }, ); } /** * Updates the source file stored in the project at the specified path. * @param filePath - File path of the source file. * @param sourceFileText - Text of the source file. * @param options - Options for updating the source file. */ updateSourceFile(filePath: string, sourceFileText: string, options?: { scriptKind?: ts.ScriptKind }): ts.SourceFile; /** * Updates the source file stored in the project. The `fileName` of the source file object is used to tell which file to update. * @param newSourceFile - The new source file. */ updateSourceFile(newSourceFile: ts.SourceFile): ts.SourceFile; updateSourceFile(filePathOrSourceFile: string | ts.SourceFile, sourceFileText?: string, options?: { scriptKind?: ts.ScriptKind }) { if (typeof filePathOrSourceFile === "string") return this.createSourceFile(filePathOrSourceFile, sourceFileText, options); // ensure this has the language service properties set incrementVersion(filePathOrSourceFile); ensureScriptSnapshot(filePathOrSourceFile); return this._sourceFileCache.setSourceFile(filePathOrSourceFile); function incrementVersion(sourceFile: ts.SourceFile) { let version = (sourceFile as any).version || "-1"; const parsedVersion = parseInt(version, 10); if (isNaN(parsedVersion)) version = "0"; else version = (parsedVersion + 1).toString(); (sourceFile as any).version = version; } function ensureScriptSnapshot(sourceFile: ts.SourceFile) { if ((sourceFile as any).scriptSnapshot == null) (sourceFile as any).scriptSnapshot = ts.ScriptSnapshot.fromString(sourceFile.text); } } /** * Removes the source file at the provided file path. * @param filePath - File path of the source file. */ removeSourceFile(filePath: string): void; /** * Removes the provided source file based on its `fileName`. * @param sourceFile - Source file to remove. */ removeSourceFile(sourceFile: ts.SourceFile): void; removeSourceFile(filePathOrSourceFile: string | ts.SourceFile) { this._sourceFileCache.removeSourceFile(this._fileSystemWrapper.getStandardizedAbsolutePath( typeof filePathOrSourceFile === "string" ? filePathOrSourceFile : filePathOrSourceFile.fileName, )); } /** * Adds the source files the project's source files depend on to the project. * @remarks * * This should be done after source files are added to the project, preferably once to * avoid doing more work than necessary. * * This is done by default when creating a Project and providing a tsconfig.json and * not specifying to not add the source files. */ resolveSourceFileDependencies() { // creating a program will resolve any dependencies this.createProgram(); } /** @internal */ async _addSourceFilesForTsConfigResolver(tsConfigResolver: TsConfigResolver, compilerOptions: ts.CompilerOptions) { const sourceFiles: ts.SourceFile[] = []; await Promise.all( tsConfigResolver.getPaths(compilerOptions).filePaths .map(p => this.addSourceFileAtPath(p).then(s => sourceFiles.push(s))), ); return sourceFiles; } /** @internal */ _addSourceFilesForTsConfigResolverSync(tsConfigResolver: TsConfigResolver, compilerOptions: ts.CompilerOptions) { return tsConfigResolver.getPaths(compilerOptions).filePaths.map(p => this.addSourceFileAtPathSync(p)); } /** @internal */ private _oldProgram: ts.Program | undefined; /** * Creates a new program. * Note: You should get a new program any time source files are added, removed, or changed. */ createProgram(options?: ts.CreateProgramOptions): ts.Program { const oldProgram = this._oldProgram; const program = ts.createProgram({ rootNames: Array.from(this._sourceFileCache.getSourceFilePaths()), options: this.compilerOptions.get(), host: this.compilerHost, oldProgram, configFileParsingDiagnostics: this.configFileParsingDiagnostics, ...options, }); this._oldProgram = program; return program; } /** * Gets the language service. */ @Memoize getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.languageServiceHost, this._sourceFileCache.documentRegistry); } /** * Gets a source file by a file name or file path. Throws an error if it doesn't exist. * @param fileNameOrPath - File name or path that the path could end with or equal. */ getSourceFileOrThrow(fileNameOrPath: string): ts.SourceFile; /** * Gets a source file by a search function. Throws an error if it doesn't exist. * @param searchFunction - Search function. */ getSourceFileOrThrow(searchFunction: (file: ts.SourceFile) => boolean): ts.SourceFile; getSourceFileOrThrow(fileNameOrSearchFunction: string | ((file: ts.SourceFile) => boolean)): ts.SourceFile { const sourceFile = this.getSourceFile(fileNameOrSearchFunction); if (sourceFile != null) return sourceFile; // explain to the user why it couldn't find the file if (typeof fileNameOrSearchFunction === "string") { const fileNameOrPath = FileUtils.standardizeSlashes(fileNameOrSearchFunction); if (FileUtils.pathIsAbsolute(fileNameOrPath) || fileNameOrPath.indexOf("/") >= 0) { const errorFileNameOrPath = this._fileSystemWrapper.getStandardizedAbsolutePath(fileNameOrPath); throw new errors.InvalidOperationError(`Could not find source file in project at the provided path: ${errorFileNameOrPath}`); } else { throw new errors.InvalidOperationError(`Could not find source file in project with the provided file name: ${fileNameOrSearchFunction}`); } } else { throw new errors.InvalidOperationError(`Could not find source file in project based on the provided condition.`); } } /** * Gets a source file by a file name or file path. Returns undefined if none exists. * @param fileNameOrPath - File name or path that the path could end with or equal. */ getSourceFile(fileNameOrPath: string): ts.SourceFile | undefined; /** * Gets a source file by a search function. Returns undefined if none exists. * @param searchFunction - Search function. */ getSourceFile(searchFunction: (file: ts.SourceFile) => boolean): ts.SourceFile | undefined; /** * @internal */ getSourceFile(fileNameOrSearchFunction: string | ((file: ts.SourceFile) => boolean)): ts.SourceFile | undefined; getSourceFile(fileNameOrSearchFunction: string | ((file: ts.SourceFile) => boolean)): ts.SourceFile | undefined { const filePathOrSearchFunction = getFilePathOrSearchFunction(this._fileSystemWrapper); if (isStandardizedFilePath(filePathOrSearchFunction)) { // when a file path is specified, return even source files not in the project return this._sourceFileCache.getSourceFileFromCacheFromFilePath(filePathOrSearchFunction); } const allSoureFilesIterable = this.getSourceFiles(); return selectSmallestDirPathResult(function*() { for (const sourceFile of allSoureFilesIterable) { if (filePathOrSearchFunction(sourceFile)) yield sourceFile; } }()); function getFilePathOrSearchFunction(fileSystemWrapper: TransactionalFileSystem): StandardizedFilePath | ((file: ts.SourceFile) => boolean) { if (fileNameOrSearchFunction instanceof Function) return fileNameOrSearchFunction; const fileNameOrPath = FileUtils.standardizeSlashes(fileNameOrSearchFunction); if (FileUtils.pathIsAbsolute(fileNameOrPath) || fileNameOrPath.indexOf("/") >= 0) return fileSystemWrapper.getStandardizedAbsolutePath(fileNameOrPath); else return def => FileUtils.pathEndsWith(def.fileName, fileNameOrPath); } function selectSmallestDirPathResult(results: Iterable<ts.SourceFile>) { let result: ts.SourceFile | undefined; // Select the result with the shortest directory path... this could be more efficient // and better, but it will do for now... for (const sourceFile of results) { if (result == null || FileUtils.getDirPath(sourceFile.fileName).length < FileUtils.getDirPath(result.fileName).length) result = sourceFile; } return result; } // workaround to help the type checker figure this out function isStandardizedFilePath(obj: any): obj is StandardizedFilePath { return typeof obj === "string"; } } /** Gets the source files in the project. */ getSourceFiles() { return Array.from(this._sourceFileCache.getSourceFiles()); } /** * Formats an array of diagnostics with their color and context into a string. * @param diagnostics - Diagnostics to get a string of. * @param options - Collection of options. For example, the new line character to use (defaults to the OS' new line character). */ formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray<ts.Diagnostic>, opts: { newLineChar?: "\n" | "\r\n" } = {}) { return ts.formatDiagnosticsWithColorAndContext(diagnostics, { getCurrentDirectory: () => this._fileSystemWrapper.getCurrentDirectory(), getCanonicalFileName: fileName => fileName, getNewLine: () => opts.newLineChar || runtime.getEndOfLine(), }); } /** * Gets a ts.ModuleResolutionHost for the project. */ @Memoize getModuleResolutionHost(): ts.ModuleResolutionHost { return createModuleResolutionHost({ transactionalFileSystem: this._fileSystemWrapper, getEncoding: () => this.compilerOptions.getEncoding(), sourceFileContainer: this._sourceFileCache, }); } }
the_stack
import type { MLASTDoctype, MLASTElementCloseTag, MLASTNode, MLASTOmittedElement, MLASTParentNode, MLASTTag, MLASTText, } from '@markuplint/ml-ast'; import type { CommentNode, Document, DocumentFragment, Element, Node, TextNode, ElementLocation, Location, } from 'parse5'; import { getEndCol, getEndLine, isPotentialCustomElementName, sliceFragment, uuid } from '@markuplint/parser-utils'; import { parse, parseFragment } from 'parse5'; import parseRawTag from './parse-raw-tag'; interface TraversalNode { childNodes?: P5Node[]; content?: P5Fragment; } type P5Node = Node & TraversalNode; type P5LocatableNode = (TextNode | Element | CommentNode) & TraversalNode; type P5Document = Document & TraversalNode; type P5Fragment = DocumentFragment & TraversalNode; const P5_OPTIONS = { sourceCodeLocationInfo: true }; export function createTree( rawCode: string, isFragment: boolean, offsetOffset: number, offsetLine: number, offsetColumn: number, ) { const doc = isFragment ? (parseFragment(rawCode, P5_OPTIONS) as P5Fragment) : (parse(rawCode, P5_OPTIONS) as P5Document); return createTreeRecursive(doc, null, rawCode, offsetOffset, offsetLine, offsetColumn); } function createTreeRecursive( rootNode: P5Node, parentNode: MLASTParentNode | null, rawHtml: string, offsetOffset: number, offsetLine: number, offsetColumn: number, ): MLASTNode[] { const nodeList: MLASTNode[] = []; const childNodes = getChildNodes(rootNode); let prevNode: MLASTNode | null = null; for (const p5node of childNodes) { const node = nodeize(p5node, prevNode, parentNode, rawHtml, offsetOffset, offsetLine, offsetColumn); if (!node) { continue; } if (prevNode) { if (node.type !== 'endtag') { prevNode.nextNode = node; } node.prevNode = prevNode; } prevNode = node; nodeList.push(node); } return nodeList; } function nodeize( originNode: P5Node, prevNode: MLASTNode | null, parentNode: MLASTParentNode | null, rawHtml: string, offsetOffset: number, offsetLine: number, offsetColumn: number, ): MLASTNode | null { const nextNode = null; const location = getLocation(originNode); if (!location) { const prevToken = prevNode || parentNode; const startOffset = prevToken ? prevToken.endOffset : 0; const endOffset = prevToken ? prevToken.endOffset : 0; const startLine = prevToken ? prevToken.endLine : 0; const endLine = prevToken ? prevToken.endLine : 0; const startCol = prevToken ? prevToken.endCol : 0; const endCol = prevToken ? prevToken.endCol : 0; const node: MLASTOmittedElement = { uuid: uuid(), raw: '', startOffset: startOffset + offsetOffset, endOffset: endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: endCol + (endLine === 1 ? offsetColumn : 0), nodeName: originNode.nodeName, type: 'omittedtag', namespace: getNamespace(originNode), parentNode, prevNode, nextNode, isFragment: false, isGhost: true, isCustomElement: false, }; node.childNodes = createTreeRecursive(originNode, node, rawHtml, offsetOffset, offsetLine, offsetColumn); return node; } const { startOffset, endOffset, startLine, endLine, startCol, endCol } = location; const raw = rawHtml.slice(startOffset, endOffset || startOffset); switch (originNode.nodeName) { case '#documentType': { return { uuid: uuid(), raw, // @ts-ignore name: originNode.name || '', // @ts-ignore publicId: originNode.publicId || '', // @ts-ignore systemId: originNode.systemId || '', startOffset: startOffset + offsetOffset, endOffset: endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: endCol + (endLine === 1 ? offsetColumn : 0), nodeName: '#doctype', type: 'doctype', parentNode, prevNode, _addPrevNode: 102, nextNode, isFragment: false, isGhost: false, } as MLASTDoctype; } case '#text': { const node: MLASTText = { uuid: uuid(), raw, startOffset: startOffset + offsetOffset, endOffset: endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: endCol + (endLine === 1 ? offsetColumn : 0), nodeName: '#text', type: 'text', parentNode, prevNode, nextNode, isFragment: false, isGhost: false, }; return node; } case '#comment': { return { uuid: uuid(), raw, startOffset: startOffset + offsetOffset, endOffset: endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: endCol + (endLine === 1 ? offsetColumn : 0), nodeName: '#comment', type: 'comment', parentNode, prevNode, nextNode, isFragment: false, isGhost: false, }; } default: { const tagLoc = 'startTag' in location ? location.startTag : null; const startTagRaw = tagLoc ? rawHtml.slice(tagLoc.startOffset, tagLoc.endOffset) : rawHtml.slice(startOffset, endOffset || startOffset); const tagTokens = parseRawTag( startTagRaw, startLine, startCol, startOffset, offsetOffset, offsetLine, offsetColumn, ); const tagName = tagTokens.tagName; const isCustomElement = isPotentialCustomElementName(tagName); let endTag: MLASTElementCloseTag | null = null; let endTagLoc = 'endTag' in location ? location.endTag : null; /** * Patch: Create endTag for SVG Element * @see https://github.com/inikulin/parse5/issues/352 */ if ( !endTagLoc && 'namespaceURI' in originNode && originNode.namespaceURI === 'http://www.w3.org/2000/svg' ) { const belowRawHTMLFromStartTagEnd = rawHtml.slice(location.endOffset); const endTagMatched = belowRawHTMLFromStartTagEnd.match(new RegExp(`^</\\s*${tagName}[^>]*>`, 'm')); const endTag = endTagMatched && endTagMatched[0]; if (endTag) { endTagLoc = sliceFragment(rawHtml, location.endOffset, location.endOffset + endTag.length); } } if (endTagLoc) { const { startOffset, endOffset, startLine, endLine, startCol, endCol } = endTagLoc; const endTagRaw = rawHtml.slice(startOffset, endOffset); const endTagTokens = parseRawTag( endTagRaw, startLine, startCol, startOffset, offsetOffset, offsetLine, offsetColumn, ); const endTagName = endTagTokens.tagName; endTag = { uuid: uuid(), raw: endTagRaw, startOffset: startOffset + offsetOffset, endOffset: endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: endCol + (endLine === 1 ? offsetColumn : 0), nodeName: endTagName, type: 'endtag', namespace: getNamespace(originNode), attributes: endTagTokens.attrs, parentNode, prevNode, nextNode, pearNode: null, isFragment: false, isGhost: false, tagOpenChar: '</', tagCloseChar: '>', isCustomElement, }; } const _endOffset = startOffset + startTagRaw.length; const _endLine = getEndLine(startTagRaw, startLine); const _endCol = getEndCol(startTagRaw, startCol); const startTag: MLASTTag = { uuid: uuid(), raw: startTagRaw, startOffset: startOffset + offsetOffset, endOffset: _endOffset + offsetOffset, startLine: startLine + offsetLine, endLine: _endLine + offsetLine, startCol: startCol + (startLine === 1 ? offsetColumn : 0), endCol: _endCol + (startLine === _endLine ? offsetColumn : 0), nodeName: tagName, type: 'starttag', namespace: getNamespace(originNode), attributes: tagTokens.attrs, hasSpreadAttr: false, parentNode, prevNode, nextNode, pearNode: endTag, selfClosingSolidus: tagTokens.selfClosingSolidus, endSpace: tagTokens.endSpace, isFragment: false, isGhost: false, tagOpenChar: '<', tagCloseChar: '>', isCustomElement, }; if (endTag) { endTag.pearNode = startTag; } startTag.childNodes = createTreeRecursive( originNode, startTag, rawHtml, offsetOffset, offsetLine, offsetColumn, ); return startTag; } } } /** * getChildNodes * * - If node has "content" property then parse as document fragment. * - If node is <noscript> then that childNodes is a TextNode. But parse as document fragment it for disabled script. */ function getChildNodes(rootNode: P5Node | P5Document | P5Fragment) { if (rootNode.nodeName === 'noscript') { const textNode = rootNode.childNodes[0]; if (!textNode || textNode.nodeName !== '#text') { return []; } // @ts-ignore const html: string = textNode.value; // @ts-ignore const { startOffset, startLine, startCol } = textNode.sourceCodeLocation; const breakCount = startLine - 1; const indentWidth = startCol - 1; const offsetSpaces = ' '.repeat(startOffset - Math.max(breakCount, 0) - Math.max(indentWidth, 0)) + '\n'.repeat(breakCount) + ' '.repeat(indentWidth); const fragment = parseFragment(`${offsetSpaces}${html}`, P5_OPTIONS); const childNodes = fragment.childNodes.slice(offsetSpaces ? 1 : 0); // const childNodes = ('childNodes' in _childNodes && _childNodes.childNodes) || []; return childNodes; } return rootNode.content ? rootNode.content.childNodes : rootNode.childNodes || []; } function hasLocation(node: P5Node): node is P5LocatableNode { return 'sourceCodeLocation' in node; } function getLocation(node: P5Node): Location | ElementLocation | null { if (hasLocation(node) && node.sourceCodeLocation) { return node.sourceCodeLocation; } return null; } function getNamespace(node: P5Node) { if ('namespaceURI' in node) { return node.namespaceURI; } return ''; }
the_stack
import { strShimUndefined, strShimObject, strShimFunction, throwTypeError, ObjClass, ObjProto, ObjAssign, ObjHasOwnProperty, ObjDefineProperty } from "@microsoft/applicationinsights-shims"; // RESTRICT and AVOID circular dependencies you should not import other contained modules or export the contents of this file directly // Added to help with minfication const strOnPrefix = "on"; const strAttachEvent = "attachEvent"; const strAddEventHelper = "addEventListener"; const strDetachEvent = "detachEvent"; const strRemoveEventListener = "removeEventListener"; const _objDefineProperty = ObjDefineProperty; const _objFreeze = ObjClass["freeze"]; const _objSeal = ObjClass["seal"]; export function objToString(obj: any) { return ObjProto.toString.call(obj); } export function isTypeof(value: any, theType: string): boolean { return typeof value === theType; } export function isUndefined(value: any): boolean { return value === undefined || typeof value === strShimUndefined; } export function isNotUndefined(value: any): boolean { return !isUndefined(value); } export function isNullOrUndefined(value: any): boolean { return (value === null || isUndefined(value)); } export function isNotNullOrUndefined(value: any): boolean { return !isNullOrUndefined(value); } export function hasOwnProperty(obj: any, prop: string): boolean { return obj && ObjHasOwnProperty.call(obj, prop); } export function isObject(value: any): boolean { // Changing to inline for performance return typeof value === strShimObject; } export function isFunction(value: any): value is Function { // Changing to inline for performance return typeof value === strShimFunction; } /** * Binds the specified function to an event, so that the function gets called whenever the event fires on the object * @param obj Object to add the event too. * @param eventNameWithoutOn String that specifies any of the standard DHTML Events without "on" prefix * @param handlerRef Pointer that specifies the function to call when event fires * @param useCapture [Optional] Defaults to false * @returns True if the function was bound successfully to the event, otherwise false */ export function attachEvent(obj: any, eventNameWithoutOn: string, handlerRef: any, useCapture: boolean = false) { let result = false; if (!isNullOrUndefined(obj)) { try { if (!isNullOrUndefined(obj[strAddEventHelper])) { // all browsers except IE before version 9 obj[strAddEventHelper](eventNameWithoutOn, handlerRef, useCapture); result = true; } else if (!isNullOrUndefined(obj[strAttachEvent])) { // IE before version 9 obj[strAttachEvent](strOnPrefix + eventNameWithoutOn, handlerRef); result = true; } } catch (e) { // Just Ignore any error so that we don't break any execution path } } return result; } /** * Removes an event handler for the specified event * @param Object to remove the event from * @param eventNameWithoutOn {string} - The name of the event * @param handlerRef {any} - The callback function that needs to be executed for the given event * @param useCapture [Optional] Defaults to false */ export function detachEvent(obj: any, eventNameWithoutOn: string, handlerRef: any, useCapture: boolean = false) { if (!isNullOrUndefined(obj)) { try { if (!isNullOrUndefined(obj[strRemoveEventListener])) { obj[strRemoveEventListener](eventNameWithoutOn, handlerRef, useCapture); } else if (!isNullOrUndefined(obj[strDetachEvent])) { obj[strDetachEvent](strOnPrefix + eventNameWithoutOn, handlerRef); } } catch (e) { // Just Ignore any error so that we don't break any execution path } } } /** * Validates that the string name conforms to the JS IdentifierName specification and if not * normalizes the name so that it would. This method does not identify or change any keywords * meaning that if you pass in a known keyword the same value will be returned. * This is a simplified version * @param name The name to validate */ export function normalizeJsName(name: string): string { let value = name; let match = /([^\w\d_$])/g; if (match.test(name)) { value = name.replace(match, "_"); } return value; } /** * This is a helper function for the equivalent of arForEach(objKeys(target), callbackFn), this is a * performance optimization to avoid the creation of a new array for large objects * @param target The target object to find and process the keys * @param callbackfn The function to call with the details */ export function objForEachKey(target: any, callbackfn: (name: string, value: any) => void) { if (target) { for (let prop in target) { if (ObjHasOwnProperty.call(target, prop)) { callbackfn.call(target, prop, target[prop]); } } } } /** * The strEndsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. * @param value - The value to check whether it ends with the search value. * @param search - The characters to be searched for at the end of the value. * @returns true if the given search value is found at the end of the string, otherwise false. */ export function strEndsWith(value: string, search: string) { if (value && search) { let searchLen = search.length; let valLen = value.length; if (value === search) { return true; } else if (valLen >= searchLen) { let pos = valLen - 1; for (let lp = searchLen - 1; lp >= 0; lp--) { if (value[pos] != search[lp]) { return false; } pos--; } return true; } } return false; } /** * The strStartsWith() method determines whether a string starts with the characters of the specified string, returning true or false as appropriate. * @param value - The value to check whether it ends with the search value. * @param checkValue - The characters to be searched for at the start of the value. * @returns true if the given search value is found at the start of the string, otherwise false. */ export function strStartsWith(value: string, checkValue: string) { // Using helper for performance and because string startsWith() is not available on IE let result = false; if (value && checkValue) { let chkLen = checkValue.length; if (value === checkValue) { return true; } else if (value.length >= chkLen) { for (let lp = 0; lp < chkLen; lp++) { if (value[lp] !== checkValue[lp]) { return false; } } result = true; } } return result; } /** * A simple wrapper (for minification support) to check if the value contains the search string. * @param value - The string value to check for the existence of the search value * @param search - The value search within the value */ export function strContains(value: string, search: string) { if (value && search) { return value.indexOf(search) !== -1; } return false; } /** * Check if an object is of type Date */ export function isDate(obj: any): obj is Date { return objToString(obj) === "[object Date]"; } /** * Check if an object is of type Array */ export function isArray(obj: any): boolean { return objToString(obj) === "[object Array]"; } /** * Check if an object is of type Error */ export function isError(obj: any): obj is Error { return objToString(obj) === "[object Error]"; } /** * Checks if the type of value is a string. * @param {any} value - Value to be checked. * @return {boolean} True if the value is a string, false otherwise. */ export function isString(value: any): value is string { // Changing to inline for performance return typeof value === "string"; } /** * Checks if the type of value is a number. * @param {any} value - Value to be checked. * @return {boolean} True if the value is a number, false otherwise. */ export function isNumber(value: any): value is number { // Changing to inline for performance return typeof value === "number"; } /** * Checks if the type of value is a boolean. * @param {any} value - Value to be checked. * @return {boolean} True if the value is a boolean, false otherwise. */ export function isBoolean(value: any): value is boolean { // Changing to inline for performance return typeof value === "boolean"; } /** * Checks if the type of value is a Symbol. * This only returns a boolean as returning value is Symbol will cause issues for older TypeScript consumers * @param {any} value - Value to be checked. * @return {boolean} True if the value is a Symbol, false otherwise. */ export function isSymbol(value: any): boolean { return typeof value === "symbol"; } /** * Convert a date to I.S.O. format in IE8 */ export function toISOString(date: Date) { if (isDate(date)) { const pad = (num: number) => { let r = String(num); if (r.length === 1) { r = "0" + r; } return r; } return date.getUTCFullYear() + "-" + pad(date.getUTCMonth() + 1) + "-" + pad(date.getUTCDate()) + "T" + pad(date.getUTCHours()) + ":" + pad(date.getUTCMinutes()) + ":" + pad(date.getUTCSeconds()) + "." + String((date.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) + "Z"; } } /** * Performs the specified action for each element in an array. This helper exists to avoid adding a polyfil for older browsers * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would * cause a testing requirement to test with and without the implementations * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. It can return -1 to break out of the loop * @param thisArg [Optional] An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ export function arrForEach<T>(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => void|number, thisArg?: any): void { let len = arr.length; try { for (let idx = 0; idx < len; idx++) { if (idx in arr) { if (callbackfn.call(thisArg || arr, arr[idx], idx, arr) === -1) { break; } } } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } } /** * Returns the index of the first occurrence of a value in an array. This helper exists to avoid adding a polyfil for older browsers * that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype * implementation. Note: For consistency this will not use the Array.prototype.xxxx implementation if it exists as this would * cause a testing requirement to test with and without the implementations * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ export function arrIndexOf<T>(arr: T[], searchElement: T, fromIndex?: number): number { let len = arr.length; let from = fromIndex || 0; try { for (let lp = Math.max(from >= 0 ? from : len - Math.abs(from), 0); lp < len; lp++) { if (lp in arr && arr[lp] === searchElement) { return lp; } } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } return -1; } /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. This helper exists * to avoid adding a polyfil for older browsers that do not define Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page * checks for presence/absence of the prototype implementation. Note: For consistency this will not use the Array.prototype.xxxx * implementation if it exists as this would cause a testing requirement to test with and without the implementations * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ export function arrMap<T, R>(arr: T[], callbackfn: (value: T, index?: number, array?: T[]) => R, thisArg?: any): R[] { let len = arr.length; let _this = thisArg || arr; let results = new Array(len); try { for (let lp = 0; lp < len; lp++) { if (lp in arr) { results[lp] = callbackfn.call(_this, arr[lp], arr); } } } catch (e) { // This can happen with some native browser objects, but should not happen for the type we are checking for } return results; } /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is * provided as an argument in the next call to the callback function. This helper exists to avoid adding a polyfil for older browsers that do not define * Array.prototype.xxxx (eg. ES3 only, IE8) just in case any page checks for presence/absence of the prototype implementation. Note: For consistency * this will not use the Array.prototype.xxxx implementation if it exists as this would cause a testing requirement to test with and without the implementations * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ export function arrReduce<T, R>(arr: T[], callbackfn: (previousValue: T | R, currentValue?: T, currentIndex?: number, array?: T[]) => R, initialValue?: R): R { let len = arr.length; let lp = 0; let value; // Specifically checking the number of passed arguments as the value could be anything if (arguments.length >= 3) { value = arguments[2]; } else { while (lp < len && !(lp in arr)) { lp++; } value = arr[lp++]; } while (lp < len) { if (lp in arr) { value = callbackfn(value, arr[lp], lp, arr); } lp++; } return value; } /** * helper method to trim strings (IE8 does not implement String.prototype.trim) */ export function strTrim(str: any): string { if (typeof str !== "string") { return str; } return str.replace(/^\s+|\s+$/g, ""); } let _objKeysHasDontEnumBug = !({ toString: null }).propertyIsEnumerable("toString"); let _objKeysDontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ]; /** * Returns the names of the enumerable string properties and methods of an object. This helper exists to avoid adding a polyfil for older browsers * that do not define Object.keys eg. ES3 only, IE8 just in case any page checks for presence/absence of the prototype implementation. * Note: For consistency this will not use the Object.keys implementation if it exists as this would cause a testing requirement to test with and without the implementations * @param obj Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ export function objKeys(obj: {}): string[] { var objType = typeof obj; if (objType !== strShimFunction && (objType !== strShimObject || obj === null)) { throwTypeError("objKeys called on non-object"); } let result: string[] = []; for (let prop in obj) { if (obj && ObjHasOwnProperty.call(obj, prop)) { result.push(prop); } } if (_objKeysHasDontEnumBug) { let dontEnumsLength = _objKeysDontEnums.length; for (let lp = 0; lp < dontEnumsLength; lp++) { if (obj && ObjHasOwnProperty.call(obj, _objKeysDontEnums[lp])) { result.push(_objKeysDontEnums[lp]); } } } return result; } /** * Try to define get/set object property accessors for the target object/prototype, this will provide compatibility with * existing API definition when run within an ES5+ container that supports accessors but still enable the code to be loaded * and executed in an ES3 container, providing basic IE8 compatibility. * @param target The object on which to define the property. * @param prop The name of the property to be defined or modified. * @param getProp The getter function to wire against the getter. * @param setProp The setter function to wire against the setter. * @returns True if it was able to create the accessors otherwise false */ export function objDefineAccessors<T>(target: any, prop: string, getProp?: () => T, setProp?: (v: T) => void): boolean { if (_objDefineProperty) { try { let descriptor: PropertyDescriptor = { enumerable: true, configurable: true } if (getProp) { descriptor.get = getProp; } if (setProp) { descriptor.set = setProp; } _objDefineProperty(target, prop, descriptor); return true; } catch (e) { // IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw // We will just ignore this here. } } return false; } export function objFreeze<T>(value: T): T { if (_objFreeze) { value = _objFreeze(value) as T; } return value; } export function objSeal<T>(value: T): T { if (_objSeal) { value = _objSeal(value) as T; } return value; } /** * Return the current time via the Date now() function (if available) and falls back to (new Date()).getTime() if now() is unavailable (IE8 or less) * https://caniuse.com/#search=Date.now */ export function dateNow() { let dt = Date; if (dt.now) { return dt.now(); } return new dt().getTime(); } /** * Returns the name of object if it's an Error. Otherwise, returns empty string. */ export function getExceptionName(object: any): string { if (isError(object)) { return object.name; } return ""; } /** * Sets the provided value on the target instance using the field name when the provided chk function returns true, the chk * function will only be called if the new value is no equal to the original value. * @param target - The target object * @param field - The key of the target * @param value - The value to set * @param valChk - [Optional] Callback to check the value that if supplied will be called check if the new value can be set * @param srcChk - [Optional] Callback to check to original value that if supplied will be called if the new value should be set (if allowed) * @returns The existing or new value, depending what was set */ export function setValue<T, K extends keyof T>(target: T, field: K, value: T[K], valChk?: (value: T[K]) => boolean, srcChk?: (value: T[K]) => boolean) { let theValue = value; if (target) { theValue = target[field]; if (theValue !== value && (!srcChk || srcChk(theValue)) && (!valChk || valChk(value))) { theValue = value; target[field] = theValue; } } return theValue; } /** * Returns the current value from the target object if not null or undefined otherwise sets the new value and returns it * @param target - The target object to return or set the default value * @param field - The key for the field to set on the target * @param defValue - [Optional] The value to set if not already present, when not provided a empty object will be added */ export function getSetValue<T, K extends keyof T>(target: T, field: K, defValue?: T[K]): T[K] { let theValue; if (target) { theValue = target[field]; if (!theValue && isNullOrUndefined(theValue)) { // Supports having the default as null theValue = !isUndefined(defValue) ? defValue : {} as any; target[field] = theValue; } } else { // Expanded for performance so we only check defValue if required theValue = !isUndefined(defValue) ? defValue : {} as any; } return theValue; } export function isNotTruthy(value: any) { return !value; } export function isTruthy(value: any) { return !!value; } export function throwError(message: string): never { throw new Error(message); } /** * Effectively assigns all enumerable properties (not just own properties) and functions (including inherited prototype) from * the source object to the target, it attempts to use proxy getters / setters (if possible) and proxy functions to avoid potential * implementation issues by assigning prototype functions as instance ones * * This method is the primary method used to "update" the snippet proxy with the ultimate implementations. * * Special ES3 Notes: * Updates (setting) of direct property values on the target or indirectly on the source object WILL NOT WORK PROPERLY, updates to the * properties of "referenced" object will work (target.context.newValue = 10 => will be reflected in the source.context as it's the * same object). ES3 Failures: assigning target.myProp = 3 -> Won't change source.myProp = 3, likewise the reverse would also fail. * @param target - The target object to be assigned with the source properties and functions * @param source - The source object which will be assigned / called by setting / calling the targets proxies * @param chkSet - An optional callback to determine whether a specific property/function should be proxied * @memberof Initialization */ export function proxyAssign(target: any, source: any, chkSet?: (name: string, isFunc?: boolean, source?: any, target?: any) => boolean) { if (target && source && target !== source && isObject(target) && isObject(source)) { // effectively apply/proxy full source to the target instance for (const field in source) { if (isString(field)) { let value = source[field] as any; if (isFunction(value)) { if (!chkSet || chkSet(field, true, source, target)) { // Create a proxy function rather than just copying the (possible) prototype to the new object as an instance function target[field as string] = (function(funcName: string) { return function() { // Capture the original arguments passed to the method var originalArguments = arguments; return source[funcName].apply(source, originalArguments); } })(field); } } else if (!chkSet || chkSet(field, false, source, target)) { if (hasOwnProperty(target, field)) { // Remove any previous instance property delete target[field]; } if (!objDefineAccessors(target, field, () => { return source[field]; }, (theValue) => { source[field] = theValue; })) { // Unable to create an accessor, so just assign the values as a fallback // -- this will (mostly) work for objects // -- but will fail for accessing primitives (if the source changes it) and all types of "setters" as the source won't be modified target[field as string] = value; } } } } } return target; } /** * Simpler helper to create a dynamic class that implements the interface and populates the values with the defaults. * Only instance properties (hasOwnProperty) values are copied from the defaults to the new instance * @param defaults Simple helper */ export function createClassFromInterface<T>(defaults?: T) { return class { constructor() { if (defaults) { objForEachKey(defaults, (field, value) => { (this as any)[field] = value; }); } } } as new () => T; } /** * A helper function to assist with JIT performance for objects that have properties added / removed dynamically * this is primarily for chromium based browsers and has limited effects on Firefox and none of IE. Only call this * function after you have finished "updating" the object, calling this within loops reduces or defeats the benefits. * This helps when iterating using for..in, objKeys() and objForEach() * @param theObject - The object to be optimized if possible */ export function optimizeObject<T>(theObject: T): T { // V8 Optimization to cause the JIT compiler to create a new optimized object for looking up the own properties // primarily for object with <= 19 properties for >= 20 the effect is reduced or non-existent if (theObject) { theObject = ObjClass(ObjAssign ? ObjAssign({}, theObject) : theObject); } return theObject; }
the_stack
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ClipboardModule } from '@angular/cdk/clipboard'; import { NgxTimeDisplayComponent as TestComponent } from './time-display.component'; import { MomentModule } from 'ngx-moment'; import moment from 'moment-timezone'; import { InjectionService } from '../../services/injection/injection.service'; import { TimeZoneModule } from '../../pipes/time-zone/time-zone.module'; const MOON_LANDING = '1969-07-20T20:17:43Z'; const allTimeZones = [ 'Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre', 'Africa/Brazzaville', 'Africa/Bujumbura', 'Africa/Cairo', 'Africa/Casablanca', 'Africa/Ceuta', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Douala', 'Africa/El_Aaiun', 'Africa/Freetown', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Juba', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Kigali', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Lome', 'Africa/Luanda', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Malabo', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Africa/Mogadishu', 'Africa/Monrovia', 'Africa/Nairobi', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Porto-Novo', 'Africa/Tripoli', 'Africa/Tunis', 'Africa/Windhoek', 'America/Adak', 'America/Anchorage', 'America/Anguilla', 'America/Antigua', 'America/Argentina/Buenos_Aires', 'America/Aruba', 'America/Asuncion', 'America/Atikokan', 'America/Barbados', 'America/Belize', 'America/Blanc-Sablon', 'America/Bogota', 'America/Cancun', 'America/Caracas', 'America/Cayenne', 'America/Cayman', 'America/Chicago', 'America/Chihuahua', 'America/Costa_Rica', 'America/Cuiaba', 'America/Curacao', 'America/Danmarkshavn', 'America/Dawson_Creek', 'America/Denver', 'America/Dominica', 'America/Edmonton', 'America/El_Salvador', 'America/Fortaleza', 'America/Godthab', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guatemala', 'America/Guayaquil', 'America/Guyana', 'America/Halifax', 'America/Havana', 'America/Hermosillo', 'America/Jamaica', 'America/Kralendijk', 'America/La_Paz', 'America/Lima', 'America/Los_Angeles', 'America/Lower_Princes', 'America/Managua', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Matamoros', 'America/Mexico_City', 'America/Miquelon', 'America/Montevideo', 'America/Montserrat', 'America/Nassau', 'America/New_York', 'America/Noronha', 'America/Ojinaga', 'America/Panama', 'America/Paramaribo', 'America/Phoenix', 'America/Port_of_Spain', 'America/Port-au-Prince', 'America/Puerto_Rico', 'America/Punta_Arenas', 'America/Regina', 'America/Rio_Branco', 'America/Santiago', 'America/Santo_Domingo', 'America/Sao_Paulo', 'America/Scoresbysund', 'America/St_Barthelemy', 'America/St_Johns', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Tegucigalpa', 'America/Thule', 'America/Tijuana', 'America/Toronto', 'America/Tortola', 'America/Vancouver', 'America/Winnipeg', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Macquarie', 'Antarctica/Mawson', 'Antarctica/Palmer', 'Antarctica/Syowa', 'Antarctica/Vostok', 'Arctic/Longyearbyen', 'Asia/Aden', 'Asia/Almaty', 'Asia/Amman', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Baghdad', 'Asia/Bahrain', 'Asia/Baku', 'Asia/Bangkok', 'Asia/Beirut', 'Asia/Bishkek', 'Asia/Brunei', 'Asia/Chita', 'Asia/Colombo', 'Asia/Damascus', 'Asia/Dhaka', 'Asia/Dili', 'Asia/Dubai', 'Asia/Dushanbe', 'Asia/Hebron', 'Asia/Ho_Chi_Minh', 'Asia/Hong_Kong', 'Asia/Hovd', 'Asia/Irkutsk', 'Asia/Jakarta', 'Asia/Jayapura', 'Asia/Jerusalem', 'Asia/Kabul', 'Asia/Kamchatka', 'Asia/Karachi', 'Asia/Kathmandu', 'Asia/Kolkata', 'Asia/Kuala_Lumpur', 'Asia/Kuwait', 'Asia/Macau', 'Asia/Makassar', 'Asia/Manila', 'Asia/Muscat', 'Asia/Nicosia', 'Asia/Novosibirsk', 'Asia/Omsk', 'Asia/Phnom_Penh', 'Asia/Pyongyang', 'Asia/Qatar', 'Asia/Riyadh', 'Asia/Sakhalin', 'Asia/Seoul', 'Asia/Shanghai', 'Asia/Singapore', 'Asia/Taipei', 'Asia/Tashkent', 'Asia/Tbilisi', 'Asia/Tehran', 'Asia/Thimphu', 'Asia/Tokyo', 'Asia/Ulaanbaatar', 'Asia/Vientiane', 'Asia/Vladivostok', 'Asia/Yangon', 'Asia/Yekaterinburg', 'Asia/Yerevan', 'Atlantic/Azores', 'Atlantic/Bermuda', 'Atlantic/Canary', 'Atlantic/Cape_Verde', 'Atlantic/Faroe', 'Atlantic/Reykjavik', 'Atlantic/South_Georgia', 'Atlantic/St_Helena', 'Atlantic/Stanley', 'Australia/Adelaide', 'Australia/Brisbane', 'Australia/Darwin', 'Australia/Eucla', 'Australia/Lord_Howe', 'Australia/Perth', 'Australia/Sydney', 'Etc/GMT+1', 'Etc/GMT+10', 'Etc/GMT+11', 'Etc/GMT+12', 'Etc/GMT+2', 'Etc/GMT+3', 'Etc/GMT+4', 'Etc/GMT+5', 'Etc/GMT+6', 'Etc/GMT+7', 'Etc/GMT+8', 'Etc/GMT+9', 'Etc/GMT-1', 'Etc/GMT-10', 'Etc/GMT-11', 'Etc/GMT-12', 'Etc/GMT-13', 'Etc/GMT-14', 'Etc/GMT-2', 'Etc/GMT-3', 'Etc/GMT-4', 'Etc/GMT-5', 'Etc/GMT-6', 'Etc/GMT-7', 'Etc/GMT-8', 'Etc/GMT-9', 'Etc/UTC', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Athens', 'Europe/Belgrade', 'Europe/Berlin', 'Europe/Bratislava', 'Europe/Brussels', 'Europe/Bucharest', 'Europe/Budapest', 'Europe/Chisinau', 'Europe/Copenhagen', 'Europe/Dublin', 'Europe/Gibraltar', 'Europe/Guernsey', 'Europe/Helsinki', 'Europe/Isle_of_Man', 'Europe/Istanbul', 'Europe/Jersey', 'Europe/Kaliningrad', 'Europe/Kiev', 'Europe/Lisbon', 'Europe/Ljubljana', 'Europe/London', 'Europe/Luxembourg', 'Europe/Madrid', 'Europe/Malta', 'Europe/Mariehamn', 'Europe/Minsk', 'Europe/Monaco', 'Europe/Moscow', 'Europe/Oslo', 'Europe/Paris', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Riga', 'Europe/Rome', 'Europe/Samara', 'Europe/San_Marino', 'Europe/Sarajevo', 'Europe/Skopje', 'Europe/Sofia', 'Europe/Stockholm', 'Europe/Tallinn', 'Europe/Tirane', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Vilnius', 'Europe/Volgograd', 'Europe/Warsaw', 'Europe/Zagreb', 'Europe/Zurich', 'Indian/Antananarivo', 'Indian/Chagos', 'Indian/Christmas', 'Indian/Cocos', 'Indian/Comoro', 'Indian/Kerguelen', 'Indian/Mahe', 'Indian/Maldives', 'Indian/Mauritius', 'Indian/Mayotte', 'Indian/Reunion', 'Pacific/Apia', 'Pacific/Auckland', 'Pacific/Bougainville', 'Pacific/Chatham', 'Pacific/Chuuk', 'Pacific/Easter', 'Pacific/Efate', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Fiji', 'Pacific/Funafuti', 'Pacific/Galapagos', 'Pacific/Gambier', 'Pacific/Guadalcanal', 'Pacific/Guam', 'Pacific/Honolulu', 'Pacific/Kiritimati', 'Pacific/Majuro', 'Pacific/Marquesas', 'Pacific/Nauru', 'Pacific/Niue', 'Pacific/Norfolk', 'Pacific/Noumea', 'Pacific/Pago_Pago', 'Pacific/Palau', 'Pacific/Pitcairn', 'Pacific/Pohnpei', 'Pacific/Port_Moresby', 'Pacific/Rarotonga', 'Pacific/Saipan', 'Pacific/Tahiti', 'Pacific/Tarawa', 'Pacific/Tongatapu', 'Pacific/Wake', 'Pacific/Wallis' ]; describe('NgxTimeDisplayComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [MomentModule, ClipboardModule, TimeZoneModule], declarations: [TestComponent], schemas: [NO_ERRORS_SCHEMA], providers: [InjectionService] }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should set defaults', () => { expect(component.datetime).toBeDefined(Date); expect(component.defaultInputTimeZone).toBeUndefined(); expect(component.displayTimeZone).toBeUndefined(); expect(component.displayMode).toBe('user'); expect(component.displayFormat).toBe('LLLL'); expect(component.clipFormat).toBe('LLLL'); expect(component.timezones.UTC).toEqual('Etc/UTC'); expect(component.timezones.Local).toEqual(''); }); it('should support all timezones', () => { component.datetime = new Date(); component.timezones = allTimeZones.reduce((acc, curr, index) => { acc[`Zone [${index}]`] = curr; return acc; }, {}); component.ngOnChanges(); fixture.detectChanges(); expect(Object.keys(component.timeValues).length).toEqual(allTimeZones.length); for (const key in component.timeValues) { expect(component.timeValues[key]).toBeTruthy(); expect(component.timeValues[key]).not.toContain('Coordinated Universal Time'); } }); describe('should set timeValues and titleValue', () => { it('current date when no date provided', () => { component.ngOnChanges(); fixture.detectChanges(); expect(component.internalDatetime).toBeDefined(); expect(Object.keys(component.timeValues).length).toEqual(2); expect(component.titleValue).toContain('[Local]'); expect(component.titleValue).toContain('[UTC]'); }); it('when user date provided', () => { const date = '2000-02-05 8:30 AM'; component.datetime = new Date(date); // note: browser timezone component.displayFormat = 'fullDateTime'; component.ngOnChanges(); fixture.detectChanges(); expect(component.internalDatetime.toDateString()).toEqual('Sat Feb 05 2000'); expect(Object.keys(component.timeValues).length).toEqual(2); expect(component.titleValue).toContain('Sat, Feb 5, 2000 8:30 AM -08:00 (PST)'); // note: need TZ set to PST expect(component.titleValue).toContain('[Local]'); // expect(component.titleValue).toContain('Feb 05, 2000 08:30 AM'); expect(component.titleValue).toContain('[UTC]'); for (const key in component.timeValues) { expect(component.timeValues[key]).toBeTruthy(); expect(component.timeValues[key]).not.toContain('Coordinated Universal Time'); } }); it('when iso date provided', () => { component.datetime = new Date(MOON_LANDING); // note: browser UTC component.displayFormat = 'fullDateTime'; component.ngOnChanges(); fixture.detectChanges(); expect(component.internalDatetime.toDateString()).toEqual('Sun Jul 20 1969'); expect(Object.keys(component.timeValues).length).toEqual(2); expect(component.titleValue).toContain('[Local]'); expect(component.titleValue).toContain('Sun, Jul 20, 1969 8:17 PM +00:00 (UTC)'); // note: defaults to UTC expect(component.titleValue).toContain('[UTC]'); for (const key in component.timeValues) { expect(component.timeValues[key]).toBeTruthy(); expect(component.timeValues[key]).not.toContain('Coordinated Universal Time'); } }); }); describe('should handle bad inputs', () => { it('should handle bad date', () => { (moment as any).suppressDeprecationWarnings = true; component.datetime = 'Tomarrow'; component.ngOnChanges(); fixture.detectChanges(); expect(Object.keys(component.timeValues).length).toEqual(0); }); it('should handle bad timezone', () => { (moment as any).suppressDeprecationWarnings = true; component.datetime = new Date(); component.displayFormat = 'fullDateTime'; component.timezones = { Test: 'Timbuktu' }; component.ngOnChanges(); fixture.detectChanges(); expect(component.timeValues['Test'].display).toContain('Coordinated Universal Time'); }); }); });
the_stack