text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import type {
ApolloQueryResult,
ErrorPolicy,
QueryOptions,
SubscribeToMoreOptions,
WatchQueryFetchPolicy,
WatchQueryOptions,
} from '@apollo/client/core';
import type {
ComponentDocument,
FetchMoreParams,
Data,
MaybeTDN,
MaybeVariables,
NextFetchPolicyFunction,
Variables,
} from '@apollo-elements/core/types';
import { GraphQLScriptChildMixin } from '@apollo-elements/mixins/graphql-script-child-mixin';
import { ApolloElement } from './apollo-element.js';
import {
ApolloQueryController,
ApolloQueryControllerOptions,
} from '@apollo-elements/core/apollo-query-controller';
import { NetworkStatus } from '@apollo/client/core';
import { controlled } from '@apollo-elements/core/decorators';
import { customElement, state, property } from '@lit/reactive-element/decorators.js';
import { bound } from '@apollo-elements/core/lib/bound';
declare global { interface HTMLElementTagNameMap { 'apollo-query': ApolloQueryElement } }
/**
* Render a GraphQL query to the DOM
*
* @example <caption>Render a query to Shadow DOM</caption>
* ```html
* <apollo-query>
* <script type="application/graphql">
* query MyProfile {
* profile { name picture }
* }
* </script>
* <template>
* <img loading="lazy" src="{{ data.profile.picture }}" alt="{{ data.profile.name }}"/>
* </template>
* </apollo-query>
* ```
*
* @example <caption>Setting query and variables using the DOM</caption>
* ```html
* <apollo-query id="query-element" template="avatar-template"></apollo-query>
*
* <template id="avatar-template">
* <img loading="lazy" src="{{ data.profile.picture }}" alt="{{ data.profile.name }}"/>
* </template>
*
* <script type="module">
* import { gql } from '@apollo/client/core';
* const el = document.getElementById('query-element');
* el.query = gql`
* query MyProfile($size: Int) {
* profile { name picture(size: $size) }
* }
* `;
* el.variables = { size: 48 };
* </script>
* ```
*/
@customElement('apollo-query')
export class ApolloQueryElement<D extends MaybeTDN = MaybeTDN, V = MaybeVariables<D>> extends
GraphQLScriptChildMixin(ApolloElement)<D, V> {
static readonly is = 'apollo-query';
controller: ApolloQueryController<D, V> = new ApolloQueryController<D, V>(this);
/** @summary Flags an element that's ready and able to auto subscribe */
@controlled({ readonly: true }) @state() canAutoSubscribe = false;
@controlled() @state() options: ApolloQueryControllerOptions<D, V> = {};
/**
* `networkStatus` is useful if you want to display a different loading indicator (or no indicator at all)
* depending on your network status as it provides a more detailed view into the state of a network request
* on your component than `loading` does. `networkStatus` is an enum with different number values between 1 and 8.
* These number values each represent a different network state.
*
* 1. `loading`: The query has never been run before and the request is now pending. A query will still have this network status even if a result was returned from the cache, but a query was dispatched anyway.
* 2. `setVariables`: If a query’s variables change and a network request was fired then the network status will be setVariables until the result of that query comes back. React users will see this when options.variables changes on their queries.
* 3. `fetchMore`: Indicates that fetchMore was called on this query and that the network request created is currently in flight.
* 4. `refetch`: It means that refetch was called on a query and the refetch request is currently in flight.
* 5. Unused.
* 6. `poll`: Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to poll every 10 seconds whenever a poll request has been sent but not resolved.
* 7. `ready`: No request is in flight for this query, and no errors happened. Everything is OK.
* 8. `error`: No request is in flight for this query, but one or more errors were detected.
*
* If the network status is less then 7 then it is equivalent to `loading` being true. In fact you could
* replace all of your `loading` checks with `networkStatus < 7` and you would not see a difference.
* It is recommended that you use `loading`, however.
*/
@controlled() @state() networkStatus = NetworkStatus.ready;
/**
* @summary A GraphQL document containing a single query.
*/
@controlled() @state() query: null | ComponentDocument<D> = null;
/** @summary Context passed to the link execution chain. */
@controlled({ path: 'options' }) @state() context?: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
/**
* If data was read from the cache with missing fields,
* partial will be true. Otherwise, partial will be falsy.
*
* @summary True when the query returned partial data.
*/
@controlled() @state() partial = false;
/**
* If true, perform a query refetch if the query result is marked as being partial,
* and the returned data is reset to an empty Object by the Apollo Client QueryManager
* (due to a cache miss).
*
* The default value is false for backwards-compatibility's sake,
* but should be changed to true for most use-cases.
*
* @summary Set to retry any partial query results.
*/
@controlled({ path: 'options' })
@property({ type: Boolean, attribute: 'partial-refetch' })
partialRefetch?: boolean;
/**
* @summary The time interval (in milliseconds) on which this query should be refetched from the server.
*/
@controlled({ path: 'options' })
@property({ type: Number, attribute: 'poll-interval' })
pollInterval?: number;
/**
* Opt into receiving partial results from the cache for queries
* that are not fully satisfied by the cache.
*/
@controlled({ path: 'options' })
@property({ type: Boolean, attribute: 'return-partial-data' })
returnPartialData?: boolean;
/**
* When true, the component will not automatically subscribe to new data.
* Call the `subscribe()` method to do so.
* @attr no-auto-subscribe
*/
@controlled({ path: 'options' })
@property({ type: Boolean, attribute: 'no-auto-subscribe' })
noAutoSubscribe = false;
/**
* @summary Whether or not updates to the network status should trigger next on the observer of this query.
*/
@controlled({ path: 'options' })
@property({ type: Boolean, attribute: 'notify-on-network-status-change' })
notifyOnNetworkStatusChange = false;
/**
* errorPolicy determines the level of events for errors in the execution result. The options are:
* - `none` (default): any errors from the request are treated like runtime errors and the observable is stopped (XXX this is default to lower breaking changes going from AC 1.0 => 2.0)
* - `ignore`: errors from the request do not stop the observable, but also don't call `next`
* - `all`: errors are treated like data and will notify observables
* @summary [Error Policy](https://www.apollographql.com/docs/react/api/core/ApolloClient/#ErrorPolicy) for the query.
* @attr error-policy
*/
@controlled({ path: 'options' })
@property({ attribute: 'error-policy' })
errorPolicy?: ErrorPolicy;
/**
* Determines where the client may return a result from. The options are:
*
* - `cache-first` (default): return result from cache, fetch from network if cached result is not available.
* - `cache-and-network`: return result from cache first (if it exists), then return network result once it's available.
* - `cache-only`: return result from cache if available, fail otherwise.
* - `no-cache`: return result from network, fail if network call doesn't succeed, don't save to cache
* - `network-only`: return result from network, fail if network call doesn't succeed, save to cache
* - `standby`: only for queries that aren't actively watched, but should be available for refetch and updateQueries.
*
* @summary The [fetchPolicy](https://www.apollographql.com/docs/react/api/core/ApolloClient/#FetchPolicy) for the query.
* @attr fetch-policy
*/
@controlled({ path: 'options' })
@property({ attribute: 'fetch-policy' })
fetchPolicy?: WatchQueryFetchPolicy;
/**
* When someone chooses cache-and-network or network-only as their
* initial FetchPolicy, they often do not want future cache updates to
* trigger unconditional network requests, which is what repeatedly
* applying the cache-and-network or network-only policies would seem
* to imply. Instead, when the cache reports an update after the
* initial network request, it may be desirable for subsequent network
* requests to be triggered only if the cache result is incomplete.
* The nextFetchPolicy option provides a way to update
* options.fetchPolicy after the intial network request, without
* having to set options.
*
* @summary Set to prevent subsequent network requests when the fetch policy is `cache-and-network` or `network-only`.
* @attr next-fetch-policy
*/
@controlled({ path: 'options' })
@property({ attribute: 'next-fetch-policy' })
nextFetchPolicy?: WatchQueryFetchPolicy | NextFetchPolicyFunction<D, V>;
/**
* Exposes the [`ObservableQuery#refetch`](https://www.apollographql.com/docs/react/api/apollo-client.html#ObservableQuery.refetch) method.
*
* @param variables The new set of variables. If there are missing variables, the previous values of those variables will be used..
*/
@bound public async refetch(
variables?: Variables<D, V>
): Promise<ApolloQueryResult<Data<D>>> {
return this.controller.refetch(variables);
}
/**
* Resets the observableQuery and subscribes.
* @param params options for controlling how the subscription subscribes
*/
@bound public subscribe(
params?: Partial<WatchQueryOptions<Variables<D, V>, Data<D>>>
): ZenObservable.Subscription {
return this.controller.subscribe(params);
}
/**
* Lets you pass a GraphQL subscription and updateQuery function
* to subscribe to more updates for your query.
*
* The `updateQuery` parameter is a function that takes the previous query data,
* then a `{ subscriptionData: TSubscriptionResult }` object,
* and returns an object with updated query data based on the new results.
*/
@bound public subscribeToMore<TSubscriptionVariables, TSubscriptionData>(
options: SubscribeToMoreOptions<Data<D>, TSubscriptionVariables, TSubscriptionData>
): (() => void) | void {
return this.controller.subscribeToMore(options);
}
/**
* Executes a Query once and updates the with the result
*/
@bound public async executeQuery(
params?: Partial<QueryOptions<Variables<D, V>, Data<D>>>
): Promise<ApolloQueryResult<Data<D>>> {
return this.controller.executeQuery(params);
}
/**
* Exposes the `ObservableQuery#fetchMore` method.
* https://www.apollographql.com/docs/react/api/core/ObservableQuery/#ObservableQuery.fetchMore
*
* The optional `updateQuery` parameter is a function that takes the previous query data,
* then a `{ subscriptionData: TSubscriptionResult }` object,
* and returns an object with updated query data based on the new results.
*
* The optional `variables` parameter is an optional new variables object.
*/
@bound public async fetchMore(
params?: Partial<FetchMoreParams<D, V>>
): Promise<ApolloQueryResult<Data<D>>> {
return this.controller.fetchMore(params);
}
@bound public startPolling(ms: number): void {
return this.controller.startPolling(ms);
}
@bound public stopPolling(): void {
return this.controller.stopPolling();
}
} | the_stack |
import { asmcode } from "./asm/asmcode";
import { asm, Register, X64Assembler } from "./assembler";
import { proc2 } from "./bds/symbols";
import "./codealloc";
import { abstract, Bufferable, emptyFunc, Encoding } from "./common";
import { AllocatedPointer, cgate, chakraUtil, jshook, NativePointer, runtimeError, StaticPointer, StructurePointer, uv_async, VoidPointer } from "./core";
import { dllraw } from "./dllraw";
import { FunctionGen } from "./functiongen";
import { isBaseOf } from "./util";
import util = require('util');
export type ParamType = makefunc.Paramable;
const functionMap = new AllocatedPointer(0x100);
chakraUtil.JsAddRef(functionMap);
const callNativeFunction:(stackSize:number, writer:(stackptr:NativePointer)=>void, nativefunc:VoidPointer)=>NativePointer = chakraUtil.JsCreateFunction(asmcode.callNativeFunction, null);
const breakBeforeCallNativeFunction:(stackSize:number, writer:(stackptr:NativePointer)=>void, nativefunc:VoidPointer)=>NativePointer = chakraUtil.JsCreateFunction(asmcode.breakBeforeCallNativeFunction, null);
const callJsFunction = asmcode.callJsFunction;
function initFunctionMap():void {
function chakraCoreToDef(funcName:keyof typeof asmcode):void {
(asmcode as any)[funcName] = cgate.GetProcAddress(chakraCoreDll, funcName);
}
const chakraCoreDll = cgate.GetModuleHandleW('ChakraCore.dll');
asmcode.GetCurrentThreadId = dllraw.kernel32.GetCurrentThreadId;
asmcode.uv_async_alloc = uv_async.alloc;
asmcode.uv_async_post = uv_async.post;
asmcode.uv_async_call = uv_async.call;
asmcode.vsnprintf = proc2.vsnprintf;
asmcode.js_null = chakraUtil.asJsValueRef(null);
asmcode.js_undefined = chakraUtil.asJsValueRef(undefined);
asmcode.runtimeErrorRaise = runtimeError.raise;
chakraCoreToDef('JsNumberToInt');
chakraCoreToDef('JsCallFunction');
chakraCoreToDef('JsConstructObject');
chakraCoreToDef('JsGetAndClearException');
asmcode.pointer_js2class = chakraUtil.pointer_js2class;
asmcode.jshook_fireError = jshook.fireErrorPointer;
asmcode.NativePointer = chakraUtil.asJsValueRef(NativePointer);
}
initFunctionMap();
const makefuncTypeMap:makefunc.Paramable[] = [];
function remapType(type:ParamType):makefunc.Paramable {
if (typeof type === 'number') {
if (makefuncTypeMap.length === 0) {
const { RawTypeId } = require('./legacy');
const { bool_t, int32_t, int64_as_float_t, float64_t, float32_t, bin64_t, void_t } = require('./nativetype') as typeof import('./nativetype');
makefuncTypeMap[RawTypeId.Boolean] = bool_t;
makefuncTypeMap[RawTypeId.Int32] = int32_t;
makefuncTypeMap[RawTypeId.FloatAsInt64] = int64_as_float_t;
makefuncTypeMap[RawTypeId.Float64] = float64_t;
makefuncTypeMap[RawTypeId.Float32] = float32_t;
makefuncTypeMap[RawTypeId.StringAnsi] = makefunc.Ansi;
makefuncTypeMap[RawTypeId.StringUtf8] = makefunc.Utf8;
makefuncTypeMap[RawTypeId.StringUtf16] = makefunc.Utf16;
makefuncTypeMap[RawTypeId.Buffer] = makefunc.Buffer;
makefuncTypeMap[RawTypeId.Bin64] = bin64_t;
makefuncTypeMap[RawTypeId.JsValueRef] = makefunc.JsValueRef;
makefuncTypeMap[RawTypeId.Void] = void_t;
}
const res = makefuncTypeMap[type];
if (!res) throw Error(`Invalid RawTypeId: ${type}`);
return res;
}
return type;
}
type InstanceTypeOnly<T> = T extends {prototype:infer V} ? V : never;
type TypeFrom_js2np<T extends ParamType> = InstanceTypeOnly<T>|null;
type TypeFrom_np2js<T extends ParamType> = InstanceTypeOnly<T>;
export type TypesFromParamIds_js2np<T extends ParamType[]> = {
[key in keyof T]: T[key] extends null ? void : T[key] extends ParamType ? TypeFrom_js2np<T[key]> : T[key];
};
export type TypesFromParamIds_np2js<T extends ParamType[]> = {
[key in keyof T]: T[key] extends null ? void : T[key] extends ParamType ? TypeFrom_np2js<T[key]> : T[key];
};
export interface MakeFuncOptions<THIS extends { new(): VoidPointer|void; }>
{
/**
* *Pointer, 'this' parameter passes as first parameter.
*/
this?:THIS;
/**
* it allocates at the first parameter with the returning class and returns it.
* if this is defined, it allocates at the second parameter.
*/
structureReturn?:boolean;
/**
* Option for native debugging
*/
nativeDebugBreak?:boolean;
/**
* Option for JS debugging
*/
jsDebugBreak?:boolean;
/**
* for makefunc.np
* jump to onError when JsCallFunction is failed (js exception, wrong thread, etc)
*/
onError?:VoidPointer|null;
/**
* code chunk name, default: js function name
*/
name?:string;
}
type GetThisFromOpts<OPTS extends MakeFuncOptions<any>|null> =
OPTS extends MakeFuncOptions<infer THIS> ?
THIS extends { new(): VoidPointer; } ? InstanceType<THIS> : void : void;
export type FunctionFromTypes_np<
OPTS extends MakeFuncOptions<any>|null,
PARAMS extends ParamType[],
RETURN extends ParamType> =
(this:GetThisFromOpts<OPTS>, ...args: TypesFromParamIds_np2js<PARAMS>) => TypeFrom_js2np<RETURN>;
export type FunctionFromTypes_js<
PTR extends VoidPointer|[number, number?],
OPTS extends MakeFuncOptions<any>|null,
PARAMS extends ParamType[],
RETURN extends ParamType> =
((this:GetThisFromOpts<OPTS>, ...args: TypesFromParamIds_js2np<PARAMS>) => TypeFrom_np2js<RETURN>)& {
pointer:PTR;
};
export type FunctionFromTypes_js_without_pointer<
OPTS extends MakeFuncOptions<any>|null,
PARAMS extends ParamType[],
RETURN extends ParamType> =
((this:GetThisFromOpts<OPTS>, ...args: TypesFromParamIds_js2np<PARAMS>) => TypeFrom_np2js<RETURN>);
function invalidParameterError(paramName:string, expected:string, actual:unknown):never {
throw TypeError(`unexpected parameter type (${paramName}, expected=${expected}, actual=${actual != null ? (actual as any).constructor.name : actual})`);
}
export namespace makefunc {
export const temporalKeeper:any[] = [];
export const temporalDtors:(()=>void)[] = [];
export const getter = Symbol('getter');
export const setter = Symbol('setter');
export const setToParam = Symbol('makefunc.writeToParam');
export const getFromParam = Symbol('makefunc.readFromParam');
export const useXmmRegister = Symbol('makefunc.returnWithXmm0');
export const dtor = Symbol('makefunc.dtor');
export const ctor_move = Symbol('makefunc.ctor_move');
export const size = Symbol('makefunc.size');
export const registerDirect = Symbol('makefunc.registerDirect');
export interface Paramable {
name:string;
[getter](ptr:StaticPointer, offset?:number):any;
[setter](ptr:StaticPointer, value:any, offset?:number):void;
[getFromParam](stackptr:StaticPointer, offset?:number):any;
[setToParam](stackptr:StaticPointer, param:any, offset?:number):void;
[useXmmRegister]:boolean;
[ctor_move](to:StaticPointer, from:StaticPointer):void;
[dtor](ptr:StaticPointer):void;
[size]:number;
[registerDirect]?:boolean;
isTypeOf(v:unknown):boolean;
/**
* allow downcasting
*/
isTypeOfWeak(v:unknown):boolean;
}
export interface ParamableT<T> extends Paramable {
prototype:T;
[getFromParam](stackptr:StaticPointer, offset?:number):T|null;
[setToParam](stackptr:StaticPointer, param:T extends VoidPointer ? (T|null) : T, offset?:number):void;
[useXmmRegister]:boolean;
isTypeOf<V>(this:{prototype:V}, v:unknown):v is V;
isTypeOfWeak(v:unknown):boolean;
}
export class ParamableT<T> {
constructor(
public readonly name:string,
_getFromParam:(stackptr:StaticPointer, offset?:number)=>T|null,
_setToParam:(stackptr:StaticPointer, param:T extends VoidPointer ? (T|null) : T, offset?:number)=>void,
_ctor_move:(to:StaticPointer, from:StaticPointer)=>void,
isTypeOf:(v:unknown)=>boolean,
isTypeOfWeak:(v:unknown)=>boolean = isTypeOf) {
this[getFromParam] = _getFromParam;
this[setToParam] = _setToParam;
this[ctor_move] = _ctor_move;
this.isTypeOf = isTypeOf as any;
this.isTypeOfWeak = isTypeOfWeak as any;
}
}
ParamableT.prototype[useXmmRegister] = false;
/**
* allocate temporal memory for using in NativeType
* it will removed at native returning
*/
export function tempAlloc(size:number):StaticPointer {
const ptr = new AllocatedPointer(size);
temporalKeeper.push(ptr);
return ptr;
}
/**
* allocate temporal memory for using in NativeType
* it will removed at native returning
*/
export function tempValue(type:Paramable, value:unknown):StaticPointer {
const ptr = tempAlloc(Math.max(type[size], 8)); // XXX: setToParam needs 8 bytes for primitive types
type[setToParam](ptr, value);
return ptr;
}
/**
* allocate temporal string for using in NativeType
* it will removed at native returning
*/
export function tempString(str:string, encoding?:Encoding):StaticPointer {
const ptr = AllocatedPointer.fromString(str, encoding);
temporalKeeper.push(ptr);
return ptr;
}
export function npRaw(func:(stackptr:NativePointer)=>void, onError:VoidPointer, opts?:{name?:string, nativeDebugBreak?:boolean}|null):VoidPointer {
chakraUtil.JsAddRef(func);
const code = asm();
if (opts == null) opts = {};
if (opts.nativeDebugBreak) code.debugBreak();
return code
.mov_r_c(Register.r10, chakraUtil.asJsValueRef(func))
.mov_r_c(Register.r11, onError)
.jmp64(callJsFunction, Register.rax)
.unwind()
.alloc(opts.name || func.name || `#np_call`);
}
/**
* make the JS function as a native function.
*
* wrapper codes are not deleted permanently.
* do not use it dynamically.
*/
export function np<RETURN extends ParamType, OPTS extends MakeFuncOptions<any>|null, PARAMS extends ParamType[]>(
jsfunction: FunctionFromTypes_np<OPTS, PARAMS, RETURN>,
returnType: RETURN, opts?: OPTS, ...params: PARAMS): VoidPointer {
if (typeof jsfunction !== 'function') invalidParameterError('arg1', 'function', jsfunction);
const options:MakeFuncOptions<any> = opts! || {};
const returnTypeResolved = remapType(returnType);
const paramsTypeResolved = params.map(remapType);
const result = returnTypeResolved[makefunc.useXmmRegister] ? asmcode.addressof_xmm0Value : asmcode.addressof_raxValue;
const gen = new FunctionGen;
if (options.jsDebugBreak) gen.writeln('debugger;');
gen.import('temporalKeeper', temporalKeeper);
gen.import('temporalDtors', temporalDtors);
gen.writeln('const keepIdx=temporalKeeper.length;');
gen.writeln('const dtorIdx=temporalDtors.length;');
gen.import('getter', getter);
gen.import('getFromParam', getFromParam);
let offset = 0;
function param(varname:string, type:Paramable):void {
args.push(varname);
gen.import(`${varname}_t`, type);
if (offset >= 0x20) { // args memory space
if (type[registerDirect]) {
gen.writeln(`const ${varname}=${varname}_t[getter](stackptr, ${offset+0x58});`);
} else {
gen.writeln(`const ${varname}=${varname}_t[getFromParam](stackptr, ${offset+0x58});`);
}
} else { // args register space
if (type[registerDirect]) {
gen.writeln(`const ${varname}=${varname}_t[getter](stackptr, ${offset});`);
} else if (type[useXmmRegister]) {
gen.writeln(`const ${varname}=${varname}_t[getFromParam](stackptr, ${offset+0x20});`);
} else {
gen.writeln(`const ${varname}=${varname}_t[getFromParam](stackptr, ${offset});`);
}
}
offset += 8;
}
if (options.structureReturn) {
if (isBaseOf(returnTypeResolved, StructurePointer)) {
param(`retVar`, returnTypeResolved);
} else {
param(`retVar`, StaticPointer);
}
}
const args:string[] = [];
if (options.this != null) {
param(`thisVar`, options.this);
} else {
args.push('null');
}
for (let i=0;i<paramsTypeResolved.length;i++) {
const type = paramsTypeResolved[i];
param(`arg${i}`, type);
}
gen.import('jsfunction', jsfunction);
gen.import('result', result);
gen.import('returnTypeResolved', returnTypeResolved);
gen.import('setToParam', setToParam);
gen.import('ctor_move', ctor_move);
if (options.structureReturn) {
gen.writeln(`const res=jsfunction.call(${args.join(',')});`);
gen.writeln('returnTypeResolved[ctor_move](retVar, res);');
if (isBaseOf(returnTypeResolved, StructurePointer)) {
gen.writeln('returnTypeResolved[setToParam](result, retVar);');
} else {
gen.writeln('result.setPointer(retVar);');
}
} else {
gen.writeln(`const res=jsfunction.call(${args.join(',')});`);
gen.writeln('returnTypeResolved[setToParam](result, res);');
}
gen.writeln('for (let i=temporalDtors.length-1; i>=dtorIdx; i--) {');
gen.writeln(' temporalDtors[i]();');
gen.writeln('}');
gen.writeln('temporalDtors.length = dtorIdx;');
gen.writeln('temporalKeeper.length = keepIdx;');
if (jsfunction.name) {
if (opts == null) opts = {name: jsfunction.name} as OPTS;
else if (opts.name == null) opts.name = jsfunction.name;
}
return npRaw(gen.generate('stackptr'), options.onError || asmcode.jsend_crash, opts);
}
/**
* make the native function as a JS function.
*
* @param returnType *_t or *Pointer
* @param params *_t or *Pointer
*/
export function js<PTR extends VoidPointer|[number, number?], OPTS extends MakeFuncOptions<any>|null, RETURN extends ParamType, PARAMS extends ParamType[]>(
functionPointer: PTR,
returnType:RETURN,
opts?: OPTS,
...params: PARAMS):
FunctionFromTypes_js<PTR, OPTS, PARAMS, RETURN> {
const options:MakeFuncOptions<any> = opts! || {};
const returnTypeResolved = remapType(returnType);
const paramsTypeResolved = params.map(remapType);
let countOnCpp = params.length;
if (options.this != null) countOnCpp++;
const paramsSize = countOnCpp * 8;
let stackSize = Math.max(paramsSize, 0x20); // minimum stack for stable
// 16 bytes align
stackSize += 0x8;
stackSize = ((stackSize + 0xf) & ~0xf);
const ncall = options.nativeDebugBreak ? breakBeforeCallNativeFunction : callNativeFunction;
const gen = new FunctionGen;
if (options.jsDebugBreak) gen.writeln('debugger;');
if (functionPointer instanceof Array) {
// virtual function
const vfoff = functionPointer[0];
const thisoff = functionPointer[1] || 0;
gen.writeln(`const vftable=this.getPointer(${thisoff});`);
gen.writeln(`const func=vftable.getPointer(${vfoff});`);
} else {
if (!(functionPointer instanceof VoidPointer)) throw TypeError(`arg1, expected=*Pointer, actual=${functionPointer}`);
gen.import('func', functionPointer);
}
const returnTypeIsClass = isBaseOf(returnTypeResolved, StructurePointer);
const paramPairs:[string, Paramable][] = [];
if (options.this != null) {
paramPairs.push(['this', options.this]);
}
if (options.structureReturn) {
if (returnTypeIsClass) {
paramPairs.push([`retVar`, returnTypeResolved]);
} else {
paramPairs.push([`retVar`, VoidPointer]);
}
}
gen.import('invalidParameterError', invalidParameterError);
gen.import('setToParam', setToParam);
gen.import('setter', setter);
gen.import('temporalKeeper', temporalKeeper);
gen.import('temporalDtors', temporalDtors);
for (let i=0;i<paramsTypeResolved.length;i++) {
const varname = `arg${i}`;
const type = paramsTypeResolved[i];
paramPairs.push([varname, type]);
gen.writeln(`if (!${varname}_t.isTypeOfWeak(${varname})) invalidParameterError("${varname}", "${type.name}", ${varname});`);
}
gen.writeln('const keepIdx=temporalKeeper.length;');
gen.writeln('const dtorIdx=temporalDtors.length;');
function writeNcall():void {
gen.writeln('ncall(stackSize, stackptr=>{');
let offset = 0;
for (const [varname, type] of paramPairs) {
gen.import(`${varname}_t`, type);
if (type[registerDirect]) {
gen.writeln(` ${varname}_t[setter](stackptr, ${varname}, ${offset});`);
} else {
gen.writeln(` ${varname}_t[setToParam](stackptr, ${varname}, ${offset});`);
}
offset += 8;
}
gen.writeln('}, func);');
}
let returnVar = 'out';
gen.import('stackSize', stackSize);
gen.import('ncall', ncall);
if (options.structureReturn) {
gen.import('returnTypeResolved', returnTypeResolved);
if (returnTypeIsClass) {
gen.writeln('const retVar=new returnTypeResolved(true);');
returnVar = 'retVar';
writeNcall();
} else {
gen.import('getter', getter);
gen.import('AllocatedPointer', AllocatedPointer);
gen.import('returnTypeDtor', returnTypeResolved[dtor]);
gen.import('sizeSymbol', size);
gen.writeln('const retVar = new AllocatedPointer(returnTypeResolved[sizeSymbol]);');
writeNcall();
const getterFunc = returnTypeResolved[getter];
if (getterFunc !== emptyFunc) {
gen.writeln('const out=returnTypeResolved[getter](retVar);');
} else {
returnVar = '';
}
gen.writeln('returnTypeDtor(retVar);');
}
} else {
const result = returnTypeResolved[makefunc.useXmmRegister] ? asmcode.addressof_xmm0Value : asmcode.addressof_raxValue;
gen.import('result', result);
gen.import('returnTypeResolved', returnTypeResolved);
gen.import('getFromParam', getFromParam);
writeNcall();
if (returnTypeIsClass && returnTypeResolved[registerDirect]) {
gen.import('sizeSymbol', size);
gen.writeln('const out=new returnTypeResolved(true);');
gen.writeln(`out.copyFrom(result, returnTypeResolved[sizeSymbol]);`);
} else {
const getterFunc = returnTypeResolved[getFromParam];
if (getterFunc !== emptyFunc) {
gen.writeln('const out=returnTypeResolved[getFromParam](result);');
} else {
returnVar = '';
}
}
}
gen.writeln('for (let i = temporalDtors.length-1; i>= dtorIdx; i--) {');
gen.writeln(' temporalDtors[i]();');
gen.writeln('}');
gen.writeln('temporalDtors.length = dtorIdx;');
gen.writeln('temporalKeeper.length = keepIdx;');
if (returnVar !== '') gen.writeln(`return ${returnVar};`);
const args:string[] = [];
for (let i=0;i<paramsTypeResolved.length;i++) {
args.push('arg'+i);
}
const funcout = gen.generate(...args) as any;
funcout.pointer = functionPointer;
return funcout;
}
export import asJsValueRef = chakraUtil.asJsValueRef;
export const Ansi = new ParamableT<string>(
'Ansi',
(stackptr, offset)=>stackptr.getPointer().getString(undefined, offset, Encoding.Ansi),
(stackptr, param, offset)=>{
if (param === null) {
stackptr.setPointer(null, offset);
} else {
const buf = tempAlloc(param.length*2+1);
const len = buf.setString(param, 0, Encoding.Ansi);
buf.setUint8(0, len);
stackptr.setPointer(buf, offset);
}
},
abstract,
v=>v === null || typeof v === 'string'
);
export const Utf8 = new ParamableT<string>(
'Utf8',
(stackptr, offset)=>stackptr.getPointer().getString(undefined, offset, Encoding.Utf8),
(stackptr, param, offset)=>stackptr.setPointer(param === null ? null : tempString(param), offset),
abstract,
v=>v === null || typeof v === 'string'
);
export const Utf16 = new ParamableT<string>(
'Utf16',
(stackptr, offset)=>stackptr.getPointer().getString(undefined, offset, Encoding.Utf16),
(stackptr, param, offset)=>stackptr.setPointer(param === null ? null : tempString(param, Encoding.Utf16), offset),
abstract,
v=>v === null || typeof v === 'string'
);
export const Buffer = new ParamableT<VoidPointer|Bufferable>(
'Buffer',
(stackptr, offset)=>stackptr.getPointer(offset),
(stackptr, param, offset)=>{
if (param !== null && !(param instanceof VoidPointer)) {
param = VoidPointer.fromAddressBuffer(param);
}
stackptr.setPointer(param, offset);
},
abstract,
v=>{
if (v === null) return true;
if (v instanceof VoidPointer) return true;
if (v instanceof DataView) return true;
if (v instanceof ArrayBuffer) return true;
if (v instanceof Uint8Array) return true;
if (v instanceof Int32Array) return true;
if (v instanceof Uint16Array) return true;
if (v instanceof Uint32Array) return true;
if (v instanceof Int8Array) return true;
if (v instanceof Int16Array) return true;
return false;
}
);
export const JsValueRef = new ParamableT<any>(
'JsValueRef',
(stackptr, offset)=>stackptr.getJsValueRef(offset),
(stackptr, param, offset)=>stackptr.setJsValueRef(param, offset),
abstract,
()=>true
);
}
export interface MakeFuncOptionsWithName<THIS extends { new(): VoidPointer|void; }> extends MakeFuncOptions<THIS> {
/**
* name of the native stack trace
*/
name?:string;
}
declare module "./assembler"
{
interface X64Assembler
{
/**
* asm.alloc + makefunc.js
* allocates it on the executable memory. and make it as a JS function.
*/
make<OPTS extends MakeFuncOptionsWithName<any>|null, RETURN extends ParamType, PARAMS extends ParamType[]>(
returnType: RETURN, opts?: OPTS, ...params: PARAMS):
FunctionFromTypes_js<StaticPointer, OPTS, PARAMS, RETURN>;
}
namespace asm
{
function const_str(str:string, encoding?:BufferEncoding):Buffer;
}
}
declare module "./core"
{
interface VoidPointerConstructor extends makefunc.Paramable{
isTypeOf<T>(this:{new():T}, v:unknown):v is T;
}
interface VoidPointer
{
[asm.splitTwo32Bits]():[number, number];
[util.inspect.custom](depth:number, options:Record<string, any>):unknown;
}
}
declare global
{
interface Uint8Array
{
[asm.splitTwo32Bits]():[number, number];
}
}
VoidPointer.prototype[util.inspect.custom] = function() {
return `${this.constructor.name} { ${this.toString()} }`;
};
VoidPointer[makefunc.size] = 8;
VoidPointer[makefunc.getter] = function<THIS extends VoidPointer>(this:{new(ptr?:VoidPointer):THIS}, ptr:StaticPointer, offset?:number):THIS{
return ptr.getPointerAs(this, offset);
};
VoidPointer[makefunc.setter] = function<THIS extends VoidPointer>(this:{new():THIS}, ptr:StaticPointer, value:VoidPointer, offset?:number):void{
ptr.setPointer(value, offset);
};
VoidPointer[makefunc.setToParam] = function(stackptr:StaticPointer, param:VoidPointer, offset?:number):void {
stackptr.setPointer(param, offset);
};
VoidPointer[makefunc.getFromParam] = function(stackptr:StaticPointer, offset?:number):VoidPointer|null {
return stackptr.getNullablePointerAs(this, offset);
};
makefunc.ParamableT.prototype[makefunc.useXmmRegister] = false;
VoidPointer[makefunc.useXmmRegister] = false;
VoidPointer.prototype[asm.splitTwo32Bits] = function() {
return [this.getAddressLow(), this.getAddressHigh()];
};
Uint8Array.prototype[asm.splitTwo32Bits] = function() {
const ptr = new NativePointer;
ptr.setAddressFromBuffer(this);
return [ptr.getAddressLow(), ptr.getAddressHigh()];
};
VoidPointer.isTypeOf = function<T>(this:{new():T}, v:unknown):v is T {
return v === null || v instanceof this;
};
VoidPointer.isTypeOfWeak = function(v:unknown):boolean{
return v === null || v instanceof VoidPointer;
};
X64Assembler.prototype.make = function<OPTS extends MakeFuncOptionsWithName<any>|null, RETURN extends ParamType, PARAMS extends ParamType[]>(
this:X64Assembler, returnType:RETURN, opts?:OPTS, ...params:PARAMS):
FunctionFromTypes_js<StaticPointer, OPTS, PARAMS, RETURN>{
return makefunc.js(this.alloc(opts && opts.name), returnType, opts, ...params);
}; | the_stack |
interface IAnimation {
/**
* 透明度,参数范围 0~1
*/
opacity(value: number): IAnimation;
/**
* 颜色值
*/
backgroundColor(color: string): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
width(length: number): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
height(length: number): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
top(length: number): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
left(length: number): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
bottom(length: number): IAnimation;
/**
* 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值
*/
right(length: number): IAnimation;
/**
* deg的范围-180~180,从原点顺时针旋转一个deg角度
*/
rotate(deg: number): IAnimation;
/**
* deg的范围-180~180,在X轴旋转一个deg角度
*/
rotateX(deg: number): IAnimation;
/**
* deg的范围-180~180,在Y轴旋转一个deg角度
*/
rotateY(deg: number): IAnimation;
/**
* deg的范围-180~180,在Z轴旋转一个deg角度
*/
rotateZ(deg: number): IAnimation;
/**
* 同transform-function rotate3d
*/
rotate3d(x: number, y: number, z: number, deg: number): IAnimation;
/**
* 一个参数时,表示在X轴、Y轴同时缩放sx倍数;两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数
*/
scale(sx: number, sy?: number): IAnimation;
/**
* 在X轴缩放sx倍数
*/
scaleX(sx: number): IAnimation;
/**
* 在Y轴缩放sy倍数
*/
scaleY(sy: number): IAnimation;
/**
* 在Z轴缩放sy倍数
*/
scaleZ(sz: number): IAnimation;
/**
* 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数
*/
scale3d(sx: number, sy: number, sz: number): IAnimation;
/**
* 一个参数时,表示在X轴偏移tx,单位px;两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。
*/
translate(tx: number, ty?: number): IAnimation;
/**
* 在X轴偏移tx,单位px
*/
translateX(tx: number): IAnimation;
/**
* 在Y轴偏移tx,单位px
*/
translateY(tx: number): IAnimation;
/**
* 在Z轴偏移tx,单位px
*/
translateZ(tx: number): IAnimation;
/**
* 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px
*/
translate3d(tx: number, ty: number, tz: number): IAnimation;
/**
* 参数范围-180~180;一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度;两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度
*/
skew(ax: number, ay?: number): IAnimation;
/**
* 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度
*/
skewX(ax: number): IAnimation;
/**
* 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度
*/
skewY(ay: number): IAnimation;
/**
* 同transform-function matrix
*/
matrix(a, b, c, d, tx, ty): IAnimation;
/**
* 同transform-function matrix3d
*/
matrix3d(): IAnimation;
}
interface ICanvasContext {
/**
* 设置填充色, 如果没有设置 fillStyle,默认颜色为 black。
*/
setFillStyle(color: string): void;
/**
* 设置边框颜色, 如果没有设置 fillStyle,默认颜色为 black。
*/
setStrokeStyle(color: string): void;
/**
* 设置阴影
*/
setShadow(offsetX: number, offsetY: number, blur: number, color: string): void;
/**
* 创建一个线性的渐变颜色。需要使用 addColorStop() 来指定渐变点,至少要两个。
*/
createLinearGradient(x0: number, y0: number, x1: number, y1: number): void;
/**
* 创建一个圆形的渐变颜色。 起点在圆心,终点在圆环。 需要使用 addColorStop() 来指定渐变点,至少要两个。
*/
createCircularGradient(x: number, y: number, r: number): void;
/**
* 创建一个颜色的渐变点。小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。需要使用 addColorStop() 来指定渐变点,至少要两个。
*/
addColorStop(stop: number, color: string): void;
/**
* 设置线条端点的样式
*/
setLineCap(lineCap: 'butt' | 'round' | 'square'): void;
/**
* 设置两线相交处的样式
*/
setLineJoin(lineJoin: 'bevel' | 'round' | 'miter'): void;
/**
* 设置线条宽度
*/
setLineWidth(lineWidth: number): void;
/**
* 设置最大倾斜
*/
setMiterLimit(miterLimit: number): void;
/**
* 添加一个矩形路径到当前路径。
*/
rect(x: number, y: number, width: number, height: number): void;
/**
* 填充一个矩形。用 setFillStyle() 设置矩形的填充色,如果没设置默认是黑色。
*/
fillRect(x: number, y: number, width: number, height: number): void;
/**
* 一个矩形(非填充)。用 setFillStroke() 设置矩形线条的颜色,如果没设置默认是黑色。
*/
strokeRect(x: number, y: number, width: number, height: number): void;
/**
* 在给定的矩形区域内,清除画布上的像素
*/
clearRect(x: number, y: number, width: number, height: number): void;
/**
* 对当前路径进行填充
*/
fill(): void;
/**
* 对当前路径进行描边
*/
stroke(): void;
/**
* 开始一个路径
*/
beginPath(): void;
/**
* 关闭一个路径
*/
closePath(): void;
/**
* 把路径移动到画布中的指定点,但不创建线条。
*/
moveTo(x: number, y: number): void;
/**
* 添加一个新点,然后在画布中创建从该点到最后指定点的线条。
*/
lineTo(x: number, y: number): void;
/**
* 添加一个弧形路径到当前路径,顺时针绘制。
*/
arc(x: number, y: number, radius: number, startAngle: number, sweepAngle: number): void;
/**
* 创建二次方贝塞尔曲线
*/
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void;
/**
* 创建三次方贝塞尔曲线
*/
bezierCurveTo(cpx1: number, cpy1: number, cpx2: number, cpy2: number, x: number, y: number): void;
/**
* 对横纵坐标进行缩放
*/
scale(scaleWidth: number/**横坐标缩放的倍数1 = 100%,0.5 = 50%,2 = 200%,依次类 */, scaleHeight: number/** 纵坐标轴缩放的倍数1 = 100%,0.5 = 50%,2 = 200%,依次类 */): void;
/**
* 对坐标轴进行顺时针旋转
*/
rotate(deg: number/**degrees * Math.PI/180;degrees范围为0~360;旋转角度,以弧度计 */): void;
/**
* 对坐标原点进行缩放
*/
translate(x: number/**水平坐标平移量 */, y: number/**竖直坐标平移量 */): void;
/**
* 在画布上绘制被填充的文本
*/
fillText(text: string, x: number, y: number): void;
/**
* 设置字体大小
*/
setFontSize(fontSize: number): void;
/**
* 在画布上绘制图像
*/
drawImage(imageResource: string, x: number, y: number, width: number, height: number): void;
/**
* 设置全局画笔透明度。
*/
setGlobalAlpha(alpha: number): void;
/**
* 保存当前坐标轴的缩放、旋转、平移信息
*/
save(): void;
/**
* 恢复之前保存过的坐标轴的缩放、旋转、平移信息
*/
restore(): void;
/**
* 进行绘图
*/
draw(): void;
}
interface IAudioContext {
/**
* 播放
*/
play: () => void;
/**
* 暂停
*/
pause: () => void;
/**
* 跳转到指定位置,单位 s
*/
seek: (position: number) => void;
}
interface IVideoContext {
/**
* 播放
*/
play: () => void;
/**
* 暂停
*/
pause: () => void;
/**
* 跳转到指定位置,单位 s
*/
seek: (position: number) => void;
/**
* 发送弹幕,danmu 包含两个属性 text, color。
*/
sendDanmu: (danmu: {text: string; color: string;}) => void;
}
interface IMapContext {
/**
* 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 wx.openLocation
*/
getCenterLocation: (obj: {
/**
* 接口调用成功的回调函数 ,res = { longitude: "经度", latitude: "纬度"}
*/
success?: (res: {longitude: string; latitude: string}) => void;
/**
* 接口调用失败的回调函数
*/
fail?: () => void;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: () => void;
}) => void;
/**
* 将地图中心移动到当前定位点,需要配合map组件的show-location使用
*/
moveToLocation: () => void;
}
interface Application {
setData: (obj: any) => void;
}
interface AppConstructor {
new (): Application;
(opts: {
/**
* 生命周期函数--监听小程序初始化
*/
onLaunch?: () => void;
/**
* 生命周期函数--监听小程序显示
*/
onShow?: () => void;
/**
* 生命周期函数--监听小程序隐藏
*/
onHide?: () => void;
[key: string]: any;
}): Application;
}
declare var App: AppConstructor;
declare function getApp(): Application;
declare function getCurrentPages(): Page[];
interface Page {
setData: (obj: any) => void;
}
interface PageConstructor {
new (): Page;
(opts: {
/**
* 页面的初始数据
*/
data?: any;
/**
* 页面的初始数据
*/
onLoad?: () => void;
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady?: () => void;
/**
* 生命周期函数--监听页面显示
*/
onShow?: () => void;
/**
* 生命周期函数--监听页面隐藏
*/
onHide?: () => void;
/**
* 生命周期函数--监听页面卸载
*/
onUnload?: () => void;
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefreash?: () => void;
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom?: () => void;
/**
* 用户点击右上角分享
*/
onShareAppMessage?: () => {
/**
* 分享标题, 默认值当前小程序名称
*/
title: string;
/**
* 分享描述, 默认值当前小程序名称
*/
desc: string;
/**
* 分享路径 默认值当前页面 path ,必须是以 / 开头的完整路径
*/
path: string;
};
[key: string]: any;
}): Page;
}
declare var Page: PageConstructor;
declare var tt: {
// # 网络 #
request(obj: {
/**
* 开发者服务器接口地址
*/
url: string;
/**
* 请求的参数
*/
data?: any | string;
/**
* 设置请求的 header , header 中不能设置 Referer
*/
header?: any;
/**
* 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
*/
method?: string;
/**
* 默认为 json。如果设置了 dataType 为 json,则会尝试对响应的数据做一次 JSON.parse
*/
dataType?: string;
/**
* 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'}
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 将本地资源上传到开发者服务器。如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,可通过此接口将本地资源上传到指定服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。
*/
uploadFile(obj: {
/**
* 开发者服务器 url
*/
url: string;
/**
* 要上传文件资源的路径
*/
filePath: string;
/**
* 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
*/
name: string;
/**
* HTTP 请求 Header , header 中不能设置 Referer
*/
header?: any;
/**
* HTTP 请求中其他额外的 form data
*/
formData?: any;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。
*/
downloadFile(obj: {
/**
* 下载资源的 url
*/
url: string;
/**
* HTTP 请求 Header
*/
header?: any;
/**
* 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'}
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 创建一个 WebSocket 连接;一个微信小程序同时只能有一个 WebSocket 连接,如果当前已存在一个 WebSocket 连接,会自动关闭该连接,并重新创建一个 WebSocket 连接。
*/
connectSocket(obj: {
/**
* 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
*/
url: string;
/**
* 请求的数据
*/
data?: any;
/**
* HTTP Header , header 中不能设置 Referer
*/
header?: any;
/**
* 默认是GET,有效值: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
*/
method?: string;
/**
* 子协议数组
*/
protocols?: string[];
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 监听WebSocket连接打开事件。
*/
onSocketOpen(callback: Function): void;
/**
* 监听WebSocket错误。
*/
onSocketError(callback: Function): void;
/**
* 通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。
*/
sendSocketMessage(obj: {
/**
* 需要发送的内容
*/
data: undefined;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 监听WebSocket接受到服务器的消息事件。
*/
onSocketMessage(callback: Function): void;
/**
* 关闭WebSocket连接。
*/
closeSocket(obj: {
/**
* 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
*/
code?: number;
/**
* 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
*/
reason?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 监听WebSocket关闭。
*/
onSocketClose(callback: Function): void;
// # 媒体 #
/**
* 从本地相册选择图片或使用相机拍照。
*/
chooseImage(obj: {
/**
* 最多可以选择的图片张数,默认9
*/
count?: number;
/**
* original 原图,compressed 压缩图,默认二者都有
*/
sizeType?: string[];
/**
* album 从相册选图,camera 使用相机,默认二者都有
*/
sourceType?: string[];
/**
* 成功则返回图片的本地文件路径列表 tempFilePaths
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 预览图片。
*/
previewImage(obj: {
/**
* 当前显示图片的链接,不填则默认为 urls 的第一张
*/
current?: string;
/**
* 需要预览的图片链接列表
*/
urls: string[];
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 获取图片信息
*/
getImageInfo(obj: {
/**
* 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径
*/
src: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
saveImageToPhotosAlbum(obj: {
/**
* 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径
*/
filePath: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 开始录音。当主动调用wx.stopRecord,或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。当用户离开小程序时,此接口无法调用。
*/
startRecord(obj: {
/**
* 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'}
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 主动调用停止录音。
*/
stopRecord(): void;
/**
* 开始播放语音,同时只允许一个语音文件正在播放,如果前一个语音文件还没播放完,将中断前一个语音播放。
*/
playVoice(obj: {
/**
* 需要播放的语音文件的文件路径
*/
filePath: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 暂停正在播放的语音。再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。如果想从头开始播放,需要先调用 wx.stopVoice。
*/
pauseVoice(): void;
/**
* 结束播放语音。
*/
stopVoice(): void;
/**
* 获取后台音乐播放状态。
*/
getBackgroundAudioPlayerState(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 使用后台播放器播放音乐,对于微信客户端来说,只能同时有一个后台音乐在播放。当用户离开小程序后,音乐将暂停播放;当用户点击“显示在聊天顶部”时,音乐不会暂停播放;当用户在其他小程序占用了音乐播放器,原有小程序内的音乐将停止播放。
*/
playBackgroundAudio(obj: {
/**
* 音乐链接,目前支持的格式有 m4a, aac, mp3, wav
*/
dataUrl: string;
/**
* 音乐标题
*/
title?: string;
/**
* 封面URL
*/
coverImgUrl?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 暂停播放音乐。
*/
pauseBackgroundAudio(): void;
/**
* 控制音乐播放进度。
*/
seekBackgroundAudio(obj: {
/**
* 音乐位置,单位:秒
*/
position: number;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 停止播放音乐。
*/
stopBackgroundAudio(): void;
/**
* 监听音乐播放。
*/
onBackgroundAudioPlay(callback: Function): void;
/**
* 监听音乐暂停。
*/
onBackgroundAudioPause(callback: Function): void;
/**
* 监听音乐停止。
*/
onBackgroundAudioStop(callback: Function): void;
getBackgroundAudioManager(): void;
/**
* 创建并返回 audio 上下文 audioContext 对象
*/
createAudioContext(audioId: string): IAudioContext;
/**
* 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。
*/
chooseVideo(obj: {
/**
* album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera']
*/
sourceType?: string[];
/**
* 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒
*/
maxDuration?: number;
/**
* 默认调起的为前置还是后置摄像头。front: 前置,back: 后置,默认 back
*/
camera?: string;
/**
* 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
saveVideoToPhotosAlbum(obj: {
/**
* 视频文件路径,可以是临时文件路径也可以是永久文件路径
*/
filePath: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 创建并返回 video 上下文 videoContext 对象
*/
createVideoContext(videoId: string): IVideoContext;
// # 文件 #
/**
* 保存文件到本地。
*/
saveFile(obj: {
/**
* 需要保存的文件的临时路径
*/
tempFilePath: string;
/**
* 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'}
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 获取本地已保存的文件列表
*/
getSavedFileList(obj: {
/**
* 接口调用成功的回调函数,返回结果见success返回参数说明
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 获取本地文件的文件信息。此接口只能用于获取已保存到本地的文件,若需要获取临时文件信息,请使用 wx.getFileInfo 接口。
*/
getSavedFileInfo(obj: {
/**
* 文件路径
*/
filePath: string;
/**
* 接口调用成功的回调函数,返回结果见success返回参数说明
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 删除本地存储的文件
*/
removeSavedFile(obj: {
/**
* 需要删除的文件路径
*/
filePath: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx
*/
openDocument(obj: {
/**
* 文件路径,可通过 downFile 获得
*/
filePath: string;
/**
* 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx
*/
fileType?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getFileInfo(obj: {
/**
* 本地文件路径
*/
filePath: string;
/**
* 计算文件摘要的算法,默认值 md5,有效值:md5,sha1
*/
digestAlgorithm?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
// # 数据缓存 #
/**
* 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
*/
setStorage(obj: {
/**
* 本地缓存中的指定的 key
*/
key: string;
/**
* 需要存储的内容
*/
data: any;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
*/
setStorageSync(key: string, data: any, ): void;
/**
* 从本地缓存中异步获取指定 key 对应的内容。
*/
getStorage(obj: {
/**
* 本地缓存中的指定的 key
*/
key: string;
/**
* 接口调用的回调函数,res = {data: key对应的内容}
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 从本地缓存中同步获取指定 key 对应的内容。
*/
getStorageSync(key: string): void;
/**
* 异步获取当前storage的相关信息
*/
getStorageInfo(obj: {
/**
* 接口调用的回调函数,详见返回参数说明
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 同步获取当前storage的相关信息
*/
getStorageInfoSync(): void;
/**
* 从本地缓存中异步移除指定 key 。
*/
removeStorage(obj: {
/**
* 本地缓存中的指定的 key
*/
key: string;
/**
* 接口调用的回调函数
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 从本地缓存中同步移除指定 key 。
*/
removeStorageSync(key: string): void;
/**
* 清理本地数据缓存。
*/
clearStorage(): void;
/**
* 同步清理本地数据缓存
*/
clearStorageSync(): void;
// # 位置 #
/**
* 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。
*/
getLocation(obj: {
/**
* 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标
*/
type?: string;
/**
* 接口调用成功的回调函数,返回内容详见返回参数说明。
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 打开地图选择位置
*/
chooseLocation(obj: {
/**
* 接口调用成功的回调函数,返回内容详见返回参数说明。
*/
success: Function;
/**
* 用户取消时调用
*/
cancel?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 使用微信内置地图查看位置
*/
openLocation(obj: {
/**
* 纬度,范围为-90~90,负数表示南纬
*/
latitude: number;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude: number;
/**
* 缩放比例,范围5~18,默认为18
*/
scale?: number;
/**
* 位置名
*/
name?: string;
/**
* 地址的详细说明
*/
address?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 创建并返回 map 上下文 mapContext 对象
*/
createMapContext(mapId: string): IMapContext;
// # 设备 #
/**
* 获取系统信息。
*/
getSystemInfo(obj: {
/**
* 接口调用成功的回调
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 获取系统信息同步接口
*/
getSystemInfoSync(): void;
/**
* 获取网络类型。
*/
getNetworkType(obj: {
/**
* 接口调用成功,返回网络类型 networkType
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
onNetworkStatusChange(callback: Function): void;
setScreenBrightness(obj: {
/**
* 屏幕亮度值,范围 0~1,0 最暗,1 最亮
*/
value: number;
/**
* 接口调用成功
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getScreenBrightness(obj: {
/**
* 接口调用成功
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
vibrateLong(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
vibrateShort(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 wx.stopAccelerometer 停止监听。
*/
onAccelerometerChange(callback: Function): void;
startAccelerometer(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
stopAccelerometer(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 监听罗盘数据,频率:5次/秒,接口调用后会自动开始监听,可使用wx.stopCompass停止监听。
*/
onCompassChange(callback: Function): void;
startCompass(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
stopCompass(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
makePhoneCall(obj: {
/**
* 需要拨打的电话号码
*/
phoneNumber: string;
/**
* 接口调用成功的回调
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 调起客户端扫码界面,扫码成功后返回对应的结果
*/
scanCode(obj: {
/**
* 是否只能从相机扫码,不允许从相册选择图片
*/
onlyFromCamera?: boolean;
/**
* 接口调用成功的回调函数,返回内容详见返回参数说明。
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
setClipboardData(obj: {
/**
* 需要设置的内容
*/
data: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getClipboardData(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
openBluetoothAdapter(obj: {
/**
* 成功则返回成功初始化信息
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
closeBluetoothAdapter(obj: {
/**
* 成功则返回成功关闭模块信息
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getBluetoothAdapterState(obj: {
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
onBluetoothAdapterStateChange(callback: Function): void;
startBluetoothDevicesDiscovery(obj: {
/**
* 蓝牙设备主 service 的 uuid 列表
*/
services?: Array<any>;
/**
* 是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同
*/
allowDuplicatesKey?: boolean;
/**
* 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报
*/
interval?: number;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
stopBluetoothDevicesDiscovery(obj: {
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getBluetoothDevices(obj: {
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
onBluetoothDeviceFound(callback: Function): void;
getConnectedBluetoothDevices(obj: {
/**
* 蓝牙设备主 service 的 uuid 列表
*/
services: Array<any>;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
createBLEConnection(obj: {
/**
* 蓝牙设备 id,参考 getDevices 接口
*/
deviceId: string;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
closeBLEConnection(obj: {
/**
* 蓝牙设备 id,参考 getDevices 接口
*/
deviceId: string;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getBLEDeviceServices(obj: {
/**
* 蓝牙设备 id,参考 getDevices 接口
*/
deviceId: string;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getBLEDeviceCharacteristics(obj: {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId: string;
/**
* 蓝牙服务 uuid
*/
serviceId: string;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
readBLECharacteristicValue(obj: {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId: string;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId: string;
/**
* 蓝牙特征值的 uuid
*/
characteristicId: string;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
writeBLECharacteristicValue(obj: {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId: string;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId: string;
/**
* 蓝牙特征值的 uuid
*/
characteristicId: string;
/**
* 蓝牙设备特征值对应的二进制值(注意:vConsole 无法打印出 ArrayBuffer 类型数据)
*/
value: undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
notifyBLECharacteristicValueChange(obj: {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId: string;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId: string;
/**
* 蓝牙特征值的 uuid
*/
characteristicId: string;
/**
* true: 启用 notify; false: 停用 notify
*/
state: boolean;
/**
* 成功则返回本机蓝牙适配器状态
*/
success: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
onBLEConnectionStateChange(callback: Function): void;
onBLECharacteristicValueChange(callback: Function): void;
startBeaconDiscovery(obj: {
/**
* iBeacon设备广播的 uuids
*/
uuids: string[];
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
stopBeaconDiscovery(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getBeacons(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
onBeaconUpdate(callback: Function): void;
onBeaconServiceChange(callback: Function): void;
onUserCaptureScreen(callback: Function): void;
addPhoneContact(obj: {
/**
* 头像本地文件路径
*/
photoFilePath?: string;
/**
* 昵称
*/
nickName?: string;
/**
* 姓氏
*/
lastName?: string;
/**
* 中间名
*/
middleName?: string;
/**
* 名字
*/
firstName: string;
/**
* 备注
*/
remark?: string;
/**
* 手机号
*/
mobilePhoneNumber?: string;
/**
* 微信号
*/
weChatNumber?: string;
/**
* 联系地址国家
*/
addressCountry?: string;
/**
* 联系地址省份
*/
addressState?: string;
/**
* 联系地址城市
*/
addressCity?: string;
/**
* 联系地址街道
*/
addressStreet?: string;
/**
* 联系地址邮政编码
*/
addressPostalCode?: string;
/**
* 公司
*/
organization?: string;
/**
* 职位
*/
title?: string;
/**
* 工作传真
*/
workFaxNumber?: string;
/**
* 工作电话
*/
workPhoneNumber?: string;
/**
* 公司电话
*/
hostNumber?: string;
/**
* 电子邮件
*/
email?: string;
/**
* 网站
*/
url?: string;
/**
* 工作地址国家
*/
workAddressCountry?: string;
/**
* 工作地址省份
*/
workAddressState?: string;
/**
* 工作地址城市
*/
workAddressCity?: string;
/**
* 工作地址街道
*/
workAddressStreet?: string;
/**
* 工作地址邮政编码
*/
workAddressPostalCode?: string;
/**
* 住宅传真
*/
homeFaxNumber?: string;
/**
* 住宅电话
*/
homePhoneNumber?: string;
/**
* 住宅地址国家
*/
homeAddressCountry?: string;
/**
* 住宅地址省份
*/
homeAddressState?: string;
/**
* 住宅地址城市
*/
homeAddressCity?: string;
/**
* 住宅地址街道
*/
homeAddressStreet?: string;
/**
* 住宅地址邮政编码
*/
homeAddressPostalCode?: string;
/**
* 接口调用成功
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
// # 界面 #
/**
* 显示消息提示框
*/
showToast(obj: {
/**
* 提示的内容
*/
title: string;
/**
* 图标,有效值 "success", "loading"
*/
icon?: string;
/**
* 自定义图标的本地路径,image 的优先级高于 icon
*/
image?: string;
/**
* 提示的延迟时间,单位毫秒,默认:1500
*/
duration?: number;
/**
* 是否显示透明蒙层,防止触摸穿透,默认:false
*/
mask?: boolean;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
showLoading(obj: {
/**
* 提示的内容
*/
title: string;
/**
* 是否显示透明蒙层,防止触摸穿透,默认:false
*/
mask?: boolean;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 隐藏消息提示框
*/
hideToast(): void;
hideLoading(): void;
/**
* 显示模态弹窗
*/
showModal(obj: {
/**
* 提示的标题
*/
title: string;
/**
* 提示的内容
*/
content: string;
/**
* 是否显示取消按钮,默认为 true
*/
showCancel?: boolean;
/**
* 取消按钮的文字,默认为"取消",最多 4 个字符
*/
cancelText?: string;
/**
* 取消按钮的文字颜色,默认为"#000000"
*/
cancelColor?: undefined;
/**
* 确定按钮的文字,默认为"确定",最多 4 个字符
*/
confirmText?: string;
/**
* 确定按钮的文字颜色,默认为"#3CC51F"
*/
confirmColor?: undefined;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 显示操作菜单
*/
showActionSheet(obj: {
/**
* 按钮的文字数组,数组长度最大为6个
*/
itemList: undefined;
/**
* 按钮的文字颜色,默认为"#000000"
*/
itemColor?: undefined;
/**
* 接口调用成功的回调函数,详见返回参数说明
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
setTopBarText(obj: {
/**
* 置顶栏文字内容
*/
text: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 动态设置当前页面的标题。
*/
setNavigationBarTitle(obj: {
/**
* 页面标题
*/
title: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 在当前页面显示导航条加载动画。
*/
showNavigationBarLoading(): void;
/**
* 隐藏导航条加载动画。
*/
hideNavigationBarLoading(): void;
/**
* 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。
*/
navigateTo(obj: {
/**
* 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数。参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;如 'path?key=value&key2=value2'
*/
url: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 关闭当前页面,跳转到应用内的某个页面。
*/
redirectTo(obj: {
/**
* 需要跳转的应用内非 tabBar 的页面的路径,路径后可以带参数。参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;如 'path?key=value&key2=value2'
*/
url: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
reLaunch(obj: {
/**
* 需要跳转的应用内页面路径 , 路径后可以带参数。参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔;如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数
*/
url: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
*/
switchTab(obj: {
/**
* 需要跳转的 tabBar 页面的路径(需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数
*/
url: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 关闭当前页面,返回上一页面或多级页面。可通过 getCurrentPages()) 获取当前的页面栈,决定需要返回几层。
*/
navigateBack(obj: {
/**
* 返回的页面数,如果 delta 大于现有页面数,则返回到首页。
*/
delta?: number;
}): void;
/**
* 创建一个动画实例animation。调用实例的方法来描述动画。最后通过动画实例的export方法导出动画数据传递给组件的animation属性。
*/
createAnimation(obj: {
/**
* 400
*/
duration?: number;
/**
* "linear"
*/
timingFunction?: string;
/**
* 0
*/
delay?: number;
/**
* "50% 50% 0"
*/
transformOrigin?: string;
}): IAnimation;
pageScrollTo(obj: {
/**
* 滚动到页面的目标位置(单位px)
*/
scrollTop: number;
}): void;
/**
* 创建 canvas 绘图上下文(指定 canvasId).Tip: 需要指定 canvasId,该绘图上下文只作用于对应的 <canvas/>
*/
createCanvasContext(canvasId: string): ICanvasContext;
/**
* 把当前画布的内容导出生成图片,并返回文件路径
*/
canvasToTempFilePath(canvasId: string): void;
startPullDownRefresh(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 停止当前页面下拉刷新。
*/
stopPullDownRefresh(): void;
// # WXML节点信息 #
// # 第三方平台 #
getExtConfig(obj: {
/**
* 返回第三方平台自定义的数据
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getExtConfigSync(): void;
// # 开放接口 #
/**
* 调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)。用户数据的加解密通讯需要依赖会话密钥完成。
*/
login(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 通过上述接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用wx.checkSession接口检测当前用户登录态是否有效。登录态过期后开发者可以再调用wx.login获取新的用户登录态。
*/
checkSession(obj: {
/**
* 接口调用成功的回调函数,登录态未过期
*/
success?: Function;
/**
* 接口调用失败的回调函数,登录态已过期
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
authorize(obj: {
/**
* 需要获取权限的scope,详见 scope 列表
*/
scope: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 获取用户信息,withCredentials 为 true 时需要先调用 wx.login 接口。
*/
getUserInfo(obj: {
/**
* 是否带上登录态信息
*/
withCredentials?: boolean;
/**
* 指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文
*/
lang?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
/**
* 发起微信支付。
*/
requestPayment(obj: {
/**
* 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
*/
timeStamp: string;
/**
* 随机字符串,长度为32个字符以下。
*/
nonceStr: string;
/**
* 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
*/
package: string;
/**
* 签名算法,暂支持 MD5
*/
signType: string;
/**
* 签名,具体签名方案参见小程序支付接口文档;
*/
paySign: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
chooseAddress(obj: {
/**
* 返回用户选择的收货地址信息
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
addCard(obj: {
/**
* 需要添加的卡券列表,列表内对象说明请参见请求对象说明
*/
cardList: undefined;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
openCard(obj: {
/**
* 需要打开的卡券列表,列表内参数详见openCard 请求对象说明
*/
cardList: undefined;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
openSetting(obj: {
/**
* 接口调用成功的回调函数,返回内容详见返回参数说明。
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getSetting(obj: {
/**
* 接口调用成功的回调函数,返回内容详见返回参数说明。
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
getWeRunData(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
navigateToMiniProgram(obj: {
/**
* 要打开的小程序 appId
*/
appId: string;
/**
* 打开的页面路径,如果为空则打开首页
*/
path?: string;
/**
* 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch(),App.onShow() 中获取到这份数据。详情
*/
extraData?: any;
/**
* 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是体验版或正式版,则打开的小程序必定是正式版。默认值 release
*/
envVersion?: string;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
chooseInvoiceTitle(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
checkIsSupportSoterAuthentication(obj: {
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
// # 数据 #
/**
* 自定义分析数据上报接口。使用前,需要在小程序管理后台自定义分析中新建事件,配置好事件名与字段。
*/
reportAnalytics(eventName: string, data: string, ): void;
// # 拓展接口 #
arrayBufferToBase64(arrayBuffer: string): void;
base64ToArrayBuffer(base64: string): void;
// # 调试接口 #
setEnableDebug(obj: {
/**
* 是否打开调试
*/
enableDebug: boolean;
/**
* 接口调用成功的回调函数
*/
success?: Function;
/**
* 接口调用失败的回调函数
*/
fail?: Function;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: Function;
}): void;
} | the_stack |
import {
Component, EventHandler, Event, Property, setStyleAttribute, addClass, removeClass,
isNullOrUndefined, EmitType, NotifyPropertyChanges, BaseEventArgs, INotifyPropertyChanged,
Animation, AnimationModel, AnimationOptions, Browser, createElement
} from '@syncfusion/ej2-base';
import { Sidebar } from '../src/sidebar/sidebar';
import { profile, inMB, getMemoryProfile } from './common.spec';
describe('Sidebar', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe("Sidebar DOM class Testing ", () => {
let sidebar: any;
beforeEach((): void => {
let ele: HTMLElement = document.createElement("div");
let sibin: HTMLElement = document.createElement("div");
ele.innerHTML = "<h3>Testing of Sidebar</h3>"
sibin.innerHTML = "Side bar";
sibin.className = 'e-content-section';
ele.id = "sidebar";
ele.style.width = "300px";
ele.style.height = "100%";
document.body.style.margin = "0px";
let div: any = document.createElement('div');
let span: any = document.createElement('span');
div.className = 'e-context-element';
div.appendChild(span);
document.body.appendChild(div);
document.body.appendChild(ele);
document.body.appendChild(sibin);
});
afterEach((): void => {
if (sidebar) {
sidebar.destroy();
}
document.body.innerHTML = "";
});
//width test case
it("Sidebar width test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ width: '250px' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("250px");
});
it("Sidebar width px number test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ width: 250 }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("250px");
});
it("Sidebar width em test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ width: '10em' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("10em");
});
it("Sidebar width % test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ width: '50%' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("50%");
});
it("Sidebar width test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ width: '250' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("250px");
});
it("Sidebar default width test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("auto");
});
it("Sidebar width onproperty change test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.width = "500px";
sidebar.dataBind();
sidebar.show();
expect(document.getElementById('sidebar').style.width).toBe("500px");
});
// RTL test case
it("Sidebar with enableRtl true test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableRtl: true }, ele);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-rtl')).toBe(true);
});
it("Sidebar with enableRtl false test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableRtl: false }, ele);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-rtl')).toBe(false);
});
// animation test case
it("Sidebar with animation disabled test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ animate: false, type: 'Push' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-disable-animation')).toBe(true);
});
it("Sidebar auto type animation test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ type: 'Auto' }, ele);
expect(sidebar.element.classList.contains('e-transition')).toBe(true);
sidebar.destroy();
expect(sidebar.element.classList.length).toBe(0);
});
// e-visibility test case
it("Sidebar with e-visibility test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Push' }, ele);
expect(document.getElementById('sidebar').classList.contains('e-visibility')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-visibility')).toBe(false);
});
//e-visibility test case
it("Sidebar with e-visibility test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto' }, ele);
expect(document.getElementById('sidebar').classList.contains('e-visibility')).toBe(false);
});
//mediaQuery test case
it("Sidebar with auto type and mediaQuery test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto', mediaQuery: '(min-width:1400px)' }, ele);
expect(document.getElementById('sidebar').classList.contains('e-visibility')).toBe(false);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(false);
});
it("Sidebar with auto type and mediaQuer list test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto', mediaQuery: window.matchMedia('min-width:1400px') }, ele);
expect(document.getElementById('sidebar').classList.contains('e-visibility')).toBe(false);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(false);
});
// animation onproperty change test case
it("Sidebar with animation disabled test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ animate: false, type: 'Push' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-disable-animation')).toBe(true);
sidebar.animate = true;
sidebar.dataBind();
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-disable-animation')).toBe(false);
sidebar.hide();
sidebar.dataBind();
expect(document.getElementById('sidebar').classList.contains('e-disable-animation')).toBe(false);
});
// RTL tes case
it("enabledRtl onproperty test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.enableRtl = true;
sidebar.dataBind();
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-rtl')).toBe(true);
sidebar.enableRtl = false;
sidebar.dataBind();
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-rtl')).toBe(false);
});
// Tab Index
it('tab index of focus element', () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
expect(sidebar.element.getAttribute('tabindex') === '0').toBe(true);
});
it('while give tab index to the sidebar component', () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.element.tabIndex = '4';
expect(sidebar.element.getAttribute('tabindex') === '4').toBe(true);
});
it('Tab index checking while destroy the component', () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
ele.setAttribute('tabindex', '1');
sidebar = new Sidebar({}, ele);
sidebar.destroy();
expect(ele.getAttribute('tabindex') === '1').toBe(true);
});
it('Tab index checking while destroy the Angular component', () => {
let element: any = createElement('ejs-sidebar', { id: 'sidebarTag' });
element.setAttribute('tabindex', '1');
document.body.appendChild(element);
let sidebarEle = new Sidebar();
sidebarEle.appendTo(element);
sidebarEle.destroy();
expect(element.getAttribute('tabindex') === '1').toBe(true);
});
it("Sidebar slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide" }, ele);
sidebar.show();
});
it("Sidebar slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true }, ele);
});
it("Sidebar main content animation class testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide" }, ele);
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-content-section')).classList.contains('e-content-animation')).toBe(true);
});
it("Sidebar push with left position testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", width: '400px' }, ele);
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("400px");
sidebar.position = 'Right';
sidebar.dataBind();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("400px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
sidebar.hide();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
sidebar.position = 'Left';
sidebar.show();
sidebar.dataBind();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("400px");
});
//enableGestures test case
it("Sidebar enableGestures test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableGestures: true, type: "Push" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
//onProperty test case
sidebar.enableGestures = false;
sidebar.dataBind();
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(false);
});
it("Sidebar with swipe towards right direction test case", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Right',
startX: 20,
distanceX: 60,
velocity: 0.5
};
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableGestures: true, type: "Push" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
});
it("Sidebar with swipe towards left direction test case", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Left',
startX: 20,
distanceX: 60,
velocity: 0.5
};
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableGestures: true, type: "Push" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
});
it("Sidebar with swipe towards left direction with right position test case", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Left', startX: window.innerWidth - 20,
distanceX: 60,
velocity: 0.5
};
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableGestures: true, position: 'Right', type: "Push" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
});
it("Sidebar with swipe towards left direction with right position test case", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Right', startX: 20,
distanceX: 60,
velocity: 0.5
};
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableGestures: true, position: 'Right', type: "Push" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
});
it("Sidebar with swipe towards right direction test case (event)", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Right',
startX: 20,
distanceX: 60,
velocity: 0.5
};
let openCount:number=0;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
enableGestures: true, type: "Push",
open: ()=>{ openCount++; }
}, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
});
it("Sidebar with swipe towards left direction test case (event)", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Left',
startX: 20,
distanceX: 60,
velocity: 0.5
};
let openCount:number=0;
let closeCount:number=0;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
enableGestures: true,
type: "Push",
open: ()=>{ openCount++; },
close: ()=>{ closeCount++; }
}, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
expect(openCount).toBe(1);
sidebar.enableGestureHandler(touch);
expect(openCount).toBe(1);
});
it("Sidebar with swipe towards left direction with right position test case (event)", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Left', startX: window.innerWidth - 20,
distanceX: 60,
velocity: 0.5
};
let openCount:number=0;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
enableGestures: true, position: 'Right', type: "Push",
open: ()=>{ openCount++; }
}, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(openCount).toBe(1);
sidebar.enableGestureHandler(touch);
expect(openCount).toBe(1);
});
it("Sidebar with swipe towards right direction with right position test case (event)", () => {
let touch: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ },
swipeDirection: 'Right', startX: 20,
distanceX: 60,
velocity: 0.5
};
let openCount:number=0;
let closeCount:number=0;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
enableGestures: true, position: 'Right', type: "Push",
open: ()=>{ openCount++; },
close: ()=>{ closeCount++; }
}, ele);
expect(document.getElementById('sidebar').classList.contains('e-touch')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
sidebar.enableGestureHandler(touch);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
expect(openCount).toBe(1);
expect(closeCount).toBe(1);
sidebar.enableGestureHandler(touch);
expect(closeCount).toBe(1);
});
it("Sidebar Base property Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({}, ele);
expect(sidebar.type == 'Auto').toEqual(true);
expect(sidebar.position == 'Left').toEqual(true);
expect(isNullOrUndefined(document.getElementById('sidebar'))).toEqual(false);
expect(isNullOrUndefined(sidebar.height)).toEqual(false);
expect(isNullOrUndefined(sidebar.width)).toEqual(false);
expect(isNullOrUndefined(sidebar.showBackdrop)).toEqual(false);
expect(sidebar.mediaQuery == null).toEqual(true);
});
it("Sidebar slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide" }, ele);
sidebar.show();
});
it("Sidebar slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", }, ele);
});
it("Sidebar push type testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push" }, ele);
sidebar.show();
});
it("Sidebar over type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over" }, ele);
sidebar.show();
expect(document.body.clientWidth == sibling.clientWidth).toEqual(true);
});
it("Sidebar over type with left position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Auto", width: '300px' }, ele);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-push')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
});
it("Sidebar over type with right position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Auto", width: '300px', position: "Right" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-push')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
});
it("Sidebar openOnInit with push type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push" }, ele);
expect(ele.classList.contains("e-close")).toEqual(true);
});
it("Sidebar openOnInit with slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide" }, ele);
// expect(new WebKitCSSMatrix(window.getComputedStyle(sibling).webkitTransform).m41 == (ele.offsetWidth)).toEqual(true);
});
it("Sidebar openOnInit over type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over" }, ele);
sidebar.show();
expect(document.body.clientWidth == sibling.clientWidth).toEqual(true);
});
it("Sidebar e-dock Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.style.transform).toBe("");
});
it("Sidebar closeOnDocumentClick test", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ closeOnDocumentClick: true, type: 'Push' }, ele);
sidebar.show();
triggerMouseEvent(<HTMLElement>document.querySelector('.e-content-section'), 'mousedown');
expect(sidebar.element.classList.contains('e-close')).toBe(true);
});
// IsOpen property against test cases in normal case
it("isOpen false against auto", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Auto' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen true against auto", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Auto' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against slide", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Slide' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against slide", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Slide' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against push", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against push", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against over", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against over", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
// IsOpen property against test cases in dock case
it("isOpen false against auto in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Auto', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen true against auto in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Auto', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against slide in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Slide', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against slide in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Slide', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against push in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against push in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against over in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against over in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar closeOnDocumentClick onproperty change test", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ closeOnDocumentClick: false, type: 'Push' }, ele);
sidebar.show();
sidebar.closeOnDocumentClick = true;
sidebar.dataBind();
triggerMouseEvent(<HTMLElement>document.querySelector('.e-content-section'), 'mousedown');
expect(sidebar.element.classList.contains('e-close')).toBe(true);
});
function triggerMouseEvent(node?: any, eventType?: any) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
node.dispatchEvent(clickEvent);
}
it("Sidebar without dock size test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("auto");
expect(ele.style.transform).toBe("");
});
it("Sidebar with dock size(250px) default test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: "250px", width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(ele.style.transform).toBe("");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size default test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size(250px) closed test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: "250px", width: '300px', isOpen: false }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("300px");
expect(ele.style.transform).toBe("");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size closed test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '150', width: '300px', isOpen: false }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("300px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size slide test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Slide' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(ele.style.transform).toBe("translateX(-100%) translateX(300px)");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size push test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Push' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(ele.style.transform).toBe("translateX(-100%) translateX(300px)");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size over test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Over' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(ele.style.transform).toBe("translateX(-100%) translateX(300px)");
expect(sidebar.isOpen).toBe(false);
});
//mediaQuery test case
it("Sidebar with mediaQuery greater than 700px test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Push', mediaQuery: window.matchMedia('(min-width:700px)') }, ele);
expect(ele.classList.contains("e-open")).toEqual(true);
});
it("Sidebar with mediaQuery less than 400px test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Push', mediaQuery: '(max-width:400px)' }, ele);
expect(ele.classList.contains("e-close")).toEqual(true);
});
it("Sidebar with mediaQuery less than 400px test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto', mediaQuery: '(max-width:400px)' }, ele);
expect(ele.classList.contains("e-close")).toEqual(false);
sidebar.mediaQuery ='(min-width:700px)';
sidebar.dataBind();
expect(ele.classList.contains("e-open")).toEqual(true);
});
it("Sidebar with on demand open propertytest case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto', mediaQuery: '(max-width:400px)' }, ele);
//expect(ele.classList.contains("e-close")).toEqual(false);
sidebar.isOpen = true;
sidebar.dataBind();
//expect(ele.classList.contains("e-open")).toEqual(true);
sidebar.isOpen = false;
sidebar.dataBind();
//expect(ele.classList.contains("e-open")).toEqual(false);
//expect(ele.classList.contains("e-close")).toEqual(true);
});
// position Testing
it("Sidebar position:right Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", position: "Right" }, ele);
sidebar.show();
// expect(new WebKitCSSMatrix(window.getComputedStyle(sibling).webkitTransform).m41 == -(ele.offsetWidth)).toEqual(true);
});
it("Sidebar position:right push type width Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right" }, ele);
sidebar.show();
});
it("Sidebar position:right over type width Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", position: "Right" }, ele);
sidebar.show();
expect(document.body.clientWidth == sibling.clientWidth).toEqual(true);
});
it("Sidebar position:right inital open Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right" }, ele);
expect(ele.classList.contains("e-close")).toEqual(true);
});
it("Sidebar position:right && openOnInit with slide type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", position: "Right" }, ele);
});
it("Sidebar position:right && openOnInit , push type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right" }, ele);
});
it("Sidebar position:right && openOnInit and over type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", position: "Right" }, ele);
expect(document.body.clientWidth == sibling.clientWidth).toEqual(true);
});
//context property test case
it("Sidebar context propert test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right", target: <HTMLElement>document.querySelector('.e-context-element') }, ele);
expect(document.querySelectorAll('.e-context-element .e-sidebar')[0].classList.contains('e-sidebar')).toBe(true);
expect(document.querySelectorAll('.e-context-element')[0].classList.contains('e-sidebar-context')).toBe(true);
expect(document.querySelectorAll('.e-context-element .e-sidebar')[0].classList.contains('e-sidebar-absolute')).toBe(true);
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).classList.contains('e-content-animation')).toBe(true);
sidebar.show();
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.transform).toBe('translateX(0px)');
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight).toBe((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight);
sidebar.hide();
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.transform).toBe('translateX(0px)');
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight).toBe('0px');
});
//context property test case
it("Sidebar context with backdrop propert test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right", target: <HTMLElement>document.querySelector('.e-context-element'), showBackdrop: true }, ele);
expect(document.querySelectorAll('.e-context-element .e-sidebar')[0].classList.contains('e-sidebar')).toBe(true);
expect(document.querySelectorAll('.e-context-element')[0].classList.contains('e-sidebar-context')).toBe(true);
expect(document.querySelectorAll('.e-context-element .e-sidebar')[0].classList.contains('e-sidebar-absolute')).toBe(true);
sidebar.show();
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.transform).toBe('translateX(0px)');
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight).toBe((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight);
expect((document.getElementById('sidebar').nextElementSibling.classList.contains('e-backdrop'))).toBe(true);
sidebar.hide();
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.transform).toBe('translateX(0px)');
expect((<HTMLElement>document.getElementById('sidebar').nextElementSibling).style.marginRight).toBe('0px');
expect((document.getElementById('sidebar').nextElementSibling.classList.contains('e-backdrop'))).toBe(false);
});
//BACKDROP
it("Sidebar backdrop testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", showBackdrop: true }, ele);
expect(sibling.classList.contains('e-overlay')).toEqual(false);
sidebar.hide();
expect(sibling.classList.contains('e-overlay')).toEqual(false);
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-sidebar-overlay')).style.display).toEqual('block');
expect(((<HTMLElement>document.querySelector('.e-sidebar-overlay')).classList.contains('e-sidebar-overlay'))).toBe(true);
//onproperty changes
sidebar.showBackdrop = false;
sidebar.dataBind();
sidebar.show();
expect(sibling.classList.contains('e-overlay')).toEqual(false);
sidebar.hide();
expect(sibling.classList.contains('e-overlay')).toEqual(false);
sidebar.show();
sidebar.showBackdrop = true;
sidebar.dataBind();
expect((<HTMLElement>document.querySelector('.e-sidebar-overlay')).style.display).toEqual('block');
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-sidebar-overlay')).style.display).toEqual('block');
sidebar.hide();
expect(sibling.classList.contains('e-overlay')).toEqual(false);
});
it("Sidebar backdrop with auto type test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", showBackdrop: true }, ele);
expect(sibling.classList.contains('e-overlay')).toEqual(false);
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-sidebar-overlay')).style.display).toEqual('block');
sidebar.hide();
expect(document.querySelector('.e-sidebar-overlay')).toBe(null);
sidebar.type = 'Auto';
sidebar.dataBind();
expect((<HTMLElement>document.querySelector('.e-sidebar-overlay')).style.display).toEqual('block');
sidebar.hide();
expect(document.querySelector('.e-sidebar-overlay')).toBe(null);
});
//persisitence test case
it("Sidebar persisitence test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", enablePersistence: true }, ele);
//onproperty change
sidebar.type = "Over"
sidebar.dataBind();
sidebar.destroy();
sidebar = new Sidebar({ enablePersistence: true }, ele);
expect(document.getElementById('sidebar').classList.contains('e-over')).toBe(true);
});
// enableDock onproperty changes test case
it("Sidebar zindex property test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Over', zIndex: '300' }, ele);
sidebar.enableDock = true;
sidebar.dataBind();
expect(sidebar.enableDock).toEqual(true);
})
// zindex property test case
it("Sidebar zindex property test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Over', zIndex: '300' }, ele);
sidebar.show();
expect(ele.classList.contains("e-open") && sidebar.getState()).toEqual(true);
expect(document.getElementById('sidebar').style.zIndex).toEqual('300');
sidebar.type = "Push";
sidebar.dataBind();
expect(document.getElementById('sidebar').style.zIndex).toEqual('300');
//onproperty change test case
sidebar.zIndex = '100';
sidebar.dataBind();
expect(document.getElementById('sidebar').style.zIndex).toEqual('100');
})
// show method testing
it("Sidebar show with show testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.show();
expect(ele.classList.contains("e-open") && sidebar.getState()).toEqual(true);
});
// hide method testing
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.hide();
expect(ele.classList.contains("e-close") && !sidebar.getState()).toEqual(true);
});
//toggle testing
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Push' }, ele);
sidebar.toggle()
expect(ele.classList.contains("e-open") && sidebar.getState()).toEqual(true);
});
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Auto' }, ele);
sidebar.toggle();
expect(ele.classList.contains("e-close") && !sidebar.getState()).toEqual(true);
sidebar.toggle();
expect(ele.classList.contains("e-open") && sidebar.getState()).toEqual(true);
sidebar.toggle();
expect(ele.classList.contains("e-close") && !sidebar.getState()).toEqual(true);
});
//toggle testing
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.toggle();
expect(ele.classList.contains("e-close") && !sidebar.getState()).toEqual(true);
});
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.show();
sidebar.toggle();
expect(ele.classList.contains("e-close") && !sidebar.getState()).toEqual(true);
});
it("Sidebar hide method testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Push' }, ele);
sidebar.toggle();
expect(ele.classList.contains("e-open")).toEqual(true);
});
// getState testing
it("Sidebar getState with show testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.show();
expect(ele.classList.contains("e-open") && sidebar.getState()).toEqual(true);
});
it("Sidebar getState with hide testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.hide();
expect(!ele.classList.contains("e-open") && !sidebar.getState()).toEqual(true);
});
// open on init with auto close option
it("Sidebar getState with hide testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
// sidebar = new Sidebar({ mediaQuery:null},ele);
expect(!ele.classList.contains("e-open") && !sidebar.getState()).toEqual(true);
});
it("Sidebar getState with mediaQuery null testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ mediaQuery: null, type: 'Push' }, ele);
expect(ele.classList.contains("e-close")).toEqual(true);
});
it("Sidebar getState with mediaQuery 500 to 800 string testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
let ac: string = '(min-width:500px) and (max-width:1300px)';
sidebar = new Sidebar({ mediaQuery: ac, type: 'Push' }, ele);
expect(ele.classList.contains("e-open")).toEqual(true);
});
it("Sidebar getState with mediaQuery list 500 to 800 string testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
let ac:MediaQueryList = window.matchMedia('(min-width:500px) and (max-width:1300px)');
sidebar = new Sidebar({ mediaQuery: ac, type: 'Push' }, ele);
expect(ele.classList.contains("e-open")).toEqual(true);
});
it("Sidebar getState with mediaQuery screen size testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
let ac: string = '(min-width:' + (screen.width - 100) + 'px) and (max-width:' + (screen.width + 100) + 'px)';
// sidebar = new Sidebar({ mediaQuery:ac},ele);
expect(ele.classList.contains("e-close")).toEqual(false);
});
it("Sidebar getState with mediaQuery maximum testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
let ac: string = '(min-width:' + (screen.width + 100) + 'px) and (max-width:' + (screen.width + 500) + 'px)';
// sidebar = new Sidebar({ mediaQuery:ac},ele);
// expect(ele.classList.contains("e-close")).toEqual(true);
});
// set model
it("Sidebar with dynamic type slide Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: 'Slide' }, ele);
// sidebar.type = 'Slide';
// expect(document.body.scrollWidth == document.body.clientWidth).toEqual(false);
});
it("Sidebar with dynamic type push testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({}, ele);
sidebar.type = 'Push';
sidebar.dataBind();
// expect(document.body.clientWidth == sibling.clientWidth && window.getComputedStyle(sibling).getPropertyValue('padding-left') == window.getComputedStyle(ele).width).toEqual(true);
});
it("Sidebar dynamic over type Testing", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", }, ele);
// expect(document.body.clientWidth == sibling.clientWidth && window.getComputedStyle(sibling).getPropertyValue('padding-left') == window.getComputedStyle(ele).width).toEqual(true);
sidebar.type = 'Over';
sidebar.dataBind();
// expect(document.body.clientWidth == sibling.clientWidth).toEqual(true);
});
// closeOnDocumentClick property test case
it("Sidebar closeOnDocumentClick Testing", () => {
let sidebar: any;
let mouseEventArgs: any = {
preventDefault: (): void => { /** NO Code */ },
currentTarget: null,
target: document.body,
stopPropagation: (): void => { /** NO Code */ }
};
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", closeOnDocumentClick: true }, ele);
sidebar.documentclickHandler(mouseEventArgs);
expect(ele.classList.contains("e-close")).toEqual(true);
});
// enableDock property test case
it("Sidebar push type with dock type test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", enableDock: true, dockSize: 300 }, ele);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(300px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
});
it("without docksize with right position property test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, width: "auto", position: 'Right' }, ele);
expect(document.getElementById('sidebar').style.width).toEqual('auto');
sidebar.show();
sidebar.setTimeOut();
sidebar.hide();
sidebar.setTimeOut();
});
it("without docksize with right position property test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, width: "auto" }, ele);
expect(document.getElementById('sidebar').style.width).toEqual('auto');
sidebar.show();
sidebar.setTimeOut();
sidebar.hide();
sidebar.setTimeOut();
})
// open event test case
it("Sidebar open event test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
type: "Push", open: function (args: any) {
expect(args.name).toBe("open");
expect(args.isInteracted).toBe(false);
expect(args.event).toBe(null);
}
}, ele);
sidebar.show();
});
// close event test case
it("Sidebar close event test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
type: "Push", close: function (args: any) {
expect(args.name).toBe("close");
expect(args.isInteracted).toBe(false);
expect(args.event).toBe(null);
}
}, ele);
sidebar.hide();
});
// change event test case
it("Sidebar change event test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({
type: "Push", change: function (args: any) {
expect(args.name).toBe("change");
}
}, ele);
sidebar.show();
});
it("Sidebar slide type with dock type test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", enableDock: true, dockSize: 300, width: "300px" }, ele);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(300px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(300px)");
expect(document.getElementById('sidebar').classList.contains('e-slide')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-left')).toBe(true);
});
//Spec for dynamically changing the type property
it("Setting spell mistake type on on property change", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({
change: function (args: any) {
expect(args.name).toBe("change");
}
}, ele);
sidebar.type= "Slide";
sidebar.dataBind();
expect(sidebar.element.classList.contains('e-slide')).toBe(true);
sidebar.type= "abc";
sidebar.dataBind();
expect(sidebar.element.classList.contains('e-push')).toBe(true);
sidebar.type= "Auto";
sidebar.dataBind();
expect(sidebar.element.classList.contains('e-push')).toBe(true);
sidebar.type= "Over";
sidebar.dataBind();
expect(sidebar.element.classList.contains('e-over')).toBe(true);
});
it("Sidebar over type with dock type test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", enableDock: true, dockSize: 300, width: '300px' }, ele);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(300px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
expect(document.getElementById('sidebar').classList.contains('e-over')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-left')).toBe(true);
});
it("Sidebar with 'Push' type , 'Left' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", enableDock: true, dockSize: 200, width: '300px' }, ele);
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
sidebar.transitionEnd();
expect(document.getElementById('sidebar').style.width).toEqual('200px');
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(200px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("200px");
expect(document.getElementById('sidebar').classList.contains('e-push')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-left')).toBe(true);
});
it("Sidebar with 'Push' type , 'Right' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", enableDock: true, position: 'Right', dockSize: 200, width: '300px' }, ele);
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
sidebar.transitionEnd();
expect(document.getElementById('sidebar').style.width).toEqual('200px');
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("200px");
expect(document.getElementById('sidebar').classList.contains('e-push')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-right')).toBe(true);
});
it("Sidebar with 'Slide' type , 'Left' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", enableDock: true, dockSize: 300, width: '300px' }, ele);
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(300px)");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(300px)");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(300px)");
sidebar.hide();
sidebar.transitionEnd();
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(300px)");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(300px)");
expect(document.getElementById('sidebar').classList.contains('e-slide')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-left')).toBe(true);
});
it("Sidebar with 'Slide' type , 'Right' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", enableDock: true, dockSize: 200, width: '300px', position: "Right" }, ele);
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(-200px)");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(-300px)");
sidebar.hide();
sidebar.transitionEnd();
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(-200px)");
expect(document.getElementById('sidebar').classList.contains('e-slide')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-right')).toBe(true);
});
it("Sidebar with 'Over' type , 'Left' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", enableDock: true, dockSize: 200, width: '300px' }, ele);
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
sidebar.transitionEnd()
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(-100%) translateX(200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
expect(document.getElementById('sidebar').classList.contains('e-over')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-left')).toBe(true);
});
it("Sidebar with 'Over' type , 'Right' position and dock enabled test case", () => {
let sidebar: any;
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", enableDock: true, dockSize: 200, width: '300px', position: 'Right' }, ele);
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.show();
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect(document.getElementById('sidebar').style.width).toEqual("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
sidebar.transitionEnd();
expect(document.getElementById('sidebar').style.transform).toEqual("translateX(100%) translateX(-200px)");
expect(document.getElementById('sidebar').style.width).toEqual("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("200px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
expect(document.getElementById('sidebar').classList.contains('e-over')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-right')).toBe(true);
});
function slidetypeLeftpositionShow(): void {
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(300px)");
}
function slidetypeLeftpositionHide(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
function pushtypeLeftpositionShow(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
function pushtypeLeftpositionHide(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
it("Sidebar push type with left position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Left", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-left')).toEqual(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
pushtypeLeftpositionShow();
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
pushtypeLeftpositionHide();
//onproperty change
sidebar.type = "Slide";
sidebar.dataBind();
expect(document.getElementById('sidebar').classList.contains('e-left')).toEqual(true);
expect(document.getElementById('sidebar').classList.contains('e-slide')).toBe(true);
sidebar.show();
slidetypeLeftpositionShow();
sidebar.hide();
slidetypeLeftpositionHide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
});
it("Sidebar push type with right position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Push", position: "Right", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-right')).toEqual(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("300px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
//onproperty change
sidebar.type = "Slide";
sidebar.dataBind();
sidebar.show();
slidetypeRightpositionShow();
sidebar.hide();
slidetypeRightpositionHide();
});
it("Sidebar slide type with left position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", position: "Left", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-left')).toEqual(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
slidetypeLeftpositionShow();
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
slidetypeLeftpositionHide();
});
function slidetypeRightpositionShow(): void {
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(-300px)");
}
function slidetypeRightpositionHide(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
it("Sidebar slide type with right position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Slide", position: "Right", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
expect(document.getElementById('sidebar').classList.contains('e-right')).toEqual(true);
sidebar.show();
slidetypeRightpositionShow();
sidebar.hide();
slidetypeRightpositionHide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
});
function overtypeRightpositionShow(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
function overtypeRightpositionHide(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginRight).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
function overtypeLeftpositionShow(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
function overtypeLeftpositionHide(): void {
expect(document.getElementById('sidebar').style.width).toEqual('300px');
expect(document.getElementById('sidebar').style.transform).toEqual("");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("0px");
expect((<HTMLElement>document.querySelector('.e-content-section')).style.transform).toBe("translateX(0px)");
}
it("Sidebar over type with left position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", position: "Left", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-left')).toEqual(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
overtypeLeftpositionShow();
sidebar.hide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
overtypeLeftpositionHide();
//onproperty change
sidebar.type = "Slide";
sidebar.dataBind();
sidebar.show();
slidetypeLeftpositionShow();
sidebar.hide();
slidetypeLeftpositionHide();
});
it("Sidebar over type with right position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Over", position: "Right", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-right')).toEqual(true);
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
sidebar.show();
expect(document.getElementById('sidebar').classList.contains('e-open')).toBe(true);
overtypeRightpositionShow();
sidebar.hide();
overtypeRightpositionHide();
expect(document.getElementById('sidebar').classList.contains('e-close')).toBe(true);
//onproperty changes
sidebar.position = "Left";
sidebar.dataBind();
sidebar.show();
overtypeLeftpositionShow();
sidebar.hide();
overtypeLeftpositionHide();
//onproperty changes
sidebar.position = "Right";
sidebar.dataBind();
sidebar.show();
overtypeRightpositionShow();
sidebar.hide();
overtypeRightpositionHide();
});
describe("Sidebar auto type in mobile test case ", () => {
let sidebar: any;
beforeEach((): void => {
let ele: HTMLElement = document.createElement("div");
let sibin: HTMLElement = document.createElement("div");
ele.innerHTML = "<h3>Testing of Sidebar</h3>";
sibin.innerHTML = "Side bar";
sibin.className = 'e-content-section';
ele.id = "sidebar";
ele.style.width = "300px";
ele.style.height = "100%";
document.body.style.margin = "0px";
let div: any = document.createElement('div');
let span: any = document.createElement('span');
div.className = 'e-context-element';
div.appendChild(span);
document.body.appendChild(div);
document.body.appendChild(ele);
document.body.appendChild(sibin);
let androidPhoneUa: string = 'Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JWR66Y) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.92 Safari/537.36';
Browser.userAgent = androidPhoneUa;
});
afterEach((): void => {
if (sidebar) {
sidebar.destroy();
}
document.body.innerHTML = "";
let androidPhoneUa: string = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36';
Browser.userAgent = androidPhoneUa;
});
it("Sidebar type auto with left position test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ type: "Auto", position: "Left", width: "300px" }, ele);
expect(document.getElementById('sidebar').classList.contains('e-over')).toBe(true);
sidebar.resize();
});
it("Sidebar type auto with enable dock test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ type: 'Auto', enableDock: true }, ele);
expect(sidebar.position == 'Left').toEqual(true);
expect(isNullOrUndefined(document.getElementById('sidebar'))).toEqual(false);
expect(isNullOrUndefined(sidebar.height)).toEqual(false);
expect(isNullOrUndefined(sidebar.width)).toEqual(false);
expect(isNullOrUndefined(sidebar.showBackdrop)).toEqual(false);
});
it("Sidebar type slide with overflow-x hidden class test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ type: 'Slide' }, ele);
sidebar.show();
expect(document.body.classList.contains('e-sidebar-overflow')).toBe(true);
sidebar.hide();
expect(document.body.classList.contains('e-sidebar-overflow')).toBe(false);
});
it("Sidebar type auto in mobile test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ type: 'Auto', enableDock: true, dockSize: '300px' }, ele);
expect(sidebar.position == 'Left').toEqual(true);
expect(isNullOrUndefined(document.getElementById('sidebar'))).toEqual(false);
expect(isNullOrUndefined(sidebar.height)).toEqual(false);
expect(isNullOrUndefined(sidebar.width)).toEqual(false);
expect(isNullOrUndefined(sidebar.showBackdrop)).toEqual(false);
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
sidebar.show();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
sidebar.hide();
expect((<HTMLElement>document.querySelector('.e-content-section')).style.marginLeft).toBe("300px");
});
it("Sidebar default destroy test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({}, ele);
sidebar.destroy();
expect(sidebar.element.classList.length).toBe(0);
});
it("Sidebar target destroy test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ target: <HTMLElement>document.querySelector('.e-context-element') }, ele);
sidebar.destroy();
expect(sidebar.element.classList.length).toBe(0);
});
// IsOpen property against test cases in normal case
it("isOpen false against auto", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Auto' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against auto", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Auto' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against slide", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Slide' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against slide", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Slide' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against push", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against push", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against over", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against over", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
// IsOpen property against test cases in dock case
it("isOpen false against auto in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Auto', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against auto in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Auto', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against slide in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Slide', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against slide in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Slide', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against push in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against push in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("isOpen false against over in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: false, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-close')).toBe(true);
expect(sidebar.isOpen).toBe(false);
});
it("isOpen true against over in dock mode", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ isOpen: true, type: 'Push', enableDock: true, dockSize: '72px' }, ele);
expect(sidebar.element.classList.contains('e-open')).toBe(true);
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size slide test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size slide test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Slide' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size push test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Push' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size over test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Over' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(false);
expect(ele.classList.contains("e-close")).toEqual(true);
expect(ele.style.width).toEqual("300px");
expect(sidebar.isOpen).toBe(false);
});
it("Sidebar with dock size test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', isOpen: true, width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size slide test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Slide', isOpen: true, width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size push test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Push', isOpen: true, width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar with dock size over test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
let sibling: HTMLElement = <HTMLElement>ele.nextElementSibling;
sidebar = new Sidebar({ enableDock: true, dockSize: '300', type: 'Over', isOpen: true, width: '500px' }, ele);
expect(ele.classList.contains("e-dock")).toEqual(true);
expect(ele.classList.contains("e-open")).toEqual(true);
expect(ele.classList.contains("e-close")).toEqual(false);
expect(ele.style.width).toEqual("500px");
expect(sidebar.isOpen).toBe(true);
});
it("Sidebar target property onproperty change test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({}, ele);
sidebar.target = <HTMLElement>document.querySelector('.e-context-element');
sidebar.dataBind();
expect(sidebar.element.parentElement.classList.contains('e-sidebar-context')).toBe(true);
expect(sidebar.element.classList.contains('e-sidebar-absolute')).toBe(true);
sidebar.target = null;
sidebar.dataBind();
expect(sidebar.element.parentElement.classList.contains('e-sidebar-context')).toBe(false);
expect(sidebar.element.classList.contains('e-sidebar-absolute')).toBe(false);
});
it("Sidebar target string type test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({}, ele);
sidebar.target = '.e-context-element';
sidebar.dataBind();
expect(sidebar.element.parentElement.classList.contains('e-sidebar-context')).toBe(true);
expect(sidebar.element.classList.contains('e-sidebar-absolute')).toBe(true);
sidebar.target = null;
sidebar.dataBind();
expect(sidebar.element.parentElement.classList.contains('e-sidebar-context')).toBe(false);
expect(sidebar.element.classList.contains('e-sidebar-absolute')).toBe(false);
});
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
describe("Sidebar testing ", () => {
let sidebar: any;
let sidebar1: any;
beforeEach((): void => {
let ele: HTMLElement = document.createElement("div");
let ele1: HTMLElement = document.createElement("div");
let target: HTMLElement = document.createElement("div");
let sibin: HTMLElement = document.createElement("div");
ele.innerHTML = "<h3>Testing of Sidebar</h3>";
ele1.innerHTML = "<h3>Testing of Sidebar1</h3>";
sibin.innerHTML = "Side bar";
sibin.className = "sibling";
target.className = 'maincontent';
ele.style.height = "300px";
ele.id = "sidebar";
ele1.id = "sidebar1";
document.body.style.margin = "0px";
target.appendChild(sibin);
document.body.appendChild(ele);
document.body.appendChild(ele1);
document.body.appendChild(target);
});
afterEach((): void => {
if (sidebar) {
sidebar.destroy();
}
if (sidebar1) {
sidebar1.destroy();
}
document.body.innerHTML = "";
});
it("two Sidebar with same target test case", () => {
let ele: HTMLElement = document.getElementById("sidebar");
sidebar = new Sidebar({ type: 'Push', target: '.maincontent', width: '250px' }, ele);
let ele1: HTMLElement = document.getElementById("sidebar1");
sidebar1 = new Sidebar({ type: 'Push', position: 'Right', target: '.maincontent', width: '300px' }, ele1);
let aniEle: any = document.getElementsByClassName('e-content-animation');
expect(aniEle.length).toBe(1);
expect(aniEle[0].classList.contains('sibling')).toBe(true);
expect(aniEle[0].style.marginLeft).toBe('0px');
expect(aniEle[0].style.marginRight).toBe('0px');
sidebar.show();
sidebar1.show();
let aniEle1: any = document.getElementsByClassName('e-content-animation');
expect(aniEle1.length).toBe(1);
expect(aniEle1[0].classList.contains('sibling')).toBe(true);
expect(aniEle1[0].style.marginLeft).toBe('250px');
expect(aniEle1[0].style.marginRight).toBe('300px');
});
}); | the_stack |
'use strict';
import * as paths from 'path';
import { Uri } from 'vscode';
import { UriComparer } from '../comparers';
import { DocumentSchemes } from '../constants';
import { Container } from '../container';
import { GitCommit, GitFile, GitRevision } from '../git/git';
import { Logger } from '../logger';
import { debug, memoize, Strings } from '../system';
const emptyStr = '';
const slash = '/';
export interface GitCommitish {
fileName?: string;
repoPath: string;
sha?: string;
versionedPath?: string;
}
interface UriComponents {
scheme: string;
authority: string;
path: string;
query: string;
fragment: string;
}
interface UriEx {
new (): Uri;
new (scheme: string, authority: string, path: string, query: string, fragment: string): Uri;
// Use this ctor, because vscode doesn't validate it
new (components: UriComponents): Uri;
}
export class GitUri extends (Uri as any as UriEx) {
static is(uri: any): uri is GitUri {
return uri instanceof GitUri;
}
readonly repoPath?: string;
readonly sha?: string;
readonly versionedPath?: string;
constructor(uri?: Uri);
constructor(uri: Uri, commit: GitCommitish);
constructor(uri: Uri, repoPath: string | undefined);
constructor(uri?: Uri, commitOrRepoPath?: GitCommitish | string) {
if (uri == null) {
super('unknown', emptyStr, emptyStr, emptyStr, emptyStr);
return;
}
if (uri.scheme === DocumentSchemes.GitLens) {
const data = JSON.parse(uri.query) as UriRevisionData;
// Fixes issues with uri.query:
// When Uri's come from the FileSystemProvider, the uri.query only contains the root repo info (not the actual file path)
// When Uri's come from breadcrumbs (via the FileSystemProvider), the uri.query contains the wrong file path
if (data.path !== uri.path) {
if (data.path.startsWith('//') && !uri.path.startsWith('//')) {
data.path = `/${uri.path}`;
} else {
data.path = uri.path;
}
}
super({
scheme: uri.scheme,
authority: uri.authority,
path: data.path,
query: JSON.stringify(data),
fragment: uri.fragment,
});
this.repoPath = data.repoPath;
if (GitRevision.isUncommittedStaged(data.ref) || !GitRevision.isUncommitted(data.ref)) {
this.sha = data.ref;
}
return;
}
if (commitOrRepoPath === undefined) {
super(uri);
return;
}
if (typeof commitOrRepoPath === 'string') {
super(uri);
this.repoPath = commitOrRepoPath;
return;
}
const [authority, fsPath] = GitUri.ensureValidUNCPath(
uri.authority,
GitUri.resolve(commitOrRepoPath.fileName ?? uri.fsPath, commitOrRepoPath.repoPath),
);
let path;
switch (uri.scheme) {
case 'https':
case 'http':
case 'file':
if (!fsPath) {
path = slash;
} else if (!fsPath.startsWith(slash)) {
path = `/${fsPath}`;
} else {
path = fsPath;
}
break;
default:
path = fsPath;
break;
}
super({
scheme: uri.scheme,
authority: authority,
path: path,
query: uri.query,
fragment: uri.fragment,
});
this.repoPath = commitOrRepoPath.repoPath;
this.versionedPath = commitOrRepoPath.versionedPath;
if (GitRevision.isUncommittedStaged(commitOrRepoPath.sha) || !GitRevision.isUncommitted(commitOrRepoPath.sha)) {
this.sha = commitOrRepoPath.sha;
}
}
@memoize()
get directory(): string {
return GitUri.getDirectory(this.relativeFsPath);
}
@memoize()
get fileName(): string {
return paths.basename(this.relativeFsPath);
}
@memoize()
get isUncommitted() {
return GitRevision.isUncommitted(this.sha);
}
@memoize()
get isUncommittedStaged() {
return GitRevision.isUncommittedStaged(this.sha);
}
@memoize()
private get relativeFsPath() {
return this.repoPath == null || this.repoPath.length === 0
? this.fsPath
: paths.relative(this.repoPath, this.fsPath);
}
@memoize()
get relativePath() {
return Strings.normalizePath(this.relativeFsPath);
}
@memoize()
get shortSha() {
return GitRevision.shorten(this.sha);
}
@memoize<GitUri['documentUri']>(options => `${options?.useVersionedPath ? 'versioned' : ''}`)
documentUri({ useVersionedPath }: { useVersionedPath?: boolean } = {}) {
if (useVersionedPath && this.versionedPath !== undefined) return GitUri.file(this.versionedPath);
if (this.scheme !== 'file') return this;
return GitUri.file(this.fsPath);
}
equals(uri: Uri | undefined) {
if (!UriComparer.equals(this, uri)) return false;
return this.sha === (GitUri.is(uri) ? uri.sha : undefined);
}
getFormattedFilename(options: { suffix?: string; truncateTo?: number } = {}): string {
return GitUri.getFormattedFilename(this.fsPath, options);
}
getFormattedPath(options: { relativeTo?: string; suffix?: string; truncateTo?: number } = {}): string {
return GitUri.getFormattedPath(this.fsPath, { relativeTo: this.repoPath, ...options });
}
@memoize()
toFileUri() {
return GitUri.file(this.fsPath);
}
private static ensureValidUNCPath(authority: string, fsPath: string): [string, string] {
// Check for authority as used in UNC shares or use the path as given
if (fsPath[0] === slash && fsPath[1] === slash) {
const index = fsPath.indexOf(slash, 2);
if (index === -1) {
authority = fsPath.substring(2);
fsPath = slash;
} else {
authority = fsPath.substring(2, index);
fsPath = fsPath.substring(index) || slash;
}
}
return [authority, fsPath];
}
static file(path: string, useVslsScheme?: boolean) {
const uri = Uri.file(path);
if (Container.vsls.isMaybeGuest && useVslsScheme !== false) {
return uri.with({ scheme: DocumentSchemes.Vsls });
}
return uri;
}
static fromCommit(commit: GitCommit, previous: boolean = false) {
if (!previous) return new GitUri(commit.uri, commit);
return new GitUri(commit.previousUri, {
repoPath: commit.repoPath,
sha: commit.previousSha,
});
}
static fromFile(file: string | GitFile, repoPath: string, ref?: string, original: boolean = false): GitUri {
const uri = GitUri.resolveToUri(
typeof file === 'string' ? file : (original && file.originalFileName) || file.fileName,
repoPath,
);
return ref == null || ref.length === 0
? new GitUri(uri, repoPath)
: new GitUri(uri, { repoPath: repoPath, sha: ref });
}
static fromRepoPath(repoPath: string, ref?: string) {
return ref == null || ref.length === 0
? new GitUri(GitUri.file(repoPath), repoPath)
: new GitUri(GitUri.file(repoPath), { repoPath: repoPath, sha: ref });
}
static fromRevisionUri(uri: Uri): GitUri {
return new GitUri(uri);
}
@debug({
exit: uri => `returned ${Logger.toLoggable(uri)}`,
})
static async fromUri(uri: Uri): Promise<GitUri> {
if (GitUri.is(uri)) return uri;
if (!Container.git.isTrackable(uri)) return new GitUri(uri);
if (uri.scheme === DocumentSchemes.GitLens) return new GitUri(uri);
// If this is a git uri, find its repoPath
if (uri.scheme === DocumentSchemes.Git) {
try {
const data: { path: string; ref: string } = JSON.parse(uri.query);
const repoPath = await Container.git.getRepoPath(data.path);
let ref;
switch (data.ref) {
case emptyStr:
case '~':
ref = GitRevision.uncommittedStaged;
break;
case null:
ref = undefined;
break;
default:
ref = data.ref;
break;
}
const commitish: GitCommitish = {
fileName: data.path,
repoPath: repoPath!,
sha: ref,
};
return new GitUri(uri, commitish);
} catch {}
}
if (uri.scheme === DocumentSchemes.PRs) {
try {
const data: {
baseCommit: string;
headCommit: string;
isBase: boolean;
fileName: string;
prNumber: number;
status: number;
remoteName: string;
} = JSON.parse(uri.query);
let repoPath = Strings.normalizePath(uri.fsPath);
if (repoPath.endsWith(data.fileName)) {
repoPath = repoPath.substr(0, repoPath.length - data.fileName.length - 1);
} else {
repoPath = (await Container.git.getRepoPath(uri.fsPath))!;
}
const commitish: GitCommitish = {
fileName: data.fileName,
repoPath: repoPath,
sha: data.isBase ? data.baseCommit : data.headCommit,
};
return new GitUri(uri, commitish);
} catch {}
}
return new GitUri(uri, await Container.git.getRepoPath(uri));
}
static getDirectory(fileName: string, relativeTo?: string): string {
let directory: string | undefined = paths.dirname(fileName);
directory = relativeTo != null ? GitUri.relativeTo(directory, relativeTo) : Strings.normalizePath(directory);
return directory == null || directory.length === 0 || directory === '.' ? emptyStr : directory;
}
static getFormattedFilename(
fileNameOrUri: string | Uri,
options: {
suffix?: string;
truncateTo?: number;
} = {},
): string {
const { suffix = emptyStr, truncateTo } = options;
let fileName: string;
if (fileNameOrUri instanceof Uri) {
fileName = fileNameOrUri.fsPath;
} else {
fileName = fileNameOrUri;
}
let file = paths.basename(fileName);
if (truncateTo != null && file.length >= truncateTo) {
return Strings.truncateMiddle(file, truncateTo);
}
if (suffix) {
if (truncateTo != null && file.length + suffix.length >= truncateTo) {
return `${Strings.truncateMiddle(file, truncateTo - suffix.length)}${suffix}`;
}
file += suffix;
}
return file;
}
static getFormattedPath(
fileNameOrUri: string | Uri,
options: {
relativeTo?: string;
suffix?: string;
truncateTo?: number;
},
): string {
const { relativeTo, suffix = emptyStr, truncateTo } = options;
let fileName: string;
if (fileNameOrUri instanceof Uri) {
fileName = fileNameOrUri.fsPath;
} else {
fileName = fileNameOrUri;
}
let file = paths.basename(fileName);
if (truncateTo != null && file.length >= truncateTo) {
return Strings.truncateMiddle(file, truncateTo);
}
if (suffix) {
if (truncateTo != null && file.length + suffix.length >= truncateTo) {
return `${Strings.truncateMiddle(file, truncateTo - suffix.length)}${suffix}`;
}
file += suffix;
}
const directory = GitUri.getDirectory(fileName, relativeTo);
if (!directory) return file;
file = `/${file}`;
if (truncateTo != null && file.length + directory.length >= truncateTo) {
return `${Strings.truncateLeft(directory, truncateTo - file.length)}${file}`;
}
return `${directory}${file}`;
}
static relativeTo(fileNameOrUri: string | Uri, relativeTo: string | undefined): string {
const fileName = fileNameOrUri instanceof Uri ? fileNameOrUri.fsPath : fileNameOrUri;
const relativePath =
relativeTo == null || relativeTo.length === 0 || !paths.isAbsolute(fileName)
? fileName
: paths.relative(relativeTo, fileName);
return Strings.normalizePath(relativePath);
}
static git(fileName: string, repoPath?: string) {
const path = GitUri.resolve(fileName, repoPath);
return Uri.parse(
// Change encoded / back to / otherwise uri parsing won't work properly
`${DocumentSchemes.Git}:/${encodeURIComponent(path).replace(/%2F/g, slash)}?${encodeURIComponent(
JSON.stringify({
// Ensure we use the fsPath here, otherwise the url won't open properly
path: Uri.file(path).fsPath,
ref: '~',
}),
)}`,
);
}
static resolve(fileName: string, repoPath?: string) {
const normalizedFileName = Strings.normalizePath(fileName);
if (repoPath === undefined) return normalizedFileName;
const normalizedRepoPath = Strings.normalizePath(repoPath);
if (normalizedFileName == null || normalizedFileName.length === 0) return normalizedRepoPath;
if (normalizedFileName.startsWith(normalizedRepoPath)) return normalizedFileName;
return Strings.normalizePath(paths.join(normalizedRepoPath, normalizedFileName));
}
static resolveToUri(fileName: string, repoPath?: string) {
return GitUri.file(this.resolve(fileName, repoPath));
}
static toKey(fileName: string): string;
static toKey(uri: Uri): string;
static toKey(fileNameOrUri: string | Uri): string;
static toKey(fileNameOrUri: string | Uri): string {
return Strings.normalizePath(typeof fileNameOrUri === 'string' ? fileNameOrUri : fileNameOrUri.fsPath);
// return typeof fileNameOrUri === 'string'
// ? GitUri.file(fileNameOrUri).toString(true)
// : fileNameOrUri.toString(true);
}
static toRevisionUri(uri: GitUri): Uri;
static toRevisionUri(ref: string, fileName: string, repoPath: string): Uri;
static toRevisionUri(ref: string, file: GitFile, repoPath: string): Uri;
static toRevisionUri(uriOrRef: string | GitUri, fileNameOrFile?: string | GitFile, repoPath?: string): Uri {
let fileName: string;
let ref: string | undefined;
let shortSha: string | undefined;
if (typeof uriOrRef === 'string') {
if (typeof fileNameOrFile === 'string') {
fileName = fileNameOrFile;
} else {
//if (fileNameOrFile!.status === 'D') {
fileName = GitUri.resolve(fileNameOrFile!.originalFileName ?? fileNameOrFile!.fileName, repoPath);
// } else {
// fileName = GitUri.resolve(fileNameOrFile!.fileName, repoPath);
}
ref = uriOrRef;
shortSha = GitRevision.shorten(ref);
} else {
fileName = uriOrRef.fsPath;
ref = uriOrRef.sha;
shortSha = uriOrRef.shortSha;
repoPath = uriOrRef.repoPath!;
}
if (ref == null || ref.length === 0) {
return Uri.file(fileName);
}
if (GitRevision.isUncommitted(ref)) {
return GitRevision.isUncommittedStaged(ref) ? GitUri.git(fileName, repoPath) : Uri.file(fileName);
}
const filePath = Strings.normalizePath(fileName, { addLeadingSlash: true });
const data: UriRevisionData = {
path: filePath,
ref: ref,
repoPath: Strings.normalizePath(repoPath!),
};
const uri = Uri.parse(
// Replace / in the authority with a similar unicode characters otherwise parsing will be wrong
`${DocumentSchemes.GitLens}://${encodeURIComponent(shortSha.replace(/\//g, '\u200A\u2215\u200A'))}${
// Change encoded / back to / otherwise uri parsing won't work properly
filePath === slash ? emptyStr : encodeURIComponent(filePath).replace(/%2F/g, slash)
}?${encodeURIComponent(JSON.stringify(data))}`,
);
return uri;
}
}
interface UriRevisionData {
path: string;
ref?: string;
repoPath: string;
} | the_stack |
import _ from "lodash";
import { CompletionMsg, MsgType, OscType, OscValues } from "../osc-types";
/**
* Call and response is where an OSC command is sent to the
* server which later responds with a message whose first items
* match 'response', followed by the contents of the response.
*/
export interface CallAndResponse {
call: MsgType;
response: MsgType;
}
/**
* Many scsynth OSC commands accept lists of params:
*
* [\freq, 440, \pan, 0, \amp, 0.9]
*
* In supercollider.js these can be passed as objects:
*
* {freq: 440, pan: 0, amp: 0.9}
*
* or as a list:
*
* [['freq', 440], ['pan', 0], ['amp', 0.9]]
*/
type PairsType = Params | ParamList;
// {name: value, ...}
export interface Params {
[name: string]: OscType;
}
// [[name, value], [name2, value2], ...]
type Param = OscType[];
type ParamList = Param[];
/**
* Flatten {} or [[ ], ...] to []
*/
function flattenPairs(pairs: PairsType): OscType[] {
if (_.isPlainObject(pairs)) {
return _.flatten(_.toPairs(pairs));
}
if (_.isArray(pairs)) {
return _.flatten(pairs);
}
throw new TypeError(
`Received ${typeof pairs} ${JSON.stringify(pairs)}. Expected \{key: value, ...\} or [[key, value],...]`,
);
}
/**
* Add actions for specifying relationship of newly adding node
* to its targetID
*
* - 0 add the new group to the the head of the group specified by the add target ID.
* - 1 add the new group to the the tail of the group specified by the add target ID.
* - 2 add the new group just before the node specified by the add target ID.
* - 3 add the new group just after the node specified by the add target ID.
* - 4 the new node replaces the node specified by the add target ID. The target node is freed.
* @memberof msg
*/
export enum AddActions {
HEAD = 0,
TAIL = 1,
BEFORE = 2,
AFTER = 3,
REPLACE = 4,
}
/**
* Tell server to exit
*
*/
export function quit(): MsgType {
return ["/quit"];
}
/**
* Register to receive notifications from server
* Asynchronous. Replies with `/done /notify clientID`. If this client has registered for notifications before, this may be the same ID. Otherwise it will be a new one. Clients can use this ID in multi-client situations to avoid conflicts in node IDs, bus indices, buffer numbers, etc.
* @param {int} on - start or stop
If argument is 1, server will remember your return address and send you notifications. 0 will stop sending notifications.
*/
export function notify(on = 1, clientId = 0): CallAndResponse {
return {
call: ["/notify", on, clientId],
response: ["/done", "/notify"], // => clientID, maxLogins
};
}
/**
* Query for server status.
* Server replies with `/status.reply`
*/
export function status(): CallAndResponse {
return {
call: ["/status"],
response: ["/status.reply"], // => status array
};
}
/**
* Execute a command defined by a UGen Plug-in
*/
export function cmd(command: number, args: OscValues = []): MsgType {
return ["/cmd", command, ...args];
}
/**
* Dump incoming OSC messages to stdout
* @param {int} code -
* 0 turn dumping OFF.
* 1 print the parsed contents of the message.
* 2 print the contents in hexadecimal.
* 3 print both the parsed and hexadecimal representations of the contents.
*/
export function dumpOSC(code = 1): MsgType {
return ["/dumpOSC", code];
}
/**
* Notify when async commands have completed.
*
* Replies with a `/synced` message when all asynchronous commands received before this one have completed. The reply will contain the sent unique ID.
*
* Asynchronous. Replies with `/synced ID` .
*
* @param {int} id - a unique number identifying this command.
*/
export function sync(id: number): CallAndResponse {
return {
call: ["/sync", id],
response: ["/synced", id],
};
}
/**
* Clear all scheduled bundles. Removes all bundles from the scheduling queue.
*/
export function clearSched(): MsgType {
return ["/clearSched"];
}
/**
* Enable/disable error message posting.
* @param {int} on
*/
export function error(on = 1): MsgType {
return ["/error", on];
}
/**** Synth Definition Commands ** */
/**
* Loads a file of synth definitions from a data buffer included in the message. Resident definitions with the same names are overwritten.
*
* Asynchronous. Replies with `/done`.
*
* @param {Buffer} buffer - A node global datatype: new Buffer(array)
* @param {Array} completionMsg
*/
export function defRecv(buffer: Buffer, completionMsg: CompletionMsg | null = null): CallAndResponse {
return {
call: ["/d_recv", buffer, completionMsg],
response: ["/done", "/d_recv"],
};
}
/**
* Load synth definition.
*
* Loads a file of synth definitions. Resident definitions with the same names are overwritten.
* Asynchronous. Replies with `/done`.
* @param {String} path
* @param {Array} completionMsg
*/
export function defLoad(path: string, completionMsg: CompletionMsg | null = null): CallAndResponse {
return {
call: ["/d_load", path, completionMsg],
response: ["/done"],
};
}
/**
* Load a directory of synth definitions.
*
* Asynchronous. Replies with `/done`.
*
* @param {String} path
* @param {Array} completionMsg
*/
export function defLoadDir(path: string, completionMsg: CompletionMsg | null = null): CallAndResponse {
return {
call: ["/d_loadDir", path, completionMsg],
response: ["/done"],
};
}
/**
* Delete synth definition.
*
* The definition is removed immediately, and does not wait for synth nodes based on that definition to end.
*
* @param {String} defName
*/
export function defFree(defName: string): MsgType {
return ["/d_free", defName];
}
/******* Node Commands ********************** */
/**
* Delete/free a node
* @param {int} nodeID
*/
export function nodeFree(nodeID: number): MsgType {
return ["/n_free", nodeID];
}
/**
* Stop/start a node from running
*
* Save computation by turning a node (and its children) off
* but without removing it from the UGen graph
* @param {int} nodeID
* @param {int} on - binary boolean
*/
export function nodeRun(nodeID: number, on = 1): MsgType {
return ["/n_run", nodeID, on];
}
/**
* Set a node's control value(s).
*
* Takes a list of pairs of control indices and values and sets the controls to
* those values. If the node is a group, then it sets the controls of every node
* in the group.
*
* This message now supports array type tags (`$[` and `$]`) in the control/value
* component of the OSC message. Arrayed control values are applied in the
* manner of `n_setn` (i.e., sequentially starting at the indexed or named control).
*
* I think this also takes `[freq, 440]`
*
* @example
* ```js
* nodeSet(id, [[0, 440], ...])
* ```
*
* @param {int} nodeID
* @param {object|Array} pairs - `[[key, value], ...]` or `{key: value, ...}`
*/
export function nodeSet(nodeID: number, pairs: PairsType): MsgType {
return ["/n_set", nodeID, ...flattenPairs(pairs)];
}
/**
* Set ranges of a node's control value(s).
*
* Set contiguous ranges of control indices to sets of values. For each range,
* the starting control index is given followed by the number of controls to change,
* followed by the values. If the node is a group, then it sets the controls of every
* node in the group.
*
* @param {int} nodeID -
* @param {Array} valueSets - `[[controlName|index, numValues, value1, ... valueN], ...]`
*/
export function nodeSetn(nodeID: number, valueSets: PairsType): MsgType {
return ["/n_setn", nodeID, ...flattenPairs(valueSets)];
}
/**
* Fill ranges of a node's control value(s).
*
* Set contiguous ranges of control indices to single values. For each range,
* the starting control index is given followed by the number of controls to
* change, followed by the value to fill. If the node is a group, then it
* sets the controls of every node in the group.
*
* @param {int} nodeID -
* @param {Array} triples - `[[key, numValuesToFill, value], ...]`
*/
export function nodeFill(nodeID: number, triples: PairsType = []): MsgType {
return ["/n_fill", nodeID, ...flattenPairs(triples)];
}
/**
* Map a node's controls to read from a bus.
*
* @param {int} nodeID -
* @param {Array|object} pairs - `[[controlName, busID], ...]`
*
* Takes a list of pairs of control names or indices and bus indices and causes those controls to be read continuously from a global control bus. If the node is a group, then it maps the controls of every node in the group. If the control bus index is -1 then any current mapping is undone. Any n_set, n_setn and n_fill command will also unmap the control.
*/
export function nodeMap(nodeID: number, pairs: PairsType = []): MsgType {
return ["/n_map", nodeID, ...flattenPairs(pairs)];
}
/**
* Map a node's controls to read from buses.
*
* Takes a list of triples of control names or indices, bus indices, and number of controls to map and causes those controls to be mapped sequentially to buses. If the node is a group, then it maps the controls of every node in the group. If the control bus index is -1 then any current mapping is undone. Any n_set, n_setn and n_fill command will also unmap the control.
*
* @param {int} nodeID -
* @param {Array} triples - `[[controlName|index, busID, numControlsToMap], ...]`
*/
export function nodeMapn(nodeID: number, triples: PairsType = []): MsgType {
return ["/n_mapn", nodeID, ...flattenPairs(triples)];
}
/**
* Map a node's controls to read from an audio bus.
*
* Takes a list of pairs of control names or indices and audio bus indices and causes those controls to be read continuously from a global audio bus. If the node is a group, then it maps the controls of every node in the group. If the audio bus index is -1 then any current mapping is undone. Any n_set, n_setn and n_fill command will also unmap the control. For the full audio rate signal, the argument must have its rate set to \ar.
*
* @param {int} nodeID -
* @param {Array} pairs - `[[controlName|index, audioBusID], ...]`
*/
export function nodeMapAudio(nodeID: number, pairs: PairsType): MsgType {
return ["/n_mapa", nodeID, ...flattenPairs(pairs)];
}
/**
* Map a node's controls to read from audio buses.
*
* @param {int} nodeID -
* @param {Array} triples - `[[controlName|index, audioBusID, numControlsToMap], ...]`
*
* Takes a list of triples of control names or indices, audio bus indices, and number of controls to map and causes those controls to be mapped sequentially to buses. If the node is a group, then it maps the controls of every node in the group. If the audio bus index is -1 then any current mapping is undone. Any `n_set`, `n_setn` and `n_fill` command will also unmap the control. For the full audio rate signal, the argument must have its rate set to `\ar`.
*/
export function nodeMapAudion(nodeID: number, triples: PairsType = []): MsgType {
return ["/n_mapan", nodeID, ...flattenPairs(triples)];
}
/**
* Places node A in the same group as node B, to execute immediately before node B.
*
* @param {int} moveNodeID - the node to move (A)
* @param {int} beforeNodeID - the node to move A before
*/
export function nodeBefore(moveNodeID: number, beforeNodeID: number): MsgType {
return ["/n_before", moveNodeID, beforeNodeID];
}
/**
* Places node A in the same group as node B, to execute immediately after node B.
*
* @param {int} moveNodeID - the ID of the node to place (A)
* @param {int} afterNodeID - the ID of the node after which the above is placed (B)
*/
export function nodeAfter(moveNodeID: number, afterNodeID: number): MsgType {
return ["/n_after", moveNodeID, afterNodeID];
}
/**
* Get info about a node.
*
* The server sends an `/n_info` message for each node to registered clients.
* See Node Notifications for the format of the `/n_info` message.
*
* @param {int} nodeID
*/
export function nodeQuery(nodeID: number): CallAndResponse {
return {
call: ["/n_query", nodeID],
response: ["/n_info", nodeID],
};
}
/**
* Trace a node.
*
* Causes a synth to print out the values of the inputs and outputs of its unit generators for one control period. Causes a group to print the node IDs and names of each node in the group for one control period.
*
* @param {int} nodeID
*/
export function nodeTrace(nodeID: number): MsgType {
return ["/n_trace", nodeID];
}
/**
* Move and order a list of nodes.
*
* Move the listed nodes to the location specified by the target and add action, and place them in the order specified. Nodes which have already been freed will be ignored.
*
* @param {int} addAction
* @param {int} targetID
* @param {Array.<int>} nodeIDs
*/
export function nodeOrder(addAction: number, targetID: number, nodeIDs: [number]): MsgType {
return ["/n_order", addAction, targetID, ...nodeIDs];
}
/***** Synth Commands ** */
/**
* Create a new synth.
Create a new synth from a named, compiled and already loaded synth definition, give it an ID, and add it to the tree of nodes.
There are four ways to add the node to the tree as determined by the add action argument
Controls may be set when creating the synth. The control arguments are the same as for the `n_set` command.
If you send `/s_new` with a synth ID of -1, then the server will generate an ID for you. The server reserves all negative IDs. Since you don't know what the ID is, you cannot talk to this node directly later. So this is useful for nodes that are of finite duration and that get the control information they need from arguments and buses or messages directed to their group. In addition no notifications are sent when there are changes of state for this node, such as `/n_go`, `/n_end`, `/n_on`, `/n_off`.
If you use a node ID of -1 for any other command, such as `/n_map`, then it refers to the most recently created node by `/s_new` (auto generated ID or not). This is how you can map the controls of a node with an auto generated ID. In a multi-client situation, the only way you can be sure what node -1 refers to is to put the messages in a bundle.
This message now supports array type tags (`$[` and `$]`) in the control/value component of the OSC message. Arrayed control values are applied in the manner of n_setn (i.e., sequentially starting at the indexed or named control). See the linkGuides/NodeMessaging helpfile.
* @param {object} args
* - key: a control index or name
* - value: floating point and integer arguments are interpreted
* as control value.
* A symbol argument consisting of the letter 'c' or 'a' (for control or audio) followed by the bus's index.
* @return OSC message
*/
export function synthNew(
defName: string,
nodeID = -1,
addAction: number = AddActions.TAIL,
targetID = 0,
args: PairsType = [],
): MsgType {
return ["/s_new", defName, nodeID, addAction, targetID, ...flattenPairs(args)];
}
/**
* Get control value(s).
* @param {int} synthID
* @param {Array.<int|String>} controlNames - index or names
Replies with the corresponding `/n_set` command.
*/
export function synthGet(synthID: number, controlNames: [number | string]): CallAndResponse {
return {
call: ["/s_get", synthID, ...controlNames],
response: ["/n_set", synthID],
};
}
/**
Get ranges of control value(s).
* @param {int} synthID
* @param {int|String} controlName - a control index or name
* @param {int} n - number of sequential controls to get (M)
Get contiguous ranges of controls. Replies with the corresponding `/n_setn` command.
*/
export function synthGetn(synthID: number, controlName: number | string, n: number): CallAndResponse {
return {
call: ["/s_getn", synthID, controlName, n],
response: ["/n_setn", synthID],
};
}
/**
* Auto-reassign synths' ID to a reserved value.
This command is used when the client no longer needs to communicate with the synth and wants to have the freedom to reuse the ID. The server will reassign this synth to a reserved negative number. This command is purely for bookkeeping convenience of the client. No notification is sent when this occurs.
* @param {Array} synthIDs
*/
export function synthNoid(synthIDs: [number]): MsgType {
return ["/s_noid", ...synthIDs];
}
/****** Group Commands *** */
/**
Create a new group.
Create a new group and add it to the tree of nodes.
There are four ways to add the group to the tree as determined by the add action argument
* @param {int} nodeID - new group ID
* @param {int} addAction
* @param {int} targetID
*/
export function groupNew(nodeID: number, addAction: number = AddActions.HEAD, targetID = 0): MsgType {
return ["/g_new", nodeID, _.isUndefined(addAction) ? AddActions.HEAD : addAction, targetID || 0];
}
/**
Create a new parallel group. supernova only
Create a new parallel group and add it to the tree of nodes. Parallel groups are relaxed groups, their child nodes are evaluated in unspecified order.
There are four ways to add the group to the tree as determined by the add action argument
Multiple groups may be created in one command by adding arguments. (not implemented here)
* @param {int} groupID - new group ID
* @param {int} addAction - add action
* @param {int} targetID
*/
export function parallelGroupNew(groupID: number, addAction: number = AddActions.HEAD, targetID = 0): MsgType {
return ["/p_new", groupID, addAction, targetID];
}
/**
* Moves node to the head (first to be executed) of the group.
*
* @param {int} groupID
* @param {int} nodeID
* @param {...int} rest - more node IDs to also move to head
*/
export function groupHead(groupID: number, nodeID: number, ...rest: number[]): MsgType {
return ["/g_head", groupID, nodeID, ...rest];
}
/**
* Moves node to the tail (last to be executed) of the group.
* @param {int} groupID
* @param {int} nodeID
* @param {...int} rest - more node IDs to also move to tail
*/
export function groupTail(groupID: number, nodeID: number, ...rest: number[]): MsgType {
return ["/g_tail", groupID, nodeID, ...rest];
}
/**
Frees all immediate children nodes in the group
* @param {int} groupID
*/
export function groupFreeAll(groupID: number): MsgType {
return ["/g_freeAll", groupID];
}
/**
* Free all synths in this group and all its sub-groups.
*
* Traverses all groups below this group and frees all the synths. Sub-groups are not freed.
*
* @param {int} groupID
*/
export function groupDeepFree(groupID: number): MsgType {
return ["/g_deepFree", groupID];
}
/**
* Post a representation of this group's node subtree to STDOUT
Posts a representation of this group's node subtree, i.e. all the groups and synths contained within it, optionally including the current control values for synths.
* @param {int} groupID
* @param {int} dumpControlValues - if not 0 post current control (arg) values for synths to STDOUT
*
*/
export function groupDumpTree(groupID: number, dumpControlValues = 0): MsgType {
return ["/g_dumpTree", groupID, dumpControlValues];
}
/**
* Get a representation of this group's node subtree.
Request a representation of this group's node subtree, i.e. all the groups and synths contained within it. Replies to the sender with a `/g_queryTree.reply` message listing all of the nodes contained within the group in the following format:
* param {int} - flag: if synth control values are included 1, else 0
* param {int} nodeID - of the requested group
* param {int} - number of child nodes contained within the requested group
* then for each node in the subtree:
* param {int} nodeID -
* param {int} - number of child nodes contained within this node. If -1 this is a synth, if >=0 it's a group
* then, if this node is a synth:
* strongsymbol the SynthDef name for this node.
* then, if flag (see above) is true:
* param {int} - numControls for this synth (M)
* multiple:
* param {string|int} - control name or index
* param {float|String} value or control bus mapping symbol (e.g. 'c1')
* N.B. The order of nodes corresponds to their execution order on the server. Thus child nodes (those contained within a group) are listed immediately following their parent. See the method Server:queryAllNodes for an example of how to process this reply.
*
* @param {int} groupID
* @param {int} dumpControlValues - if not 0 the current control (arg) values for synths will be included
*/
export function groupQueryTree(groupID: number, dumpControlValues = 0): CallAndResponse {
return {
call: ["/g_queryTree", groupID, dumpControlValues],
response: ["/g_queryTree.reply", groupID],
};
}
/***** Unit Generator Commands *** */
/**
* Send a command to a unit generator.
*
* Sends all arguments following the command name to the unit generator to be performed. Commands are defined by unit generator plug ins.
*
* @param {int} nodeID -
* @param {int} uGenIndex - unit generator index
* @param {String} command -
* @param {Array} args
*/
export function ugenCmd(nodeID: number, uGenIndex: number, command: string, args: OscValues = []): MsgType {
return ["/u_cmd", nodeID, uGenIndex, command, ...args];
}
/***** Buffer Commands *** */
// Buffers are stored in a global array, indexed by integers starting at zero.
/**
* Allocates zero filled buffer to number of channels and samples.
* Asynchronous. Replies with `/done /b_alloc bufNum`.
* @param {int} bufferID
* @param {int} numFrames
* @param {int} numChannels
* @param {Array} completionMsg - (optional)
*/
export function bufferAlloc(
bufferID: number,
numFrames: number,
numChannels: number,
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
return {
call: ["/b_alloc", bufferID, numFrames, numChannels, completionMsg],
response: ["/done", "/b_alloc", bufferID],
};
}
/**
* Allocate buffer space and read a sound file.
Allocates buffer to number of channels of file and number of samples requested, or fewer if sound file is smaller than requested. Reads sound file data from the given starting frame in the file. If the number of frames argument is less than or equal to zero, the entire file is read.
* Asynchronous. Replies with `/done /b_allocRead bufNum`.
* @param {int} bufferID
* @param {String} path - name of a sound file.
* @param {int} startFrame - starting frame in file (optional. default = 0)
* @param {int} numFramesToRead - number of frames to read (optional. default = 0, see below)
* @param {Array} completionMsg - (optional)
*/
export function bufferAllocRead(
bufferID: number,
path: string,
startFrame = 0,
numFramesToRead = -1,
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
return {
call: ["/b_allocRead", bufferID, path, startFrame, numFramesToRead, completionMsg],
response: ["/done", "/b_allocRead", bufferID],
};
}
/**
* Allocate buffer space and read channels from a sound file.
As `b_allocRead`, but reads individual channels into the allocated buffer in the order specified.
* Asynchronous. Replies with `/done /b_allocReadChannel bufNum`.
* @param {int} bufferID - buffer number
* @param {String} path - path name of a sound file
* @param {int} startFrame - starting frame in file
* @param {int} numFramesToRead - number of frames to read
* @param {Array.<int>} channels - source file channel indices
* @param {Array} completionMsg - (optional)
*/
export function bufferAllocReadChannel(
bufferID: number,
path: string,
startFrame: number,
numFramesToRead: number,
channels: number[],
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
const call: MsgType = ["/b_allocReadChannel", bufferID, path, startFrame, numFramesToRead, ...channels];
if (completionMsg) {
call.push(completionMsg);
}
return {
call: call,
response: ["/done", "/b_allocReadChannel", bufferID],
};
}
/**
* Read sound file data into an existing buffer.
Reads sound file data from the given starting frame in the file and writes it to the given starting frame in the buffer. If number of frames is less than zero, the entire file is read.
If reading a file to be used by `DiskIn` ugen then you will want to set "leave file open" to one, otherwise set it to zero.
* Asynchronous. Replies with `/done /b_read bufNum`.
*
* @param {int} bufferID
* @param {String} path - path name of a sound file.
* @param {int} startFrame - starting frame in file (optional. default = 0)
* @param {int} numFramesToRead - number of frames to read (optional. default = -1, see below)
* @param {int} startFrameInBuffer - starting frame in buffer (optional. default = 0)
* @param {int} leaveFileOpen - leave file open (optional. default = 0)
* @param {Array} completionMsg - (optional)
*/
export function bufferRead(
bufferID: number,
path: string,
startFrame = 0,
numFramesToRead = -1,
startFrameInBuffer = 0,
leaveFileOpen = 0,
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
return {
call: ["/b_read", bufferID, path, startFrame, numFramesToRead, startFrameInBuffer, leaveFileOpen, completionMsg],
response: ["/done", "/b_read", bufferID],
};
}
/**
* Read sound file channel data into an existing buffer.
* As `b_read`, but reads individual channels in the order specified. The number of channels requested must match the number of channels in the buffer.
* Asynchronous. Replies with `/done /b_readChannel bufNum`.
* @param {int} bufferID
* @param {String} path - of a sound file
* @param {int} startFrame - starting frame in file
* @param {int} numFramesToRead - number of frames to read
* @param {int} startFrameInBuffer - starting frame in buffer
* @param {int} leaveFileOpen - leave file open
* @param {Array.<int>} channels - source file channel indexes
* @param {Array} completionMsg
*/
export function bufferReadChannel(
bufferID: number,
path: string,
startFrame = 0,
numFramesToRead = -1,
startFrameInBuffer = 0,
leaveFileOpen = 0,
channels: number[] = [],
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
const call: MsgType = [
"/b_readChannel",
bufferID,
path,
startFrame,
numFramesToRead,
startFrameInBuffer,
leaveFileOpen,
...channels,
];
call.push(completionMsg);
return {
call: call,
response: ["/done", "/b_readChannel", bufferID],
};
}
/**
* Write buffer contents to a sound file.
* Not all combinations of header format and sample format are possible.
If number of frames is less than zero, all samples from the starting frame to the end of the buffer are written.
If opening a file to be used by DiskOut ugen then you will want to set "leave file open" to one, otherwise set it to zero. If "leave file open" is set to one then the file is created, but no frames are written until the DiskOut ugen does so.
* Asynchronous. Replies with `/done /b_write bufNum`.
* @param {int} bufferID
* @param {String} path - path name of a sound file.
* @param {String} headerFormat -
* Header format is one of: "aiff", "next", "wav", "ircam"", "raw"
* @param {String} sampleFormat -
* Sample format is one of: "int8", "int16", "int24", "int32", "float", "double", "mulaw", "alaw"
* @param {int} numFramesToWrite - number of frames to write (optional. default = -1, see below)
* @param {int} startFrameInBuffer - starting frame in buffer (optional. default = 0)
* @param {int} leaveFileOpen - leave file open (optional. default = 0)
* @param {Array} completionMsg - (optional)
*/
export function bufferWrite(
bufferID: number,
path: string,
headerFormat = "aiff",
sampleFormat = "float",
numFramesToWrite = -1,
startFrameInBuffer = 0,
leaveFileOpen = 0,
completionMsg: CompletionMsg | null = null,
): CallAndResponse {
return {
call: [
"/b_write",
bufferID,
path,
headerFormat,
sampleFormat,
numFramesToWrite,
startFrameInBuffer,
leaveFileOpen,
completionMsg,
],
response: ["/done", "/b_write", bufferID],
};
}
/**
* Frees buffer space allocated for this buffer.
*
* Asynchronous. Replies with `/done /b_free bufNum`.
*
* @param {int} bufferID
* @param {Array} completionMsg - (optional)
*/
export function bufferFree(bufferID: number, completionMsg: CompletionMsg | null = null): CallAndResponse {
return {
call: ["/b_free", bufferID, completionMsg],
response: ["/done", "/b_free", bufferID],
};
}
/**
* Sets all samples in the buffer to zero.
*
* Asynchronous. Replies with `/done /b_zero bufNum`.
* @param {int} bufferID
* @param {Array} completionMsg - (optional)
*/
export function bufferZero(bufferID: number, completionMsg: CompletionMsg | null = null): CallAndResponse {
return {
call: ["/b_zero", bufferID, completionMsg],
response: ["/done", "/b_zero", bufferID],
};
}
/**
* Takes a list of pairs of sample indices and values and sets the samples to those values.
* @param {int} bufferID
* @param {Array} pairs - `[[frame, value], ...]`
*/
export function bufferSet(bufferID: number, pairs: PairsType): MsgType {
return ["/b_set", bufferID, ...flattenPairs(pairs)];
}
/**
* Set ranges of sample value(s).
* Set contiguous ranges of sample indices to sets of values. For each range, the starting sample index is given followed by the number of samples to change, followed by the values.
* @param {int} bufferID
* @param {int} startFrame
* @param {Array.<float>} values
*/
export function bufferSetn(bufferID: number, startFrame: number, values: number[] = []): MsgType {
return ["/b_setn", bufferID, startFrame, values.length, ...values];
}
/**
* Fill ranges of samples with a value
* Set contiguous ranges of sample indices to single values. For each range, the starting sample index is given followed by the number of samples to change, followed by the value to fill. This is only meant for setting a few samples, not whole buffers or large sections.
* @param {int} bufferID
* @param {int} startFrame
* @param {int} numFrames
* @param {float} value
*/
export function bufferFill(bufferID: number, startFrame: number, numFrames: number, value: number): MsgType {
return ["/b_fill", bufferID, startFrame, numFrames, value];
}
/**
* Call a command to fill a buffer.
* Plug-ins can define commands that operate on buffers. The arguments after the command name are defined by the command. The currently defined buffer fill commands are listed below in a separate section.
* Asynchronous. Replies with `/done /b_gen bufNum`.
* @param {int} bufferID
* @param {String} command
* @param {Array} args
*/
export function bufferGen(bufferID: number, command: string, args: OscValues = []): CallAndResponse {
return {
call: ["/b_gen", bufferID, command, ...args],
response: ["/done", "/b_gen", bufferID],
};
}
/**
* After using a buffer with `DiskOut`, close the soundfile and write header information.
* Asynchronous. Replies with `/done /b_close bufNum`.
* @param {int} bufferID
*/
export function bufferClose(bufferID: number): CallAndResponse {
return {
call: ["/b_close", bufferID],
response: ["/done", "/b_close", bufferID],
};
}
/**
* Get buffer info.
* Responds to the sender with a `/b_info` message with:
* multiple:
* param {int} bufferID
* param {int} - number of frames
* param {int} - number of channels
* param {float} sample rate
* @param {int} bufferID
*/
export function bufferQuery(bufferID: number): CallAndResponse {
return {
call: ["/b_query", bufferID],
response: ["/b_info", bufferID], // => [numFrames, numChannels, sampleRate]
};
}
/**
* Get sample value(s).
* Replies with the corresponding `/b_set` command.
*
* @param {int} bufferID - buffer number
* @param {Array} framesArray - sample indices to return
*/
export function bufferGet(bufferID: number, framesArray: [number]): CallAndResponse {
return {
call: ["/b_get", bufferID, ...framesArray],
response: ["/b_set", bufferID], // => sampleValues
};
}
/**
Get ranges of sample value(s).
Get contiguous ranges of samples. Replies with the corresponding `b_setn` command. This is only meant for getting a few samples, not whole buffers or large sections.
* @param {int} bufferID
* @param {int} startFrame - starting sample index
* @param {int} numFrames - number of sequential samples to get (M)
*/
export function bufferGetn(bufferID: number, startFrame: number, numFrames: number): CallAndResponse {
return {
call: ["/b_getn", bufferID, startFrame, numFrames],
response: ["/b_setn", bufferID], // => sampleValues
};
}
/***** Control Bus Commands *** */
/**
* Takes a list of pairs of bus indices and values and sets the buses to those values.
*
* @param {Array} pairs - `[[busID, value], ...]`
*/
export function controlBusSet(pairs: PairsType): MsgType {
return ["/c_set", ...flattenPairs(pairs)];
}
/**
* Set ranges of bus value(s).
* Set contiguous ranges of buses to sets of values. For each range, the starting bus index is given followed by the number of channels to change, followed by the values.
*
* @param {Array} triples - `[[firstBusID, numBussesToChange, value], ...]`
*/
export function controlBusSetn(triples: PairsType = []): MsgType {
return ["/c_setn", ...flattenPairs(triples)];
}
/**
* Fill ranges of bus value(s).
*
* Set contiguous ranges of buses to single values. For each range, the starting sample index is given followed by the number of buses to change, followed by the value to fill.
*
* TODO: What is difference to `c_setn` ?
*
* @param {Array} triples - `[[firstBusID, numBussesToChange, value], ...]`
*/
export function controlBusFill(triples: PairsType = []): MsgType {
return ["/c_fill", ...flattenPairs(triples)];
}
/**
* Get control bus values
*
* Takes a bus ID and replies with the corresponding `c_set` command.
*
* @param {Number} busID
*/
export function controlBusGet(busID: number): CallAndResponse {
return {
call: ["/c_get", busID],
response: ["/c_set", busID], // => busValue
};
}
/**
* Get contiguous ranges of buses. Replies with the corresponding `c_setn` command.
*
* @param {int} startBusIndex - starting bus index
* @param {int} numBusses - number of sequential buses to get (M)
*/
export function controlBusGetn(startBusIndex: number, numBusses: number): CallAndResponse {
return {
call: ["/c_getn", startBusIndex, numBusses],
response: ["/c_setn", startBusIndex], // => busValues
};
}
/***** Non Real Time Mode Commands *** */
/**
End real time mode, close file. Not yet implemented on server
This message should be sent in a bundle in non real time mode.
The bundle timestamp will establish the ending time of the file.
This command will end non real time mode and close the sound file.
Replies with `/done`.
*/
export function nonRealTimeEnd(): CallAndResponse {
return {
call: ["/nrt_end"],
response: ["/done"],
};
} | the_stack |
import * as assert from 'assert';
import { context, ROOT_CONTEXT, SpanStatusCode } from '@opentelemetry/api';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node';
import {
InMemorySpanExporter,
ReadableSpan,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { HookHandlerDoneFunction } from 'fastify/types/hooks';
import { FastifyReply } from 'fastify/types/reply';
import { FastifyRequest } from 'fastify/types/request';
import * as http from 'http';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { ANONYMOUS_NAME } from '../src/instrumentation';
import { AttributeNames, FastifyInstrumentation } from '../src';
const URL = require('url').URL;
const httpRequest = {
get: (options: http.ClientRequestArgs | string) => {
return new Promise((resolve, reject) => {
return http.get(options, resp => {
let data = '';
resp.on('data', chunk => {
data += chunk;
});
resp.on('end', () => {
resolve(data);
});
resp.on('error', err => {
reject(err);
});
});
});
},
};
const httpInstrumentation = new HttpInstrumentation();
const instrumentation = new FastifyInstrumentation();
const contextManager = new AsyncHooksContextManager().enable();
const memoryExporter = new InMemorySpanExporter();
const provider = new NodeTracerProvider();
const spanProcessor = new SimpleSpanProcessor(memoryExporter);
instrumentation.setTracerProvider(provider);
httpInstrumentation.setTracerProvider(provider);
context.setGlobalContextManager(contextManager);
provider.addSpanProcessor(spanProcessor);
instrumentation.enable();
httpInstrumentation.enable();
import 'fastify-express';
import { FastifyInstance } from 'fastify/types/instance';
const Fastify = require('fastify');
function getSpans(): ReadableSpan[] {
const spans = memoryExporter.getFinishedSpans().filter(s => {
return (
s.instrumentationLibrary.name === '@opentelemetry/instrumentation-fastify'
);
});
return spans;
}
describe('fastify', () => {
let PORT: number;
let app: FastifyInstance;
function startServer(): Promise<void> {
return new Promise<void>(resolve =>
app.listen(0, (err, address) => {
const url = new URL(address);
PORT = parseInt(url.port, 10);
resolve();
})
);
}
beforeEach(async () => {
instrumentation.enable();
app = Fastify();
app.register(require('fastify-express'));
});
afterEach(async () => {
await new Promise<void>(resolve =>
app.close(() => {
resolve();
})
);
contextManager.disable();
contextManager.enable();
memoryExporter.reset();
instrumentation.disable();
});
describe('when fastify is disabled', () => {
it('should not generate any spans', async () => {
instrumentation.disable();
app.get('/test', (req, res) => {
res.send('OK');
});
await startServer();
await httpRequest.get(`http://localhost:${PORT}/test`);
const spans = getSpans();
assert.strictEqual(spans.length, 0); // http instrumentation only
});
});
describe('when fastify is enabled', () => {
it('should generate span for anonymous middleware', async () => {
app.get('/test', (req, res) => {
res.send('OK');
});
await startServer();
await httpRequest.get(`http://localhost:${PORT}/test`);
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 5);
const span = spans[3];
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'request_handler',
'plugin.name': 'fastify-express',
[SemanticAttributes.HTTP_ROUTE]: '/test',
});
assert.strictEqual(span.name, `request handler - ${ANONYMOUS_NAME}`);
const baseSpan = spans[1];
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
it('should generate span for named handler', async () => {
// eslint-disable-next-line prefer-arrow-callback
app.get('/test', function namedHandler(req, res) {
res.send('OK');
});
await startServer();
await httpRequest.get(`http://localhost:${PORT}/test`);
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 5);
const span = spans[3];
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'request_handler',
'fastify.name': 'namedHandler',
'plugin.name': 'fastify-express',
[SemanticAttributes.HTTP_ROUTE]: '/test',
});
assert.strictEqual(span.name, 'request handler - namedHandler');
const baseSpan = spans[1];
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
describe('when subsystem is registered', () => {
beforeEach(async () => {
httpInstrumentation.enable();
async function subsystem(fastify: FastifyInstance) {
fastify.addHook(
'onRequest',
async (
req: FastifyRequest,
res: FastifyReply,
next: HookHandlerDoneFunction
) => {
next();
}
);
fastify.use((req, res, next) => {
next();
});
// eslint-disable-next-line prefer-arrow-callback
fastify.get('/test/:id', function foo(req, res) {
res.send('OK');
});
fastify.get('/test-error', () => {
throw Error('foo');
});
}
app.register(subsystem);
await startServer();
await httpRequest.get(`http://localhost:${PORT}/test/1`);
assert.strictEqual(getSpans().length, 4);
});
it('should change name for parent http route', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const changedRootSpan = spans[2];
const span = spans[4];
assert.strictEqual(changedRootSpan.name, 'GET /test/:id');
assert.strictEqual(span.name, 'request handler - foo');
assert.strictEqual(span.parentSpanId, spans[3].spanContext().spanId);
});
it('should create span for fastify express runConnect', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const baseSpan = spans[0];
const span = spans[1];
assert.strictEqual(span.name, 'middleware - runConnect');
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'middleware',
'plugin.name': 'fastify-express',
'hook.name': 'onRequest',
});
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
it('should create span for fastify express for enhanceRequest', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const baseSpan = spans[2];
const span = spans[0];
assert.strictEqual(span.name, 'middleware - enhanceRequest');
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'middleware',
'plugin.name': 'fastify-express',
'hook.name': 'onRequest',
});
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
it('should create span for request', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const baseSpan = spans[3];
const span = spans[4];
assert.strictEqual(span.name, 'request handler - foo');
assert.deepStrictEqual(span.attributes, {
'plugin.name': 'subsystem',
'fastify.type': 'request_handler',
'fastify.name': 'foo',
'http.route': '/test/:id',
});
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
it('should update http.route for http span', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const span = spans[2];
assert.strictEqual(span.attributes['http.route'], '/test/:id');
});
it('should create span for subsystem anonymous middleware', async () => {
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const baseSpan = spans[1];
const span = spans[3];
assert.strictEqual(span.name, `middleware - ${ANONYMOUS_NAME}`);
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'middleware',
'plugin.name': 'subsystem',
'hook.name': 'onRequest',
});
assert.strictEqual(span.parentSpanId, baseSpan.spanContext().spanId);
});
it('should update span with error that was raised', async () => {
memoryExporter.reset();
await httpRequest.get(`http://localhost:${PORT}/test-error`);
const spans = memoryExporter.getFinishedSpans();
assert.strictEqual(spans.length, 6);
const span = spans[4];
assert.strictEqual(span.name, 'request handler - anonymous');
assert.deepStrictEqual(span.status, {
code: SpanStatusCode.ERROR,
message: 'foo',
});
assert.deepStrictEqual(span.attributes, {
'fastify.type': 'request_handler',
'plugin.name': 'subsystem',
'http.route': '/test-error',
});
});
});
describe('spans context', () => {
describe('hook callback', () => {
it('span should end upon done invocation', async () => {
let hookDone: HookHandlerDoneFunction;
const hookExecutedPromise = new Promise<void>(resolve => {
app.addHook(
'onRequest',
(_req, _reply, done: HookHandlerDoneFunction) => {
hookDone = done;
resolve();
}
);
});
app.get('/test', (_req, reply: FastifyReply) => {
reply.send('request ended in handler');
});
await startServer();
httpRequest.get(`http://localhost:${PORT}/test`);
await hookExecutedPromise;
// done was not yet called from the hook, so it should not end the span
const preDoneSpans = getSpans().filter(
s => !s.attributes[AttributeNames.PLUGIN_NAME]
);
assert.strictEqual(preDoneSpans.length, 0);
hookDone!();
const postDoneSpans = getSpans().filter(
s => !s.attributes[AttributeNames.PLUGIN_NAME]
);
assert.strictEqual(postDoneSpans.length, 1);
});
it('span should end when calling reply.send from hook', async () => {
app.addHook(
'onRequest',
(
_req: FastifyRequest,
reply: FastifyReply,
_done: HookHandlerDoneFunction
) => {
reply.send('request ended prematurely in hook');
}
);
app.get('/test', (_req: FastifyRequest, _reply: FastifyReply) => {
throw Error(
'handler should not be executed as request is ended in onRequest hook'
);
});
await startServer();
await httpRequest.get(`http://localhost:${PORT}/test`);
const spans = getSpans().filter(
s => !s.attributes[AttributeNames.PLUGIN_NAME]
);
assert.strictEqual(spans.length, 1);
});
});
});
describe('application hooks', () => {
it('onRoute not instrumented', done => {
app.addHook('onRoute', () => {
assert.strictEqual(context.active(), ROOT_CONTEXT);
});
// add a route to trigger the 'onRoute' hook
app.get('/test', (_req: FastifyRequest, reply: FastifyReply) => {
reply.send('OK');
});
startServer()
.then(() => done())
.catch(err => done(err));
});
it('onRegister is not instrumented', done => {
app.addHook('onRegister', () => {
assert.strictEqual(context.active(), ROOT_CONTEXT);
});
// register a plugin to trigger 'onRegister' hook
app.register((fastify, options, done) => {
done();
});
startServer()
.then(() => done())
.catch(err => done(err));
});
it('onReady is not instrumented', done => {
app.addHook('onReady', () => {
assert.strictEqual(context.active(), ROOT_CONTEXT);
});
startServer()
.then(() => done())
.catch(err => done(err));
});
it('onClose is not instrumented', done => {
app.addHook('onClose', () => {
assert.strictEqual(context.active(), ROOT_CONTEXT);
});
startServer()
.then(() => {
app.close().then(() => done());
})
.catch(err => done(err));
});
});
});
}); | the_stack |
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IConfiguration, AppInsightsCore, IAppInsightsCore, eLoggingSeverity, _eInternalMessageId, ITelemetryItem, ICustomProperties,
IChannelControls, hasWindow, hasDocument, isReactNative, doPerf, IDiagnosticLogger, INotificationManager, objForEachKey, proxyAssign, proxyFunctions,
arrForEach, isString, isFunction, isNullOrUndefined, isArray, throwError, ICookieMgr, addPageUnloadEventListener, addPageHideEventListener,
createUniqueNamespace, ITelemetryPlugin, IPlugin, ILoadedPlugin, UnloadHandler, removePageUnloadEventListener, removePageHideEventListener,
ITelemetryInitializerHandler, ITelemetryUnloadState, mergeEvtNamespace, _throwInternal, arrIndexOf, IDistributedTraceContext
} from "@microsoft/applicationinsights-core-js";
import { AnalyticsPlugin, ApplicationInsights } from "@microsoft/applicationinsights-analytics-js";
import { Sender } from "@microsoft/applicationinsights-channel-js";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { AjaxPlugin as DependenciesPlugin, IDependenciesPlugin } from "@microsoft/applicationinsights-dependencies-js";
import {
IUtil, Util, ICorrelationIdHelper, CorrelationIdHelper, IUrlHelper, UrlHelper, IDateTimeUtils, DateTimeUtils, ConnectionStringParser, FieldType,
IRequestHeaders, RequestHeaders, DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT,
Envelope, Event, Exception, Metric, PageView, RemoteDependencyData, IEventTelemetry,
ITraceTelemetry, IMetricTelemetry, IDependencyTelemetry, IExceptionTelemetry, IAutoExceptionTelemetry,
IPageViewTelemetry, IPageViewPerformanceTelemetry, Trace, PageViewPerformance, Data, SeverityLevel,
IConfig, ConfigurationManager, ContextTagKeys, IDataSanitizer, DataSanitizer, TelemetryItemCreator, IAppInsights, CtxTagKeys, Extensions,
IPropertiesPlugin, DistributedTracingModes, PropertiesPluginIdentifier, BreezeChannelIdentifier, AnalyticsPluginIdentifier,
ITelemetryContext as Common_ITelemetryContext, parseConnectionString
} from "@microsoft/applicationinsights-common"
import { DependencyListenerFunction, IDependencyListenerHandler } from "@microsoft/applicationinsights-dependencies-js/types/DependencyListener";
export { IUtil, ICorrelationIdHelper, IUrlHelper, IDateTimeUtils, IRequestHeaders };
"use strict";
let _internalSdkSrc: string;
// This is an exclude list of properties that should not be updated during initialization
// They include a combination of private and internal property names
const _ignoreUpdateSnippetProperties = [
"snippet", "dependencies", "properties", "_snippetVersion", "appInsightsNew", "getSKUDefaults"
];
/**
*
* @export
* @interface Snippet
*/
export interface Snippet {
config: IConfiguration & IConfig;
queue?: Array<() => void>;
sv?: string;
version?: number;
}
export interface IApplicationInsights extends IAppInsights, IDependenciesPlugin, IPropertiesPlugin {
appInsights: ApplicationInsights;
flush: (async?: boolean) => void;
onunloadFlush: (async?: boolean) => void;
getSender: () => Sender;
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): void;
clearAuthenticatedUserContext(): void;
/**
* Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered
* to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous
* unload call return `true` stating that all plugins reported that they also unloaded, the recommended
* approach is to create a new instance and initialize that instance.
* This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable
* to successfully remove any global references or they may just be completing the unload process asynchronously.
*/
unload(isAsync?: boolean, unloadComplete?: () => void): void;
/**
* Find and return the (first) plugin with the specified identifier if present
* @param pluginIdentifier
*/
getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T>;
/**
* Add a new plugin to the installation
* @param plugin - The new plugin to add
* @param replaceExisting - should any existing plugin be replaced
* @param doAsync - Should the add be performed asynchronously
*/
addPlugin<T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting: boolean, doAsync: boolean, addCb?: (added?: boolean) => void): void;
/**
* Returns the unique event namespace that should be used when registering events
*/
evtNamespace(): string;
/**
* Add a handler that will be called when the SDK is being unloaded
* @param handler - the handler
*/
addUnloadCb(handler: UnloadHandler): void;
}
// Re-exposing the Common classes as Telemetry, the list was taken by reviewing the generated code for the build while using
// the previous configuration :-
// import * as Common from "@microsoft/applicationinsights-common"
// export const Telemetry = Common;
let fieldType = {
Default: FieldType.Default,
Required: FieldType.Required,
Array: FieldType.Array,
Hidden: FieldType.Hidden
};
/**
* Telemetry type classes, e.g. PageView, Exception, etc
*/
export const Telemetry = {
__proto__: null as any,
PropertiesPluginIdentifier,
BreezeChannelIdentifier,
AnalyticsPluginIdentifier,
Util,
CorrelationIdHelper,
UrlHelper,
DateTimeUtils,
ConnectionStringParser,
FieldType: fieldType,
RequestHeaders,
DisabledPropertyName,
ProcessLegacy,
SampleRate,
HttpMethod,
DEFAULT_BREEZE_ENDPOINT,
Envelope,
Event,
Exception,
Metric,
PageView,
RemoteDependencyData,
Trace,
PageViewPerformance,
Data,
SeverityLevel,
ConfigurationManager,
ContextTagKeys,
DataSanitizer: DataSanitizer as IDataSanitizer,
TelemetryItemCreator,
CtxTagKeys,
Extensions,
DistributedTracingModes
};
/**
* Application Insights API
* @class Initialization
* @implements {IApplicationInsights}
*/
export class Initialization implements IApplicationInsights {
public snippet: Snippet;
public config: IConfiguration & IConfig;
public appInsights: ApplicationInsights;
public core: IAppInsightsCore;
public context: Common_ITelemetryContext;
constructor(snippet: Snippet) {
// NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown()
let dependencies: DependenciesPlugin;
let properties: PropertiesPlugin;
let _sender: Sender;
let _snippetVersion: string;
let _evtNamespace: string;
let _houseKeepingNamespace: string | string[];
let _core: IAppInsightsCore;
dynamicProto(Initialization, this, (_self) => {
_initDefaults();
// initialize the queue and config in case they are undefined
_snippetVersion = "" + (snippet.sv || snippet.version || "");
snippet.queue = snippet.queue || [];
snippet.version = snippet.version || 2.0; // Default to new version
let config: IConfiguration & IConfig = snippet.config || ({} as any);
if (config.connectionString) {
const cs = parseConnectionString(config.connectionString);
const ingest = cs.ingestionendpoint;
config.endpointUrl = ingest ? `${ingest}/v2/track` : config.endpointUrl; // only add /v2/track when from connectionstring
config.instrumentationKey = cs.instrumentationkey || config.instrumentationKey;
}
_self.appInsights = new AnalyticsPlugin();
properties = new PropertiesPlugin();
dependencies = new DependenciesPlugin();
_sender = new Sender();
_core = new AppInsightsCore();
_self.core = _core;
let isErrMessageDisabled = isNullOrUndefined(config.disableIkeyDeprecationMessage)? true:config.disableIkeyDeprecationMessage;
if (!config.connectionString && !isErrMessageDisabled) {
_throwInternal(_core.logger,
eLoggingSeverity.CRITICAL,
_eInternalMessageId.InstrumentationKeyDeprecation,
"Instrumentation key support will end soon, see aka.ms/IkeyMigrate");
}
_self.snippet = snippet;
_self.config = config;
_getSKUDefaults();
_self.flush = (async: boolean = true) => {
doPerf(_core, () => "AISKU.flush", () => {
arrForEach(_core.getTransmissionControls(), channels => {
arrForEach(channels, channel => {
channel.flush(async);
});
});
}, null, async);
};
_self.onunloadFlush = (async: boolean = true) => {
arrForEach(_core.getTransmissionControls(), channels => {
arrForEach(channels, (channel: IChannelControls & Sender) => {
if (channel.onunloadFlush) {
channel.onunloadFlush();
} else {
channel.flush(async);
}
})
})
};
_self.loadAppInsights = (legacyMode: boolean = false, logger?: IDiagnosticLogger, notificationManager?: INotificationManager): IApplicationInsights => {
function _updateSnippetProperties(snippet: Snippet) {
if (snippet) {
let snippetVer = "";
if (!isNullOrUndefined(_snippetVersion)) {
snippetVer += _snippetVersion;
}
if (legacyMode) {
snippetVer += ".lg";
}
if (_self.context && _self.context.internal) {
_self.context.internal.snippetVer = snippetVer || "-";
}
// apply updated properties to the global instance (snippet)
objForEachKey(_self, (field, value) => {
if (isString(field) &&
!isFunction(value) &&
field && field[0] !== "_" && // Don't copy "internal" values
arrIndexOf(_ignoreUpdateSnippetProperties, field) === -1) {
snippet[field as string] = value;
}
});
}
}
// dont allow additional channels/other extensions for legacy mode; legacy mode is only to allow users to switch with no code changes!
if (legacyMode && _self.config.extensions && _self.config.extensions.length > 0) {
throwError("Extensions not allowed in legacy mode");
}
doPerf(_self.core, () => "AISKU.loadAppInsights", () => {
const extensions = [];
extensions.push(_sender);
extensions.push(properties);
extensions.push(dependencies);
extensions.push(_self.appInsights);
// initialize core
_core.initialize(_self.config, extensions, logger, notificationManager);
_self.context = properties.context;
if (_internalSdkSrc && _self.context) {
_self.context.internal.sdkSrc = _internalSdkSrc;
}
_updateSnippetProperties(_self.snippet);
// Empty queue of all api calls logged prior to sdk download
_self.emptyQueue();
_self.pollInternalLogs();
_self.addHousekeepingBeforeUnload(this);
});
return _self;
};
_self.updateSnippetDefinitions = (snippet: Snippet) => {
// apply full appInsights to the global instance
// Note: This must be called before loadAppInsights is called
proxyAssign(snippet, _self, (name: string) => {
// Not excluding names prefixed with "_" as we need to proxy some functions like _onError
return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;
});
};
_self.emptyQueue = () => {
// call functions that were queued before the main script was loaded
try {
if (isArray(_self.snippet.queue)) {
// note: do not check length in the for-loop conditional in case something goes wrong and the stub methods are not overridden.
const length = _self.snippet.queue.length;
for (let i = 0; i < length; i++) {
const call = _self.snippet.queue[i];
call();
}
_self.snippet.queue = undefined;
delete _self.snippet.queue;
}
} catch (exception) {
const properties: any = {};
if (exception && isFunction(exception.toString)) {
properties.exception = exception.toString();
}
// need from core
// Microsoft.ApplicationInsights._InternalLogging.throwInternal(
// eLoggingSeverity.WARNING,
// _eInternalMessageId.FailedToSendQueuedTelemetry,
// "Failed to send queued telemetry",
// properties);
}
};
_self.addHousekeepingBeforeUnload = (appInsightsInstance: IApplicationInsights): void => {
// Add callback to push events when the user navigates away
if (hasWindow() || hasDocument()) {
const performHousekeeping = () => {
// Adds the ability to flush all data before the page unloads.
// Note: This approach tries to push a sync request with all the pending events onbeforeunload.
// Firefox does not respect this.Other browsers DO push out the call with < 100% hit rate.
// Telemetry here will help us analyze how effective this approach is.
// Another approach would be to make this call sync with a acceptable timeout to reduce the
// impact on user experience.
// appInsightsInstance.context._sender.triggerSend();
appInsightsInstance.onunloadFlush(false);
// Back up the current session to local storage
// This lets us close expired sessions after the cookies themselves expire
if (isFunction(this.core.getPlugin)) {
let loadedPlugin = this.core.getPlugin(PropertiesPluginIdentifier);
if (loadedPlugin) {
let propertiesPlugin: any = loadedPlugin.plugin;
if (propertiesPlugin && propertiesPlugin.context && propertiesPlugin.context._sessionManager) {
propertiesPlugin.context._sessionManager.backup();
}
}
}
};
let added = false;
let excludePageUnloadEvents = appInsightsInstance.appInsights.config.disablePageUnloadEvents;
if (!_houseKeepingNamespace) {
_houseKeepingNamespace = mergeEvtNamespace(_evtNamespace, _core.evtNamespace && _core.evtNamespace());
}
if (!appInsightsInstance.appInsights.config.disableFlushOnBeforeUnload) {
// Hook the unload event for the document, window and body to ensure that the client events are flushed to the server
// As just hooking the window does not always fire (on chrome) for page navigation's.
if (addPageUnloadEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace)) {
added = true;
}
// We also need to hook the pagehide and visibilitychange events as not all versions of Safari support load/unload events.
if (addPageHideEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace)) {
added = true;
}
// A reactNative app may not have a window and therefore the beforeunload/pagehide events -- so don't
// log the failure in this case
if (!added && !isReactNative()) {
_throwInternal(appInsightsInstance.appInsights.core.logger,
eLoggingSeverity.CRITICAL,
_eInternalMessageId.FailedToAddHandlerForOnBeforeUnload,
"Could not add handler for beforeunload and pagehide");
}
}
if (!added && !appInsightsInstance.appInsights.config.disableFlushOnUnload) {
// If we didn't add the normal set then attempt to add the pagehide and visibilitychange only
addPageHideEventListener(performHousekeeping, excludePageUnloadEvents, _houseKeepingNamespace);
}
}
};
_self.getSender = (): Sender => {
return _sender;
};
_self.unload = (isAsync?: boolean, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void => {
_self.onunloadFlush(isAsync);
// Remove any registered event handlers
if (_houseKeepingNamespace) {
removePageUnloadEventListener(null, _houseKeepingNamespace);
removePageHideEventListener(null, _houseKeepingNamespace);
}
_core.unload && _core.unload(isAsync, unloadComplete, cbTimeout);
};
proxyFunctions(_self, _self.appInsights, [
"getCookieMgr",
"trackEvent",
"trackPageView",
"trackPageViewPerformance",
"trackException",
"_onerror",
"trackTrace",
"trackMetric",
"startTrackPage",
"stopTrackPage",
"startTrackEvent",
"stopTrackEvent"
]);
proxyFunctions(_self, _getCurrentDependencies, [
"trackDependencyData",
"addDependencyListener"
]);
proxyFunctions(_self, _core, [
"addTelemetryInitializer",
"pollInternalLogs",
"stopPollingInternalLogs",
"getPlugin",
"addPlugin",
"evtNamespace",
"addUnloadCb",
"getTraceCtx"
]);
proxyFunctions(_self, () => {
let context = properties.context;
return context ? context.user : null;
}, [
"setAuthenticatedUserContext",
"clearAuthenticatedUserContext"
]);
function _getSKUDefaults() {
_self.config.diagnosticLogInterval =
_self.config.diagnosticLogInterval && _self.config.diagnosticLogInterval > 0 ? _self.config.diagnosticLogInterval : 10000;
}
// Using a function to support the dynamic adding / removal of plugins, so this will always return the current value
function _getCurrentDependencies() {
return dependencies;
}
function _initDefaults() {
_evtNamespace = createUniqueNamespace("AISKU");
_houseKeepingNamespace = null;
dependencies = null;
properties = null;
_sender = null;
_snippetVersion = null;
}
});
}
// Analytics Plugin
/**
* Get the current cookie manager for this instance
*/
public getCookieMgr(): ICookieMgr {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Log a user action or other occurrence.
* @param {IEventTelemetry} event
* @param {ICustomProperties} [customProperties]
* @memberof Initialization
*/
public trackEvent(event: IEventTelemetry, customProperties?: ICustomProperties) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Logs that a page, or similar container was displayed to the user.
* @param {IPageViewTelemetry} pageView
* @memberof Initialization
*/
public trackPageView(pageView?: IPageViewTelemetry) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log a bag of performance information via the customProperties field.
* @param {IPageViewPerformanceTelemetry} pageViewPerformance
* @memberof Initialization
*/
public trackPageViewPerformance(pageViewPerformance: IPageViewPerformanceTelemetry): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log an exception that you have caught.
* @param {IExceptionTelemetry} exception
* @param {{[key: string]: any}} customProperties Additional data used to filter pages and metrics in the portal. Defaults to empty.
* @memberof Initialization
*/
public trackException(exception: IExceptionTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Manually send uncaught exception telemetry. This method is automatically triggered
* on a window.onerror event.
* @param {IAutoExceptionTelemetry} exception
* @memberof Initialization
*/
public _onerror(exception: IAutoExceptionTelemetry): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log a diagnostic scenario such entering or leaving a function.
* @param {ITraceTelemetry} trace
* @param {ICustomProperties} [customProperties]
* @memberof Initialization
*/
public trackTrace(trace: ITraceTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log a numeric value that is not associated with a specific event. Typically used
* to send regular reports of performance indicators.
*
* To send a single measurement, just use the `name` and `average` fields
* of {@link IMetricTelemetry}.
*
* If you take measurements frequently, you can reduce the telemetry bandwidth by
* aggregating multiple measurements and sending the resulting average and modifying
* the `sampleCount` field of {@link IMetricTelemetry}.
* @param {IMetricTelemetry} metric input object argument. Only `name` and `average` are mandatory.
* @param {ICustomProperties} [customProperties]
* @memberof Initialization
*/
public trackMetric(metric: IMetricTelemetry, customProperties?: ICustomProperties): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops,
* but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view
* and send the event.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
public startTrackPage(name?: string): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
* The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
public stopTrackPage(name?: string, url?: string, customProperties?: { [key: string]: any; }, measurements?: { [key: string]: number; }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public startTrackEvent(name?: string): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Log an extended event that you started timing with `startTrackEvent`.
* @param name The string you used to identify this event in `startTrackEvent`.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
public stopTrackEvent(name: string, properties?: { [key: string]: string; }, measurements?: { [key: string]: number; }) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void): ITelemetryInitializerHandler | void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// Properties Plugin
/**
* Set the authenticated user id and the account id. Used for identifying a specific signed-in user. Parameters must not contain whitespace or ,;=|
*
* The method will only set the `authenticatedUserId` and `accountId` in the current page view. To set them for the whole session, you should set `storeInCookie = true`
* @param {string} authenticatedUserId
* @param {string} [accountId]
* @param {boolean} [storeInCookie=false]
*/
public setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie = false): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Clears the authenticated user id and account id. The associated cookie is cleared, if present.
*/
public clearAuthenticatedUserContext(): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// Dependencies Plugin
/**
* Log a dependency call (e.g. ajax)
* @param {IDependencyTelemetry} dependency
* @memberof Initialization
*/
public trackDependencyData(dependency: IDependencyTelemetry): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// Misc
/**
* Manually trigger an immediate send of all telemetry still in the buffer.
* @param {boolean} [async=true]
* @memberof Initialization
*/
public flush(async: boolean = true) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Manually trigger an immediate send of all telemetry still in the buffer using beacon Sender.
* Fall back to xhr sender if beacon is not supported.
* @param {boolean} [async=true]
* @memberof Initialization
*/
public onunloadFlush(async: boolean = true) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Initialize this instance of ApplicationInsights
* @returns {IApplicationInsights}
* @memberof Initialization
*/
public loadAppInsights(legacyMode: boolean = false, logger?: IDiagnosticLogger, notificationManager?: INotificationManager): IApplicationInsights {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Overwrite the lazy loaded fields of global window snippet to contain the
* actual initialized API methods
* @param {Snippet} snippet
* @memberof Initialization
*/
public updateSnippetDefinitions(snippet: Snippet) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Call any functions that were queued before the main script was loaded
* @memberof Initialization
*/
public emptyQueue() {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public pollInternalLogs(): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public stopPollingInternalLogs(): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public addHousekeepingBeforeUnload(appInsightsInstance: IApplicationInsights): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public getSender(): Sender {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered
* to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous
* unload call return `true` stating that all plugins reported that they also unloaded, the recommended
* approach is to create a new instance and initialize that instance.
* This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable
* to successfully remove any global references or they may just be completing the unload process asynchronously.
*/
public unload(isAsync?: boolean, unloadComplete?: () => void): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T> {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public addPlugin<T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting: boolean, doAsync: boolean, addCb?: (added?: boolean) => void): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Returns the unique event namespace that should be used
*/
public evtNamespace(): string {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Add an unload handler that will be called when the SDK is being unloaded
* @param handler - the handler
*/
public addUnloadCb(handler: UnloadHandler): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Add an ajax listener which is called just prior to the request being sent and before the correlation headers are added, to allow you
* to access the headers and modify the values used to generate the distributed tracing correlation headers. (added in v2.8.4)
* @param dependencyListener - The Telemetry Initializer function
* @returns - A IDependencyListenerHandler to enable the initializer to be removed
*/
public addDependencyListener(dependencyListener: DependencyListenerFunction): IDependencyListenerHandler {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
/**
* Gets the current distributed trace context for this instance if available
*/
public getTraceCtx(): IDistributedTraceContext | null | undefined {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
}
// tslint:disable-next-line
(function () {
let sdkSrc = null;
let isModule = false;
let cdns: string[] = [
"://js.monitor.azure.com/",
"://az416426.vo.msecnd.net/"
];
try {
// Try and determine whether the sdk is being loaded from the CDN
// currentScript is only valid during initial processing
let scrpt = (document || {} as any).currentScript;
if (scrpt) {
sdkSrc = scrpt.src;
// } else {
// // We need to update to at least typescript 2.9 for this to work :-(
// // Leaving as a stub for now so after we upgrade this breadcrumb is available
// let meta = import.meta;
// sdkSrc = (meta || {}).url;
// isModule = true;
}
} catch (e) {
// eslint-disable-next-line no-empty
}
if (sdkSrc) {
try {
let url = sdkSrc.toLowerCase();
if (url) {
let src = "";
for (let idx = 0; idx < cdns.length; idx++) {
if (url.indexOf(cdns[idx]) !== -1) {
src = "cdn" + (idx + 1);
if (url.indexOf("/scripts/") === -1) {
if (url.indexOf("/next/") !== -1) {
src += "-next";
} else if (url.indexOf("/beta/") !== -1) {
src += "-beta";
}
}
_internalSdkSrc = src + (isModule ? ".mod" : "");
break;
}
}
}
} catch (e) {
// eslint-disable-next-line no-empty
}
}
})(); | the_stack |
import { Ace, require as acequire } from 'ace-builds';
import 'ace-builds/src-noconflict/ext-language_tools';
import 'ace-builds/src-noconflict/ext-searchbox';
import 'js-slang/dist/editors/ace/theme/source';
import { Variant } from 'js-slang/dist/types';
import * as React from 'react';
import AceEditor, { IAceEditorProps, IEditorProps } from 'react-ace';
import * as AceBuilds from 'ace-builds';
import { HotKeys } from 'react-hotkeys';
import { useMergedRef } from '../utils/Hooks';
import { keyBindings, KeyFunction } from './EditorHotkeys';
import { AceMouseEvent, HighlightedLines, Position } from './EditorTypes';
// =============== Hooks ===============
// TODO: Should further refactor into EditorBase + different variants.
// Ideally, hooks should be specified by the parent component instead.
import useHighlighting from './UseHighlighting';
import useNavigation from './UseNavigation';
import useRefactor from './UseRefactor';
import useShareAce from './UseShareAce';
import useTypeInference from './UseTypeInference';
import { getModeString, selectMode } from '../utils/AceHelper';
export type EditorKeyBindingHandlers = { [name in KeyFunction]?: () => void };
export type EditorHook = (
inProps: Readonly<EditorProps>,
outProps: IAceEditorProps,
keyBindings: EditorKeyBindingHandlers,
reactAceRef: React.MutableRefObject<AceEditor | null>
) => void;
/**
* @property editorValue - The string content of the react-ace editor
* @property handleEditorChange - A callback function
* for the react-ace editor's `onChange`
* @property handleEvalEditor - A callback function for evaluation
* of the editor's content, using `slang`
*/
export type EditorProps = DispatchProps & StateProps & OnEvent;
type DispatchProps = {
handleDeclarationNavigate: (cursorPosition: Position) => void;
handleEditorEval: () => void;
handleEditorValueChange: (newCode: string) => void;
handleReplValueChange?: (newCode: string) => void;
handleReplEval?: () => void;
handleEditorUpdateBreakpoints: (breakpoints: string[]) => void;
handlePromptAutocomplete: (row: number, col: number, callback: any) => void;
handleSendReplInputToOutput?: (newOutput: string) => void;
handleSetSharedbConnected?: (connected: boolean) => void;
handleUpdateHasUnsavedChanges?: (hasUnsavedChanges: boolean) => void;
};
type StateProps = {
breakpoints: string[];
editorSessionId: string;
editorValue: string;
highlightedLines: HighlightedLines[];
isEditorAutorun: boolean;
newCursorPosition?: Position;
sourceChapter?: number;
externalLibraryName?: string;
sourceVariant?: Variant;
hooks?: EditorHook[];
};
type OnEvent = {
onSelectionChange?: (value: any, event?: any) => void;
onCursorChange?: (value: any, event?: any) => void;
onInput?: (event?: any) => void;
onLoad?: (editor: Ace.Editor) => void;
onValidate?: (annotations: Ace.Annotation[]) => void;
onBeforeLoad?: (ace: typeof AceBuilds) => void;
onChange?: (value: string, event?: any) => void;
onSelection?: (selectedText: string, event?: any) => void;
onCopy?: (value: string) => void;
onPaste?: (value: string) => void;
onFocus?: (event: any, editor?: Ace.Editor) => void;
onBlur?: (event: any, editor?: Ace.Editor) => void;
onScroll?: (editor: IEditorProps) => void;
};
const EventT: Array<keyof OnEvent> = [
'onSelectionChange',
'onCursorChange',
'onInput',
'onLoad',
'onValidate',
'onBeforeLoad',
'onChange',
'onSelection',
'onCopy',
'onPaste',
'onFocus',
'onBlur',
'onScroll'
];
const getMarkers = (
highlightedLines: StateProps['highlightedLines']
): IAceEditorProps['markers'] => {
return highlightedLines.map(lineNums => ({
startRow: lineNums[0],
startCol: 0,
endRow: lineNums[1],
endCol: 1,
className: 'myMarker',
type: 'fullLine'
}));
};
const makeHandleGutterClick =
(handleEditorUpdateBreakpoints: DispatchProps['handleEditorUpdateBreakpoints']) =>
(e: AceMouseEvent) => {
const target = e.domEvent.target! as HTMLDivElement;
if (
target.className.indexOf('ace_gutter-cell') === -1 ||
!e.editor.isFocused() ||
e.clientX > 35 + target.getBoundingClientRect().left
) {
return;
}
// Breakpoint related.
const row = e.getDocumentPosition().row;
const content = e.editor.session.getLine(row);
const breakpoints = e.editor.session.getBreakpoints();
if (
breakpoints[row] === undefined &&
content.length !== 0 &&
!content.includes('//') &&
!content.includes('debugger;')
) {
e.editor.session.setBreakpoint(row, undefined!);
} else {
e.editor.session.clearBreakpoint(row);
}
e.stop();
handleEditorUpdateBreakpoints(e.editor.session.getBreakpoints());
};
// Note: This is untestable/unused because JS-hint has been removed.
const makeHandleAnnotationChange = (session: Ace.EditSession) => () => {
const annotations = session.getAnnotations();
let count = 0;
for (const anno of annotations) {
if (anno.type === 'info') {
anno.type = 'error';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // Probably some undocumented type
anno.className = 'ace_error';
count++;
}
}
if (count !== 0) {
session.setAnnotations(annotations);
}
};
const makeCompleter = (handlePromptAutocomplete: DispatchProps['handlePromptAutocomplete']) => ({
getCompletions: (
editor: Ace.Editor,
session: Ace.EditSession,
pos: Ace.Point,
prefix: string,
callback: () => void
) => {
// Don't prompt if prefix starts with number
if (prefix && /\d/.test(prefix.charAt(0))) {
callback();
return;
}
// Cursor col is insertion location i.e. last char col + 1
handlePromptAutocomplete(pos.row + 1, pos.column, callback);
}
});
const moveCursor = (editor: AceEditor['editor'], position: Position) => {
editor.selection.clearSelection();
editor.moveCursorToPosition(position);
editor.renderer.showCursor();
editor.renderer.scrollCursorIntoView(position, 0.5);
};
/* Override handler, so does not trigger when focus is in editor */
const handlers = {
goGreen: () => {}
};
const EditorBase = React.memo(
React.forwardRef<AceEditor, EditorProps>(function EditorBase(props, forwardedRef) {
const reactAceRef: React.MutableRefObject<AceEditor | null> = React.useRef(null);
// Refs for things that technically shouldn't change... but just in case.
const handleEditorUpdateBreakpointsRef = React.useRef(props.handleEditorUpdateBreakpoints);
const handlePromptAutocompleteRef = React.useRef(props.handlePromptAutocomplete);
React.useEffect(() => {
handleEditorUpdateBreakpointsRef.current = props.handleEditorUpdateBreakpoints;
handlePromptAutocompleteRef.current = props.handlePromptAutocomplete;
}, [props.handleEditorUpdateBreakpoints, props.handlePromptAutocomplete]);
// Handles input into AceEditor causing app to scroll to the top on iOS Safari
React.useEffect(() => {
const isIOS = /iPhone|iPad|iPod/.test(navigator.userAgent);
if (isIOS) {
document.body.style.position = 'fixed';
document.body.style.width = '100%';
}
return () => {
document.body.style.position = '';
document.body.style.width = '';
};
}, []);
const [sourceChapter, sourceVariant, externalLibraryName] = [
props.sourceChapter || 1,
props.sourceVariant || 'default',
props.externalLibraryName || 'NONE'
];
// this function defines the Ace language and highlighting mode for the
// given combination of chapter, variant and external library. it CANNOT be
// put in useEffect as it MUST be called before the mode is set on the Ace
// editor, and use(Layout)Effect runs after that happens.
//
// this used to be in useMemo, but selectMode now checks if the mode is
// already defined and doesn't do it, so it is now OK to keep calling this
// unconditionally.
selectMode(sourceChapter, sourceVariant, externalLibraryName);
React.useLayoutEffect(() => {
if (!reactAceRef.current) {
return;
}
const editor = reactAceRef.current.editor;
const session = editor.getSession();
// NOTE: Everything in this function is designed to run exactly ONCE per instance of react-ace.
// The () => ref.current() are designed to use the latest instance only.
// NOTE: the two `any`s below are because the Ace editor typedefs are
// hopelessly incomplete
editor.on(
'gutterclick' as any,
makeHandleGutterClick((...args) => handleEditorUpdateBreakpointsRef.current(...args)) as any
);
// Change all info annotations to error annotations
session.on('changeAnnotation' as any, makeHandleAnnotationChange(session));
// Start autocompletion
acequire('ace/ext/language_tools').setCompleters([
makeCompleter((...args) => handlePromptAutocompleteRef.current(...args))
]);
// This should run exactly once.
}, []);
React.useLayoutEffect(() => {
if (!reactAceRef.current) {
return;
}
const newCursorPosition = props.newCursorPosition;
if (newCursorPosition) {
moveCursor(reactAceRef.current.editor, newCursorPosition);
}
}, [props.newCursorPosition]);
const {
handleUpdateHasUnsavedChanges,
handleEditorValueChange,
isEditorAutorun,
handleEditorEval
} = props;
const keyHandlers: EditorKeyBindingHandlers = {
evaluate: handleEditorEval
};
const aceEditorProps: IAceEditorProps = {
className: 'react-ace',
editorProps: {
$blockScrolling: Infinity
},
markers: React.useMemo(() => getMarkers(props.highlightedLines), [props.highlightedLines]),
fontSize: 17,
height: '100%',
highlightActiveLine: false,
mode: getModeString(sourceChapter, sourceVariant, externalLibraryName),
theme: 'source',
value: props.editorValue,
width: '100%',
setOptions: {
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
fontFamily: "'Inconsolata', 'Consolas', monospace"
}
};
// Hooks must not change after an editor is instantiated, so to prevent that
// we store the original value and always use that only
const [hooks] = React.useState(props.hooks);
if (hooks) {
// Note: the following is extremely non-standard use of hooks
// DO NOT refactor this into any form where the hook is called from a lambda
for (const hook of hooks) {
hook(props, aceEditorProps, keyHandlers, reactAceRef);
}
}
const hooksOnChange = aceEditorProps.onChange;
aceEditorProps.onChange = React.useCallback(
(newCode: string, delta: Ace.Delta) => {
if (!reactAceRef.current) {
return;
}
handleEditorValueChange(newCode);
if (handleUpdateHasUnsavedChanges) {
handleUpdateHasUnsavedChanges(true);
}
const annotations = reactAceRef.current.editor.getSession().getAnnotations();
if (isEditorAutorun && annotations.length === 0) {
handleEditorEval();
}
hooksOnChange && hooksOnChange(newCode, delta);
},
[
handleEditorValueChange,
handleUpdateHasUnsavedChanges,
isEditorAutorun,
hooksOnChange,
handleEditorEval
]
);
aceEditorProps.commands = Object.entries(keyHandlers)
.filter(([_, exec]) => exec)
.map(([name, exec]) => ({ name, bindKey: keyBindings[name], exec: exec! }));
// Merge in .onEvent ace editor props
// This prevents user errors such as
// TRYING TO ADD AN ONCHANGE PROP WHICH KILLS THE ABOVE ONCHANGE.
// **triggered**
EventT.forEach(eventT => {
const propFn = props[eventT];
if (propFn) {
/* eslint-disable */
const currFn = aceEditorProps[eventT];
if (!currFn) {
// Typescript isn't smart enough to know that the types of both LHS/RHS are the same.
// @ts-ignore
aceEditorProps[eventT] = propFn;
} else {
aceEditorProps[eventT] = function (...args: any[]) {
// Impossible to define a function which takes in the arbitrary number of correct arguments...
// @ts-ignore
currFn(...args);
// @ts-ignore
propFn(...args);
};
}
/* eslint-enable */
}
});
return (
<HotKeys className="Editor" handlers={handlers}>
<div className="row editor-react-ace">
<AceEditor {...aceEditorProps} ref={useMergedRef(reactAceRef, forwardedRef)} />
</div>
</HotKeys>
);
})
);
// don't create a new list every render.
const hooks = [useHighlighting, useNavigation, useTypeInference, useShareAce, useRefactor];
const Editor = React.forwardRef<AceEditor, EditorProps>((props, ref) => (
<EditorBase {...props} hooks={hooks} ref={ref} />
));
export default Editor; | the_stack |
export const rpcContractResponse = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{ prim: 'option', args: [{ prim: 'key_hash' }], annots: ['%key'] },
{ prim: 'sapling_transaction', args: [{ int: '8' }], annots: ['%transaction'] }
]
}
]
}
]
},
{ prim: 'storage', args: [{ prim: 'sapling_state', args: [{ int: '8' }] }] },
{
prim: 'code',
args: [
[
{ prim: 'DUP' },
{ prim: 'CDR' },
{ prim: 'SWAP' },
{ prim: 'CAR' },
{ prim: 'DUP' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'SWAP' },
{
prim: 'ITER',
args: [
[
{ prim: 'DIG', args: [{ int: '3' }] },
{ prim: 'SWAP' },
{ prim: 'DUP' },
{ prim: 'DUG', args: [{ int: '2' }] },
{ prim: 'CDR' },
{ prim: 'SAPLING_VERIFY_UPDATE' },
{
prim: 'IF_NONE',
args: [
[
{ prim: 'PUSH', args: [{ prim: 'int' }, { int: '10' }] },
{ prim: 'FAILWITH' }
],
[]
]
},
{ prim: 'DUP' },
{ prim: 'CDR' },
{ prim: 'DUG', args: [{ int: '4' }] },
{ prim: 'DUP' },
{ prim: 'CAR' },
{ prim: 'DUP' },
{ prim: 'ABS' },
{ prim: 'PUSH', args: [{ prim: 'mutez' }, { int: '1' }] },
{ prim: 'MUL' },
{ prim: 'PUSH', args: [{ prim: 'int' }, { int: '0' }] },
{ prim: 'DIG', args: [{ int: '2' }] },
{ prim: 'DUP' },
{ prim: 'DUG', args: [{ int: '3' }] },
{ prim: 'COMPARE' },
{ prim: 'GT' },
{
prim: 'IF',
args: [
[
{ prim: 'SWAP' },
{ prim: 'DROP' },
{ prim: 'SWAP' },
{ prim: 'DROP' },
{ prim: 'DUG', args: [{ int: '2' }] },
{ prim: 'CAR' },
{
prim: 'IF_NONE',
args: [
[
{ prim: 'PUSH', args: [{ prim: 'int' }, { int: '15' }] },
{ prim: 'FAILWITH' }
],
[]
]
},
{ prim: 'IMPLICIT_ACCOUNT' },
{ prim: 'DIG', args: [{ int: '2' }] },
{ prim: 'UNIT' },
{ prim: 'TRANSFER_TOKENS' },
{ prim: 'CONS' }
],
[
{ prim: 'DIG', args: [{ int: '2' }] },
{ prim: 'DROP' },
{ prim: 'DIG', args: [{ int: '2' }] },
{ prim: 'CAR' },
{
prim: 'IF_NONE',
args: [
[{ prim: 'SWAP' }, { prim: 'DROP' }],
[
{
prim: 'PUSH',
args: [
{ prim: 'string' },
{
string:
'WrongCondition: ~ operation.key.is_some()'
}
]
},
{ prim: 'FAILWITH' }
]
]
},
{ prim: 'AMOUNT' },
{ prim: 'COMPARE' },
{ prim: 'EQ' },
{
prim: 'IF',
args: [
[],
[
{
prim: 'PUSH',
args: [
{ prim: 'string' },
{
string:
'WrongCondition: sp.amount == amount_tez.value'
}
]
},
{ prim: 'FAILWITH' }
]
]
}
]
]
}
]
]
},
{ prim: 'SWAP' },
{ prim: 'DROP' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'SWAP' },
{ prim: 'ITER', args: [[{ prim: 'CONS' }]] },
{ prim: 'PAIR' }
]
]
}
],
storage: { int: '14' }
}
};
export const rpcContractResponse2 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{
prim: 'sapling_transaction',
args: [{ int: '8' }]
},
{ prim: 'option', args: [{ prim: 'key_hash' }], annots: ['%key'] }
]
}
]
},
{
prim: 'storage',
args: [
{
prim: 'pair',
args: [
{ prim: 'mutez', annots: ['%balance'] },
{ prim: 'sapling_state', args: [{ int: '8' }], annots: ['%ledger1'] },
{ prim: 'sapling_state', args: [{ int: '8' }], annots: ['%ledger2'] }
]
}
]
},
{
prim: 'code',
args: [[{ prim: 'DUP' }]]
}
],
storage: { prim: 'Pair', args: [{ int: '0' }, { int: '17' }, { int: '18' }] }
}
};
// KT1NQh57yhVyT9cKhvjjaSmZ9YHZgwkAhJsB
export const rpcContractResponse3 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'list',
args: [
{
prim: 'pair',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'option', args: [{ prim: 'key_hash' }] }
]
}
]
}
]
},
{ prim: 'storage', args: [{ prim: 'sapling_state', args: [{ int: '8' }] }] },
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'SWAP' },
{ prim: 'DIP', args: [[{ prim: 'SWAP' }]] },
{ prim: 'AMOUNT' },
{ prim: 'SWAP' },
{ prim: 'DIP', args: [[{ prim: 'SWAP' }]] },
{
prim: 'ITER',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'DIP', args: [[{ prim: 'SWAP' }]] },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DUP' },
{
prim: 'DIP',
args: [
[
{ prim: 'ABS' },
{ prim: 'PUSH', args: [{ prim: 'mutez' }, { int: '1' }] },
{ prim: 'MUL' }
]
]
},
[
{ prim: 'GT' },
{
prim: 'IF',
args: [
[
{
prim: 'DIP',
args: [
{ int: '2' },
[
[
{
prim: 'IF_NONE',
args: [
[
[
{ prim: 'UNIT' },
{ prim: 'FAILWITH' }
]
],
[]
]
}
],
{ prim: 'IMPLICIT_ACCOUNT' }
]
]
},
{ prim: 'SWAP' },
{
prim: 'DIP',
args: [
[
{ prim: 'UNIT' },
{ prim: 'TRANSFER_TOKENS' },
{ prim: 'SWAP' },
{ prim: 'DIP', args: [[{ prim: 'CONS' }]] }
]
]
}
],
[
{ prim: 'DIP', args: [{ int: '2' }, [{ prim: 'SWAP' }]] },
{ prim: 'DIP', args: [[{ prim: 'SWAP' }]] },
{ prim: 'SWAP' },
{ prim: 'SUB' },
{
prim: 'DIP',
args: [
{ int: '2' },
[
[
{
prim: 'IF_NONE',
args: [
[],
[
[
{ prim: 'UNIT' },
{ prim: 'FAILWITH' }
]
]
]
}
]
]
]
},
{ prim: 'SWAP' }
]
]
}
]
]
]
},
{
prim: 'DIP',
args: [
[
{ prim: 'PUSH', args: [{ prim: 'mutez' }, { int: '0' }] },
[
[{ prim: 'COMPARE' }, { prim: 'EQ' }],
{ prim: 'IF', args: [[], [[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]]] }
]
]
]
},
{ prim: 'SWAP' },
{ prim: 'PAIR' }
]
]
}
],
storage: { int: '53' }
}
};
// KT1P7WdaJCnyyz83oBrHrFUPsxeVawGy4TSB
export const rpcContractResponse4 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{ prim: 'bool' },
{ prim: 'sapling_transaction', args: [{ int: '8' }], annots: [':left'] },
{ prim: 'sapling_transaction', args: [{ int: '8' }], annots: [':right'] }
]
}
]
},
{
prim: 'storage',
args: [
{
prim: 'pair',
args: [
{ prim: 'sapling_state', args: [{ int: '8' }], annots: [':left'] },
{ prim: 'sapling_state', args: [{ int: '8' }], annots: [':right'] }
]
}
]
},
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'UNPAIR' },
{ prim: 'DIP', args: [[{ prim: 'UNPAIR' }]] },
{ prim: 'DIP', args: [{ int: '3' }, [{ prim: 'UNPAIR' }]] },
{ prim: 'DIP', args: [{ int: '2' }, [{ prim: 'SWAP' }]] },
{
prim: 'IF',
args: [
[
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DROP' },
{
prim: 'DIP',
args: [
[
{ prim: 'DIP', args: [[{ prim: 'DUP' }]] },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DROP' },
{ prim: 'DROP' }
]
]
}
],
[
{ prim: 'DIP', args: [[{ prim: 'DUP' }]] },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DROP' },
{ prim: 'DROP' },
{
prim: 'DIP',
args: [
[
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DROP' }
]
]
}
]
]
},
{ prim: 'PAIR' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'PAIR' }
]
]
}
],
storage: { prim: 'Pair', args: [{ int: '54' }, { int: '55' }] }
}
};
// KT1R11DJKeYmt7Wzu21fQPeYdByyPWLbDqyF
export const rpcContractResponse5 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [{ prim: 'list', args: [{ prim: 'sapling_transaction', args: [{ int: '8' }] }] }]
},
{ prim: 'storage', args: [{ prim: 'unit' }] },
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'SAPLING_EMPTY_STATE', args: [{ int: '8' }] },
{ prim: 'SWAP' },
{
prim: 'ITER',
args: [
[
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'UNPAIR' },
{ prim: 'DROP' }
]
]
},
{ prim: 'DROP' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'PAIR' }
]
]
}
],
storage: { prim: 'Unit' }
}
};
// KT1GZBKBSaDDEkEH4xreMJH3oSfjsqRn8MTL
export const rpcContractResponse6 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{
prim: 'contract',
args: [
{
prim: 'or',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'sapling_state', args: [{ int: '8' }] }
]
}
]
},
{ prim: 'sapling_transaction', args: [{ int: '8' }] }
]
}
]
},
{ prim: 'storage', args: [{ prim: 'unit' }] },
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'UNPAIR' },
{ prim: 'SWAP' },
{ prim: 'SAPLING_EMPTY_STATE', args: [{ int: '8' }] },
{ prim: 'SWAP' },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[{ prim: 'IF_NONE', args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []] }],
{ prim: 'UNPAIR' },
{ prim: 'DROP' },
{ prim: 'PUSH', args: [{ prim: 'mutez' }, { int: '0' }] },
{ prim: 'SWAP' },
{ prim: 'RIGHT', args: [{ prim: 'sapling_transaction', args: [{ int: '8' }] }] },
{ prim: 'TRANSFER_TOKENS' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'SWAP' },
{ prim: 'CONS' },
{ prim: 'PAIR' }
]
]
}
],
storage: { prim: 'Unit' }
}
};
// KT1XpFASuiYhShqteQ4QjSfR21ERq2R3ZfrH
export const rpcContractResponse7 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'or',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'sapling_state', args: [{ int: '8' }] }
]
}
]
},
{
prim: 'storage',
args: [{ prim: 'option', args: [{ prim: 'sapling_transaction', args: [{ int: '8' }] }] }]
},
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{
prim: 'IF_LEFT',
args: [
[{ prim: 'DIP', args: [[{ prim: 'DROP' }]] }, { prim: 'SOME' }],
[
{
prim: 'DIP',
args: [
[
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
]
]
]
},
{ prim: 'SWAP' },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[
{
prim: 'IF_NONE',
args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []]
}
],
{ prim: 'DROP' },
{ prim: 'NONE', args: [{ prim: 'sapling_transaction', args: [{ int: '8' }] }] }
]
]
},
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'PAIR' }
]
]
}
],
storage: { prim: 'None' }
}
};
// KT1KnF4vZMgTRgy9hniwV9pYpPj4b7HEV8fU
export const rpcContractResponse8 = {
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'sapling_state', args: [{ int: '8' }] }
]
}
]
},
{ prim: 'storage', args: [{ prim: 'sapling_state', args: [{ int: '8' }] }] },
{
prim: 'code',
args: [
[
{ prim: 'UNPAIR' },
{ prim: 'UNPAIR' },
{ prim: 'DIP', args: [{ int: '2' }, [{ prim: 'DROP' }]] },
{ prim: 'SAPLING_VERIFY_UPDATE' },
[{ prim: 'IF_NONE', args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []] }],
{ prim: 'UNPAIR' },
{ prim: 'DROP' },
{ prim: 'NIL', args: [{ prim: 'operation' }] },
{ prim: 'PAIR' }
]
]
}
],
storage: { int: '56' }
}
};
export const example9 = {
// To test comb pair forging/unforging
// Not a valid contract
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'sapling_state', args: [{ int: '8' }] },
{ prim: 'int', annots: ['%test'] },
{ prim: 'int', annots: ['%test2'] },
{ prim: 'mutez', annots: ['%test3'] },
{ prim: 'nat', annots: ['%test4'] },
{ prim: 'int', annots: ['%test5'] },
{ prim: 'int', annots: ['%test6'] },
{ prim: 'mutez', annots: ['%test7'] },
{ prim: 'nat', annots: ['%test8'] },
{ prim: 'int', annots: ['%test9'] },
{ prim: 'int', annots: ['%test10'] },
{ prim: 'mutez', annots: ['%test11'] },
{ prim: 'nat', annots: ['%test12'] },
{ prim: 'int', annots: ['%test13'] },
{ prim: 'int', annots: ['%test14'] },
{ prim: 'mutez', annots: ['%test15'] },
{ prim: 'nat', annots: ['%test16'] }
],
annots: ['%combPairAnnot']
}
]
},
{ prim: 'storage', args: [{ prim: 'sapling_state', args: [{ int: '8' }] }] },
{
prim: 'code',
args: [
[ { prim: 'DUP' } ]
]
}
],
storage: { int: '56' }
}
};
export const example10 = {
// To test comb pair forging/unforging
// Not a valid contract
balance: '0',
script: {
code: [
{
prim: 'parameter',
args: [
{
prim: 'pair',
args: [
{ prim: 'sapling_transaction', args: [{ int: '8' }] },
{ prim: 'sapling_state', args: [{ int: '8' }] },
{ prim: 'int' },
{ prim: 'int' },
{ prim: 'mutez' },
{ prim: 'nat' },
{ prim: 'int' },
{ prim: 'int' },
{ prim: 'mutez' },
{ prim: 'nat' },
{ prim: 'int' },
{ prim: 'int' },
{ prim: 'mutez' },
{ prim: 'nat' },
{ prim: 'int'},
{ prim: 'int'},
{ prim: 'mutez' },
{ prim: 'nat'}
]
}
]
},
{ prim: 'storage', args: [{ prim: 'sapling_state', args: [{ int: '8' }] }] },
{
prim: 'code',
args: [
[ { prim: 'DUP' } ]
]
}
],
storage: { int: '56' }
}
}; | the_stack |
import { EditState } from "./toolDefinitions";
export const DRAG_RADIUS = 3;
export function hasPointerEvents(): boolean {
return typeof window != "undefined" && !!(window as any).PointerEvent;
}
export function isTouchEnabled(): boolean {
return typeof window !== "undefined" &&
('ontouchstart' in window // works on most browsers
|| (navigator && navigator.maxTouchPoints > 0)); // works on IE10/11 and Surface);
}
export function isBitmapSupported(): boolean {
return !!window.createImageBitmap;
}
export enum MapTools {
Pan,
Stamp,
Object,
Erase
}
export class Bitmask {
protected mask: Uint8Array;
constructor(public width: number, public height: number) {
this.mask = new Uint8Array(Math.ceil(width * height / 8));
}
set(col: number, row: number) {
const cellIndex = col + this.width * row;
const index = cellIndex >> 3;
const offset = cellIndex & 7;
this.mask[index] |= (1 << offset);
}
get(col: number, row: number) {
const cellIndex = col + this.width * row;
const index = cellIndex >> 3;
const offset = cellIndex & 7;
return (this.mask[index] >> offset) & 1;
}
}
export interface IPointerEvents {
up: string,
down: string[],
move: string,
enter: string,
leave: string
}
export const pointerEvents: IPointerEvents = (() => {
if (hasPointerEvents()) {
return {
up: "pointerup",
down: ["pointerdown"],
move: "pointermove",
enter: "pointerenter",
leave: "pointerleave"
}
} else if (isTouchEnabled()) {
return {
up: "mouseup",
down: ["mousedown", "touchstart"],
move: "touchmove",
enter: "touchenter",
leave: "touchend"
}
} else {
return {
up: "mouseup",
down: ["mousedown"],
move: "mousemove",
enter: "mouseenter",
leave: "mouseleave"
}
}
})();
export interface ClientCoordinates {
clientX: number;
clientY: number;
}
export function clientCoord(ev: PointerEvent | MouseEvent | TouchEvent): ClientCoordinates {
if ((ev as TouchEvent).touches) {
const te = ev as TouchEvent;
if (te.touches.length) {
return te.touches[0];
}
return te.changedTouches[0];
}
return (ev as PointerEvent | MouseEvent);
}
/**
* Similar to fireClickOnEnter, but interactions limited to enter key / ignores
* space bar.
*/
export function fireClickOnlyOnEnter(e: React.KeyboardEvent<HTMLElement>): void {
const charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode === 13 /** enter key **/) {
e.preventDefault();
(e.currentTarget as HTMLElement).click();
}
}
export interface GestureTarget {
onClick(coord: ClientCoordinates, isRightClick?: boolean): void;
onDragStart(coord: ClientCoordinates, isRightClick?: boolean): void;
onDragMove(coord: ClientCoordinates): void;
onDragEnd(coord: ClientCoordinates): void;
}
export class GestureState {
startX: number;
startY: number;
currentX: number;
currentY: number;
isDrag: boolean;
constructor(protected target: GestureTarget, coord: ClientCoordinates, public isRightClick: boolean) {
this.startX = coord.clientX;
this.startY = coord.clientY;
this.currentX = coord.clientX;
this.currentY = coord.clientY;
}
update(coord: ClientCoordinates) {
this.currentX = coord.clientX;
this.currentY = coord.clientY;
if (!this.isDrag && this.distance() > DRAG_RADIUS) {
this.isDrag = true;
this.target.onDragStart(coord, this.isRightClick);
}
else if (this.isDrag) {
this.target.onDragMove(coord);
}
}
end(coord?: ClientCoordinates) {
if (coord) {
this.update(coord);
}
coord = coord || { clientX: this.currentX, clientY: this.currentY };
if (this.isDrag) {
this.target.onDragEnd(coord);
}
else {
this.target.onClick(coord, this.isRightClick);
}
}
distance() {
return Math.sqrt(Math.pow(this.currentX - this.startX, 2) + Math.pow(this.currentY - this.startY, 2));
}
}
export function bindGestureEvents(el: HTMLElement, target: GestureTarget) {
if (hasPointerEvents()) {
bindPointerEvents(el, target);
}
else if (isTouchEnabled()) {
bindTouchEvents(el, target);
}
else {
bindMouseEvents(el, target);
}
}
function bindPointerEvents(el: HTMLElement, target: GestureTarget) {
let state: GestureState;
el.addEventListener("pointerup", ev => {
if (state) {
state.end(clientCoord(ev));
ev.preventDefault();
}
state = undefined;
});
el.addEventListener("pointerdown", ev => {
if (state) state.end();
state = new GestureState(target, clientCoord(ev), isRightClick(ev));
ev.preventDefault();
});
el.addEventListener("pointermove", ev => {
if (state) {
state.update(clientCoord(ev));
ev.preventDefault();
}
});
el.addEventListener("pointerleave", ev => {
if (state) {
state.end(clientCoord(ev));
ev.preventDefault();
}
state = undefined;
});
}
function bindMouseEvents(el: HTMLElement, target: GestureTarget) {
let state: GestureState;
el.addEventListener("mouseup", ev => {
if (state) state.end(clientCoord(ev));
state = undefined;
});
el.addEventListener("mousedown", ev => {
if (state) state.end();
state = new GestureState(target, clientCoord(ev), isRightClick(ev));
});
el.addEventListener("mousemove", ev => {
if (state) state.update(clientCoord(ev));
});
el.addEventListener("mouseleave", ev => {
if (state) state.end(clientCoord(ev));
state = undefined;
});
}
function bindTouchEvents(el: HTMLElement, target: GestureTarget) {
let state: GestureState;
let touchIdentifier: number | undefined;
el.addEventListener("touchend", ev => {
if (state && touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
state.end(touch);
state = undefined;
ev.preventDefault();
}
}
});
el.addEventListener("touchstart", ev => {
if (state) state.end();
touchIdentifier = ev.changedTouches[0].identifier;
state = new GestureState(target, ev.changedTouches[0], isRightClick(ev));
});
el.addEventListener("touchmove", ev => {
if (state && touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
state.update(touch);
ev.preventDefault();
}
}
});
el.addEventListener("touchcancel", ev => {
if (state && touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
state.end(touch);
state = undefined;
ev.preventDefault();
}
}
});
}
function getTouch(ev: TouchEvent, identifier: number) {
for (let i = 0; i < ev.changedTouches.length; i++) {
if (ev.changedTouches[i].identifier === identifier) {
return ev.changedTouches[i];
}
}
return undefined;
}
function isRightClick(ev: MouseEvent | PointerEvent | TouchEvent) {
if ((ev as MouseEvent | PointerEvent).button > 0) return true;
return false;
}
export interface Color { r: number, g: number, b: number, a?: number }
export function imageStateToBitmap(state: pxt.sprite.ImageState) {
const base = pxt.sprite.Bitmap.fromData(state.bitmap);
if (state.floating && state.floating.bitmap) {
const floating = pxt.sprite.Bitmap.fromData(state.floating.bitmap);
floating.x0 = state.layerOffsetX || 0;
floating.y0 = state.layerOffsetY || 0;
base.apply(floating, true);
}
return base;
}
export function imageStateToTilemap(state: pxt.sprite.ImageState) {
const base = pxt.sprite.Tilemap.fromData(state.bitmap);
if (state.floating && state.floating.bitmap) {
const floating = pxt.sprite.Tilemap.fromData(state.floating.bitmap);
floating.x0 = state.layerOffsetX || 0;
floating.y0 = state.layerOffsetY || 0;
base.apply(floating, true);
}
return base;
}
export function applyBitmapData(bitmap: pxt.sprite.BitmapData, data: pxt.sprite.BitmapData, x0: number = 0, y0: number = 0): pxt.sprite.BitmapData {
if (!bitmap || !data) return bitmap;
const base = pxt.sprite.Bitmap.fromData(bitmap);
const layer = pxt.sprite.Bitmap.fromData(data);
layer.x0 = x0;
layer.y0 = y0;
base.apply(layer, true);
return base.data();
}
export interface TilemapPatch {
map: string;
layers: string[];
tiles: string[];
}
export function createTilemapPatchFromFloatingLayer(editState: EditState, tileset: pxt.TileSet): TilemapPatch {
if (!editState.floating) return undefined;
const tilemap = pxt.sprite.Tilemap.fromData(editState.floating.image.data());
const copyTilemap = new pxt.sprite.Tilemap(tilemap.width, tilemap.height);
const layers = editState.floating.overlayLayers ?
editState.floating.overlayLayers.map(bitmap => pxt.sprite.base64EncodeBitmap(bitmap.data())) : [];
let referencedTiles: pxt.Tile[] = [];
for (let x = 0; x < tilemap.width; x++) {
for (let y = 0; y < tilemap.height; y++) {
const tile = tileset.tiles[tilemap.get(x, y)]
const index = referencedTiles.indexOf(tile);
if (index === -1) {
copyTilemap.set(x, y, referencedTiles.length);
referencedTiles.push(tile);
}
else {
copyTilemap.set(x, y, index);
}
}
}
return {
map: pxt.sprite.hexEncodeTilemap(copyTilemap),
layers,
tiles: referencedTiles.map(t => pxt.sprite.base64EncodeBitmap(t.bitmap))
};
} | the_stack |
import { Component, ElementRef, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { Title } from '@angular/platform-browser';
// Third party imports
import { Observable } from 'rxjs';
// App imports
import { APIClient } from 'src/app/swagger';
import AppServices from '../../../shared/service/appServices';
import { AzureClouds, AzureField, AzureForm, ResourceGroupOption, VnetOptionType } from './azure-wizard.constants';
import {
AzureInstanceType,
AzureRegionalClusterParams,
AzureResourceGroup,
AzureVirtualMachine,
AzureVirtualNetwork
} from 'src/app/swagger/models';
import { AzureAccountParamsKeys, AzureProviderStepComponent } from './provider-step/azure-provider-step.component';
import { AzureOsImageStepComponent } from './os-image-step/azure-os-image-step.component';
import { CliFields, CliGenerator } from '../wizard/shared/utils/cli-generator';
import { VnetStepComponent } from './vnet-step/vnet-step.component';
import { ExportService } from '../../../shared/service/export.service';
import { FormDataForHTML, FormUtility } from '../wizard/shared/components/steps/form-utility';
import { ImportParams, ImportService } from "../../../shared/service/import.service";
import { NodeSettingField } from '../wizard/shared/components/steps/node-setting-step/node-setting-step.fieldmapping';
import { NodeSettingStepComponent } from './node-setting-step/node-setting-step.component';
import { OsImageField } from '../wizard/shared/components/steps/os-image-step/os-image-step.fieldmapping';
import { TanzuEventType } from '../../../shared/service/Messenger';
import { WizardBaseDirective } from '../wizard/shared/wizard-base/wizard-base';
import { WizardForm } from '../wizard/shared/constants/wizard.constants';
@Component({
selector: 'app-azure-wizard',
templateUrl: './azure-wizard.component.html',
styleUrls: ['./azure-wizard.component.scss']
})
export class AzureWizardComponent extends WizardBaseDirective implements OnInit {
constructor(
router: Router,
private importService: ImportService,
private exportService: ExportService,
formBuilder: FormBuilder,
private apiClient: APIClient,
titleService: Title,
el: ElementRef) {
super(router, el, titleService, formBuilder);
}
protected supplyFileImportedEvent(): TanzuEventType {
return TanzuEventType.AZURE_CONFIG_FILE_IMPORTED;
}
protected supplyFileImportErrorEvent(): TanzuEventType {
return TanzuEventType.AZURE_CONFIG_FILE_IMPORT_ERROR;
}
protected supplyWizardName(): string {
return 'AzureWizard';
}
protected supplyStepData(): FormDataForHTML[] {
return [
this.AzureProviderForm,
this.AzureVnetForm,
this.AzureNodeSettingForm,
this.MetadataForm,
this.AzureNetworkForm,
this.IdentityForm,
this.AzureOsImageForm,
this.CeipForm,
];
}
ngOnInit() {
super.ngOnInit();
this.titleService.setTitle(this.title + ' Azure');
this.registerServices();
this.subscribeToServices();
}
// From the user-entered data, create an accountParams object to send to the azure endpoint for verification
private createCredentialParamsObject() {
const chosenCloudObject = this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_AZURECLOUD);
const azureCloud = chosenCloudObject ? chosenCloudObject.name : '';
return {
tenantId: this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_TENANT),
clientId: this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_CLIENT),
clientSecret: this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_CLIENTSECRET),
subscriptionId: this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_SUBSCRIPTION),
azureCloud
};
}
getPayload(): any {
const payload: AzureRegionalClusterParams = {};
payload.azureAccountParams = this.createCredentialParamsObject();
const mappings = [
["location", AzureForm.PROVIDER, AzureField.PROVIDER_REGION],
["sshPublicKey", AzureForm.PROVIDER, AzureField.PROVIDER_SSHPUBLICKEY],
];
mappings.forEach(attr => payload[attr[0]] = this.getFieldValue(attr[1], attr[2]));
payload.controlPlaneFlavor = this.getStoredClusterPlan(AzureForm.NODESETTING);
const nodeTypeField = payload.controlPlaneFlavor === 'prod' ? NodeSettingField.INSTANCE_TYPE_PROD
: NodeSettingField.INSTANCE_TYPE_DEV;
payload.controlPlaneMachineType = this.getFieldValue(AzureForm.NODESETTING, nodeTypeField);
payload.workerMachineType = AppServices.appDataService.isModeClusterStandalone() ? payload.controlPlaneMachineType :
this.getFieldValue(AzureForm.NODESETTING, NodeSettingField.WORKER_NODE_INSTANCE_TYPE);
payload.machineHealthCheckEnabled =
this.getBooleanFieldValue(AzureForm.NODESETTING, NodeSettingField.MACHINE_HEALTH_CHECKS_ENABLED);
const resourceGroupOption = this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_RESOURCEGROUPOPTION);
const resourceGroupField = resourceGroupOption === ResourceGroupOption.EXISTING ? AzureField.PROVIDER_RESOURCEGROUPEXISTING :
AzureField.PROVIDER_RESOURCEGROUPCUSTOM;
payload.resourceGroup = this.getFieldValue(AzureForm.PROVIDER, resourceGroupField);
payload.clusterName = this.getMCName();
// Retrieve vnet info
payload.vnetResourceGroup = this.getFieldValue(AzureForm.VNET, AzureField.VNET_RESOURCE_GROUP);
const vnetOption = this.getFieldValue(AzureForm.VNET, AzureField.VNET_EXISTING_OR_CUSTOM);
let vnetAttrs = [ // For new vnet
["vnetName", AzureForm.VNET, AzureField.VNET_CUSTOM_NAME],
["vnetCidr", AzureForm.VNET, AzureField.VNET_CUSTOM_CIDR],
["controlPlaneSubnet", AzureForm.VNET, AzureField.VNET_CONTROLPLANE_NEWSUBNET_NAME],
["controlPlaneSubnetCidr", AzureForm.VNET, AzureField.VNET_CONTROLPLANE_NEWSUBNET_CIDR],
["workerNodeSubnet", AzureForm.VNET, AzureField.VNET_WORKER_NEWSUBNET_NAME],
["workerNodeSubnetCidr", AzureForm.VNET, AzureField.VNET_WORKER_NEWSUBNET_CIDR],
];
if (vnetOption === VnetOptionType.EXISTING) { // for existing vnet
vnetAttrs = [
["vnetName", AzureForm.VNET, AzureField.VNET_EXISTING_NAME],
["vnetCidr", AzureForm.VNET, AzureField.VNET_CUSTOM_CIDR],
["controlPlaneSubnet", AzureForm.VNET, AzureField.VNET_CONTROLPLANE_SUBNET_NAME],
["controlPlaneSubnetCidr", AzureForm.VNET, AzureField.VNET_CONTROLPLANE_SUBNET_CIDR],
["workerNodeSubnet", AzureForm.VNET, AzureField.VNET_WORKER_SUBNET_NAME],
];
}
vnetAttrs.forEach(attr => payload[attr[0]] = this.getFieldValue(attr[1], attr[2]));
payload.enableAuditLogging = this.getBooleanFieldValue(AzureForm.NODESETTING, NodeSettingField.ENABLE_AUDIT_LOGGING);
this.initPayloadWithCommons(payload);
// private Azure cluster support
payload.isPrivateCluster = this.getBooleanFieldValue(AzureForm.VNET, AzureField.VNET_PRIVATE_CLUSTER);
payload.frontendPrivateIp = "";
if (payload.isPrivateCluster) {
payload.frontendPrivateIp = this.getFieldValue(AzureForm.VNET, AzureField.VNET_PRIVATE_IP);
}
return payload;
}
setFromPayload(payload: AzureRegionalClusterParams) {
if (payload !== undefined) {
if (payload.azureAccountParams !== undefined) {
for (const accountFieldName of Object.keys(payload.azureAccountParams)) {
// we treat azureCloud differently because it's a listbox selection where the label != key
if (accountFieldName !== 'azureCloud') {
this.storeFieldString(AzureForm.PROVIDER, accountFieldName, payload.azureAccountParams[accountFieldName]);
}
}
const azureCloudValue = payload.azureAccountParams['azureCloud'];
const azureCloud = azureCloudValue ? AzureClouds.find(cloud => cloud.name === azureCloudValue) : undefined;
if (azureCloud) {
this.storeFieldString(AzureForm.PROVIDER, AzureField.PROVIDER_AZURECLOUD, azureCloud.name, azureCloud.displayName);
}
}
this.storeFieldString(AzureForm.PROVIDER, AzureField.PROVIDER_SSHPUBLICKEY, payload["sshPublicKey"]);
this.storeFieldString(AzureForm.PROVIDER, AzureField.PROVIDER_REGION, payload["location"]);
this.setStoredClusterPlan(AzureForm.NODESETTING, payload.controlPlaneFlavor);
const instanceTypeField = payload.controlPlaneFlavor === 'prod' ? NodeSettingField.INSTANCE_TYPE_PROD
: NodeSettingField.INSTANCE_TYPE_DEV;
this.storeFieldString(AzureForm.NODESETTING, instanceTypeField, payload.controlPlaneMachineType);
if (!AppServices.appDataService.isModeClusterStandalone()) {
this.storeFieldString(AzureForm.NODESETTING, NodeSettingField.WORKER_NODE_INSTANCE_TYPE, payload.workerMachineType);
}
this.storeFieldBoolean(AzureForm.NODESETTING, NodeSettingField.MACHINE_HEALTH_CHECKS_ENABLED,
payload.machineHealthCheckEnabled);
// Since we cannot tell if the resource group is custom or existing, we load it into the custom field.
// When the resource groups are retrieved, we have code that will detect if the resource group is existing.
// See azure-provider-step.component.ts's handleIfSavedCustomResourceGroupIsNowExisting()
this.storeFieldString(AzureForm.PROVIDER, AzureField.PROVIDER_RESOURCEGROUPCUSTOM, payload.resourceGroup);
this.saveMCName(payload.clusterName);
// We cannot tell if the vnet is custom or existing, so we load it into the custom field.
// When the vnet resource groups are retrieved, we have code that will detect if the vnet is existing.
// See vnet-step.component.ts's handleIfSavedVnetCustomNameIsNowExisting()
const vnetAttrs = [
['vnetResourceGroup', AzureField.VNET_RESOURCE_GROUP],
["vnetName", AzureField.VNET_CUSTOM_NAME],
["vnetCidr", AzureField.VNET_CUSTOM_CIDR],
["controlPlaneSubnet", AzureField.VNET_CONTROLPLANE_NEWSUBNET_NAME],
["controlPlaneSubnetCidr", AzureField.VNET_CONTROLPLANE_NEWSUBNET_CIDR],
["workerNodeSubnet", AzureField.VNET_WORKER_NEWSUBNET_NAME],
["workerNodeSubnetCidr", AzureField.VNET_WORKER_NEWSUBNET_CIDR],
];
vnetAttrs.forEach(attr => payload[attr[0]] = this.storeFieldString(AzureForm.VNET, attr[1], payload[attr[0]]));
this.storeFieldBoolean(AzureForm.VNET, AzureField.VNET_PRIVATE_CLUSTER, payload.isPrivateCluster);
if (payload.isPrivateCluster) {
this.storeFieldString(AzureForm.VNET, AzureField.VNET_PRIVATE_IP, payload.frontendPrivateIp);
}
this.storeFieldBoolean(AzureForm.NODESETTING, NodeSettingField.ENABLE_AUDIT_LOGGING, payload.enableAuditLogging);
this.storeFieldString(WizardForm.OSIMAGE, OsImageField.IMAGE, payload.os.name);
this.saveCommonFieldsFromPayload(payload);
AppServices.userDataService.updateWizardTimestamp(this.wizardName);
}
}
/**
* @method method to trigger deployment
*/
createRegionalCluster(payload: any): Observable<any> {
return this.apiClient.createAzureRegionalCluster(payload);
}
/**
* Return management/standalone cluster name
*/
getMCName() {
return this.getFieldValue(AzureForm.NODESETTING, NodeSettingField.CLUSTER_NAME);
}
saveMCName(clusterName: string) {
this.storeFieldString(AzureForm.NODESETTING, NodeSettingField.CLUSTER_NAME, clusterName);
}
/**
* Get the CLI used to deploy the management/standalone cluster
*/
getCli(configPath: string): string {
const cliG = new CliGenerator();
const cliParams: CliFields = {
configPath: configPath,
clusterType: this.getClusterType(),
clusterName: this.getMCName(),
extendCliCmds: []
};
return cliG.getCli(cliParams);
}
getCliEnvVariables() {
let envVariableString = '';
const resourceGroupOption = this.getFieldValue(AzureForm.PROVIDER, AzureField.PROVIDER_RESOURCEGROUPOPTION);
const azureResourceGroup = resourceGroupOption === ResourceGroupOption.EXISTING ? AzureField.PROVIDER_RESOURCEGROUPEXISTING :
AzureField.PROVIDER_RESOURCEGROUPCUSTOM;
const vnetOption = this.getFieldValue(AzureForm.VNET, AzureField.VNET_EXISTING_OR_CUSTOM);
const azureVnetName = vnetOption === VnetOptionType.EXISTING ? AzureField.VNET_EXISTING_NAME : AzureField.VNET_CUSTOM_NAME;
const azureControlPlaneSubnetName = vnetOption === VnetOptionType.EXISTING ? AzureField.VNET_CONTROLPLANE_SUBNET_NAME :
AzureField.VNET_CONTROLPLANE_NEWSUBNET_NAME;
const azureNodeSubnetName = vnetOption === VnetOptionType.EXISTING ? AzureField.VNET_WORKER_SUBNET_NAME :
AzureField.VNET_WORKER_NEWSUBNET_NAME;
const fieldsMapping = {
AZURE_RESOURCE_GROUP: [AzureForm.PROVIDER, azureResourceGroup],
AZURE_VNET_RESOURCE_GROUP: [AzureForm.VNET, AzureField.VNET_RESOURCE_GROUP],
AZURE_VNET_NAME: [AzureForm.VNET, azureVnetName],
AZURE_VNET_CIDR: [AzureForm.VNET, AzureField.VNET_CUSTOM_CIDR],
AZURE_CONTROL_PLANE_SUBNET_NAME: [AzureForm.VNET, azureControlPlaneSubnetName],
AZURE_CONTROL_PLANE_SUBNET_CIDR: [AzureForm.VNET, AzureField.VNET_CONTROLPLANE_NEWSUBNET_CIDR],
AZURE_NODE_SUBNET_NAME: [AzureForm.VNET, azureNodeSubnetName],
AZURE_NODE_SUBNET_CIDR: [AzureForm.VNET, AzureField.VNET_WORKER_NEWSUBNET_CIDR]
}
let fields = [];
if (vnetOption === VnetOptionType.EXISTING) {
fields = [
'AZURE_RESOURCE_GROUP',
'AZURE_VNET_RESOURCE_GROUP',
'AZURE_VNET_NAME',
'AZURE_CONTROL_PLANE_SUBNET_NAME',
'AZURE_NODE_SUBNET_NAME'
];
} else {
fields = [
'AZURE_RESOURCE_GROUP',
'AZURE_VNET_RESOURCE_GROUP',
'AZURE_VNET_NAME',
'AZURE_VNET_CIDR',
'AZURE_CONTROL_PLANE_SUBNET_NAME',
'AZURE_CONTROL_PLANE_SUBNET_CIDR',
'AZURE_NODE_SUBNET_NAME',
'AZURE_NODE_SUBNET_CIDR'
];
}
fields.forEach(field => {
const temp = fieldsMapping[field];
envVariableString += `${field}="${this.getFieldValue(temp[0], temp[1])}" `;
});
return envVariableString;
}
applyTkgConfig() {
return this.apiClient.applyTKGConfigForAzure({ params: this.getPayload() });
}
/**
* Retrieve the config file from the backend and return as a string
*/
retrieveExportFile() {
return this.apiClient.exportTKGConfigForAzure({ params: this.getPayload() });
}
exportConfiguration() {
const wizard = this; // capture 'this' outside the context of the closure below
this.exportService.export(
this.retrieveExportFile(),
(failureMessage) => { wizard.displayError(failureMessage); }
);
}
// HTML convenience methods
//
get AzureProviderForm(): FormDataForHTML {
return { name: AzureForm.PROVIDER, title: 'IaaS Provider', description: 'Validate the Azure provider credentials for Tanzu',
i18n: {title: 'IaaS provder step name', description: 'IaaS provder step description'},
clazz: AzureProviderStepComponent};
}
get AzureVnetForm(): FormDataForHTML {
return { name: AzureForm.VNET, title: 'Azure VNet Settings', description: 'Specify an Azure VNet CIDR',
i18n: {title: 'vnet step name', description: 'vnet step description'},
clazz: VnetStepComponent};
}
get AzureNodeSettingForm(): FormDataForHTML {
return { name: AzureForm.NODESETTING, title: FormUtility.titleCase(this.clusterTypeDescriptor) + ' Cluster Settings',
description: `Specifying the resources backing the ${this.clusterTypeDescriptor} cluster`,
i18n: {title: 'node setting step name', description: 'node setting step description'},
clazz: NodeSettingStepComponent};
}
get AzureOsImageForm(): FormDataForHTML {
return this.getOsImageForm(AzureOsImageStepComponent);
}
get AzureNetworkForm(): FormDataForHTML {
return FormUtility.formWithOverrides(this.NetworkForm, {description: 'Specify an Azure VNet CIDR'});
}
//
// HTML convenience methods
// returns TRUE if the file contents appear to be a valid config file for Azure
// returns FALSE if the file is empty or does not appear to be valid. Note that in the FALSE
// case we also alert the user.
importFileValidate(nameFile: string, fileContents: string): boolean {
if (fileContents.includes('AZURE_')) {
return true;
}
alert(nameFile + ' is not a valid Azure configuration file!');
return false;
}
importFileRetrieveClusterParams(fileContents: string): Observable<AzureRegionalClusterParams> {
return this.apiClient.importTKGConfigForAzure( { params: { filecontents: fileContents } } );
}
importFileProcessClusterParams(event: TanzuEventType, nameFile: string, azureClusterParams: AzureRegionalClusterParams) {
this.setFromPayload(azureClusterParams);
this.resetToFirstStep();
this.importService.publishImportSuccess(event, nameFile);
}
// returns TRUE if user (a) will not lose data on import, or (b) confirms it's OK
onImportButtonClick() {
let result = true;
if (!this.isOnFirstStep()) {
result = confirm('Importing will overwrite any data you have entered. Proceed with import?');
}
return result;
}
onImportFileSelected(event) {
const params: ImportParams<AzureRegionalClusterParams> = {
eventSuccess: this.supplyFileImportedEvent(),
eventFailure: this.supplyFileImportErrorEvent(),
file: event.target.files[0],
validator: this.importFileValidate,
backend: this.importFileRetrieveClusterParams.bind(this),
onSuccess: this.importFileProcessClusterParams.bind(this),
onFailure: this.importService.publishImportFailure
}
this.importService.import(params);
// clear file reader target so user can re-select same file if needed
event.target.value = '';
}
private subscribeToServices() {
AppServices.messenger.subscribe<string>(TanzuEventType.AZURE_REGION_CHANGED, event => {
const region = event.payload;
if (region) {
AppServices.dataServiceRegistrar.trigger([
TanzuEventType.AZURE_GET_RESOURCE_GROUPS,
TanzuEventType.AZURE_GET_INSTANCE_TYPES
], { location: region });
AppServices.dataServiceRegistrar.trigger([TanzuEventType.AZURE_GET_OS_IMAGES]);
} else {
AppServices.dataServiceRegistrar.clear<AzureResourceGroup>(TanzuEventType.AZURE_GET_RESOURCE_GROUPS);
AppServices.dataServiceRegistrar.clear<AzureInstanceType>(TanzuEventType.AZURE_GET_INSTANCE_TYPES);
AppServices.dataServiceRegistrar.clear<AzureVirtualMachine>(TanzuEventType.AZURE_GET_OS_IMAGES);
}
});
}
private registerServices() {
const wizard = this;
AppServices.dataServiceRegistrar.register<AzureResourceGroup>(TanzuEventType.AZURE_GET_RESOURCE_GROUPS,
(payload: {location: string}) => { return wizard.apiClient.getAzureResourceGroups(payload); },
"Failed to retrieve resource groups for the particular region." );
AppServices.dataServiceRegistrar.register<AzureInstanceType>(TanzuEventType.AZURE_GET_INSTANCE_TYPES,
(payload: {location: string}) => { return wizard.apiClient.getAzureInstanceTypes(payload); },
"Failed to retrieve Azure VM sizes" );
AppServices.dataServiceRegistrar.register<AzureVirtualMachine>(TanzuEventType.AZURE_GET_OS_IMAGES,
() => { return wizard.apiClient.getAzureOSImages(); },
"Failed to retrieve list of OS images from the specified Azure Server." );
AppServices.dataServiceRegistrar.register<AzureVirtualNetwork>(TanzuEventType.AZURE_GET_VNETS,
(payload: {resourceGroupName: string, location: string}) => { return wizard.apiClient.getAzureVnets(payload)},
"Failed to retrieve list of VNets from the specified Azure Server." );
}
} | the_stack |
import {
compareFileNames,
compareFileExtensions,
compareFileNamesDefault,
compareFileExtensionsDefault,
compareFileNamesUpper,
compareFileExtensionsUpper,
compareFileNamesLower,
compareFileExtensionsLower,
compareFileNamesUnicode,
compareFileExtensionsUnicode,
} from 'vs/base/common/comparers';
import * as assert from 'assert';
const compareLocale = (a: string, b: string) => a.localeCompare(b);
const compareLocaleNumeric = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true });
suite('Comparers', () => {
test('compareFileNames', () => {
//
// Comparisons with the same results as compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNames(null, null) === 0, 'null should be equal');
assert(compareFileNames(null, 'abc') < 0, 'null should be come before real values');
assert(compareFileNames('', '') === 0, 'empty should be equal');
assert(compareFileNames('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileNames('z', 'A') > 0, 'z comes after A');
assert(compareFileNames('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileNames('bbb.aaa', 'aaa.bbb') > 0, 'compares the whole name all at once by locale');
assert(compareFileNames('aggregate.go', 'aggregate_repo.go') > 0, 'compares the whole name all at once by locale');
// dotfile comparisons
assert(compareFileNames('.abc', '.abc') === 0, 'equal dotfile names should be equal');
assert(compareFileNames('.env.', '.gitattributes') < 0, 'filenames starting with dots and with extensions should still sort properly');
assert(compareFileNames('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileNames('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
assert(compareFileNames('.aaa_env', '.aaa.env') < 0, 'an underscore in a dotfile name will sort before a dot');
// dotfile vs non-dotfile comparisons
assert(compareFileNames(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileNames('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileNames('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileNames('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
assert(compareFileNames('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileNames('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileNames('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileNames('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileNames('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileNames('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileNames('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileNames('a.ext1', 'b.Ext1') < 0, 'if names are different and extensions with numbers are equal except for case, filenames are sorted in name order');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileNames), ['A2.txt', 'a10.txt', 'a20.txt', 'A100.txt'], 'filenames with number and case differences compare numerically');
//
// Comparisons with different results than compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNames('a', 'A') !== compareLocale('a', 'A'), 'the same letter sorts in unicode order, not by locale');
assert(compareFileNames('â', 'Â') !== compareLocale('â', 'Â'), 'the same accented letter sorts in unicode order, not by locale');
assert.notDeepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileNames), ['artichoke', 'Artichoke', 'art', 'Art'].sort(compareLocale), 'words with the same root and different cases do not sort in locale order');
assert.notDeepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileNames), ['email', 'Email', 'émail', 'Émail'].sort(compareLocale), 'the same base characters with different case or accents do not sort in locale order');
// numeric comparisons
assert(compareFileNames('abc02.txt', 'abc002.txt') > 0, 'filenames with equivalent numbers and leading zeros sort in unicode order');
assert(compareFileNames('abc.txt1', 'abc.txt01') > 0, 'same name plus extensions with equal numbers sort in unicode order');
assert(compareFileNames('art01', 'Art01') !== 'art01'.localeCompare('Art01', undefined, { numeric: true }),
'a numerically equivalent word of a different case does not compare numerically based on locale');
assert(compareFileNames('a.ext1', 'a.Ext1') > 0, 'if names are equal and extensions with numbers are equal except for case, filenames are sorted in full filename unicode order');
});
test('compareFileExtensions', () => {
//
// Comparisons with the same results as compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensions(null, null) === 0, 'null should be equal');
assert(compareFileExtensions(null, 'abc') < 0, 'null should come before real files without extension');
assert(compareFileExtensions('', '') === 0, 'empty should be equal');
assert(compareFileExtensions('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileExtensions('z', 'A') > 0, 'z comes after A');
assert(compareFileExtensions('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileExtensions('file.ext', 'file.ext') === 0, 'equal full names should be equal');
assert(compareFileExtensions('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileExtensions('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileExtensions('bbb.aaa', 'aaa.bbb') < 0, 'files should be compared by extensions even if filenames compare differently');
// dotfile comparisons
assert(compareFileExtensions('.abc', '.abc') === 0, 'equal dotfiles should be equal');
assert(compareFileExtensions('.md', '.Gitattributes') > 0, 'dotfiles sort alphabetically regardless of case');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensions(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileExtensions('.env', 'aaa.env') < 0, 'if equal extensions, filenames should be compared, empty filename should come before others');
assert(compareFileExtensions('.MD', 'a.md') < 0, 'if extensions differ in case, files sort by extension in unicode order');
// numeric comparisons
assert(compareFileExtensions('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileExtensions('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileExtensions('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensions('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileExtensions('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileExtensions('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileExtensions('abc2.txt2', 'abc1.txt10') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensions('txt.abc1', 'txt.abc1') === 0, 'equal extensions with numbers should be equal');
assert(compareFileExtensions('txt.abc1', 'txt.abc2') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensions('txt.abc2', 'txt.abc10') < 0, 'extensions with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileExtensions('a.ext1', 'b.ext1') < 0, 'if equal extensions with numbers, names should be compared');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileExtensions), ['A2.txt', 'a10.txt', 'a20.txt', 'A100.txt'], 'filenames with number and case differences compare numerically');
//
// Comparisons with different results from compareFileExtensionsDefault
//
// name-only comparisions
assert(compareFileExtensions('a', 'A') !== compareLocale('a', 'A'), 'the same letter of different case does not sort by locale');
assert(compareFileExtensions('â', 'Â') !== compareLocale('â', 'Â'), 'the same accented letter of different case does not sort by locale');
assert.notDeepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileExtensions), ['artichoke', 'Artichoke', 'art', 'Art'].sort(compareLocale), 'words with the same root and different cases do not sort in locale order');
assert.notDeepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileExtensions), ['email', 'Email', 'émail', 'Émail'].sort((a, b) => a.localeCompare(b)), 'the same base characters with different case or accents do not sort in locale order');
// name plus extension comparisons
assert(compareFileExtensions('a.MD', 'a.md') < 0, 'case differences in extensions sort in unicode order');
assert(compareFileExtensions('a.md', 'A.md') > 0, 'case differences in names sort in unicode order');
assert(compareFileExtensions('a.md', 'b.MD') > 0, 'when extensions are the same except for case, the files sort by extension');
assert(compareFileExtensions('aggregate.go', 'aggregate_repo.go') < 0, 'when extensions are equal, names sort in dictionary order');
// dotfile comparisons
assert(compareFileExtensions('.env', '.aaa.env') < 0, 'a dotfile with an extension is treated as a name plus an extension - equal extensions');
assert(compareFileExtensions('.env', '.env.aaa') > 0, 'a dotfile with an extension is treated as a name plus an extension - unequal extensions');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensions('.env', 'aaa') > 0, 'filenames without extensions come before dotfiles');
assert(compareFileExtensions('.md', 'A.MD') > 0, 'a file with an uppercase extension sorts before a dotfile of the same lowercase extension');
// numeric comparisons
assert(compareFileExtensions('abc.txt01', 'abc.txt1') < 0, 'extensions with equal numbers sort in unicode order');
assert(compareFileExtensions('art01', 'Art01') !== compareLocaleNumeric('art01', 'Art01'), 'a numerically equivalent word of a different case does not compare by locale');
assert(compareFileExtensions('abc02.txt', 'abc002.txt') > 0, 'filenames with equivalent numbers and leading zeros sort in unicode order');
assert(compareFileExtensions('txt.abc01', 'txt.abc1') < 0, 'extensions with equivalent numbers sort in unicode order');
assert(compareFileExtensions('a.ext1', 'b.Ext1') > 0, 'if names are different and extensions with numbers are equal except for case, filenames are sorted in extension unicode order');
assert(compareFileExtensions('a.ext1', 'a.Ext1') > 0, 'if names are equal and extensions with numbers are equal except for case, filenames are sorted in extension unicode order');
});
test('compareFileNamesDefault', () => {
//
// Comparisons with the same results as compareFileNames
//
// name-only comparisons
assert(compareFileNamesDefault(null, null) === 0, 'null should be equal');
assert(compareFileNamesDefault(null, 'abc') < 0, 'null should be come before real values');
assert(compareFileNamesDefault('', '') === 0, 'empty should be equal');
assert(compareFileNamesDefault('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileNamesDefault('z', 'A') > 0, 'z comes after A');
assert(compareFileNamesDefault('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileNamesDefault('file.ext', 'file.ext') === 0, 'equal full names should be equal');
assert(compareFileNamesDefault('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileNamesDefault('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileNamesDefault('bbb.aaa', 'aaa.bbb') > 0, 'files should be compared by names even if extensions compare differently');
assert(compareFileNamesDefault('aggregate.go', 'aggregate_repo.go') > 0, 'compares the whole filename in locale order');
// dotfile comparisons
assert(compareFileNamesDefault('.abc', '.abc') === 0, 'equal dotfile names should be equal');
assert(compareFileNamesDefault('.env.', '.gitattributes') < 0, 'filenames starting with dots and with extensions should still sort properly');
assert(compareFileNamesDefault('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileNamesDefault('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
assert(compareFileNamesDefault('.aaa_env', '.aaa.env') < 0, 'an underscore in a dotfile name will sort before a dot');
// dotfile vs non-dotfile comparisons
assert(compareFileNamesDefault(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileNamesDefault('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileNamesDefault('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileNamesDefault('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
assert(compareFileNamesDefault('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileNamesDefault('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileNamesDefault('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileNamesDefault('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileNamesDefault('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileNamesDefault('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileNamesDefault('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileNamesDefault('a.ext1', 'b.Ext1') < 0, 'if names are different and extensions with numbers are equal except for case, filenames are compared by full filename');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileNamesDefault), ['A2.txt', 'a10.txt', 'a20.txt', 'A100.txt'], 'filenames with number and case differences compare numerically');
//
// Comparisons with different results than compareFileNames
//
// name-only comparisons
assert(compareFileNamesDefault('a', 'A') === compareLocale('a', 'A'), 'the same letter sorts by locale');
assert(compareFileNamesDefault('â', 'Â') === compareLocale('â', 'Â'), 'the same accented letter sorts by locale');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileNamesDefault), ['email', 'Email', 'émail', 'Émail'].sort(compareLocale), 'the same base characters with different case or accents sort in locale order');
// numeric comparisons
assert(compareFileNamesDefault('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest number first');
assert(compareFileNamesDefault('abc.txt1', 'abc.txt01') < 0, 'same name plus extensions with equal numbers sort shortest number first');
assert(compareFileNamesDefault('art01', 'Art01') === compareLocaleNumeric('art01', 'Art01'), 'a numerically equivalent word of a different case compares numerically based on locale');
assert(compareFileNamesDefault('a.ext1', 'a.Ext1') === compareLocale('ext1', 'Ext1'), 'if names are equal and extensions with numbers are equal except for case, filenames are sorted in extension locale order');
});
test('compareFileExtensionsDefault', () => {
//
// Comparisons with the same result as compareFileExtensions
//
// name-only comparisons
assert(compareFileExtensionsDefault(null, null) === 0, 'null should be equal');
assert(compareFileExtensionsDefault(null, 'abc') < 0, 'null should come before real files without extensions');
assert(compareFileExtensionsDefault('', '') === 0, 'empty should be equal');
assert(compareFileExtensionsDefault('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileExtensionsDefault('z', 'A') > 0, 'z comes after A');
assert(compareFileExtensionsDefault('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileExtensionsDefault('file.ext', 'file.ext') === 0, 'equal full filenames should be equal');
assert(compareFileExtensionsDefault('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileExtensionsDefault('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileExtensionsDefault('bbb.aaa', 'aaa.bbb') < 0, 'files should be compared by extension first');
// dotfile comparisons
assert(compareFileExtensionsDefault('.abc', '.abc') === 0, 'equal dotfiles should be equal');
assert(compareFileExtensionsDefault('.md', '.Gitattributes') > 0, 'dotfiles sort alphabetically regardless of case');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensionsDefault(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileExtensionsDefault('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileExtensionsDefault('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileExtensionsDefault('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileExtensionsDefault('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileExtensionsDefault('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsDefault('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order');
assert(compareFileExtensionsDefault('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileExtensionsDefault('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileExtensionsDefault('abc2.txt2', 'abc1.txt10') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsDefault('txt.abc1', 'txt.abc1') === 0, 'equal extensions with numbers should be equal');
assert(compareFileExtensionsDefault('txt.abc1', 'txt.abc2') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsDefault('txt.abc2', 'txt.abc10') < 0, 'extensions with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileExtensionsDefault('a.ext1', 'b.ext1') < 0, 'if equal extensions with numbers, full filenames should be compared');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileExtensionsDefault), ['A2.txt', 'a10.txt', 'a20.txt', 'A100.txt'], 'filenames with number and case differences compare numerically');
//
// Comparisons with different results than compareFileExtensions
//
// name-only comparisons
assert(compareFileExtensionsDefault('a', 'A') === compareLocale('a', 'A'), 'the same letter of different case sorts by locale');
assert(compareFileExtensionsDefault('â', 'Â') === compareLocale('â', 'Â'), 'the same accented letter of different case sorts by locale');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileExtensionsDefault), ['email', 'Email', 'émail', 'Émail'].sort((a, b) => a.localeCompare(b)), 'the same base characters with different case or accents sort in locale order');
// name plus extension comparisons
assert(compareFileExtensionsDefault('a.MD', 'a.md') === compareLocale('MD', 'md'), 'case differences in extensions sort by locale');
assert(compareFileExtensionsDefault('a.md', 'A.md') === compareLocale('a', 'A'), 'case differences in names sort by locale');
assert(compareFileExtensionsDefault('a.md', 'b.MD') < 0, 'when extensions are the same except for case, the files sort by name');
assert(compareFileExtensionsDefault('aggregate.go', 'aggregate_repo.go') > 0, 'names with the same extension sort in full filename locale order');
// dotfile comparisons
assert(compareFileExtensionsDefault('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileExtensionsDefault('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensionsDefault('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileExtensionsDefault('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
// numeric comparisons
assert(compareFileExtensionsDefault('abc.txt01', 'abc.txt1') > 0, 'extensions with equal numbers should be in shortest-first order');
assert(compareFileExtensionsDefault('art01', 'Art01') === compareLocaleNumeric('art01', 'Art01'), 'a numerically equivalent word of a different case compares numerically based on locale');
assert(compareFileExtensionsDefault('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest string first');
assert(compareFileExtensionsDefault('txt.abc01', 'txt.abc1') > 0, 'extensions with equivalent numbers sort shortest extension first');
assert(compareFileExtensionsDefault('a.ext1', 'b.Ext1') < 0, 'if extensions with numbers are equal except for case, full filenames should be compared');
assert(compareFileExtensionsDefault('a.ext1', 'a.Ext1') === compareLocale('a.ext1', 'a.Ext1'), 'if extensions with numbers are equal except for case, full filenames are compared in locale order');
});
test('compareFileNamesUpper', () => {
//
// Comparisons with the same results as compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesUpper(null, null) === 0, 'null should be equal');
assert(compareFileNamesUpper(null, 'abc') < 0, 'null should be come before real values');
assert(compareFileNamesUpper('', '') === 0, 'empty should be equal');
assert(compareFileNamesUpper('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileNamesUpper('z', 'A') > 0, 'z comes after A');
// name plus extension comparisons
assert(compareFileNamesUpper('file.ext', 'file.ext') === 0, 'equal full names should be equal');
assert(compareFileNamesUpper('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileNamesUpper('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileNamesUpper('bbb.aaa', 'aaa.bbb') > 0, 'files should be compared by names even if extensions compare differently');
assert(compareFileNamesUpper('aggregate.go', 'aggregate_repo.go') > 0, 'compares the full filename in locale order');
// dotfile comparisons
assert(compareFileNamesUpper('.abc', '.abc') === 0, 'equal dotfile names should be equal');
assert(compareFileNamesUpper('.env.', '.gitattributes') < 0, 'filenames starting with dots and with extensions should still sort properly');
assert(compareFileNamesUpper('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileNamesUpper('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
assert(compareFileNamesUpper('.aaa_env', '.aaa.env') < 0, 'an underscore in a dotfile name will sort before a dot');
// dotfile vs non-dotfile comparisons
assert(compareFileNamesUpper(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileNamesUpper('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileNamesUpper('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileNamesUpper('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
assert(compareFileNamesUpper('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileNamesUpper('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileNamesUpper('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileNamesUpper('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileNamesUpper('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileNamesUpper('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileNamesUpper('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileNamesUpper('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest number first');
assert(compareFileNamesUpper('abc.txt1', 'abc.txt01') < 0, 'same name plus extensions with equal numbers sort shortest number first');
assert(compareFileNamesUpper('a.ext1', 'b.Ext1') < 0, 'different names with the equal extensions except for case are sorted by full filename');
assert(compareFileNamesUpper('a.ext1', 'a.Ext1') === compareLocale('a.ext1', 'a.Ext1'), 'same names with equal and extensions except for case are sorted in full filename locale order');
//
// Comparisons with different results than compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesUpper('Z', 'a') < 0, 'Z comes before a');
assert(compareFileNamesUpper('a', 'A') > 0, 'the same letter sorts uppercase first');
assert(compareFileNamesUpper('â', 'Â') > 0, 'the same accented letter sorts uppercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileNamesUpper), ['Art', 'Artichoke', 'art', 'artichoke'], 'names with the same root and different cases sort uppercase first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileNamesUpper), ['Email', 'Émail', 'email', 'émail'], 'the same base characters with different case or accents sort uppercase first');
// numeric comparisons
assert(compareFileNamesUpper('art01', 'Art01') > 0, 'a numerically equivalent name of a different case compares uppercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileNamesUpper), ['A2.txt', 'A100.txt', 'a10.txt', 'a20.txt'], 'filenames with number and case differences group by case then compare by number');
});
test('compareFileExtensionsUpper', () => {
//
// Comparisons with the same result as compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsUpper(null, null) === 0, 'null should be equal');
assert(compareFileExtensionsUpper(null, 'abc') < 0, 'null should come before real files without extensions');
assert(compareFileExtensionsUpper('', '') === 0, 'empty should be equal');
assert(compareFileExtensionsUpper('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileExtensionsUpper('z', 'A') > 0, 'z comes after A');
// name plus extension comparisons
assert(compareFileExtensionsUpper('file.ext', 'file.ext') === 0, 'equal full filenames should be equal');
assert(compareFileExtensionsUpper('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileExtensionsUpper('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileExtensionsUpper('bbb.aaa', 'aaa.bbb') < 0, 'files should be compared by extension first');
assert(compareFileExtensionsUpper('a.md', 'b.MD') < 0, 'when extensions are the same except for case, the files sort by name');
assert(compareFileExtensionsUpper('a.MD', 'a.md') === compareLocale('MD', 'md'), 'case differences in extensions sort by locale');
assert(compareFileExtensionsUpper('aggregate.go', 'aggregate_repo.go') > 0, 'when extensions are equal, compares the full filename');
// dotfile comparisons
assert(compareFileExtensionsUpper('.abc', '.abc') === 0, 'equal dotfiles should be equal');
assert(compareFileExtensionsUpper('.md', '.Gitattributes') > 0, 'dotfiles sort alphabetically regardless of case');
assert(compareFileExtensionsUpper('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileExtensionsUpper('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensionsUpper(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileExtensionsUpper('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileExtensionsUpper('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
assert(compareFileExtensionsUpper('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileExtensionsUpper('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
// numeric comparisons
assert(compareFileExtensionsUpper('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileExtensionsUpper('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileExtensionsUpper('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsUpper('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order');
assert(compareFileExtensionsUpper('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileExtensionsUpper('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileExtensionsUpper('abc2.txt2', 'abc1.txt10') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsUpper('txt.abc1', 'txt.abc1') === 0, 'equal extensions with numbers should be equal');
assert(compareFileExtensionsUpper('txt.abc1', 'txt.abc2') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsUpper('txt.abc2', 'txt.abc10') < 0, 'extensions with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileExtensionsUpper('a.ext1', 'b.ext1') < 0, 'if equal extensions with numbers, full filenames should be compared');
assert(compareFileExtensionsUpper('abc.txt01', 'abc.txt1') > 0, 'extensions with equal numbers should be in shortest-first order');
assert(compareFileExtensionsUpper('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest string first');
assert(compareFileExtensionsUpper('txt.abc01', 'txt.abc1') > 0, 'extensions with equivalent numbers sort shortest extension first');
assert(compareFileExtensionsUpper('a.ext1', 'b.Ext1') < 0, 'different names and extensions that are equal except for case are sorted in full filename order');
assert(compareFileExtensionsUpper('a.ext1', 'a.Ext1') === compareLocale('a.ext1', 'b.Ext1'), 'same names and extensions that are equal except for case are sorted in full filename locale order');
//
// Comparisons with different results than compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsUpper('Z', 'a') < 0, 'Z comes before a');
assert(compareFileExtensionsUpper('a', 'A') > 0, 'the same letter sorts uppercase first');
assert(compareFileExtensionsUpper('â', 'Â') > 0, 'the same accented letter sorts uppercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileExtensionsUpper), ['Art', 'Artichoke', 'art', 'artichoke'], 'names with the same root and different cases sort uppercase names first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileExtensionsUpper), ['Email', 'Émail', 'email', 'émail'], 'the same base characters with different case or accents sort uppercase names first');
// name plus extension comparisons
assert(compareFileExtensionsUpper('a.md', 'A.md') > 0, 'case differences in names sort uppercase first');
assert(compareFileExtensionsUpper('art01', 'Art01') > 0, 'a numerically equivalent word of a different case sorts uppercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileExtensionsUpper), ['A2.txt', 'A100.txt', 'a10.txt', 'a20.txt',], 'filenames with number and case differences group by case then sort by number');
});
test('compareFileNamesLower', () => {
//
// Comparisons with the same results as compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesLower(null, null) === 0, 'null should be equal');
assert(compareFileNamesLower(null, 'abc') < 0, 'null should be come before real values');
assert(compareFileNamesLower('', '') === 0, 'empty should be equal');
assert(compareFileNamesLower('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileNamesLower('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileNamesLower('file.ext', 'file.ext') === 0, 'equal full names should be equal');
assert(compareFileNamesLower('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileNamesLower('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileNamesLower('bbb.aaa', 'aaa.bbb') > 0, 'files should be compared by names even if extensions compare differently');
assert(compareFileNamesLower('aggregate.go', 'aggregate_repo.go') > 0, 'compares full filenames');
// dotfile comparisons
assert(compareFileNamesLower('.abc', '.abc') === 0, 'equal dotfile names should be equal');
assert(compareFileNamesLower('.env.', '.gitattributes') < 0, 'filenames starting with dots and with extensions should still sort properly');
assert(compareFileNamesLower('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileNamesLower('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
assert(compareFileNamesLower('.aaa_env', '.aaa.env') < 0, 'an underscore in a dotfile name will sort before a dot');
// dotfile vs non-dotfile comparisons
assert(compareFileNamesLower(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileNamesLower('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileNamesLower('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileNamesLower('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
assert(compareFileNamesLower('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileNamesLower('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileNamesLower('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileNamesLower('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileNamesLower('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileNamesLower('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileNamesLower('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileNamesLower('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest number first');
assert(compareFileNamesLower('abc.txt1', 'abc.txt01') < 0, 'same name plus extensions with equal numbers sort shortest number first');
assert(compareFileNamesLower('a.ext1', 'b.Ext1') < 0, 'different names and extensions that are equal except for case are sorted in full filename order');
assert(compareFileNamesLower('a.ext1', 'a.Ext1') === compareLocale('a.ext1', 'b.Ext1'), 'same names and extensions that are equal except for case are sorted in full filename locale order');
//
// Comparisons with different results than compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesLower('z', 'A') < 0, 'z comes before A');
assert(compareFileNamesLower('a', 'A') < 0, 'the same letter sorts lowercase first');
assert(compareFileNamesLower('â', 'Â') < 0, 'the same accented letter sorts lowercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileNamesLower), ['art', 'artichoke', 'Art', 'Artichoke'], 'names with the same root and different cases sort lowercase first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileNamesLower), ['email', 'émail', 'Email', 'Émail'], 'the same base characters with different case or accents sort lowercase first');
// numeric comparisons
assert(compareFileNamesLower('art01', 'Art01') < 0, 'a numerically equivalent name of a different case compares lowercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileNamesLower), ['a10.txt', 'a20.txt', 'A2.txt', 'A100.txt'], 'filenames with number and case differences group by case then compare by number');
});
test('compareFileExtensionsLower', () => {
//
// Comparisons with the same result as compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsLower(null, null) === 0, 'null should be equal');
assert(compareFileExtensionsLower(null, 'abc') < 0, 'null should come before real files without extensions');
assert(compareFileExtensionsLower('', '') === 0, 'empty should be equal');
assert(compareFileExtensionsLower('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileExtensionsLower('Z', 'a') > 0, 'Z comes after a');
// name plus extension comparisons
assert(compareFileExtensionsLower('file.ext', 'file.ext') === 0, 'equal full filenames should be equal');
assert(compareFileExtensionsLower('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileExtensionsLower('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileExtensionsLower('bbb.aaa', 'aaa.bbb') < 0, 'files should be compared by extension first');
assert(compareFileExtensionsLower('a.md', 'b.MD') < 0, 'when extensions are the same except for case, the files sort by name');
assert(compareFileExtensionsLower('a.MD', 'a.md') === compareLocale('MD', 'md'), 'case differences in extensions sort by locale');
// dotfile comparisons
assert(compareFileExtensionsLower('.abc', '.abc') === 0, 'equal dotfiles should be equal');
assert(compareFileExtensionsLower('.md', '.Gitattributes') > 0, 'dotfiles sort alphabetically regardless of case');
assert(compareFileExtensionsLower('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileExtensionsLower('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensionsLower(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileExtensionsLower('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileExtensionsLower('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
assert(compareFileExtensionsLower('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileExtensionsLower('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
// numeric comparisons
assert(compareFileExtensionsLower('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileExtensionsLower('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileExtensionsLower('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsLower('abc2.txt', 'abc10.txt') < 0, 'filenames with numbers should be in numerical order');
assert(compareFileExtensionsLower('abc02.txt', 'abc010.txt') < 0, 'filenames with numbers that have leading zeros sort numerically');
assert(compareFileExtensionsLower('abc1.10.txt', 'abc1.2.txt') > 0, 'numbers with dots between them are treated as two separate numbers, not one decimal number');
assert(compareFileExtensionsLower('abc2.txt2', 'abc1.txt10') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsLower('txt.abc1', 'txt.abc1') === 0, 'equal extensions with numbers should be equal');
assert(compareFileExtensionsLower('txt.abc1', 'txt.abc2') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsLower('txt.abc2', 'txt.abc10') < 0, 'extensions with numbers should be in numerical order even when they are multiple digits long');
assert(compareFileExtensionsLower('a.ext1', 'b.ext1') < 0, 'if equal extensions with numbers, full filenames should be compared');
assert(compareFileExtensionsLower('abc.txt01', 'abc.txt1') > 0, 'extensions with equal numbers should be in shortest-first order');
assert(compareFileExtensionsLower('abc02.txt', 'abc002.txt') < 0, 'filenames with equivalent numbers and leading zeros sort shortest string first');
assert(compareFileExtensionsLower('txt.abc01', 'txt.abc1') > 0, 'extensions with equivalent numbers sort shortest extension first');
assert(compareFileExtensionsLower('a.ext1', 'b.Ext1') < 0, 'if extensions with numbers are equal except for case, full filenames should be compared');
assert(compareFileExtensionsLower('a.ext1', 'a.Ext1') === compareLocale('a.ext1', 'a.Ext1'), 'if extensions with numbers are equal except for case, filenames are sorted in locale order');
//
// Comparisons with different results than compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsLower('z', 'A') < 0, 'z comes before A');
assert(compareFileExtensionsLower('a', 'A') < 0, 'the same letter sorts lowercase first');
assert(compareFileExtensionsLower('â', 'Â') < 0, 'the same accented letter sorts lowercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileExtensionsLower), ['art', 'artichoke', 'Art', 'Artichoke'], 'names with the same root and different cases sort lowercase names first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileExtensionsLower), ['email', 'émail', 'Email', 'Émail'], 'the same base characters with different case or accents sort lowercase names first');
// name plus extension comparisons
assert(compareFileExtensionsLower('a.md', 'A.md') < 0, 'case differences in names sort lowercase first');
assert(compareFileExtensionsLower('art01', 'Art01') < 0, 'a numerically equivalent word of a different case sorts lowercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileExtensionsLower), ['a10.txt', 'a20.txt', 'A2.txt', 'A100.txt'], 'filenames with number and case differences group by case then sort by number');
assert(compareFileExtensionsLower('aggregate.go', 'aggregate_repo.go') > 0, 'when extensions are equal, compares full filenames');
});
test('compareFileNamesUnicode', () => {
//
// Comparisons with the same results as compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesUnicode(null, null) === 0, 'null should be equal');
assert(compareFileNamesUnicode(null, 'abc') < 0, 'null should be come before real values');
assert(compareFileNamesUnicode('', '') === 0, 'empty should be equal');
assert(compareFileNamesUnicode('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileNamesUnicode('z', 'A') > 0, 'z comes after A');
// name plus extension comparisons
assert(compareFileNamesUnicode('file.ext', 'file.ext') === 0, 'equal full names should be equal');
assert(compareFileNamesUnicode('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileNamesUnicode('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileNamesUnicode('bbb.aaa', 'aaa.bbb') > 0, 'files should be compared by names even if extensions compare differently');
// dotfile comparisons
assert(compareFileNamesUnicode('.abc', '.abc') === 0, 'equal dotfile names should be equal');
assert(compareFileNamesUnicode('.env.', '.gitattributes') < 0, 'filenames starting with dots and with extensions should still sort properly');
assert(compareFileNamesUnicode('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileNamesUnicode('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
// dotfile vs non-dotfile comparisons
assert(compareFileNamesUnicode(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileNamesUnicode('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileNamesUnicode('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileNamesUnicode('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
assert(compareFileNamesUnicode('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
// numeric comparisons
assert(compareFileNamesUnicode('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileNamesUnicode('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileNamesUnicode('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileNamesUnicode('a.ext1', 'b.Ext1') < 0, 'if names are different and extensions with numbers are equal except for case, filenames are sorted by unicode full filename');
assert(compareFileNamesUnicode('a.ext1', 'a.Ext1') > 0, 'if names are equal and extensions with numbers are equal except for case, filenames are sorted by unicode full filename');
//
// Comparisons with different results than compareFileNamesDefault
//
// name-only comparisons
assert(compareFileNamesUnicode('Z', 'a') < 0, 'Z comes before a');
assert(compareFileNamesUnicode('a', 'A') > 0, 'the same letter sorts uppercase first');
assert(compareFileNamesUnicode('â', 'Â') > 0, 'the same accented letter sorts uppercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileNamesUnicode), ['Art', 'Artichoke', 'art', 'artichoke'], 'names with the same root and different cases sort uppercase first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileNamesUnicode), ['Email', 'email', 'Émail', 'émail'], 'the same base characters with different case or accents sort in unicode order');
// name plus extension comparisons
assert(compareFileNamesUnicode('aggregate.go', 'aggregate_repo.go') < 0, 'compares the whole name in unicode order, but dot comes before underscore');
// dotfile comparisons
assert(compareFileNamesUnicode('.aaa_env', '.aaa.env') > 0, 'an underscore in a dotfile name will sort after a dot');
// numeric comparisons
assert(compareFileNamesUnicode('abc2.txt', 'abc10.txt') > 0, 'filenames with numbers should be in unicode order even when they are multiple digits long');
assert(compareFileNamesUnicode('abc02.txt', 'abc010.txt') > 0, 'filenames with numbers that have leading zeros sort in unicode order');
assert(compareFileNamesUnicode('abc1.10.txt', 'abc1.2.txt') < 0, 'numbers with dots between them are sorted in unicode order');
assert(compareFileNamesUnicode('abc02.txt', 'abc002.txt') > 0, 'filenames with equivalent numbers and leading zeros sort in unicode order');
assert(compareFileNamesUnicode('abc.txt1', 'abc.txt01') > 0, 'same name plus extensions with equal numbers sort in unicode order');
assert(compareFileNamesUnicode('art01', 'Art01') > 0, 'a numerically equivalent name of a different case compares uppercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileNamesUnicode), ['A100.txt', 'A2.txt', 'a10.txt', 'a20.txt'], 'filenames with number and case differences sort in unicode order');
});
test('compareFileExtensionsUnicode', () => {
//
// Comparisons with the same result as compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsUnicode(null, null) === 0, 'null should be equal');
assert(compareFileExtensionsUnicode(null, 'abc') < 0, 'null should come before real files without extensions');
assert(compareFileExtensionsUnicode('', '') === 0, 'empty should be equal');
assert(compareFileExtensionsUnicode('abc', 'abc') === 0, 'equal names should be equal');
assert(compareFileExtensionsUnicode('z', 'A') > 0, 'z comes after A');
// name plus extension comparisons
assert(compareFileExtensionsUnicode('file.ext', 'file.ext') === 0, 'equal full filenames should be equal');
assert(compareFileExtensionsUnicode('a.ext', 'b.ext') < 0, 'if equal extensions, filenames should be compared');
assert(compareFileExtensionsUnicode('file.aaa', 'file.bbb') < 0, 'files with equal names should be compared by extensions');
assert(compareFileExtensionsUnicode('bbb.aaa', 'aaa.bbb') < 0, 'files should be compared by extension first');
assert(compareFileExtensionsUnicode('a.md', 'b.MD') < 0, 'when extensions are the same except for case, the files sort by name');
assert(compareFileExtensionsUnicode('a.MD', 'a.md') < 0, 'case differences in extensions sort in unicode order');
// dotfile comparisons
assert(compareFileExtensionsUnicode('.abc', '.abc') === 0, 'equal dotfiles should be equal');
assert(compareFileExtensionsUnicode('.md', '.Gitattributes') > 0, 'dotfiles sort alphabetically regardless of case');
assert(compareFileExtensionsUnicode('.env', '.aaa.env') > 0, 'dotfiles sort alphabetically when they contain multiple dots');
assert(compareFileExtensionsUnicode('.env', '.env.aaa') < 0, 'dotfiles with the same root sort shortest first');
// dotfile vs non-dotfile comparisons
assert(compareFileExtensionsUnicode(null, '.abc') < 0, 'null should come before dotfiles');
assert(compareFileExtensionsUnicode('.env', 'aaa.env') < 0, 'dotfiles come before filenames with extensions');
assert(compareFileExtensionsUnicode('.MD', 'a.md') < 0, 'dotfiles sort before lowercase files');
assert(compareFileExtensionsUnicode('.env', 'aaa') < 0, 'dotfiles come before filenames without extensions');
assert(compareFileExtensionsUnicode('.md', 'A.MD') < 0, 'dotfiles sort before uppercase files');
// numeric comparisons
assert(compareFileExtensionsUnicode('1', '1') === 0, 'numerically equal full names should be equal');
assert(compareFileExtensionsUnicode('abc1.txt', 'abc1.txt') === 0, 'equal filenames with numbers should be equal');
assert(compareFileExtensionsUnicode('abc1.txt', 'abc2.txt') < 0, 'filenames with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsUnicode('txt.abc1', 'txt.abc1') === 0, 'equal extensions with numbers should be equal');
assert(compareFileExtensionsUnicode('txt.abc1', 'txt.abc2') < 0, 'extensions with numbers should be in numerical order, not alphabetical order');
assert(compareFileExtensionsUnicode('a.ext1', 'b.ext1') < 0, 'if equal extensions with numbers, full filenames should be compared');
//
// Comparisons with different results than compareFileExtensionsDefault
//
// name-only comparisons
assert(compareFileExtensionsUnicode('Z', 'a') < 0, 'Z comes before a');
assert(compareFileExtensionsUnicode('a', 'A') > 0, 'the same letter sorts uppercase first');
assert(compareFileExtensionsUnicode('â', 'Â') > 0, 'the same accented letter sorts uppercase first');
assert.deepStrictEqual(['artichoke', 'Artichoke', 'art', 'Art'].sort(compareFileExtensionsUnicode), ['Art', 'Artichoke', 'art', 'artichoke'], 'names with the same root and different cases sort uppercase names first');
assert.deepStrictEqual(['email', 'Email', 'émail', 'Émail'].sort(compareFileExtensionsUnicode), ['Email', 'email', 'Émail', 'émail'], 'the same base characters with different case or accents sort in unicode order');
// name plus extension comparisons
assert(compareFileExtensionsUnicode('a.MD', 'a.md') < 0, 'case differences in extensions sort by uppercase extension first');
assert(compareFileExtensionsUnicode('a.md', 'A.md') > 0, 'case differences in names sort uppercase first');
assert(compareFileExtensionsUnicode('art01', 'Art01') > 0, 'a numerically equivalent name of a different case sorts uppercase first');
assert.deepStrictEqual(['a10.txt', 'A2.txt', 'A100.txt', 'a20.txt'].sort(compareFileExtensionsUnicode), ['A100.txt', 'A2.txt', 'a10.txt', 'a20.txt'], 'filenames with number and case differences sort in unicode order');
assert(compareFileExtensionsUnicode('aggregate.go', 'aggregate_repo.go') < 0, 'when extensions are equal, compares full filenames in unicode order');
// numeric comparisons
assert(compareFileExtensionsUnicode('abc2.txt', 'abc10.txt') > 0, 'filenames with numbers should be in unicode order');
assert(compareFileExtensionsUnicode('abc02.txt', 'abc010.txt') > 0, 'filenames with numbers that have leading zeros sort in unicode order');
assert(compareFileExtensionsUnicode('abc1.10.txt', 'abc1.2.txt') < 0, 'numbers with dots between them sort in unicode order');
assert(compareFileExtensionsUnicode('abc2.txt2', 'abc1.txt10') > 0, 'extensions with numbers should be in unicode order');
assert(compareFileExtensionsUnicode('txt.abc2', 'txt.abc10') > 0, 'extensions with numbers should be in unicode order even when they are multiple digits long');
assert(compareFileExtensionsUnicode('abc.txt01', 'abc.txt1') < 0, 'extensions with equal numbers should be in unicode order');
assert(compareFileExtensionsUnicode('abc02.txt', 'abc002.txt') > 0, 'filenames with equivalent numbers and leading zeros sort in unicode order');
assert(compareFileExtensionsUnicode('txt.abc01', 'txt.abc1') < 0, 'extensions with equivalent numbers sort in unicode order');
assert(compareFileExtensionsUnicode('a.ext1', 'b.Ext1') < 0, 'if extensions with numbers are equal except for case, unicode full filenames should be compared');
assert(compareFileExtensionsUnicode('a.ext1', 'a.Ext1') > 0, 'if extensions with numbers are equal except for case, unicode full filenames should be compared');
});
}); | the_stack |
import { privateToPublic } from 'ethereumjs-util';
import { encrypt } from 'ethers/utils/secret-storage';
import { mocked } from 'ts-jest/utils';
import type { MaybeMockedDeep } from 'ts-jest/dist/util/testing';
import { Wallet } from 'ethers/wallet';
import { userInputValidator } from '../../core/src/helpers';
import { bigNumber, warning } from '../../core/src/utils';
import {
addressValidator,
hexSequenceValidator,
} from '../../core/src/validators';
import { hexSequenceNormalizer } from '../../core/src/normalizers';
import SoftwareWallet from '../../software/src/SoftwareWallet';
import {
signTransaction,
signMessage,
verifyMessage,
} from '../../software/src/staticMethods';
import {
REQUIRED_PROPS,
WalletType,
WalletSubType,
} from '../../core/src/constants';
import { walletClass } from '../src/messages';
jest.mock('ethereumjs-util');
jest.mock('ethers/utils');
jest.mock('ethers/wallet');
jest.mock('../../core/src/validators');
jest.mock('../../software/src/staticMethods');
jest.mock('../../core/src/helpers');
jest.mock('../../core/src/normalizers');
jest.mock('../../core/src/utils');
/*
* These values are not correct. Do not use the as reference.
* If the validators wouldn't be mocked, they wouldn't pass.
*/
const address = '0xacab';
const privateKey = '12345678';
const mnemonic = 'all cows are beautiful';
const password = 'mocked-encryption-password';
const keystore = 'mocked-keystore';
const derivationPath = 'mocked-derivation-path';
const chainId = 1337;
const mockedMessage = 'mocked-message';
const mockedMessageData = 'mocked-message-data';
const mockedSignature = 'mocked-signature';
const mockedTransactionObject = {
to: 'mocked-address',
nonce: 1,
value: bigNumber(33),
chainId,
gasLimit: bigNumber(44),
gasPrice: bigNumber(55),
inputData: '1',
};
const mockedMessageObject = {
message: mockedMessage,
messageData: mockedMessageData,
};
const mockedSignatureObject = {
address: '0xacab',
message: mockedMessage,
signature: mockedSignature,
};
const ethersWallet = new Wallet(privateKey);
// @TODO I think we might want to improve this mock typing as we're using private APIs here
const mockedEthersWallet = (ethersWallet as unknown) as MaybeMockedDeep<Wallet>;
const mockedAddressValidator = mocked(addressValidator);
const mockedHexSequenceValidator = mocked(hexSequenceValidator);
const mockedPrivateToPublic = mocked(privateToPublic);
const mockedHexSequenceNormalizer = mocked(hexSequenceNormalizer);
const mockedWarning = mocked(warning);
const mockedEncrypt = mocked(encrypt);
const mockedSignTransaction = mocked(signTransaction);
const mockedUserInputValidator = mocked(userInputValidator);
const mockedSignMessage = mocked(signMessage);
const mockedVerifyMessage = mocked(verifyMessage);
describe('`Software` Wallet Module', () => {
afterEach(() => {
mockedAddressValidator.mockClear();
mockedHexSequenceValidator.mockClear();
mockedPrivateToPublic.mockClear();
mockedHexSequenceNormalizer.mockClear();
mockedWarning.mockClear();
mockedEncrypt.mockClear();
mockedSignTransaction.mockClear();
mockedUserInputValidator.mockClear();
mockedSignMessage.mockClear();
mockedEthersWallet.signMessage.mockClear();
mockedEthersWallet.sign.mockClear();
mockedVerifyMessage.mockClear();
});
describe('`SoftwareWallet` Class', () => {
test('Creates a new wallet', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
expect(testWallet).toBeInstanceOf(SoftwareWallet);
});
test('Throws if it cannot create it', async () => {
mockedAddressValidator.mockImplementationOnce(() => {
throw new Error();
});
expect(() => new SoftwareWallet(ethersWallet, { chainId })).toThrow();
});
test('The instance object has the required (correct) props', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
/*
* Address
*/
expect(testWallet).toHaveProperty('address');
/*
* Private Key
*/
expect(testWallet).toHaveProperty('privateKey');
/*
* Mnemonic
*/
expect(testWallet).toHaveProperty('mnemonic');
/*
* The correct identification type props
*/
expect(testWallet).toHaveProperty('type', WalletType.Software);
expect(testWallet).toHaveProperty('subtype', WalletSubType.Ethers);
/*
* Sign transaction method
*/
expect(testWallet).toHaveProperty('sign');
/*
* Sign message method
*/
expect(testWallet).toHaveProperty('signMessage');
/*
* Verify message method
*/
expect(testWallet).toHaveProperty('verifyMessage');
});
test('Validates the address and private key', () => {
/* eslint-disable-next-line no-new */
new SoftwareWallet(ethersWallet, { chainId });
/*
* Validates the address
*/
expect(addressValidator).toHaveBeenCalled();
expect(addressValidator).toHaveBeenCalledWith(address);
/*
* Validates the private key
*/
expect(hexSequenceValidator).toHaveBeenCalled();
expect(hexSequenceValidator).toHaveBeenCalledWith(privateKey);
});
test('Gets the private key', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await expect(testWallet.getPrivateKey()).resolves.toEqual(privateKey);
});
test('Gets the derivation path', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await expect(testWallet.getDerivationPath()).resolves.toEqual(
derivationPath,
);
});
test('Gets the mnemonic', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await expect(testWallet.getMnemonic()).resolves.toEqual(mnemonic);
});
test('Gets the public key', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
/*
* The mocked function returns the value it's passed, in this case the private
* key, so we can use that to test.
*/
await expect(testWallet.getPublicKey()).resolves.toEqual(privateKey);
});
test('Reverts the public key from the private key', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.getPublicKey();
expect(privateToPublic).toHaveBeenCalled();
});
test('Validates the newly reverted the public key', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.getPublicKey();
expect(hexSequenceValidator).toHaveBeenCalled();
expect(hexSequenceValidator).toHaveBeenCalledWith(privateKey);
});
test('Normalizes the newly reverted the public key', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.getPublicKey();
expect(hexSequenceNormalizer).toHaveBeenCalled();
expect(hexSequenceNormalizer).toHaveBeenCalledWith(privateKey);
});
test('Gets the keystore', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await expect(testWallet.getKeystore(password)).resolves.toEqual(keystore);
});
test("Can't get the keystore if no password was set", async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
/*
* The promise rejects
*/
// @ts-ignore
await expect(testWallet.getKeystore()).rejects.toEqual(
new Error(walletClass.noPassword),
);
});
test("Uses Ethers's `encrypt()` to generate the keystore", async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.getKeystore(password);
expect(encrypt).toHaveBeenCalled();
expect(encrypt).toHaveBeenCalledWith(privateKey, password);
});
test('`sign()` calls the correct static method', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.sign(mockedTransactionObject);
expect(signTransaction).toHaveBeenCalledWith({
...mockedTransactionObject,
callback: expect.any(Function),
});
});
test('Validates `sign` method user input', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.sign(mockedTransactionObject);
/*
* Validate the input
*/
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedTransactionObject,
});
});
test('`signMessages()` calls the correct static method', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.signMessage(mockedMessageObject);
expect(signMessage).toHaveBeenCalledWith({
message: mockedMessage,
messageData: mockedMessageData,
callback: expect.any(Function),
});
});
test('Validate `signMessage` method user input', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.signMessage(mockedMessageObject);
/*
* Validate the input
*/
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedMessageObject,
requiredOr: REQUIRED_PROPS.SIGN_MESSAGE,
});
});
test('`verifyMessages()` calls the correct static method', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.verifyMessage(mockedSignatureObject);
expect(verifyMessage).toHaveBeenCalled();
});
test('Validate `verifyMessage` method user input', async () => {
const testWallet = new SoftwareWallet(ethersWallet, { chainId });
await testWallet.verifyMessage(mockedSignatureObject);
/*
* Validate the input
*/
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedSignatureObject,
requiredAll: REQUIRED_PROPS.VERIFY_MESSAGE,
});
});
});
}); | the_stack |
import { ColumnName, LabelName, StalenessKind, ApproverKind, BlessingKind } from "./basic";
import * as Comments from "./comments";
import * as emoji from "./emoji";
import * as urls from "./urls";
import { PrInfo, BotResult, FileInfo } from "./pr-info";
import { ReviewInfo } from "./pr-info";
import { noNullish, flatten, unique, sameUser, min, sha256, abbrOid, txt } from "./util/util";
import * as dayjs from "dayjs";
import * as advancedFormat from "dayjs/plugin/advancedFormat";
dayjs.extend(advancedFormat);
export interface Actions {
projectColumn?: ColumnName;
labels: LabelName[];
responseComments: Comments.Comment[];
shouldClose: boolean;
shouldMerge: boolean;
shouldUpdateLabels: boolean;
reRunActionsCheckSuiteIDs?: number[];
}
function createDefaultActions(): Actions {
return {
projectColumn: "Other",
labels: [],
responseComments: [],
shouldClose: false,
shouldMerge: false,
shouldUpdateLabels: true,
};
}
function createEmptyActions(): Actions {
return {
labels: [],
responseComments: [],
shouldClose: false,
shouldMerge: false,
shouldUpdateLabels: false,
};
}
type Staleness = {
readonly kind: StalenessKind;
readonly days: number;
readonly state: "fresh" | "attention" | "nearly" | "done";
readonly explanation?: string;
readonly doTimelineActions: (actions: Actions) => void;
}
// used to pass around pr info with additional values
interface ExtendedPrInfo extends PrInfo {
readonly orig: PrInfo;
readonly editsInfra: boolean;
readonly possiblyEditsInfra: boolean; // if we can't be sure since there's too many files
readonly checkConfig: boolean;
readonly authorIsOwner: boolean;
readonly allOwners: string[];
readonly otherOwners: string[];
readonly noOtherOwners: boolean;
readonly tooManyOwners: boolean;
readonly editsOwners: boolean;
readonly canBeSelfMerged: boolean;
readonly hasValidMergeRequest: boolean; // has request following an offer
readonly pendingCriticalPackages: readonly string[]; // critical packages that need owner approval
readonly approved: boolean;
readonly approverKind: ApproverKind;
readonly requireMaintainer: boolean;
readonly blessable: boolean;
readonly blessingKind: BlessingKind;
readonly approvedReviews: (ReviewInfo & { type: "approved" })[];
readonly changereqReviews: (ReviewInfo & { type: "changereq" })[];
readonly staleReviews: (ReviewInfo & { type: "stale" })[];
readonly approvedBy: ApproverKind[];
readonly hasChangereqs: boolean;
readonly failedCI: boolean;
readonly blockedCI: boolean;
readonly staleness?: Staleness;
readonly packages: readonly string[];
readonly hasMultiplePackages: boolean; // not counting infra files
readonly hasDefinitions: boolean;
readonly hasTests: boolean;
readonly isUntested: boolean;
readonly newPackages: readonly string[];
readonly hasNewPackages: boolean;
readonly hasEditedPackages: boolean;
readonly needsAuthorAction: boolean;
readonly reviewColumn: ColumnName;
readonly isAuthor: (user: string) => boolean; // specialized version of sameUser
}
function extendPrInfo(info: PrInfo): ExtendedPrInfo {
const isAuthor = (user: string) => sameUser(user, info.author);
const authorIsOwner = info.pkgInfo.every(p => p.owners.some(isAuthor));
const editsInfra = info.pkgInfo.some(p => p.name === null);
const possiblyEditsInfra = editsInfra || info.tooManyFiles;
const checkConfig = info.pkgInfo.some(p => p.files.some(f => f.kind === "package-meta"));
const allOwners = unique(flatten(info.pkgInfo.map(p => p.owners)));
const otherOwners = allOwners.filter(o => !isAuthor(o));
const noOtherOwners = otherOwners.length === 0;
const tooManyOwners = allOwners.length > 50;
const editsOwners = info.pkgInfo.some(p => p.kind === "edit" && p.addedOwners.length + p.deletedOwners.length > 0);
const packages = noNullish(info.pkgInfo.map(p => p.name));
const hasMultiplePackages = packages.length > 1;
const hasDefinitions = info.pkgInfo.some(p => p.files.some(f => f.kind === "definition"));
const hasTests = info.pkgInfo.some(p => p.files.some(f => f.kind === "test"));
const isUntested = hasDefinitions && !hasTests;
const newPackages = noNullish(info.pkgInfo.map(p => p.kind === "add" ? p.name : null));
const hasNewPackages = newPackages.length > 0;
const hasEditedPackages = packages.length > newPackages.length;
const requireMaintainer = possiblyEditsInfra || checkConfig || hasMultiplePackages || isUntested || hasNewPackages || tooManyOwners;
const blessable = !(hasNewPackages || possiblyEditsInfra || noOtherOwners);
const blessingKind = getBlessingKind();
const approvedReviews = info.reviews.filter(r => r.type === "approved") as ExtendedPrInfo["approvedReviews"];
const changereqReviews = info.reviews.filter(r => r.type === "changereq") as ExtendedPrInfo["changereqReviews"];
const staleReviews = info.reviews.filter(r => r.type === "stale") as ExtendedPrInfo["staleReviews"];
const hasChangereqs = changereqReviews.length > 0;
const approvedBy = getApprovedBy();
const pendingCriticalPackages = getPendingCriticalPackages();
const approverKind = getApproverKind();
const approved = getApproved();
const failedCI = info.ciResult === "fail";
const blockedCI = info.ciResult === "action_required";
const ciResult = // override ciResult: treated as in-progress if it's approved (blockedCI distinguishes it from real unknown)
blockedCI && !possiblyEditsInfra ? "unknown" : info.ciResult;
const canBeSelfMerged = info.ciResult === "pass" && !info.hasMergeConflict
&& (approved || blessingKind === "merge");
const hasValidMergeRequest = !!(info.mergeOfferDate && info.mergeRequestDate && info.mergeRequestDate > info.mergeOfferDate);
const needsAuthorAction = failedCI || info.hasMergeConflict || hasChangereqs;
// => could be dropped from the extended info and replaced with: info.staleness?.kind === "Abandoned"
const staleness = getStaleness();
const reviewColumn = getReviewColumn();
return {
...info, orig: info,
authorIsOwner, editsInfra, possiblyEditsInfra, checkConfig,
allOwners, otherOwners, noOtherOwners, tooManyOwners, editsOwners,
canBeSelfMerged, hasValidMergeRequest, pendingCriticalPackages, approved, approverKind,
requireMaintainer, blessable, blessingKind, failedCI, blockedCI, ciResult, staleness,
packages, hasMultiplePackages, hasDefinitions, hasTests, isUntested, newPackages, hasNewPackages, hasEditedPackages,
approvedReviews, changereqReviews, staleReviews, approvedBy, hasChangereqs,
needsAuthorAction, reviewColumn, isAuthor
};
// Staleness timeline configurations (except for texts that are all in `comments.ts`)
function getStaleness() {
const ownersToPing = otherOwners.length === 0 ? ["«anyone?»"]
: otherOwners.filter(o => !approvedReviews.some(r => o === r.reviewer));
const mkStaleness = makeStaleness(info.now, info.author, ownersToPing);
if (canBeSelfMerged) return info.mergeOfferDate && mkStaleness( // no merge offer yet: avoid the unreviewed timeline
"Unmerged", info.mergeOfferDate, 4, 9, 30, "*REMOVE*");
if (needsAuthorAction) return mkStaleness(
"Abandoned", info.lastActivityDate, 6, 22, 30, "*REMOVE*");
if (!approved) return mkStaleness(
"Unreviewed", info.lastPushDate, 6, 10, 17, "Needs Maintainer Action");
return undefined;
}
function getBlessingKind() {
return info.maintainerBlessed === "Waiting for Author to Merge" ? "merge"
: info.maintainerBlessed === "Waiting for Code Reviews" ? "review"
: undefined;
}
function getApprovedBy() {
return hasChangereqs ? []
: approvedReviews.map(r => r.isMaintainer ? "maintainer"
: allOwners.some(o => sameUser(o, r.reviewer)) ? "owner"
: "other");
}
function getPendingCriticalPackages() {
return noNullish(info.pkgInfo.map(p =>
p.popularityLevel === "Critical" && !p.owners.some(o => approvedReviews.some(r => sameUser(o, r.reviewer)))
? p.name : null));
}
function getApproverKind() {
const blessed = blessable && blessingKind === "review";
const who: ApproverKind =
requireMaintainer ? "maintainer" : ({
"Well-liked by everyone": "other",
"Popular": "owner",
"Critical": "maintainer",
} as const)[info.popularityLevel];
return who === "maintainer" && blessed && !noOtherOwners ? "owner"
: who === "owner" && noOtherOwners ? "maintainer"
: who;
}
function getApproved() {
if (approvedBy.includes("maintainer")) return true; // maintainer approval => no need for anything else
return pendingCriticalPackages.length === 0 && approvedBy.length > 0
&& (approverKind === "other" || approvedBy.includes("maintainer") || approvedBy.includes(approverKind));
}
function getReviewColumn(): ColumnName {
// Get the project column for review with least access
// E.g. let people review, but fall back to the DT maintainers based on the access rights above
return approverKind !== "maintainer" ? "Waiting for Code Reviews"
: blessable ? "Needs Maintainer Review"
: "Needs Maintainer Action";
}
}
export function process(prInfo: BotResult,
extendedCallback: (info: ExtendedPrInfo) => void = _i => {}): Actions {
if (prInfo.type === "remove") {
return {
...createEmptyActions(),
projectColumn: prInfo.isDraft ? "Needs Author Action" : "*REMOVE*",
};
}
const actions = createDefaultActions();
const post = (c: Comments.Comment) => actions.responseComments.push(c);
if (prInfo.type === "error") {
actions.projectColumn = "Other";
actions.labels.push("Mergebot Error");
post(Comments.HadError(prInfo.author, prInfo.message));
return actions;
}
// Collect some additional info
const info = extendPrInfo(prInfo);
extendedCallback(info);
// General labelling and housekeeping
const label = (label: LabelName, cond: unknown = true) => {
const i = actions.labels.indexOf(label);
if (cond && i < 0) actions.labels.push(label);
else if (!cond && i >= 0) actions.labels.splice(i, 1);
};
label("Has Merge Conflict", info.hasMergeConflict);
label("The CI failed", info.failedCI);
label("The CI is blocked", info.ciResult === "action_required");
label("Revision needed", info.hasChangereqs);
label("Critical package", info.popularityLevel === "Critical");
label("Popular package", info.popularityLevel === "Popular");
label("Other Approved", info.approvedBy.includes("other"));
label("Owner Approved",
info.approvedBy.includes("owner")
&& info.pendingCriticalPackages.length === 0); // and *all* owners of critical packages
label("Maintainer Approved", info.approvedBy.includes("maintainer"));
label("New Definition", info.hasNewPackages);
label("Edits Owners", info.editsOwners);
label("Edits Infrastructure", info.editsInfra);
label("Possibly Edits Infrastructure", info.possiblyEditsInfra && !info.editsInfra);
label("Edits multiple packages", info.hasMultiplePackages);
label("Author is Owner", info.authorIsOwner);
label("No Other Owners", info.hasEditedPackages && info.noOtherOwners);
label("Too Many Owners", info.tooManyOwners);
label("Check Config", info.checkConfig);
label("Untested Change", info.isUntested);
label("Huge Change", info.hugeChange);
if (info.staleness?.state === "nearly" || info.staleness?.state === "done") label(info.staleness.kind);
// Update intro comment
post({ tag: "welcome", status: createWelcomeComment(info, post) });
// Ping reviewers when needed
const headCommitAbbrOid = abbrOid(info.headCommitOid);
if (!(info.hasChangereqs || info.approvedBy.includes("owner") || info.approvedBy.includes("maintainer"))) {
if (info.noOtherOwners) {
if (info.popularityLevel !== "Critical") {
const authorIsNewOwner = flatten(info.pkgInfo.map(p => p.addedOwners)).includes(info.author);
post(Comments.PingReviewersOther(info.author, info.authorIsOwner || authorIsNewOwner, urls.review(info.pr_number)));
}
} else if (info.tooManyOwners) {
post(Comments.PingReviewersTooMany(info.otherOwners));
} else {
post(Comments.PingReviewers(info.otherOwners, urls.review(info.pr_number)));
}
}
// Some step should override actions.projectColumn, the default "Other" indicates a problem
// First-timers are blocked from CI runs until approved, this case is for infra edits (require a maintainer)
if (info.ciResult === "action_required") {
actions.projectColumn = "Needs Maintainer Action";
}
// Needs author attention (bad CI, merge conflicts)
else if (info.needsAuthorAction) {
actions.projectColumn = "Needs Author Action";
if (info.hasMergeConflict) post(Comments.MergeConflicted(headCommitAbbrOid, info.author));
if (info.failedCI) post(Comments.CIFailed(headCommitAbbrOid, info.author, info.ciUrl!));
if (info.hasChangereqs) post(Comments.ChangesRequest(headCommitAbbrOid, info.author));
}
// CI is running; default column is Waiting for Reviewers
else if (info.ciResult === "unknown") {
actions.projectColumn = "Waiting for Code Reviews";
if (info.blockedCI) // => we should approve the tests (by rerunning)
actions.reRunActionsCheckSuiteIDs = info.reRunCheckSuiteIDs || undefined;
}
// CI is missing
else if (info.ciResult === "missing") {
// This bot is faster than CI in coming back to give a response, and so the bot starts flipping between
// a 'where is CI'-ish state and a 'got CI deets' state. To work around this, we wait a
// minute since the last timeline push action before label/project states can be updated
if (dayjs(info.now).diff(info.lastPushDate, "minutes") >= 1) {
label("Where is GH Actions?");
} else {
delete actions.projectColumn;
}
}
// CI is green
else if (info.ciResult === "pass") {
if (!info.canBeSelfMerged) {
actions.projectColumn = info.reviewColumn;
} else {
label("Self Merge");
// post even when merging, so it won't get deleted
post(Comments.OfferSelfMerge(info.author,
(info.tooManyOwners || info.hasMultiplePackages) ? [] : info.otherOwners,
headCommitAbbrOid));
if (info.hasValidMergeRequest) {
actions.shouldMerge = true;
actions.projectColumn = "Recently Merged";
} else {
actions.projectColumn = "Waiting for Author to Merge";
}
}
// Ping stale reviewers if any
if (info.staleReviews.length > 0) {
const { abbrOid } = min(info.staleReviews, (l, r) => +l.date - +r.date)!;
const reviewers = info.staleReviews.map(r => r.reviewer);
post(Comments.PingStaleReviewer(abbrOid, reviewers));
}
}
if (!actions.shouldMerge && info.mergeRequestUser) {
post(Comments.WaitUntilMergeIsOK(info.mergeRequestUser, headCommitAbbrOid, urls.workflow, info.mainBotCommentID));
}
// Has it: got no DT tests but is approved by DT modules and basically blocked by the DT maintainers - and it has been over 3 days?
// Send a message reminding them that they can un-block themselves by adding tests.
if (!info.hasTests && !info.hasMultiplePackages && info.approvedBy.includes("owner") && !info.editsInfra
&& info.approverKind === "maintainer" && (info.staleness?.days ?? 0) > 3) {
post(Comments.RemindPeopleTheyCanUnblockPR(info.author, info.approvedReviews.map(r => r.reviewer),
info.ciResult === "pass", headCommitAbbrOid));
}
// Timeline-related actions
info.staleness?.doTimelineActions(actions);
return actions;
}
function makeStaleness(now: Date, author: string, ownersToPing: string[]) { // curried for convenience
return (kind: StalenessKind, since: Date,
freshDays: number, attnDays: number, nearDays: number,
doneColumn: ColumnName) => {
const days = dayjs(now).diff(since, "days");
const state = days <= freshDays ? "fresh" : days <= attnDays ? "attention" : days <= nearDays ? "nearly" : "done";
const kindAndState = `${kind}:${state}`;
const explanation = Comments.StalenessExplanations[kindAndState];
const expires = dayjs(since).add(nearDays, "days").format("MMM Do");
const comment = Comments.StalenessComment(author, ownersToPing, expires)[kindAndState];
const doTimelineActions = (actions: Actions) => {
if (comment !== undefined) {
const tag = state === "done" ? kindAndState
: `${kindAndState}:${since.toISOString().replace(/T.*$/, "")}`;
actions.responseComments.push({ tag, status: comment });
}
if (state === "done") {
if (doneColumn === "*REMOVE*") actions.shouldClose = true; // close when reming
actions.projectColumn = doneColumn;
}
};
return { kind, days, state, explanation, doTimelineActions } as const;
};
}
function createWelcomeComment(info: ExtendedPrInfo, post: (c: Comments.Comment) => void) {
let content = "";
function display(...lines: string[]) {
lines.forEach(line => content += line + "\n");
}
const testsLink = info.hasNewPackages ? urls.testingNewPackages : urls.testingEditedPackages;
const specialWelcome = !info.isFirstContribution ? `` :
txt`| I see this is your first time submitting to DefinitelyTyped 👋
— I'm the local bot who will help you through the process of getting things through.`;
display(`@${info.author} Thank you for submitting this PR!${specialWelcome}`,
``,
`***This is a live comment which I will keep updated.***`);
const criticalNum = info.pkgInfo.reduce((num,pkg) => pkg.popularityLevel === "Critical" ? num+1 : num, 0);
if (criticalNum === 0 && info.popularityLevel === "Critical") throw new Error("Internal Error: unexpected criticalNum === 0");
const requiredApprover =
info.approverKind === "other" ? "type definition owners, DT maintainers or others"
: info.approverKind === "maintainer" ? "a DT maintainer"
: criticalNum <= 1 ? "type definition owners or DT maintainers"
: "all owners or a DT maintainer";
const RequiredApprover = requiredApprover[0]!.toUpperCase() + requiredApprover.substring(1);
if (info.isUntested) {
post(Comments.SuggestTesting(info.author, testsLink));
} else if (info.possiblyEditsInfra) {
display(``,
`This PR ${info.editsInfra ? "touches" : "might touch"} some part of DefinitelyTyped infrastructure, so ${
requiredApprover} will need to review it. This is rare — did you mean to do this?`);
}
const announceList = (what: string, xs: readonly string[]) => `${xs.length} ${what}${xs.length !== 1 ? "s" : ""}`;
const usersToString = (users: string[]) => users.map(u => (info.isAuthor(u) ? "✎" : "") + "@" + u).join(", ");
const reviewLink = (f: FileInfo) =>
`[\`${f.path.replace(/^types\/(.*\/)/, "$1")}\`](${
urls.review(info.pr_number)}/${info.headCommitOid}#diff-${sha256(f.path)})`;
display(``,
`## ${announceList("package", info.packages)} in this PR${
info.editsInfra ? " (and infra files)"
: info.tooManyFiles ? " (and possibly others)"
: ""}`,
``);
if (info.tooManyFiles) {
display(``,
`***Note: this PR touches too many files, check it!***`);
}
let addedSelfToManyOwners = 0;
if (info.pkgInfo.length === 0) {
display(`This PR is editing only infrastructure files!`);
}
for (const p of info.pkgInfo) {
if (p.name === null) continue;
const kind = p.kind === "add" ? " (*new!*)" : p.kind === "delete" ? " (*probably deleted!*)" : "";
const urlPart = p.name.replace(/^(.*?)__(.)/, "@$1/$2");
const authorIsOwner = !p.owners.some(info.isAuthor) ? [] : [`(author is owner)`];
display([`* \`${p.name}\`${kind} —`,
`[on npm](https://www.npmjs.com/package/${urlPart}),`,
`[on unpkg](https://unpkg.com/browse/${urlPart}@latest/)`,
...authorIsOwner].join(" "));
const approvers = info.approvedReviews.filter(r => p.owners.some(o => sameUser(o, r.reviewer))).map(r => r.reviewer);
if (approvers.length) {
display(` - owner-approval: ${usersToString(approvers)}`);
}
const displayOwners = (what: string, owners: string[]) => {
if (owners.length === 0) return;
display(` - ${announceList(`${what} owner`, owners)}: ${usersToString(owners)}`);
};
displayOwners("added", p.addedOwners);
displayOwners("removed", p.deletedOwners);
if (!info.authorIsOwner && p.owners.length >= 4 && p.addedOwners.some(info.isAuthor)) addedSelfToManyOwners++;
let showSuspects = false;
for (const file of p.files) {
if (!file.suspect) continue;
if (!showSuspects) display(` - Config files to check:`);
display(` - ${reviewLink(file)}: ${file.suspect}`);
showSuspects = true;
}
}
if (info.editsInfra) {
display(`* Infra files`);
for (const file of info.pkgInfo.find(p => p.name === null)!.files)
display(` - ${reviewLink(file)}`);
}
if (addedSelfToManyOwners > 0) {
display(``,
txt`@${info.author}: I see that you have added yourself as an
owner${addedSelfToManyOwners > 1 ? " to several packages" : ""},
are you sure you want to [become an owner](${urls.definitionOwners})?`);
}
// Lets the author know who needs to review this
display(``,
`## Code Reviews`,
``);
if (info.blessingKind === "merge") {
display("This PR can be merged.");
} else if (info.hasNewPackages) {
display(txt`This PR adds a new definition, so it needs to be reviewed by
${requiredApprover} before it can be merged.`);
} else if (info.popularityLevel === "Critical" && info.blessingKind !== "review") {
display(txt`Because this is a widely-used package, ${requiredApprover}
will need to review it before it can be merged.`);
} else if (!info.requireMaintainer) {
const and = info.hasDefinitions && info.hasTests
? "and updated the tests (👏)"
: "and there were no type definition changes";
display(txt`Because you edited one package ${and}, I can help you merge this PR
once someone else signs off on it.`);
} else if (info.blessingKind === "review") {
display("This PR can be merged once it's reviewed.");
} else {
if (info.noOtherOwners) {
display(txt`There aren't any other owners of this package,
so ${requiredApprover} will review it.`);
} else if (info.hasMultiplePackages) {
display(txt`Because this PR edits multiple packages, it can be merged
once it's reviewed by ${requiredApprover}.`);
} else if (info.checkConfig) {
display(txt`Because this PR edits the configuration file, it can be merged
once it's reviewed by ${requiredApprover}.`);
} else if (info.hugeChange) {
display(txt`Because this is a huge PR, it can be merged
once it's reviewed by ${requiredApprover}.`);
} else {
display(`This PR can be merged once it's reviewed by ${requiredApprover}.`);
}
}
if (!info.tooManyFiles) {
display(``,
`You can test the changes of this PR [in the Playground](${urls.playground(info.pr_number)}).`);
}
display(``,
`## Status`,
``,
` * ${emoji.failed(info.hasMergeConflict)} No merge conflicts`);
{
const result = emoji.result(info.ciResult);
display(` * ${result.emoji} Continuous integration tests ${result.text}`);
}
const approved = emoji.pending(!(info.approved || info.blessingKind === "merge"));
if (info.hasNewPackages) {
display(` * ${approved} Only ${requiredApprover} can approve changes when there are new packages added`);
} else if (info.editsInfra) {
const infraFiles = info.pkgInfo.find(p => p.name === null)!.files;
const links = infraFiles.map(reviewLink);
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect DT infrastructure (${links.join(", ")})`);
} else if (criticalNum > 1 && info.blessingKind === "review") {
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect more than one package`);
for (const p of info.pkgInfo) {
if (!(p.name && p.popularityLevel === "Critical")) continue;
display(` - ${emoji.pending(info.pendingCriticalPackages.includes(p.name))} ${p.name}`);
}
} else if (info.hasMultiplePackages) {
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect more than one package`);
} else if (!info.requireMaintainer || info.blessingKind === "review") {
display(` * ${approved} Most recent commit is approved by ${requiredApprover}`);
} else if (info.noOtherOwners) {
display(` * ${approved} ${RequiredApprover} can merge changes when there are no other reviewers`);
} else if (info.checkConfig) {
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect module config files`);
} else {
display(` * ${approved} Only ${requiredApprover} can approve changes [without tests](${testsLink})`);
}
display(``);
if (!info.canBeSelfMerged) {
display(txt`Once every item on this list is checked,
I'll ask you for permission to merge and publish the changes.`);
} else {
display(txt`All of the items on the list are green.
**To merge, you need to post a comment including the string "Ready to merge"**
to bring in your changes.`);
}
if (info.staleness && info.staleness.state !== "fresh") {
const expl = info.staleness.explanation;
display(``,
`## Inactive`,
``,
`This PR has been inactive for ${info.staleness.days} days${!expl ? "." : " — " + expl}`);
}
// Remove the 'now' attribute because otherwise the comment would need editing every time
// and that's spammy.
const shallowPresentationInfoCopy = { ...info.orig, now: "-" };
display(``,
`----------------------`,
`<details><summary>Diagnostic Information: What the bot saw about this PR</summary>\n\n${
"```json\n" + JSON.stringify(shallowPresentationInfoCopy, undefined, 2) + "\n```"
}\n\n</details>`);
return content.trimEnd();
} | the_stack |
import { formatUnits } from '@ethersproject/units';
import { multicall } from '../../utils';
import { BigNumber } from '@ethersproject/bignumber';
export const author = 'ursamaritimus';
export const version = '0.3.0';
/*
* PodLeader pool balance. Accepted options:
* - chefAddress: Masterchef contract address
* - pid: Mastechef pool id (starting with zero)
*
* - uniPairAddress: Address of a uniswap pair (or a sushi pair or any other with the same interface)
* - If the uniPairAddress option is provided, converts staked LP token balance to base token balance
* (based on the pair total supply and base token reserve)
* - If uniPairAddress is null or undefined, returns staked token balance of the pool
*
* - tokenAddress: Address of a token for single token Pools.
* - if the uniPairAddress is provided the tokenAddress is ignored.
*
* - weight: Integer multiplier of the result (for combining strategies with different weights, totally optional)
* - weightDecimals: Integer value of number of decimal places to apply to the final result
*
* - token0.address: Address of the uniPair token 0. If defined, the strategy will return the result for the token0.
*
* - token0.weight: Integer multiplier of the result for token0
* - token0.weightDecimals: Integer value of number of decimal places to apply to the result of token0
*
* - token1.address: Address of the uniPair token 1. If defined, the strategy will return the result for the token1.
*
* - token1,weight: Integer multiplier of the result for token1
* - token1.weightDecimal: Integer value of number of decimal places to apply to the result of token1
*
*
* - log: Boolean flag to enable or disable logging to the console (used for debugging purposes during development)
*
*
* Check the examples.json file for how to use the options.
*/
const abi = [
'function userInfo(uint256, address) view returns (uint256 amount, uint256 rewardTokenDebt)',
'function totalSupply() view returns (uint256)',
'function getReserves() view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast)',
'function token0() view returns (address)',
'function token1() view returns (address)',
'function decimals() view returns (uint8)'
];
let log: string[] = [];
let _options;
const getUserInfoCalls = (addresses: any[]) => {
const result: any[] = [];
for (const address of addresses) {
result.push([_options.chefAddress, 'userInfo', [_options.pid, address]]);
}
return result;
};
const getTokenCalls = () => {
const result: any[] = [];
if (_options.uniPairAddress != null) {
result.push([_options.uniPairAddress, 'totalSupply', []]);
result.push([_options.uniPairAddress, 'getReserves', []]);
result.push([_options.uniPairAddress, 'token0', []]);
result.push([_options.uniPairAddress, 'token1', []]);
result.push([_options.uniPairAddress, 'decimals', []]);
if (_options.token0?.address != null) {
result.push([_options.token0.address, 'decimals', []]);
}
if (_options.token1?.address != null) {
result.push([_options.token1.address, 'decimals', []]);
}
} else if (_options.tokenAddress != null) {
result.push([_options.tokenAddress, 'decimals', []]);
}
return result;
};
function arrayChunk<T>(arr: T[], chunkSize: number): T[][] {
const result: T[][] = [];
for (let i = 0, j = arr.length; i < j; i += chunkSize) {
result.push(arr.slice(i, i + chunkSize));
}
return result;
}
async function processValues(
values: any[],
tokenValues: any[],
network: any,
provider: any,
blockTag: string | number
) {
log.push(`values = ${JSON.stringify(values, undefined, 2)}`);
log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`);
printLog();
const poolStaked = values[0][0] as BigNumber;
const weight = BigNumber.from(_options.weight || 1);
const weightDecimals = BigNumber.from(10).pow(
BigNumber.from(_options.weightDecimals || 0)
);
let result = 0;
if (_options.uniPairAddress == null) {
log.push(`poolStaked = ${poolStaked}`);
if (_options.tokenAddress != null) {
const tokenDecimals = BigNumber.from(10).pow(
BigNumber.from(tokenValues[0][0])
);
log.push(`tokenDecimals = ${tokenDecimals}`);
log.push(`decimals = ${_options.decimals}`);
printLog();
result = toFloat(poolStaked.div(tokenDecimals), _options.decimals);
} else {
printLog();
result = toFloat(poolStaked, _options.decimals);
}
} else {
const uniTotalSupply = tokenValues[0][0];
const uniReserve0 = tokenValues[1][0];
const uniReserve1 = tokenValues[1][1];
const uniPairDecimalsIndex: any =
_options.uniPairAddress != null ? 4 : null;
const uniPairDecimalsCount = tokenValues[uniPairDecimalsIndex][0];
const uniPairDecimals =
uniPairDecimalsIndex != null
? BigNumber.from(10).pow(BigNumber.from(uniPairDecimalsCount || 0))
: BigNumber.from(1);
const token0Address = tokenValues[2][0];
const useToken0 =
_options.token0?.address != null &&
_options.token0.address.toString().toLowerCase() ==
token0Address?.toString().toLowerCase();
log.push(`useToken0 = ${useToken0}`);
if (useToken0) {
const token0DecimalsIndex = 5;
log.push(`token0DecimalsIndex = ${token0DecimalsIndex}`);
log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`);
printLog();
result += await GetTokenValue(
network,
provider,
blockTag,
uniTotalSupply,
uniReserve0,
uniPairDecimals,
poolStaked,
tokenValues,
token0Address,
token0DecimalsIndex,
_options.token0?.weight,
_options.token0?.weightDecimals
);
}
const token1Address = tokenValues[3][0];
const useToken1 =
_options.token1?.address != null &&
_options.token1.address.toString().toLowerCase() ==
token1Address?.toString().toLowerCase();
log.push(`useToken1 = ${useToken1}`);
if (useToken1) {
const token1DecimalsIndex = _options.token0?.address != null ? 6 : 5;
log.push(`token1DecimalsIndex = ${token1DecimalsIndex}`);
log.push(`tokenValues = ${JSON.stringify(tokenValues, undefined, 2)}`);
printLog();
result += await GetTokenValue(
network,
provider,
blockTag,
uniTotalSupply,
uniReserve1,
uniPairDecimals,
poolStaked,
tokenValues,
token1Address,
token1DecimalsIndex,
_options.token1?.weight,
_options.token1?.WeightDecimals
);
}
if (!useToken0 && !useToken1) {
log.push(`poolStaked = ${poolStaked}`);
log.push(`uniPairDecimals = ${uniPairDecimals}`);
printLog();
const tokenCount = poolStaked.toNumber() / 10 ** uniPairDecimalsCount;
log.push(`tokenCount = ${tokenCount}`);
result = tokenCount / 10 ** (_options.decimals || 0);
}
}
log.push(`result = ${result}`);
printLog();
result *= weight.toNumber() / weightDecimals.toNumber();
log.push(`weight = ${weight}`);
log.push(`weightDecimals = ${weightDecimals}`);
log.push(`result = ${result}`);
printLog();
return result;
}
function toFloat(value: BigNumber, decimals: any): number {
const decimalsResult = decimals === 0 ? 0 : decimals || 18;
log.push(`toFloat value = ${value}`);
log.push(`toFloat decimals = ${decimals}`);
log.push(`toFloat decimalsResult = ${decimalsResult}`);
printLog();
return parseFloat(formatUnits(value.toString(), decimalsResult));
}
async function GetTokenValue(
network: any,
provider: any,
blockTag: string | number,
uniTotalSupply: any,
uniReserve: any,
uniPairDecimals: BigNumber,
poolStaked: BigNumber,
tokenValues: any[],
tokenAddress: any,
tokenDecimalsIndex: any,
tokenWeight: any,
tokenWeightDecimals: any
) {
const weightDecimals = BigNumber.from(10).pow(
BigNumber.from(tokenWeightDecimals || 0)
);
const weight = BigNumber.from(tokenWeight || 1);
const tokensPerLp = uniReserve.mul(uniPairDecimals).div(uniTotalSupply);
const tokenDecimals =
tokenDecimalsIndex != null
? BigNumber.from(10).pow(
BigNumber.from(tokenValues[tokenDecimalsIndex][0] || 0)
)
: BigNumber.from(1);
log.push(`tokenAddress = ${tokenAddress}`);
log.push(`tokenDecimals = ${tokenDecimals}`);
log.push(`poolStaked = ${poolStaked}`);
log.push(`uniReserve = ${uniReserve}`);
log.push(`uniPairDecimals = ${uniPairDecimals}`);
log.push(`uniTotalSupply = ${uniTotalSupply}`);
log.push(`tokensPerLp = ${tokensPerLp}`);
log.push(`tokenWeight = ${weight}`);
log.push(`tokenWeightDecimals = ${weightDecimals}`);
printLog();
const tokenCount = poolStaked
.mul(tokensPerLp)
.div(tokenDecimals)
.mul(weight)
.div(weightDecimals);
log.push(`tokenCount = ${tokenCount}`);
return toFloat(tokenCount, _options.decimals);
}
function printLog() {
if (_options.log || false) {
console.debug(log);
log = [];
}
}
export async function strategy(
space,
network,
provider,
addresses,
options,
snapshot
) {
_options = options;
const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';
const userInfoCalls = getUserInfoCalls(addresses);
const tokenCalls = getTokenCalls();
const entries = new Map<PropertyKey, any>();
const userInfoResponse = await multicall(
network,
provider,
abi,
userInfoCalls,
{ blockTag }
);
const userInfoChunks = arrayChunk(userInfoResponse, 1);
const tokenResponse = await multicall(network, provider, abi, tokenCalls, {
blockTag
});
for (let i = 0; i < userInfoChunks.length; i++) {
const value = userInfoChunks[i];
const score = await processValues(
value,
tokenResponse,
network,
provider,
blockTag
);
entries.set(addresses[i], score);
}
return Object.fromEntries(entries);
} | the_stack |
import { ethers, providers } from 'ethers'
import { EventEmitter } from 'events'
import { Hop, Token, ChainSlug } from '@hop-protocol/sdk'
import {
getBaseExplorerUrl,
findTransferFromL1CompletedLog,
getTransferSentDetailsFromLogs,
fetchTransferFromL1Completeds,
fetchWithdrawalBondedsByTransferId,
L1Transfer,
networkIdToSlug,
queryFilterTransferFromL1CompletedEvents,
} from 'src/utils'
import { network as defaultNetwork, reactAppNetwork } from 'src/config'
import logger from 'src/logger'
import { formatError } from 'src/utils/format'
import { getNetworkWaitConfirmations } from 'src/utils/networks'
import { sigHashes } from 'src/hooks/useTransaction'
import { getProviderByNetworkName } from 'src/utils/getProvider'
interface ContructorArgs {
hash: string
networkName: string
destNetworkName?: string | null
isCanonicalTransfer?: boolean
pending?: boolean
token?: Token
timestampMs?: number
blockNumber?: number
transferId?: string | null
pendingDestinationConfirmation?: boolean
destTxHash?: string
replaced?: boolean | string
nonce?: number | undefined
from?: string | undefined
to?: string | undefined
}
class Transaction extends EventEmitter {
readonly hash: string
readonly networkName: string
destNetworkName: string | null = null
readonly isCanonicalTransfer: boolean = false
readonly provider: ethers.providers.Provider
destProvider: ethers.providers.Provider | null = null
pending: boolean = true
token: Token | null = null
timestampMs: number
blockNumber?: number
status: null | boolean = null
transferId: string | null = null
pendingDestinationConfirmation: boolean = true
destTxHash: string = ''
replaced: boolean | string = false
methodName: string = ''
nonce?: number | undefined = undefined
from?: string | undefined = undefined
to?: string | undefined = undefined
constructor({
hash,
networkName,
destNetworkName = null,
isCanonicalTransfer,
pending = true,
token,
timestampMs,
transferId = null,
pendingDestinationConfirmation = true,
destTxHash = '',
replaced = false,
nonce,
from,
to,
}: ContructorArgs) {
super()
this.hash = (hash || '').trim().toLowerCase()
this.networkName = (networkName || defaultNetwork).trim().toLowerCase()
// TODO: not sure if changing pendingDestinationConfirmation will have big effects
if (destNetworkName) {
this.destNetworkName = destNetworkName
this.pendingDestinationConfirmation = pendingDestinationConfirmation
this.destProvider = getProviderByNetworkName(destNetworkName)
}
this.provider = getProviderByNetworkName(networkName)
this.timestampMs = timestampMs || Date.now()
this.pending = pending
this.transferId = transferId
this.replaced = replaced
this.destTxHash = destTxHash
this.nonce = nonce
this.from = from
this.to = to
this.token = token || null
this.getTransaction().then((txResponse: providers.TransactionResponse) => {
const funcSig = txResponse?.data?.slice(0, 10)
this.methodName = sigHashes[funcSig]
})
this.receipt().then(async (receipt: providers.TransactionReceipt) => {
const tsDetails = getTransferSentDetailsFromLogs(receipt.logs)
this.blockNumber = receipt.blockNumber
const block = await this.provider.getBlock(receipt.blockNumber)
this.timestampMs = block.timestamp * 1000
if (tsDetails?.chainId) {
this.destNetworkName = networkIdToSlug(tsDetails.chainId)
this.destProvider = getProviderByNetworkName(this.destNetworkName)
}
// Source: L2
if (tsDetails?.transferId) {
this.transferId = tsDetails.transferId
}
this.status = !!receipt.status
const waitConfirmations = getNetworkWaitConfirmations(this.networkName)
if (waitConfirmations && receipt.status === 1 && receipt.confirmations > waitConfirmations) {
this.pending = false
}
this.emit('pending', false, this)
})
if (typeof isCanonicalTransfer === 'boolean') {
this.isCanonicalTransfer = isCanonicalTransfer
}
if (this.pendingDestinationConfirmation && this.destNetworkName) {
const sdk = new Hop(reactAppNetwork)
this.checkIsTransferIdSpent(sdk)
}
}
get explorerLink(): string {
if (this.networkName.startsWith(ChainSlug.Ethereum)) {
return this._etherscanLink()
} else if (this.networkName.startsWith(ChainSlug.Arbitrum)) {
return this._arbitrumLink()
} else if (this.networkName.startsWith(ChainSlug.Optimism)) {
return this._optimismLink()
} else if (this.networkName.startsWith(ChainSlug.Gnosis)) {
return this._gnosisLink()
} else if (this.networkName.startsWith(ChainSlug.Polygon)) {
return this._polygonLink()
} else {
return ''
}
}
get destExplorerLink(): string {
if (!this.destTxHash) return ''
if (this.destNetworkName?.startsWith(ChainSlug.Ethereum)) {
return this._etherscanLink(ChainSlug.Ethereum, this.destTxHash)
} else if (this.destNetworkName?.startsWith(ChainSlug.Arbitrum)) {
return this._arbitrumLink(this.destTxHash)
} else if (this.destNetworkName?.startsWith(ChainSlug.Optimism)) {
return this._optimismLink(this.destTxHash)
} else if (this.destNetworkName?.startsWith(ChainSlug.Gnosis)) {
return this._gnosisLink(this.destTxHash)
} else if (this.destNetworkName?.startsWith(ChainSlug.Polygon)) {
return this._polygonLink(this.destTxHash)
} else {
return ''
}
}
get truncatedHash(): string {
return `${this.hash.substring(0, 6)}…${this.hash.substring(62, 66)}`
}
async receipt() {
return this.provider.waitForTransaction(this.hash)
}
async getTransaction() {
return this.provider.getTransaction(this.hash)
}
async getDestTransaction() {
if (this.destTxHash && this.destProvider) {
return this.destProvider.getTransaction(this.destTxHash)
}
}
async checkIsTransferIdSpent(sdk: Hop) {
if (
!(
this.provider &&
this.token &&
this.destNetworkName &&
this.networkName !== this.destNetworkName
)
) {
logger.warn(`missing provider, token, destNetworkName, or same network:`, this)
return
}
try {
if (!this.pendingDestinationConfirmation) {
return true
}
const receipt = await this.receipt()
// Get the event data (topics)
const tsDetails = getTransferSentDetailsFromLogs(receipt.logs)
const bridge = sdk.bridge(this.token.symbol)
// No transferId because L1 -> L2
if (tsDetails && !tsDetails.transferId) {
const l1Bridge = await bridge.getL1Bridge(this.provider)
// Get the rest of the event data
const decodedData = l1Bridge.interface.decodeEventLog(
tsDetails?.eventName!,
tsDetails?.log.data
)
if ('amount' in decodedData) {
const { amount, deadline } = decodedData
// Query Graph Protocol for TransferFromL1Completed events
const transferFromL1Completeds = await fetchTransferFromL1Completeds(
this.destNetworkName,
tsDetails.recipient,
amount,
deadline
)
if (transferFromL1Completeds?.length) {
const lastTransfer: L1Transfer =
transferFromL1Completeds[transferFromL1Completeds.length - 1]
this.destTxHash = lastTransfer.transactionHash
this.setPendingDestinationConfirmed()
return true
}
// If TheGraph is not working...
const evs = await queryFilterTransferFromL1CompletedEvents(bridge, this.destNetworkName)
if (evs?.length) {
// Find the matching amount
const tfl1Completed = findTransferFromL1CompletedLog(
evs,
tsDetails.recipient,
amount,
deadline
)
if (tfl1Completed) {
this.destTxHash = tfl1Completed.transactionHash
this.setPendingDestinationConfirmed()
return true
}
}
logger.debug(`tx ${tsDetails.txHash.slice(0, 10)} isSpent:`, false)
}
}
// transferId found in event: TransferSent
if (tsDetails?.transferId) {
this.transferId = tsDetails.transferId
}
// Transfer from L2
// transferId found in event: TransferSent
if (this.transferId && this.destNetworkName) {
// Query Graph Protocol for WithdrawalBonded events
const withdrawalBondeds = await fetchWithdrawalBondedsByTransferId(
this.destNetworkName,
this.transferId
)
if (withdrawalBondeds?.length) {
const lastEvent = withdrawalBondeds[withdrawalBondeds.length - 1]
this.destTxHash = lastEvent.transactionHash
}
// L2 -> L1
if (this.destNetworkName === ChainSlug.Ethereum) {
const destL1Bridge = await bridge.getL1Bridge(this.provider)
const isSpent = await destL1Bridge.isTransferIdSpent(this.transferId)
if (isSpent) {
this.setPendingDestinationConfirmed()
}
logger.debug(`isSpent(${this.transferId.slice(0, 10)}: transferId):`, isSpent)
return isSpent
}
// L2 -> L2
const destL2Bridge = await bridge.getL2Bridge(this.destNetworkName)
const isSpent = await destL2Bridge.isTransferIdSpent(this.transferId)
if (isSpent) {
this.setPendingDestinationConfirmed()
}
logger.debug(`isSpent(${this.transferId.slice(0, 10)}: transferId):`, isSpent)
return isSpent
}
} catch (error) {
logger.error(formatError(error))
}
return false
}
public get isBridgeTransfer() {
return ['sendToL2', 'swapAndSend'].includes(this.methodName)
}
private _etherscanLink(networkName: string = this.networkName, txHash: string = this.hash) {
return `${getBaseExplorerUrl(networkName)}/tx/${txHash}`
}
private _arbitrumLink(txHash: string = this.hash) {
return `${getBaseExplorerUrl('arbitrum')}/tx/${txHash}`
}
private _optimismLink(txHash: string = this.hash) {
try {
const url = new URL(getBaseExplorerUrl('optimism'))
return `${url.origin}${url.pathname}/tx/${txHash}${url.search}`
} catch (err) {
return ''
}
}
private _gnosisLink(txHash: string = this.hash) {
return `${getBaseExplorerUrl('gnosis')}/tx/${txHash}`
}
private _polygonLink(txHash: string = this.hash) {
return `${getBaseExplorerUrl('polygon')}/tx/${txHash}`
}
private setPendingDestinationConfirmed() {
this.pendingDestinationConfirmation = false
this.emit('pendingDestinationConfirmation', false, this)
}
toObject() {
const {
hash,
networkName,
pending,
timestampMs,
token,
destNetworkName,
destTxHash,
isCanonicalTransfer,
pendingDestinationConfirmation,
transferId,
replaced,
methodName,
nonce,
from,
to,
} = this
return {
hash,
networkName,
pending,
timestampMs,
token,
destNetworkName,
destTxHash,
isCanonicalTransfer,
pendingDestinationConfirmation,
transferId,
replaced,
methodName,
nonce,
from,
to,
}
}
static fromObject(obj: any) {
const {
hash,
networkName,
pending,
timestampMs,
token,
destNetworkName,
destTxHash,
isCanonicalTransfer,
pendingDestinationConfirmation,
transferId,
replaced,
nonce,
from,
to,
} = obj
return new Transaction({
hash,
networkName,
pending,
timestampMs,
token,
destNetworkName,
destTxHash,
isCanonicalTransfer,
pendingDestinationConfirmation,
transferId,
replaced,
nonce,
from,
to,
})
}
}
export default Transaction | the_stack |
import {
Directive,
ExportDefaultDeclaration,
ExportSpecifier,
Expression,
FunctionDeclaration,
ImportDeclaration,
JSXAttribute,
ModuleDeclaration,
Program,
Property,
SpreadElement,
Statement,
} from 'estree-jsx'
import { analyze } from 'periscopic'
import stringifyPosition from 'unist-util-stringify-position'
import { URL } from 'url'
import create from '../estree/create'
import declarationToExpression from '../estree/declaration-to-expression'
import isDeclaration from '../estree/is-declaration'
import positionFromEstree from '../estree/position-from-estree'
import specifiersToObjectPattern from '../estree/specifiers-to-object-pattern'
export interface Options {
baseUrl?: string
useDynamicImport: boolean
outputFormat: 'program' | 'function-body'
pragma: { name: string; source: string }
pragmaFrag: { name: string; source: string }
jsxImportSource: string
jsxRuntime: 'automatic' | 'classic'
passNamedExportsToLayout: boolean
}
function mergeImports(imports: ImportDeclaration[]) {
const map: Record<string, ImportDeclaration> = imports.reduce(
(all, current) => {
if (typeof current.source.value !== 'string') {
throw new Error(
`expecting source value to be string, got ${current.source.value}`
)
}
if (!all[current.source.value]) {
all[current.source.value] = current
} else {
all[current.source.value].specifiers.push(...current.specifiers)
}
return all
},
{} as Record<string, ImportDeclaration>
)
return Object.values(map)
}
export function estreeWrapInContent(options: Options) {
const {
baseUrl,
outputFormat,
useDynamicImport,
jsxRuntime,
pragma,
pragmaFrag,
jsxImportSource,
passNamedExportsToLayout,
} = options
const pragmas: string[] = []
let content: boolean | undefined
let exportAllCount = 0
let layout: ExportDefaultDeclaration | ExportSpecifier | undefined
const exportedIdentifiers: (string | [string, string])[] = []
const replacement: (Directive | Statement | ModuleDeclaration)[] = []
return (tree, file) => {
const program = tree as Program
if (!tree.comments) tree.comments = []
if (jsxRuntime) {
pragmas.push('@jsxRuntime ' + jsxRuntime)
}
if (jsxRuntime === 'automatic' && jsxImportSource) {
pragmas.push('@jsxImportSource ' + jsxImportSource)
}
if (jsxRuntime === 'classic' && pragma) {
pragmas.push('@jsx ' + pragma.name)
}
if (jsxRuntime === 'classic' && pragmaFrag) {
if (pragmaFrag) {
pragmas.push('@jsxFrag ' + pragmaFrag.name)
}
}
if (pragmas.length > 0) {
tree.comments.unshift({ type: 'Block', value: pragmas.join(' ') })
}
if (jsxRuntime === 'classic') {
const imports: ImportDeclaration[] = [pragma, pragmaFrag].map(
({ name, source }) => ({
type: 'ImportDeclaration',
specifiers: [
{
type: 'ImportSpecifier',
imported: { type: 'Identifier', name },
local: { type: 'Identifier', name },
},
],
source: { type: 'Literal', value: source },
})
)
mergeImports(imports).forEach(handleEsm)
}
// Find the `export default`, the JSX expression, and leave the rest
// (import/exports) as they are.
for (const child of program.body) {
// export default props => <>{props.children}</>
// Treat it as an inline layout declaration.
if (child.type === 'ExportDefaultDeclaration') {
if (layout) {
file.fail(
'Cannot specify multiple layouts (previous: ' +
stringifyPosition(positionFromEstree(layout)) +
')',
positionFromEstree(child),
'recma-document:duplicate-layout'
)
}
layout = child
replacement.push({
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: { type: 'Identifier', name: 'OrgaLayout' },
init: isDeclaration(child.declaration)
? declarationToExpression(child.declaration)
: child.declaration,
},
],
})
}
// export {a, b as c} from 'd'
else if (child.type === 'ExportNamedDeclaration' && child.source) {
const source = child.source
// Remove `default` or `as default`, but not `default as`, specifier.
child.specifiers = child.specifiers.filter((specifier) => {
if (specifier.exported.name === 'default') {
if (layout) {
file.fail(
'Cannot specify multiple layouts (previous: ' +
stringifyPosition(positionFromEstree(layout)) +
')',
positionFromEstree(child),
'recma-document:duplicate-layout'
)
}
layout = specifier
// Make it just an import: `import OrgaLayout from '…'`.
handleEsm(
create(specifier, {
type: 'ImportDeclaration',
specifiers: [
// Default as default / something else as default.
specifier.local.name === 'default'
? {
type: 'ImportDefaultSpecifier',
local: { type: 'Identifier', name: 'OrgaLayout' },
}
: create(specifier.local, {
type: 'ImportSpecifier',
imported: specifier.local,
local: { type: 'Identifier', name: 'OrgaLayout' },
}),
],
source: create(source, {
type: 'Literal',
value: source.value,
}),
})
)
return false
}
return true
})
// If there are other things imported, keep it.
if (child.specifiers.length > 0) {
handleExport(child)
}
}
// export {a, b as c}
// export * from 'a'
else if (
child.type === 'ExportNamedDeclaration' ||
child.type === 'ExportAllDeclaration'
) {
handleExport(child)
} else if (child.type === 'ImportDeclaration') {
handleEsm(child)
} else if (
child.type === 'ExpressionStatement' &&
// @ts-expect-error types are wrong: `JSXElement`/`JSXFragment` are
// `Expression`s.
(child.expression.type === 'JSXFragment' ||
// @ts-expect-error "
child.expression.type === 'JSXElement')
) {
content = true
replacement.push(createOrgaContent(child.expression))
// The following catch-all branch is because plugins might’ve added
// other things.
// Normally, we only have import/export/jsx, but just add whatever’s
// there.
} else {
replacement.push(child)
}
}
if (!content) {
replacement.push(createOrgaContent())
}
exportedIdentifiers.push(['OrgaContent', 'default'])
if (outputFormat === 'function-body') {
replacement.push({
type: 'ReturnStatement',
argument: {
type: 'ObjectExpression',
properties: [
...Array.from({ length: exportAllCount }).map(
(_: undefined, index: number): SpreadElement => ({
type: 'SpreadElement',
argument: {
type: 'Identifier',
name: '_exportAll' + (index + 1),
},
})
),
...exportedIdentifiers.map((d) => {
const prop: Property = {
type: 'Property',
kind: 'init',
method: false,
computed: false,
shorthand: typeof d === 'string',
key: {
type: 'Identifier',
name: typeof d === 'string' ? d : d[1],
},
value: {
type: 'Identifier',
name: typeof d === 'string' ? d : d[0],
},
}
return prop
}),
],
},
})
} else {
replacement.push({
type: 'ExportDefaultDeclaration',
declaration: { type: 'Identifier', name: 'OrgaContent' },
})
}
program.body = replacement
function handleExport(node) {
if (node.type === 'ExportNamedDeclaration') {
// ```js
// export function a() {}
// export class A {}
// export var a = 1
// ```
if (node.declaration) {
exportedIdentifiers.push(
...analyze(node.declaration).scope.declarations.keys()
)
}
// ```js
// export {a, b as c}
// export {a, b as c} from 'd'
// ```
for (const child of node.specifiers) {
exportedIdentifiers.push(child.exported.name)
}
}
handleEsm(node)
}
function handleEsm(node) {
// Rewrite the source of the `import` / `export … from`.
// See: <https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier>
if (baseUrl && node.source) {
let value = String(node.source.value)
try {
// A full valid URL.
value = String(new URL(value))
} catch {
// Relative: `/example.js`, `./example.js`, and `../example.js`.
if (/^\.{0,2}\//.test(value)) {
value = String(new URL(value, baseUrl))
}
// Otherwise, it’s a bare specifiers.
// For example `some-package`, `@some-package`, and
// `some-package/path`.
// These are supported in Node and browsers plan to support them
// with import maps (<https://github.com/WICG/import-maps>).
}
node.source = create(node.source, { type: 'Literal', value })
}
/** @type {Statement|ModuleDeclaration|undefined} */
let replace
/** @type {Expression} */
let init
if (outputFormat === 'function-body') {
if (
// Always have a source:
node.type === 'ImportDeclaration' ||
node.type === 'ExportAllDeclaration' ||
// Source optional:
(node.type === 'ExportNamedDeclaration' && node.source)
) {
if (!useDynamicImport) {
file.fail(
'Cannot use `import` or `export … from` in `evaluate` (outputting a function body) by default: please set `useDynamicImport: true` (and probably specify a `baseUrl`)',
positionFromEstree(node),
'recma-document:invalid-esm-statement'
)
}
// Just for types.
/* c8 ignore next 3 */
if (!node.source) {
throw new Error('Expected `node.source` to be defined')
}
// ```
// import 'a'
// //=> await import('a')
// import a from 'b'
// //=> const {default: a} = await import('b')
// export {a, b as c} from 'd'
// //=> const {a, c: b} = await import('d')
// export * from 'a'
// //=> const _exportAll0 = await import('a')
// ```
init = {
type: 'AwaitExpression',
argument: create(node, {
type: 'ImportExpression',
source: node.source,
}),
}
if (
(node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration') &&
node.specifiers.length === 0
) {
replace = { type: 'ExpressionStatement', expression: init }
} else {
replace = {
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id:
node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration'
? specifiersToObjectPattern(node.specifiers)
: {
type: 'Identifier',
name: '_exportAll' + ++exportAllCount,
},
init,
},
],
}
}
} else if (node.declaration) {
replace = node.declaration
} else {
/** @type {Array.<VariableDeclarator>} */
const declarators = node.specifiers
.filter(
(specifier) => specifier.local.name !== specifier.exported.name
)
.map((specifier) => ({
type: 'VariableDeclarator',
id: specifier.exported,
init: specifier.local,
}))
if (declarators.length > 0) {
replace = {
type: 'VariableDeclaration',
kind: 'const',
declarations: declarators,
}
}
}
} else {
replace = node
}
if (replace) {
replacement.push(replace)
}
}
}
function createOrgaContent(content = undefined): FunctionDeclaration {
const props: JSXAttribute[] = []
const inject = (name: string) => {
props.push({
type: 'JSXAttribute',
name: {
type: 'JSXIdentifier',
name,
},
value: {
type: 'JSXExpressionContainer',
expression: { type: 'Identifier', name },
},
})
}
if (passNamedExportsToLayout) {
exportedIdentifiers.forEach((id) => {
(typeof id === 'string' ? [id] : id).forEach(inject)
})
}
const element = {
type: 'JSXElement',
openingElement: {
type: 'JSXOpeningElement',
name: { type: 'JSXIdentifier', name: 'OrgaLayout' },
attributes: [
...props,
{
type: 'JSXSpreadAttribute',
argument: { type: 'Identifier', name: 'props' },
},
],
selfClosing: false,
},
closingElement: {
type: 'JSXClosingElement',
name: { type: 'JSXIdentifier', name: 'OrgaLayout' },
},
children: [
{
type: 'JSXExpressionContainer',
expression: { type: 'Identifier', name: '_content' },
},
],
}
// @ts-expect-error types are wrong: `JSXElement` is an `Expression`.
const consequent: Expression = element
return {
type: 'FunctionDeclaration',
id: { type: 'Identifier', name: 'OrgaContent' },
params: [
{
type: 'AssignmentPattern',
left: { type: 'Identifier', name: 'props' },
right: { type: 'ObjectExpression', properties: [] },
},
],
body: {
type: 'BlockStatement',
body: [
{
type: 'VariableDeclaration',
kind: 'const',
declarations: [
{
type: 'VariableDeclarator',
id: { type: 'Identifier', name: '_content' },
init: content || { type: 'Literal', value: null },
},
],
},
{
type: 'ReturnStatement',
argument: {
type: 'ConditionalExpression',
test: { type: 'Identifier', name: 'OrgaLayout' },
consequent,
alternate: { type: 'Identifier', name: '_content' },
},
},
],
},
}
}
} | the_stack |
import { isLoadedPhotoSection, LoadedPhotoSection, PhotoId, PhotoSectionId } from 'common/CommonTypes'
import { assertRendererProcess } from 'common/util/ElectronUtil'
import { setLibraryActivePhotoAction, setLibraryHoverPhotoAction, setLibrarySelectionAction } from 'app/state/actions'
import { getPreselectionRange } from 'app/state/selectors'
import { PhotoLibraryPosition, SectionSelectionState, SelectionState } from 'app/state/StateTypes'
import store from 'app/state/store'
import { GridSectionLayout } from 'app/UITypes'
import { getPrevGridLayout } from './LibraryController'
assertRendererProcess()
/**
* The center in x-direction of the photo where the user started navigating using up and down keys.
* This x-position will be used to determine the best matching photo in the row below or above. We keep using the same
* x-position as long the user navigates with up/down, so the same photos will get active when the user changes the
* direction.
*/
let prevUpDownActivePhotoCenterX: number | null
export type MoveDirection = 'left' | 'right' | 'up' | 'down'
export interface LibrarySelectionController {
setActivePhoto(activePhoto: PhotoLibraryPosition | null): void
setHoverPhoto(activePhoto: PhotoLibraryPosition | null): void
moveActivePhoto(direction: MoveDirection): void
setSectionSelected(sectionId: PhotoSectionId, selected: boolean): void
setPhotoSelected(sectionId: PhotoSectionId, photoId: PhotoId, selected: boolean): void
applyPreselection(): void
clearSelection(): void
}
export const defaultLibrarySelectionController: LibrarySelectionController = {
setActivePhoto(activePhoto: PhotoLibraryPosition | null): void {
prevUpDownActivePhotoCenterX = null
store.dispatch(setLibraryActivePhotoAction(activePhoto))
},
setHoverPhoto(hoverPhoto: PhotoLibraryPosition | null): void {
store.dispatch(setLibraryHoverPhotoAction(hoverPhoto))
},
moveActivePhoto(direction: MoveDirection): void {
const state = store.getState()
const { sections } = state.data
const { activePhoto } = state.library
if (!activePhoto) {
return
}
const activeSection = sections.byId[activePhoto.sectionId]
if (!isLoadedPhotoSection(activeSection)) {
return
}
let activePhotoIndex = activeSection.photoIds.indexOf(activePhoto.photoId)
let nextSection: LoadedPhotoSection | undefined = activeSection
let nextPhotoIndex: number | null = activePhotoIndex
if (direction === 'left' || direction === 'right') {
prevUpDownActivePhotoCenterX = null
const indexDelta = (direction === 'left' ? -1 : 1)
nextPhotoIndex += indexDelta
if (nextPhotoIndex < 0 || nextPhotoIndex >= activeSection.count) {
// Try the next section
const activeSectionIndex = sections.ids.indexOf(activePhoto.sectionId)
const nextSectionIndex = activeSectionIndex + indexDelta
const nextSectionId = sections.ids[nextSectionIndex]
const nextSectionCandidate = sections.byId[nextSectionId]
if (isLoadedPhotoSection(nextSectionCandidate)) {
nextSection = nextSectionCandidate
nextPhotoIndex = (direction === 'left' ? (nextSection.count - 1) : 0)
}
}
} else {
const gridLayout = getPrevGridLayout()
const activeSectionIndex = sections.ids.indexOf(activePhoto.sectionId)
const sectionLayout = gridLayout.sectionLayouts[activeSectionIndex]
if (sectionLayout && sectionLayout.boxes) {
const currentPhotoBox = sectionLayout.boxes[activePhotoIndex]
if (currentPhotoBox) {
if (prevUpDownActivePhotoCenterX === null) {
prevUpDownActivePhotoCenterX = currentPhotoBox.left + currentPhotoBox.width / 2
}
const moveUp = direction === 'up'
nextPhotoIndex = findPhotoIndexOfNextRowAtX(prevUpDownActivePhotoCenterX, sectionLayout, moveUp, activePhotoIndex)
if (nextPhotoIndex === null) {
// Try the next section
const nextSectionIndex = activeSectionIndex + (moveUp ? -1 : 1)
const nextSectionLayout = gridLayout.sectionLayouts[nextSectionIndex]
const nextSectionId = sections.ids[nextSectionIndex]
const nextSectionCandidate = sections.byId[nextSectionId]
if (isLoadedPhotoSection(nextSectionCandidate)) {
nextSection = nextSectionCandidate
nextPhotoIndex = findPhotoIndexOfNextRowAtX(prevUpDownActivePhotoCenterX, nextSectionLayout, moveUp)
}
}
}
}
}
const nextPhotoId = (nextPhotoIndex !== null) && nextSection?.photoIds[nextPhotoIndex]
if (nextPhotoId && nextPhotoId !== activePhoto.photoId) {
store.dispatch(setLibraryActivePhotoAction({
sectionId: nextSection.id,
photoId: nextPhotoId,
}))
}
},
setSectionSelected(sectionId: PhotoSectionId, selected: boolean): void {
const state = store.getState()
const prevSelection = state.library.selection
const prevSectionSelection = prevSelection?.sectionSelectionById[sectionId]
let nextSelection: SelectionState | null = null
if (selected) {
const section = state.data.sections.byId[sectionId]
if (section && prevSectionSelection?.selectedPhotosById !== 'all') {
const nextSectionSelection: SectionSelectionState = {
sectionId,
selectedCount: section.count,
selectedPhotosById: 'all'
}
nextSelection = {
totalSelectedCount: (prevSelection?.totalSelectedCount ?? 0) - (prevSectionSelection?.selectedCount ?? 0) + section.count,
sectionSelectionById: {
...prevSelection?.sectionSelectionById,
[sectionId]: nextSectionSelection
}
}
}
} else {
if (prevSelection && prevSectionSelection) {
const nextSectionSelectionById = { ...prevSelection?.sectionSelectionById }
delete nextSectionSelectionById[sectionId]
nextSelection = {
totalSelectedCount: prevSelection.totalSelectedCount - prevSectionSelection.selectedCount,
sectionSelectionById: nextSectionSelectionById
}
}
}
if (nextSelection) {
if (nextSelection.totalSelectedCount === 0) {
nextSelection = null
}
store.dispatch(setLibrarySelectionAction(nextSelection))
}
},
setPhotoSelected(sectionId: PhotoSectionId, photoId: PhotoId, selected: boolean): void {
const state = store.getState()
const prevSelection = state.library.selection
const prevSectionSelection = prevSelection?.sectionSelectionById[sectionId] as SectionSelectionState | undefined
const prevSelectedPhotosById = prevSectionSelection?.selectedPhotosById
const section = state.data.sections.byId[sectionId]
let nextSectionSelection: SectionSelectionState | undefined = prevSectionSelection
if (selected) {
if (section && prevSelectedPhotosById !== 'all' && !prevSelectedPhotosById?.[photoId]) {
const nextSelectedCount = Math.min(section.count, (prevSectionSelection?.selectedCount ?? 0) + 1)
nextSectionSelection = {
sectionId,
selectedCount: nextSelectedCount,
selectedPhotosById:
(nextSelectedCount === section.count) ?
'all' :
{
...prevSelectedPhotosById,
[photoId]: true
}
}
}
} else {
if (isLoadedPhotoSection(section) && prevSectionSelection && (prevSelectedPhotosById === 'all' || prevSelectedPhotosById?.[photoId])) {
if (prevSectionSelection.selectedCount === 1) {
nextSectionSelection = undefined
} else if (prevSelectedPhotosById === 'all') {
const nextSelectedPhotosById: { [K in PhotoId]: true } = {}
for (const sectionPhotoId of section.photoIds) {
if (sectionPhotoId !== photoId) {
nextSelectedPhotosById[sectionPhotoId] = true
}
}
nextSectionSelection = {
sectionId,
selectedCount: section.count - 1,
selectedPhotosById: nextSelectedPhotosById
}
} else {
const nextSelectedPhotosById = { ...prevSelectedPhotosById }
delete nextSelectedPhotosById[photoId]
nextSectionSelection = {
sectionId,
selectedCount: prevSectionSelection.selectedCount - 1,
selectedPhotosById: nextSelectedPhotosById
}
}
}
}
if (nextSectionSelection !== prevSectionSelection) {
const nextTotalSelectedCount = (prevSelection?.totalSelectedCount ?? 0) - (prevSectionSelection?.selectedCount ?? 0) + (nextSectionSelection?.selectedCount ?? 0)
let nextSelection: SelectionState | null = null
if (nextTotalSelectedCount > 0) {
const nextSectionSelectionById = { ...prevSelection?.sectionSelectionById }
if (nextSectionSelection) {
nextSectionSelectionById[sectionId] = nextSectionSelection
} else {
delete nextSectionSelectionById[sectionId]
}
nextSelection = {
totalSelectedCount: (prevSelection?.totalSelectedCount ?? 0) - (prevSectionSelection?.selectedCount ?? 0) + (nextSectionSelection?.selectedCount ?? 0),
sectionSelectionById: nextSectionSelectionById
}
}
store.dispatch(setLibrarySelectionAction(nextSelection, { sectionId, photoId }))
}
},
applyPreselection() {
const state = store.getState()
const preselectionRange = getPreselectionRange(state)
const prevSelection = state.library.selection
const { sections } = state.data
if (!preselectionRange || !prevSelection) {
return
}
const { selected, startSectionIndex, endSectionIndex } = preselectionRange
let nextTotalSelectedCount = prevSelection.totalSelectedCount
const nextSectionSelectionById = { ...prevSelection.sectionSelectionById }
for (let sectionIndex = startSectionIndex; sectionIndex <= endSectionIndex; sectionIndex++) {
const sectionId = sections.ids[sectionIndex]
const section = sections.byId[sectionId]
const prevSectionSelection = prevSelection.sectionSelectionById[sectionId]
let nextSectionSelection: SectionSelectionState | null = null
if (sectionIndex !== startSectionIndex && sectionIndex !== endSectionIndex) {
nextSectionSelection = selected ? { sectionId, selectedCount: section.count, selectedPhotosById: 'all' } : null
} else if (isLoadedPhotoSection(section)) {
const prevSelectedPhotosById = prevSectionSelection?.selectedPhotosById
const startPhotoIndex = (sectionIndex === startSectionIndex) ? preselectionRange.startPhotoIndex : 0
const endPhotoIndex = (sectionIndex === endSectionIndex) ? preselectionRange.endPhotoIndex : (section.count - 1)
let selectedCount = 0
let selectedPhotosById: 'all' | { [K in PhotoId]?: true } = {}
for (let photoIndex = 0; photoIndex < section.photoIds.length; photoIndex++) {
const photoId = section.photoIds[photoIndex]
if ((photoIndex >= startPhotoIndex && photoIndex <= endPhotoIndex) ?
selected :
(prevSelectedPhotosById === 'all' || prevSelectedPhotosById?.[photoId]))
{
selectedCount++
selectedPhotosById[photoId] = true
}
}
if (selectedCount === section.count) {
selectedPhotosById = 'all'
}
nextSectionSelection = (selectedCount) ? { sectionId, selectedCount, selectedPhotosById } : null
}
nextTotalSelectedCount += (nextSectionSelection?.selectedCount ?? 0) - (prevSectionSelection?.selectedCount ?? 0)
if (nextSectionSelection) {
nextSectionSelectionById[sectionId] = nextSectionSelection
} else {
delete nextSectionSelectionById[sectionId]
}
}
store.dispatch(setLibrarySelectionAction(
nextTotalSelectedCount ?
{ totalSelectedCount: nextTotalSelectedCount, sectionSelectionById: nextSectionSelectionById } :
null,
state.library.hoverPhoto || undefined))
},
clearSelection() {
store.dispatch(setLibrarySelectionAction(null))
},
// TODO
// private setActivePhoto(sectionId: PhotoSectionId, photoId: PhotoId) {
// const props = this.props
//
// if (sectionId === props.selectedSectionId && isMac ? event.metaKey : event.ctrlKey) {
// const photoIndex = props.selectedPhotoIds.indexOf(photoId)
// const highlight = props.selectedPhotoIds && photoIndex === -1
// if (highlight) {
// if (photoIndex === -1) {
// props.setSelectedPhotos(sectionId, [ ...props.selectedPhotoIds, photoId ])
// }
// } else {
// props.setSelectedPhotos(sectionId, cloneArrayWithItemRemoved(props.selectedPhotoIds, photoId))
// }
// } else {
// props.setSelectedPhotos(sectionId, [ photoId ])
// }
// }
}
function findPhotoIndexOfNextRowAtX(preferredX: number, sectionLayout: GridSectionLayout | undefined, moveUp: boolean,
startPhotoIndex?: number): number | null
{
if (!sectionLayout || !sectionLayout.boxes) {
return null
}
let startRowTop: number
let firstPhotoIndexToCheck: number
const startPhotoBox = (startPhotoIndex !== undefined) ? sectionLayout.boxes[startPhotoIndex] : undefined
if (startPhotoBox) {
startRowTop = startPhotoBox.top
firstPhotoIndexToCheck = startPhotoIndex! + (moveUp ? -1 : 1)
} else {
startRowTop = -1
firstPhotoIndexToCheck = moveUp ? (sectionLayout.boxes.length - 1) : 0
}
let prevRowTop = -1
let bestBoxCenterXDiff = Number.POSITIVE_INFINITY
let bestPhotoIndex: number | null = null
for (let boxIndex = firstPhotoIndexToCheck; moveUp ? boxIndex >= 0 : boxIndex < sectionLayout.boxes.length; moveUp ? boxIndex-- : boxIndex++) {
const box = sectionLayout.boxes[boxIndex]
if (box.top !== startRowTop) {
if (prevRowTop === -1) {
prevRowTop = box.top
} else if (box.top !== prevRowTop) {
// We are one row too far
break
}
const boxCenterX = box.left + box.width / 2
const boxCenterXDiff = Math.abs(preferredX - boxCenterX)
if (boxCenterXDiff < bestBoxCenterXDiff) {
bestBoxCenterXDiff = boxCenterXDiff
bestPhotoIndex = boxIndex
}
}
}
return bestPhotoIndex
} | the_stack |
import { Injectable } from '@angular/core';
import { Cordova, AwesomeCordovaNativePlugin, Plugin } from '@awesome-cordova-plugins/core';
declare let clevertap: any;
/**
* @name CleverTap
* @description
* Cordova Plugin that wraps CleverTap SDK for Android and iOS
* @usage
* ```typescript
* import { CleverTap } from '@awesome-cordova-plugins/clevertap/ngx';
*
* constructor(private clevertap: CleverTap) { }
*
* ```
*/
@Plugin({
pluginName: 'CleverTap',
plugin: 'clevertap-cordova',
pluginRef: 'CleverTap',
repo: 'https://github.com/CleverTap/clevertap-cordova',
platforms: ['Android', 'iOS'],
})
@Injectable()
export class CleverTap extends AwesomeCordovaNativePlugin {
/**
* notify device ready
* NOTE: in iOS use to be notified of launch Push Notification or Deep Link
* in Android use only in android phonegap build projects
*
* @returns {Promise<any>}
*/
@Cordova()
notifyDeviceReady(): Promise<any> {
return;
}
/*******************
* Personalization
******************/
/**
* Personalization
* Enables the Personalization API
*
* @returns {Promise<any>}
*/
@Cordova()
enablePersonalization(): Promise<any> {
return;
}
/**
* Personalization
* Disables the Personalization API
*
* @returns {Promise<any>}
*/
@Cordova()
disablePersonalization(): Promise<any> {
return;
}
/**
* Enables tracking opt out for the currently active user.
*
* @param optOut {boolean}
* @returns {Promise<any>}
*/
@Cordova()
setOptOut(optOut: boolean): Promise<any> {
return;
}
/**
* Sets CleverTap SDK to offline mode.
*
* @param offline {boolean}
* @returns {Promise<any>}
*/
@Cordova()
setOffline(offline: boolean): Promise<any> {
return;
}
/**
* Enables the reporting of device network related information, including IP address. This reporting is disabled by default.
*
* @param enable {boolean}
* @returns {Promise<any>}
*/
@Cordova()
enableDeviceNetworkInfoReporting(enable: boolean): Promise<any> {
return;
}
/*******************
* Push
******************/
/**
* Registers for push notifications
*
* @returns {Promise<any>}
*/
@Cordova()
registerPush(): Promise<any> {
return;
}
/**
* Sets the device's push token
*
* @param token {string}
* @returns {Promise<any>}
*/
@Cordova()
setPushToken(token: string): Promise<any> {
return;
}
/**
* Sets the device's Xiaomi push token
*
* @param token {string}
* @returns {Promise<any>}
*/
@Cordova()
setPushXiaomiToken(token: string): Promise<any> {
return;
}
/**
* Sets the device's Baidu push token
*
* @param token {string}
* @returns {Promise<any>}
*/
@Cordova()
setPushBaiduToken(token: string): Promise<any> {
return;
}
/**
* Sets the device's Huawei push token
*
* @param token {string}
* @returns {Promise<any>}
*/
@Cordova()
setPushHuaweiToken(token: string): Promise<any> {
return;
}
/**
* Create Notification Channel for Android O+
*
* @param extras {any}
* @returns {Promise<any>}
*/
@Cordova()
createNotification(extras: any): Promise<any> {
return;
}
/**
* Create Notification Channel for Android O+
*
* @param channelID {string}
* @param channelName {string}
* @param channelDescription {string}
* @param importance {number}
* @param showBadge {boolean}
* @returns {Promise<any>}
*/
@Cordova()
createNotificationChannel(
channelID: string,
channelName: string,
channelDescription: string,
importance: number,
showBadge: boolean
): Promise<any> {
return;
}
/**
* Create Notification Channel for Android O+
*
* @param channelID {string}
* @param channelName {string}
* @param channelDescription {string}
* @param importance {number}
* @param showBadge {boolean}
* @param sound {string}
* @returns {Promise<any>}
*/
@Cordova()
createNotificationChannelWithSound(
channelID: string,
channelName: string,
channelDescription: string,
importance: number,
showBadge: boolean,
sound: string
): Promise<any> {
return;
}
/**
* Create Notification Channel with Group ID for Android O+
*
* @param channelID {string}
* @param channelName {string}
* @param channelDescription {string}
* @param importance {number}
* @param groupId {string}
* @param showBadge {boolean}
* @param sound {string}
* @returns {Promise<any>}
*/
@Cordova()
createNotificationChannelWithGroupId(
channelID: string,
channelName: string,
channelDescription: string,
importance: number,
groupId: string,
showBadge: boolean
): Promise<any> {
return;
}
/**
* Create Notification Channel with Group ID for Android O+
*
* @param channelID {string}
* @param channelName {string}
* @param channelDescription {string}
* @param importance {number}
* @param groupId {string}
* @param showBadge {boolean}
* @param sound
* @returns {Promise<any>}
*/
@Cordova()
createNotificationChannelWithGroupIdAndSound(
channelID: string,
channelName: string,
channelDescription: string,
importance: number,
groupId: string,
showBadge: boolean,
sound: string
): Promise<any> {
return;
}
/**
* Create Notification Channel Group for Android O+
*
* @param groupID {string}
* @param groupName {string}
* @returns {Promise<any>}
*/
@Cordova()
createNotificationChannelGroup(groupID: string, groupName: string): Promise<any> {
return;
}
/**
* Delete Notification Channel for Android O+
*
* @param channelID {string}
* @returns {Promise<any>}
*/
@Cordova()
deleteNotificationChannel(channelID: string): Promise<any> {
return;
}
/**
* Delete Notification Group for Android O+
*
* @param groupID {string}
* @returns {Promise<any>}
*/
@Cordova()
deleteNotificationChannelGroup(groupID: string): Promise<any> {
return;
}
/*******************
* Events
******************/
/**
* Record Screen View
*
* @param screenName {string}
* @returns {Promise<any>}
*/
@Cordova()
recordScreenView(screenName: string): Promise<any> {
return;
}
/**
* Record Event with Name
*
* @param eventName {string}
* @returns {Promise<any>}
*/
@Cordova()
recordEventWithName(eventName: string): Promise<any> {
return;
}
/**
* Record Event with Name and Event properties
*
* @param eventName {string}
* @param eventProps {any}
* @returns {Promise<any>}
*/
@Cordova()
recordEventWithNameAndProps(eventName: string, eventProps: any): Promise<any> {
return;
}
/**
* Record Charged Event with Details and Items
*
* @param details {any} object with transaction details
* @param items {any} array of items purchased
* @returns {Promise<any>}
*/
@Cordova()
recordChargedEventWithDetailsAndItems(details: any, items: any): Promise<any> {
return;
}
/**
* Get Event First Time
*
* @param eventName {string}
* callback returns epoch seconds or -1
* @returns {Promise<any>}
*/
@Cordova()
eventGetFirstTime(eventName: string): Promise<any> {
return;
}
/**
* Get Event Last Time
*
* @param eventName {string}
* callback returns epoch seconds or -1
* @returns {Promise<any>}
*/
@Cordova()
eventGetLastTime(eventName: string): Promise<any> {
return;
}
/**
* Get Event Number of Occurrences
*
* @param eventName {string}
* calls back with int or -1
* @returns {Promise<any>}
*/
@Cordova()
eventGetOccurrences(eventName: string): Promise<any> {
return;
}
/**
* Get Event Details
*
* @param eventName {string}
* calls back with object {"eventName": <string>, "firstTime":<epoch seconds>, "lastTime": <epoch seconds>, "count": <int>} or empty object
* @returns {Promise<any>}
*/
@Cordova()
eventGetDetails(eventName: string): Promise<any> {
return;
}
/**
* Get Event History
* calls back with object {"eventName1":<event1 details object>, "eventName2":<event2 details object>}
*
* @returns {Promise<any>}
*/
@Cordova()
getEventHistory(): Promise<any> {
return;
}
/*******************
* Profiles
******************/
/**
* Get the device location if available.
* On iOS:
* Calling this will prompt the user location permissions dialog.
* Please be sure to include the NSLocationWhenInUseUsageDescription key in your Info.plist.
* Uses desired accuracy of kCLLocationAccuracyHundredMeters.
* If you need background location updates or finer accuracy please implement your own location handling.
* On Android:
* Requires Location Permission in AndroidManifest e.g. "android.permission.ACCESS_COARSE_LOCATION"
* You can use location to pass it to CleverTap via the setLocation API
* for, among other things, more fine-grained geo-targeting and segmentation purposes.
* Note: on iOS the call to CleverTapSDK must be made on the main thread due to LocationManager restrictions, but the CleverTapSDK method itself is non-blocking.
* calls back with {lat:lat, lon:lon} lat and lon are floats
*
* @returns {Promise<any>}
*/
@Cordova()
getLocation(): Promise<any> {
return;
}
/**
* Set location
*
* @param lat {number}
* @param lon {number}
* @returns {Promise<any>}
*/
@Cordova()
setLocation(lat: number, lon: number): Promise<any> {
return;
}
/**
* Creates a separate and distinct user profile identified by one or more of Identity, Email, FBID or GPID values,
* and populated with the key-values included in the profile dictionary.
* If your app is used by multiple users, you can use this method to assign them each a unique profile to track them separately.
* If instead you wish to assign multiple Identity, Email, FBID and/or GPID values to the same user profile,
* use profileSet rather than this method.
* If none of Identity, Email, FBID or GPID is included in the profile dictionary,
* all properties values will be associated with the current user profile.
* When initially installed on this device, your app is assigned an "anonymous" profile.
* The first time you identify a user on this device (whether via onUserLogin or profileSet),
* the "anonymous" history on the device will be associated with the newly identified user.
* Then, use this method to switch between subsequent separate identified users.
* Please note that switching from one identified user to another is a costly operation
* in that the current session for the previous user is automatically closed
* and data relating to the old user removed, and a new session is started
* for the new user and data for that user refreshed via a network call to CleverTap.
* In addition, any global frequency caps are reset as part of the switch.
*
* @param profile {any} object
* @returns {Promise<any>}
*/
@Cordova()
onUserLogin(profile: any): Promise<any> {
return;
}
/**
* Set profile attributes
*
* @param profile {any} object
* @returns {Promise<any>}
*/
@Cordova()
profileSet(profile: any): Promise<any> {
return;
}
/**
* Get User Profile Property
*
* @param propertyName {string}
* calls back with value of propertyName or false
* @returns {Promise<any>}
*/
@Cordova()
profileGetProperty(propertyName: string): Promise<any> {
return;
}
/**
* @deprecated This method is deprecated. Use getCleverTapID() instead.
* Get a unique CleverTap identifier suitable for use with install attribution providers.
* calls back with unique CleverTap attribution identifier
*
* @returns {Promise<any>}
*/
@Cordova()
profileGetCleverTapAttributionIdentifier(): Promise<any> {
return;
}
/**
* @deprecated This method is deprecated. Use getCleverTapID() instead.
* Get User Profile CleverTapID
* calls back with CleverTapID or false
*
* @returns {Promise<any>}
*/
@Cordova()
profileGetCleverTapID(): Promise<any> {
return;
}
/**
* Get User Profile CleverTapID
* calls back with CleverTapID
*
* @returns {Promise<any>}
*/
@Cordova()
getCleverTapID(): Promise<any> {
return;
}
/**
* Remove the property specified by key from the user profile
*
* @param key {string}
* @returns {Promise<any>}
*/
@Cordova()
profileRemoveValueForKey(key: string): Promise<any> {
return;
}
/**
* Method for setting a multi-value user profile property
*
* @param key {string}
* @param values {any} array of strings
* @returns {Promise<any>}
*/
@Cordova()
profileSetMultiValues(key: string, values: any): Promise<any> {
return;
}
/**
* Method for adding a value to a multi-value user profile property
*
* @param key {string}
* @param value {string}
* @returns {Promise<any>}
*/
@Cordova()
profileAddMultiValue(key: string, value: string): Promise<any> {
return;
}
/**
* Method for adding values to a multi-value user profile property
*
* @param key {string}
* @param values {any} array of strings
* @returns {Promise<any>}
*/
@Cordova()
profileAddMultiValues(key: string, values: any): Promise<any> {
return;
}
/**
* Method for removing a value from a multi-value user profile property
*
* @param key {string}
* @param value {string}
* @returns {Promise<any>}
*/
@Cordova()
profileRemoveMultiValue(key: string, value: string): Promise<any> {
return;
}
/**
* Method for removing a value from a multi-value user profile property
*
* @param key {string}
* @param values {any} array of strings
* @returns {Promise<any>}
*/
@Cordova()
profileRemoveMultiValues(key: string, values: any): Promise<any> {
return;
}
/**
* Method for incrementing a value for a single-value profile property (if it exists).
*
* @param key {string}
* @param value {number}
* @returns {Promise<any>}
*/
@Cordova()
profileIncrementValueBy(key: string,value: number): Promise<any> {
return;
}
/**
* Method for decrementing a value for a single-value profile property (if it exists).
*
* @param key {string}
* @param value {number}
* @returns {Promise<any>}
*/
@Cordova()
profileDecrementValueBy(key: string,value: number): Promise<any> {
return;
}
/*******************
* In-App Controls
******************/
/**
* Suspends and saves inApp notifications until 'resumeInAppNotifications' is called for current session.
* Automatically resumes InApp notifications display on CleverTap shared instance creation.
* Pending inApp notifications are displayed only for current session.
*
* @returns {Promise<any>}
*/
@Cordova()
suspendInAppNotifications(): Promise<any> {
return;
}
/**
* Discards inApp notifications until 'resumeInAppNotifications' is called for current session.
* Automatically resumes InApp notifications display on CleverTap shared instance creation.
* Pending inApp notifications are not displayed.
*/
@Cordova()
discardInAppNotifications(): Promise<any> {
return;
}
/**
* Resumes displaying inApps notifications and shows pending inApp notifications if any.
*
* @returns {Promise<any>}
*/
@Cordova()
resumeInAppNotifications(): Promise<any> {
return;
}
/*******************
* Session
******************/
/**
* Get Session Elapsed Time
* calls back with seconds
*
* @returns {Promise<any>}
*/
@Cordova()
sessionGetTimeElapsed(): Promise<any> {
return;
}
/**
* Get Session Total Visits
* calls back with with int or -1
*
* @returns {Promise<any>}
*/
@Cordova()
sessionGetTotalVisits(): Promise<any> {
return;
}
/**
* Get Session Screen Count
* calls back with with int
*
* @returns {Promise<any>}
*/
@Cordova()
sessionGetScreenCount(): Promise<any> {
return;
}
/**
* Get Session Previous Visit Time
* calls back with with epoch seconds or -1
*
* @returns {Promise<any>}
*/
@Cordova()
sessionGetPreviousVisitTime(): Promise<any> {
return;
}
/**
* Get Sesssion Referrer UTM details
* object {"source": <string>, "medium": <string>, "campaign": <string>} or empty object
*
* @returns {Promise<any>}
*/
@Cordova()
sessionGetUTMDetails(): Promise<any> {
return;
}
/**
* Call this to manually track the utm details for an incoming install referrer
*
* @param source {string}
* @param medium {string}
* @param campaign {string}
* @returns {Promise<any>}
*/
@Cordova()
pushInstallReferrer(source: string, medium: string, campaign: string): Promise<any> {
return;
}
/****************************
* Notification Inbox methods
****************************/
/**
* Call this method to initialize the App Inbox
*/
@Cordova()
initializeInbox(): Promise<any> {
return;
}
/**
* Call this method to get the count of unread Inbox messages
*/
@Cordova()
getInboxMessageUnreadCount(): Promise<any> {
return;
}
/**
* Call this method to get the count of total Inbox messages
*/
@Cordova()
getInboxMessageCount(): Promise<any> {
return;
}
/**
* Call this method to open the App Inbox
*
* @param styleConfig : any or empty object
*/
@Cordova()
showInbox(styleConfig: any): Promise<any> {
return;
}
/**
* Call this to Fetch all Inbox Messages
*
* @returns {Promise<any>}
*/
@Cordova()
getAllInboxMessages(): Promise<any> {
return;
}
/**
* Call this to Fetch all Unread Inbox Messages
*
* @returns {Promise<any>}
*/
@Cordova()
getUnreadInboxMessages(): Promise<any> {
return;
}
/**
* Call this to Fetch Inbox Message For Id
*
* @param messageId {string}
* @returns {Promise<any>}
*/
@Cordova()
getInboxMessageForId(messageId: string): Promise<any> {
return;
}
/**
* Call this to Delete Inbox Message For Id
*
* @param messageId {string}
* @returns {Promise<any>}
*/
@Cordova()
deleteInboxMessageForId(messageId: string): Promise<any> {
return;
}
/**
* Call this to Mark Read Inbox Message For Id
*
* @param messageId {string}
* @returns {Promise<any>}
*/
@Cordova()
markReadInboxMessageForId(messageId: string): Promise<any> {
return;
}
/**
* Call this to Mark Push Inbox Notification Viewed Event for Id
*
* @param messageId {string}
* @returns {Promise<any>}
*/
@Cordova()
pushInboxNotificationViewedEventForId(messageId: string): Promise<any> {
return;
}
/**
* Call this to Mark Push Inbox Notification Clicked Event for Id
*
* @param messageId {string}
* @returns {Promise<any>}
*/
@Cordova()
pushInboxNotificationClickedEventForId(messageId: string): Promise<any> {
return;
}
/**
* Call this to Get All Display Units
*
* @returns {Promise<any>}
*/
@Cordova()
getAllDisplayUnits(): Promise<any> {
return;
}
/**
* Call this to Get Display Unit For Id
*
* @param id {string}
* @returns {Promise<any>}
*/
@Cordova()
getDisplayUnitForId(id: string): Promise<any> {
return;
}
/**
* Call this to Push DisplayUnit Viewed Event for ID
*
* @param id {string}
* @returns {Promise<any>}
*/
@Cordova()
pushDisplayUnitViewedEventForID(id: string): Promise<any> {
return;
}
/**
* Call this to Push DisplayUnit Clicked Event for ID
*
* @param id {string}
* @returns {Promise<any>}
*/
@Cordova()
pushDisplayUnitClickedEventForID(id: string): Promise<any> {
return;
}
/**
* Call this to Get Feature Flag for key
*
* @param key {string}
* @param defaultValue {string}
* @returns {Promise<any>}
*/
@Cordova()
getFeatureFlag(key: string, defaultValue: string): Promise<any> {
return;
}
/**
* Call this to Set Defaults for Product Config
*
* @param defaults {any}
* @returns {Promise<any>}
*/
@Cordova()
setDefaultsMap(defaults: any): Promise<any> {
return;
}
/**
* Call this for Product Config Fetch
*
* @param defaults {any}
* @returns {Promise<any>}
*/
@Cordova()
fetch(): Promise<any> {
return;
}
/**
* Call this for Product Config Fetch with Min Interval
*
* @param timeInterval {number}
* @returns {Promise<any>}
*/
@Cordova()
fetchWithMinimumFetchIntervalInSeconds(timeInterval: number): Promise<any> {
return;
}
/**
* Call this for Product Config Activate
*
* @returns {Promise<any>}
*/
@Cordova()
activate(): Promise<any> {
return;
}
/**
* Call this for Product Config Fetch and Activate
*
* @returns {Promise<any>}
*/
@Cordova()
fetchAndActivate(): Promise<any> {
return;
}
/**
* Call this to set Product Config Fetch with Min Interval
*
* @param timeInterval {number}
* @returns {Promise<any>}
*/
@Cordova()
setMinimumFetchIntervalInSeconds(timeInterval: number): Promise<any> {
return;
}
/**
* Call this to Get Last Fetch Time Interval
*
* @returns {Promise<any>}
*/
@Cordova()
getLastFetchTimeStampInMillis(): Promise<any> {
return;
}
/**
* Call this to Get String
*
* @param key {string}
* @returns {Promise<any>}
*/
@Cordova()
getString(key: string): Promise<any> {
return;
}
/**
* Call this to Get Boolean
*
* @param key {string}
* @returns {Promise<any>}
*/
@Cordova()
getBoolean(key: string): Promise<any> {
return;
}
/**
* Call this to Get Long
*
* @param key {string}
* @returns {Promise<any>}
*/
@Cordova()
getLong(key: string): Promise<any> {
return;
}
/**
* Call this to Get Double
*
* @param key {string}
* @returns {Promise<any>}
*/
@Cordova()
getDouble(key: string): Promise<any> {
return;
}
/**
* Call this to Reset Product Config
*
* @returns {Promise<any>}
*/
@Cordova()
reset(): Promise<any> {
return;
}
/*******************
* Developer Options
******************/
/**
* 0 is off, 1 is info, 2 is debug, default is 1
*
* @param level {number}
* @returns {Promise<any>}
*/
@Cordova()
setDebugLevel(level: number): Promise<any> {
return;
}
} | the_stack |
import {
createEffect,
createComputed,
createRenderEffect,
createMemo,
Accessor,
on,
createSignal
// } from "../types/index";
} from "../src";
class Animal {
#animal = null;
}
class Dog extends Animal {
#dog = null;
}
//////////////////////////////////////////////////////////////////////////
// createEffect ////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
createEffect(() => {
return "hello";
}, "init");
createEffect(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, "init");
createEffect((prev: string) => {
const p: string = prev;
return p + "hello";
}, "init");
createEffect(() => {
return "hello";
}, 123);
createEffect(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, 123);
createEffect((prev: number | string) => {
const p: number | string = prev;
return p + "hello";
}, 123);
createEffect(() => {
return "hello";
});
createEffect(_prev => {
return "hello";
});
createEffect(_prev => {});
createEffect((v: number | string): number => 123, "asdf");
createEffect((num: number | undefined): number | undefined => 123);
createEffect((num?: number): number | undefined => 123);
createEffect<number>((v: number | string): number => 123, 123);
createEffect<number | string>((v: number | string): number => 123, 123);
// @ts-expect-error undefined initial value not assignable to input parameter
createEffect((v: number | boolean): number | boolean => false);
createEffect((v: Animal): Dog => new Dog(), new Dog());
createEffect((v: Animal): Dog => new Dog(), new Animal());
createEffect(
// @ts-expect-error the Animal arg is not assignable to the Dog parameter
(v: Dog): Dog => new Dog(),
new Animal()
);
// @ts-expect-error the missing second arg is undefined, and undefined is not assignable to the Animal parameter
createEffect((v: Animal): Dog => new Dog());
createEffect<number | boolean>(
// @ts-expect-error because if number|boolean were returnable from the passed-in function, it wouldn't be assignable to the input of that function.
// TODO can we improve this? Technically, the return type of the function is always assignable to number|boolean, which is really all we should care about.
(v: number | string): number => 123,
123
);
createEffect((v: number | string): number => 123, "asdf");
createEffect((v: number) => 123, 123);
createEffect(
(v?: number) => {
return 123;
},
123,
{}
);
createEffect(() => 123);
createEffect(() => {});
createEffect(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {}
);
// @ts-expect-error undefined initial value is not assignable to the number parameter
createEffect((v: number) => 123);
createEffect(() => {
return 123;
}, 123);
createEffect(() => {
return 123;
}, undefined);
createEffect((v: number) => 123, 123);
createEffect((v?: number) => 123, undefined);
createEffect<number | undefined>(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
123
);
createEffect<number | undefined>(
// @ts-expect-error the void return is not assignable to the explicitly specified number|undefined return
v => {},
123
);
createEffect(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
undefined
);
createEffect(v => {}); // useless, but ok
// @ts-expect-error the void return is not assignable to the number|undefined parameter
createEffect((v: number) => {});
createEffect(
// @ts-expect-error void return not assignable to number parameter
(v: number) => {},
123
);
createEffect(
// @ts-expect-error undefined second arg is not assignable to the number parameter
(v: number) => {},
undefined
);
// @ts-expect-error undefined second arg is not assignable to the number parameter
createEffect((v: number) => 123, undefined);
// @ts-expect-error void not assignable to number|undefined
createEffect((v?: number) => {}, 123);
//////////////////////////////////////////////////////////////////////////
// createComputed ////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
createComputed(() => {
return "hello";
}, "init");
createComputed(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, "init");
createComputed((prev: string) => {
const p: string = prev;
return p + "hello";
}, "init");
createComputed(() => {
return "hello";
}, 123);
createComputed(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, 123);
createComputed((prev: number | string) => {
const p: number | string = prev;
return p + "hello";
}, 123);
createComputed(() => {
return "hello";
});
createComputed(_prev => {
return "hello";
});
createComputed(_prev => {});
createComputed((v: number | string): number => 123, "asdf");
createComputed((num: number | undefined): number | undefined => 123);
createComputed((num?: number): number | undefined => 123);
createComputed<number>((v: number | string): number => 123, 123);
createComputed<number | string>((v: number | string): number => 123, 123);
// @ts-expect-error undefined initial value not assignable to input parameter
createComputed((v: number | boolean): number | boolean => false);
createComputed((v: Animal): Dog => new Dog(), new Dog());
createComputed((v: Animal): Dog => new Dog(), new Animal());
createComputed(
// @ts-expect-error the Animal arg is not assignable to the Dog parameter
(v: Dog): Dog => new Dog(),
new Animal()
);
// @ts-expect-error the missing second arg is undefined, and undefined is not assignable to the Animal parameter
createComputed((v: Animal): Dog => new Dog());
createComputed<number | boolean>(
// @ts-expect-error because if number|boolean were returnable from the passed-in function, it wouldn't be assignable to the input of that function.
// TODO can we improve this? Technically, the return type of the function is always assignable to number|boolean, which is really all we should care about.
(v: number | string): number => 123,
123
);
createComputed((v: number | string): number => 123, "asdf");
createComputed((v: number) => 123, 123);
createComputed(
(v?: number) => {
return 123;
},
123,
{}
);
createComputed(() => 123);
createComputed(() => {});
createComputed(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {}
);
// @ts-expect-error undefined initial value is not assignable to the number parameter
createComputed((v: number) => 123);
createComputed(() => {
return 123;
}, 123);
createComputed(() => {
return 123;
}, undefined);
createComputed((v: number) => 123, 123);
createComputed((v?: number) => 123, undefined);
createComputed<number | undefined>(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
123
);
createComputed<number | undefined>(
// @ts-expect-error the void return is not assignable to the explicitly specified number|undefined return
v => {},
123
);
createComputed(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
undefined
);
createComputed(v => {}); // useless, but ok
// @ts-expect-error the void return is not assignable to the number|undefined parameter
createComputed((v: number) => {});
createComputed(
// @ts-expect-error void return not assignable to number parameter
(v: number) => {},
123
);
createComputed(
// @ts-expect-error undefined second arg is not assignable to the number parameter
(v: number) => {},
undefined
);
// @ts-expect-error undefined second arg is not assignable to the number parameter
createComputed((v: number) => 123, undefined);
// @ts-expect-error void not assignable to number|undefined
createComputed((v?: number) => {}, 123);
//////////////////////////////////////////////////////////////////////////
// createRenderEffect ////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
createRenderEffect(() => {
return "hello";
}, "init");
createRenderEffect(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, "init");
createRenderEffect((prev: string) => {
const p: string = prev;
return p + "hello";
}, "init");
createRenderEffect(() => {
return "hello";
}, 123);
createRenderEffect(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, 123);
createRenderEffect((prev: number | string) => {
const p: number | string = prev;
return p + "hello";
}, 123);
createRenderEffect(() => {
return "hello";
});
createRenderEffect(_prev => {
return "hello";
});
createRenderEffect(_prev => {});
createRenderEffect((v: number | string): number => 123, "asdf");
createRenderEffect((num: number | undefined): number | undefined => 123);
createRenderEffect((num?: number): number | undefined => 123);
createRenderEffect<number>((v: number | string): number => 123, 123);
createRenderEffect<number | string>((v: number | string): number => 123, 123);
// @ts-expect-error undefined initial value not assignable to input parameter
createRenderEffect((v: number | boolean): number | boolean => false);
createRenderEffect((v: Animal): Dog => new Dog(), new Dog());
createRenderEffect((v: Animal): Dog => new Dog(), new Animal());
createRenderEffect(
// @ts-expect-error the Animal arg is not assignable to the Dog parameter
(v: Dog): Dog => new Dog(),
new Animal()
);
// @ts-expect-error the missing second arg is undefined, and undefined is not assignable to the Animal parameter
createRenderEffect((v: Animal): Dog => new Dog());
createRenderEffect<number | boolean>(
// @ts-expect-error because if number|boolean were returnable from the passed-in function, it wouldn't be assignable to the input of that function.
// TODO can we improve this? Technically, the return type of the function is always assignable to number|boolean, which is really all we should care about.
(v: number | string): number => 123,
123
);
createRenderEffect((v: number | string): number => 123, "asdf");
createRenderEffect((v: number) => 123, 123);
createRenderEffect(
(v?: number) => {
return 123;
},
123,
{}
);
createRenderEffect(() => 123);
createRenderEffect(() => {});
createRenderEffect(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {}
);
// @ts-expect-error undefined initial value is not assignable to the number parameter
createRenderEffect((v: number) => 123);
createRenderEffect(() => {
return 123;
}, 123);
createRenderEffect(() => {
return 123;
}, undefined);
createRenderEffect((v: number) => 123, 123);
createRenderEffect((v?: number) => 123, undefined);
createRenderEffect<number | undefined>(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
123
);
createRenderEffect<number | undefined>(
// @ts-expect-error the void return is not assignable to the explicitly specified number|undefined return
v => {},
123
);
createRenderEffect(
// @ts-expect-error the void return is not assignable to the number|undefined parameter
(v?: number) => {},
undefined
);
createRenderEffect(v => {}); // useless, but ok
// @ts-expect-error the void return is not assignable to the number|undefined parameter
createRenderEffect((v: number) => {});
createRenderEffect(
// @ts-expect-error void return not assignable to number parameter
(v: number) => {},
123
);
createRenderEffect(
// @ts-expect-error undefined second arg is not assignable to the number parameter
(v: number) => {},
undefined
);
// @ts-expect-error undefined second arg is not assignable to the number parameter
createRenderEffect((v: number) => 123, undefined);
// @ts-expect-error void not assignable to number|undefined
createRenderEffect((v?: number) => {}, 123);
//////////////////////////////////////////////////////////////////////////
// createMemo ////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
createMemo((v: number | string): number => 123, "asdf");
createMemo((num: number | undefined): number | undefined => 123);
// Return type should be `Accessor<number | undefined>`
// Not sure how to write a test for this, becacuse `Accessor<number>` is assignable to `Accessor<number | undefined>`.
let c1 = createMemo((num?: number): number | undefined => undefined);
let n = c1();
// @ts-expect-error n might be undefined
const n2 = n + 3; // n is undefined
createMemo<number>((v: number | string): number => 123, 123);
createMemo<number | string>((v: number | string): number => 123, 123);
// @ts-expect-error undefined initial value not assignable to input parameter
createMemo((v: number | boolean): number | boolean => false);
createMemo((v: Animal): Dog => new Dog(), new Dog());
createMemo((v: Animal): Dog => new Dog(), new Animal());
createMemo(
// @ts-expect-error the Animal arg is not assignable to the Dog parameter
(v: Dog): Dog => new Dog(),
new Animal()
);
// @ts-expect-error the missing second arg is undefined, and undefined is not assignable to the Animal parameter
createMemo((v: Animal): Dog => new Dog());
createMemo<number | boolean>(
// @ts-expect-error because if number|boolean were returnable from the passed-in function, it wouldn't be assignable to the input of that function.
// TODO can we improve this? Technically, the return type of the function is always assignable to number|boolean, which is really all we should care about.
(v: number | string): number => 123,
123
);
createMemo((v: number | string): number => 123, "asdf");
createMemo((v: number) => 123, 123);
const mv0 = createMemo(() => {
return "hello";
}, "init");
const mv0t: string = mv0();
const mv1 = createMemo(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string = prev;
return p + "hello";
}, "init");
const mv1t: string = mv1();
const mv11 = createMemo((prev: string) => {
const p: string = prev;
return p + "hello";
}, "init");
const mv11t: string = mv11();
const mv2 = createMemo(() => {
return "hello";
}, 123);
const mv2t: string = mv2();
const mv3 = createMemo(prev => {
// @ts-expect-error FIXME prev is inferred as unknown, so not assignable to string|number. Can we make it inferred?
const p: string | number = prev;
return p + "hello";
}, 123);
const mv3t: string = mv3();
const mv31 = createMemo((prev: string | number) => {
const p: string | number = prev;
return p + "hello";
}, 123);
const mv31t: string = mv31();
const mv4 = createMemo(() => {
return "hello";
});
const mv4t: string = mv4();
const mv5 = createMemo(_prev => {
return "hello";
});
const mv5t: string = mv5();
const mv6 = createMemo(() => {});
const mv6t: void = mv6();
const mv7 = createMemo(_prev => {});
const mv7t: void = mv7();
const v1 = createMemo(
(v?: number) => {
return 123;
},
123,
{}
);
const v2 = createMemo(() => 123);
// @ts-expect-error number return value can not be assigned to the input string arg
const v3 = createMemo((v: string) => 123);
const v4 = createMemo(v => 123);
const v5 = createMemo(() => {});
// @ts-expect-error because void return of the effect function cannot be assigned to number | undefined of the effect function's parameter
const v6 = createMemo((v?: number) => {});
const v7 = createMemo(() => 123, 123);
const v8 = createMemo(() => 123, undefined);
// @ts-expect-error undefined initial value is not assignable to the number parameter
const v9 = createMemo((v: number) => 123);
const v10 = createMemo((v: number) => 123, 123);
const v11 = createMemo((v?: number) => 123, 123);
const v12 = createMemo((v?: number) => 123, undefined);
const v13 = createMemo((v?: number) => 123, 123);
const v14 = createMemo<number | undefined>(
// @ts-expect-error because void return of the effect function cannot be assigned to number | undefined of the effect function's parameter
(v?: number) => {},
123
);
const v15 = createMemo<number | undefined>(
// @ts-expect-error effect function does not match the specified memo type
v => {},
123
);
const v16 = createMemo(
// @ts-expect-error because void return of the effect function cannot be assigned to number | undefined of the effect function's parameter
(v?: number) => {},
undefined
);
const v17 = createMemo(v => {});
// @ts-expect-error because void return of the effect function cannot be assigned to number | undefined of the effect function's parameter
const v18 = createMemo((v: number) => {});
const v19 = createMemo(
// @ts-expect-error void is not assignable to anything
(v: number) => {},
123
);
const v20 = createMemo(
// @ts-expect-error clearly undefined can't be assigned into the input parameter of the effect function
(v: number) => {},
undefined
);
const v21 =
// @ts-expect-error and this one makes complete sense, undefined cannot go into the effect function's number parameter.
createMemo((v: number) => 123, undefined);
const v22 = createMemo(
// @ts-expect-error because void return of the effect function cannot be assigned to number | undefined of the effect function's parameter
(v?: number) => {},
123
);
const m: Accessor<number> = createMemo(
(v?: number) => {
return 123;
},
123,
{}
);
const m2: Accessor<number | undefined> = createMemo(() => 123);
// @ts-expect-error void can't be assigned to anything!
const m3: //
Accessor<undefined> = createMemo(() => {});
const m4: Accessor<void> = createMemo(() => {});
const m5: Accessor<number | undefined> = createMemo(
// @ts-expect-error void can't be assigned to anything!
(v?: number) => {}
);
const mm5 = createMemo(
// @ts-expect-error void can't be assigned to anything!
(v?: number) => {}
);
const m6: Accessor<number> = createMemo(() => 123, 123);
const m7: Accessor<number | undefined> = createMemo(() => 123, undefined);
const m8: Accessor<number> = createMemo((v: number) => 123, 123);
const m9: Accessor<number | undefined> = createMemo((v?: number) => 123, undefined);
const m10: Accessor<number | undefined> = createMemo<number | undefined>(
// @ts-expect-error void can't be assigned to anything!
(v?: number) => {},
123
);
const m11: Accessor<number | undefined> = createMemo<number | undefined>(
// @ts-expect-error void can't be assigned to anything!
v => {},
123
);
const m12: Accessor<number | undefined> = createMemo(
// @ts-expect-error void can't be assigned to anything!
(v?: number) => {},
undefined
);
const m13 = createMemo((v?: number): number | undefined => 123, undefined);
const testm13: Accessor<number | undefined> = m13;
const m14: Accessor<number> = createMemo((v?: number): number => 123, undefined);
const m15: Accessor<number> =
// @ts-expect-error undefined initial value is not assignable to the number parameter
createMemo((v: number): number => 123);
const m16: Accessor<number> =
// @ts-expect-error undefined initial value can't be assign to the number parameter
createMemo((v: number): number => 123, undefined);
const m17: Accessor<number> =
// @ts-expect-error no overload matches because the second string arg cannot be assigned to the number|boolean parameter.
createMemo((v: number | boolean): number => 123, "asdf");
const m18: Accessor<number> =
// @ts-expect-error undefined initial value is not assignable to the number parameter
createMemo((v: number | boolean): number => 123);
const m19: Accessor<number> =
// @ts-expect-error undefined initial value is not assignable to the number parameter
createMemo((v: number | string): number => 123);
// @ts-expect-error because the number return cannot be assigned to the boolean|string parameter
const m20: Accessor<number> =
// @ts-expect-error because the number return cannot be assigned to the boolean|string parameter
createMemo((v: boolean | string): number => 123);
const m21: Accessor<number> =
// @ts-expect-error because the second boolean arg cannot be assigned to the number|string parameter.
createMemo((v: number | string): number => 123, true);
const m22: Accessor<number> = createMemo((v: number | string): number => 123, "asdf");
const m23: Accessor<number> = createMemo((v?: number | string): number => 123, undefined);
const m24: Accessor<number> =
// @ts-expect-error true not assignable to number|string
createMemo((v: number | string): number => 123, true);
const asdf = createMemo<number | undefined>(() => num());
// @ts-expect-error Accessor<number | undefined> is not assignable to Accessor<number>
const asdf2: //
Accessor<number> = asdf;
//////////////////////////////////////////////////////////////////////////
// on ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
const one = () => 123;
const two = () => Boolean(Math.random());
const ef = on([one, two], ([one, two], [prevOne, prevTwo], computed): number => {
const _one: number = one;
const _two: boolean = two;
const _prevone: number = prevOne;
const _prevtwo: boolean = prevTwo;
// @ts-expect-error FIXME computed type is unknown, should be `number`.
const _computed: number = computed;
return one + +two;
});
//////////////////////////////////////////////////////////////////////////
// test explicit generic args ////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
const [num, setN] = createSignal(1);
const [bool, setBool] = createSignal(true);
const a1: Accessor<number> = createMemo<number>(() => num());
createEffect<number>(() => num());
createComputed<number>(() => num());
createRenderEffect<number>(() => num());
const a11: Accessor<number> = createMemo<number>((v?: number) => num());
createEffect<number>((v?: number) => num());
createComputed<number>((v?: number) => num());
createRenderEffect<number>((v?: number) => num());
const a12: Accessor<number> = createMemo<number>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createEffect<number>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createComputed<number>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createRenderEffect<number>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
//
const a2: Accessor<number | undefined> = createMemo<number | undefined>(() => num());
createEffect<number | undefined>(() => num());
createComputed<number | undefined>(() => num());
createRenderEffect<number | undefined>(() => num());
const a21: Accessor<number | undefined> = createMemo<number | undefined>((v?: number) => num());
createEffect<number | undefined>((v?: number) => num());
createComputed<number | undefined>((v?: number) => num());
createRenderEffect<number | undefined>((v?: number) => num());
const a22: Accessor<number | undefined> = createMemo<number | undefined>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createEffect<number | undefined>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createComputed<number | undefined>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createRenderEffect<number | undefined>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
//
const a3: Accessor<number | boolean> = createMemo<number | boolean>(() => bool());
createEffect<number | boolean>(() => bool());
createComputed<number | boolean>(() => bool());
createRenderEffect<number | boolean>(() => bool());
// FIXME
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
const a31: Accessor<number | boolean> = createMemo<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createEffect<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createComputed<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createRenderEffect<number | boolean>((v?: number) => num());
const a32: Accessor<number | boolean> = createMemo<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createEffect<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createComputed<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createRenderEffect<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
//
const a4: Accessor<number | boolean> = createMemo<number | boolean>(() => bool());
createEffect<number | boolean>(() => bool());
createComputed<number | boolean>(() => bool());
createRenderEffect<number | boolean>(() => bool());
// FIXME
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
const a41: Accessor<number | boolean> = createMemo<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createEffect<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createComputed<number | boolean>((v?: number) => num());
// @ts-expect-error this rare edge cases is not handled yet. The number return from the effect function should be assignable to number|boolean, while the initial value should be inferred as number|undefined.
createRenderEffect<number | boolean>((v?: number) => num());
const a42: Accessor<number | boolean> = createMemo<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createEffect<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createComputed<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
createRenderEffect<number | boolean>(
// @ts-expect-error the function accepts only `number` but the initial value will be `undefined`.
(v: number) => num()
);
//
const a5: Accessor<number | boolean> = createMemo<number | boolean>(() => bool(), false);
createEffect<number | boolean>(() => bool(), false);
createComputed<number | boolean>(() => bool(), false);
createRenderEffect<number | boolean>(() => bool(), false);
// 👽
const a51: Accessor<number | boolean> = createMemo<number | boolean>(
() => bool(),
// @ts-expect-error FIXME edge case: string is not assignable to to number|boolean, but really it should say that the effect function expects 0 args but 1 arg was provided.
"foo"
);
createEffect<number | boolean>(
() => bool(),
// @ts-expect-error FIXME edge case: string is not assignable to to number|boolean, but really it should say that the effect function expects 0 args but 1 arg was provided.
"foo"
);
createComputed<number | boolean>(
() => bool(),
// @ts-expect-error FIXME edge case: string is not assignable to to number|boolean, but really it should say that the effect function expects 0 args but 1 arg was provided.
"foo"
);
createRenderEffect<number | boolean>(
() => bool(),
// @ts-expect-error FIXME edge case: string is not assignable to to number|boolean, but really it should say that the effect function expects 0 args but 1 arg was provided.
"foo"
);
//////////////////////////////////////////////////////////////////////////
// on ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//
const a6: Accessor<number | boolean> = createMemo<number | boolean>(
() =>
// @ts-expect-error string return is not assignable to number|boolean
"foo"
);
createEffect<number | boolean>(
() =>
// @ts-expect-error string return is not assignable to number|boolean
"foo"
);
createComputed<number | boolean>(
() =>
// @ts-expect-error string return is not assignable to number|boolean
"foo"
);
createRenderEffect<number | boolean>(
() =>
// @ts-expect-error string return is not assignable to number|boolean
"foo"
);
// more type tests... | the_stack |
import {WasmType} from "../core/wasm-type";
import {WasmOpcode} from "../opcode";
import {WasmRuntimeProperty} from "./wasm-runtime-local";
import {ByteArray} from "../../../utils/bytearray";
import {WasmSignature} from "../core/wasm-signature";
import {Terminal} from "../../../utils/terminal";
import {WasmGlobal} from "../core/wasm-global";
/**
* Created by n.vinayakan on 02.06.17.
*/
export class WasmStackItem {
constructor(public type: WasmType, public value: number) { }
}
export class WasmStack {
list: WasmStackItem[];
constructor() {
this.list = [];
}
get length(): int32 {
return this.list.length;
}
push(item: WasmStackItem): void {
this.list.push(item);
}
pop(silent: boolean = false): WasmStackItem {
if (this.list.length === 0) {
if (!silent) {
let error = `Stack is empty`;
Terminal.warn(error);
// throw error;
}
}
return this.list.pop();
}
clear() {
this.list = [];
}
}
export class WasmRuntimeFunction {
module: string;
name: string;
isImport: boolean;
signature: WasmSignature;
locals: WasmRuntimeProperty[];
constructor() {
}
get returnType(): WasmType {
return this.signature.returnType;
}
execute(...param): WasmStackItem {
throw "Wasm runtime function execution not implemented!";
}
}
export class WasmStackContext {
stack: WasmStack;
opcodes: number[];
lastOpcode: number;
constructor(public fn: WasmRuntimeFunction) {
if (fn === undefined) {
Terminal.error("Undefined runtime function")
debugger;
}
this.stack = new WasmStack();
this.opcodes = [];
}
}
/**
* Wasm stack tracer, this is not a stack machine. this will not execute functions
* instead trace state of stack while emitting function body.
*/
export class WasmStackTracer {
memory: ByteArray;
globals: WasmStackItem[];
context: WasmStackContext = null;
functions: WasmRuntimeFunction[];
constructor() {
this.memory = new ByteArray();
}
setGlobals(globals: WasmGlobal[]) {
this.globals = [];
globals.forEach(global => {
this.globals.push(new WasmRuntimeProperty(global.type, global.name));
});
}
startFunction(index: int32) {
this.context = new WasmStackContext(this.functions[index]);
}
endFunction(skip: boolean = false) {
if (!skip && this.context.stack.length > 0) {
if (this.context.fn.returnType === WasmType.VOID) {
let error = `Function '${this.context.fn.name}' does not return anything but stack is not empty. Stack contains ${this.context.stack.length} items`
Terminal.error(error);
// throw error;
}
}
this.context = null;
}
callFunction(index: int32) {
let fn = this.functions[index];
if (fn === undefined) {
let error = "Function not defined at index " + index;
Terminal.error(error);
throw error;
}
let returnType = fn.returnType;
for (let i: int32 = 0; i < fn.signature.argumentTypes.length; i++) {
this.context.stack.pop();
}
if (returnType !== WasmType.VOID) {
this.context.stack.push(new WasmStackItem(returnType, undefined));
}
}
pushOpcode(opcode: number): string {
if (this.context !== null) {
this.context.opcodes.push(opcode);
this.context.lastOpcode = opcode;
return this.updateStack(opcode);
}
return null;
}
pushValue(value: number): string {
if (this.context !== null) {
return this.updateStack(this.context.lastOpcode, value);
}
return null;
}
private updateStack(opcode: number, value?: number): string {
let type: WasmType = null;
if (opcode !== undefined && opcode !== null) {
type = getOprandType(opcode);
}
switch (opcode) {
case WasmOpcode.CALL:
if (value !== undefined) {
this.callFunction(value);
let fn = this.functions[value];
return `call ${fn.name ? "$" + fn.name : value}`;
}
break;
case WasmOpcode.END:
this.context.stack.clear();
return "end";
case WasmOpcode.RETURN:
if (this.context.stack.length == 0) {
Terminal.warn(`Empty stack on return in function ${this.context.fn.name}`);
}
return "return";
case WasmOpcode.I32_CONST:
case WasmOpcode.I64_CONST:
case WasmOpcode.F32_CONST:
case WasmOpcode.F64_CONST:
if (value !== undefined) {
this.context.stack.push(new WasmStackItem(type, value));
return `${WasmOpcode[opcode]} ${value}`;
}
break;
case WasmOpcode.SET_LOCAL:
if (value !== undefined) {
if (this.context.fn.locals.length <= value) {
let errorMsg = `Local index ${value} out of range ${this.context.fn.locals.length} in function ${this.context.fn.name}`;
Terminal.error(errorMsg);
throw errorMsg;
} else {
let a = this.context.stack.pop();
let local = this.context.fn.locals[value];
if (a !== undefined) {
this.context.fn.locals[value].value = a.value;
}
return `${WasmOpcode[opcode]} $${local.name}`;
}
}
break;
case WasmOpcode.GET_LOCAL:
if (value !== undefined) {
let a = this.context.fn.locals[value];
this.context.stack.push(new WasmStackItem(a.type, a.value));
return `${WasmOpcode[opcode]} $${a.name}`;
}
// break;
case WasmOpcode.SET_GLOBAL:
if (value !== undefined) {
if (this.globals.length <= value) {
let errorMsg = `Global index ${value} out of range ${this.globals.length}`;
Terminal.error(errorMsg);
throw errorMsg;
} else {
let a = this.context.stack.pop();
this.globals[value].value = a.value;
return `${WasmOpcode[opcode]} ${value}`;
}
}
break;
case WasmOpcode.GET_GLOBAL:
if (value !== undefined) {
let a = this.globals[value];
this.context.stack.push(new WasmStackItem(a.type, a.value));
return `${WasmOpcode[opcode]} ${value}`;
}
break;
// ADD
case WasmOpcode.I32_ADD:
case WasmOpcode.I64_ADD:
case WasmOpcode.F32_ADD:
case WasmOpcode.F64_ADD: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value + b.value));
return WasmOpcode[opcode];
}
//SUB
case WasmOpcode.I32_SUB:
case WasmOpcode.I64_SUB:
case WasmOpcode.F32_SUB:
case WasmOpcode.F64_SUB: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value - b.value));
return WasmOpcode[opcode];
}
//MUL
case WasmOpcode.I32_MUL:
case WasmOpcode.I64_MUL:
case WasmOpcode.F32_MUL:
case WasmOpcode.F64_MUL: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value * b.value));
return WasmOpcode[opcode];
}
//DIV
case WasmOpcode.I32_DIV_S:
case WasmOpcode.I32_DIV_U:
case WasmOpcode.I64_DIV_S:
case WasmOpcode.I64_DIV_U:
case WasmOpcode.F32_DIV:
case WasmOpcode.F64_DIV: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value / b.value));
break;
}
//REM
case WasmOpcode.I32_REM_S:
case WasmOpcode.I32_REM_U:
case WasmOpcode.I64_REM_S:
case WasmOpcode.I64_REM_U: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value % b.value));
return WasmOpcode[opcode];
}
//GT
case WasmOpcode.I32_GT_S:
case WasmOpcode.I32_GT_U:
case WasmOpcode.I64_GT_S:
case WasmOpcode.I64_GT_U:
case WasmOpcode.F32_GT:
case WasmOpcode.F64_GT: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value > b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//GE
case WasmOpcode.I32_GE_S:
case WasmOpcode.I32_GE_U:
case WasmOpcode.I64_GE_S:
case WasmOpcode.I64_GE_U:
case WasmOpcode.F32_GE:
case WasmOpcode.F64_GE: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value >= b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//LT
case WasmOpcode.I32_LT_S:
case WasmOpcode.I32_LT_U:
case WasmOpcode.I64_LT_S:
case WasmOpcode.I64_LT_U:
case WasmOpcode.F32_LT:
case WasmOpcode.F64_LT: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value < b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//LE
case WasmOpcode.I32_LE_S:
case WasmOpcode.I32_LE_U:
case WasmOpcode.I64_LE_S:
case WasmOpcode.I64_LE_U:
case WasmOpcode.F32_LE:
case WasmOpcode.F64_LE: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value <= b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//EQ
case WasmOpcode.I32_EQ:
case WasmOpcode.I64_EQ:
case WasmOpcode.F32_EQ:
case WasmOpcode.F64_EQ: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value === b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//NE
case WasmOpcode.I32_NE:
case WasmOpcode.I64_NE:
case WasmOpcode.F32_NE:
case WasmOpcode.F64_NE: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value !== b.value ? 1 : 0));
return WasmOpcode[opcode];
}
//EQZ
case WasmOpcode.I32_EQZ:
case WasmOpcode.I64_EQZ: {
let a = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value === 0 ? 1 : 0));
return WasmOpcode[opcode];
}
//AND
case WasmOpcode.I32_AND:
case WasmOpcode.I64_AND: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value & b.value));
return WasmOpcode[opcode];
}
//OR
case WasmOpcode.I32_OR:
case WasmOpcode.I64_OR: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value | b.value));
return WasmOpcode[opcode];
}
//XOR
case WasmOpcode.I32_XOR:
case WasmOpcode.I64_XOR: {
let a = this.context.stack.pop();
let b = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, a.value ^ b.value));
return WasmOpcode[opcode];
}
//CTZ
case WasmOpcode.I32_CTZ:
case WasmOpcode.I64_CTZ: {
// let a = this.context.stack.pop();
// this.context.stack.push(new WasmStackItem(type, ctz(a.value)));
break;
}
//CLZ
case WasmOpcode.I32_CLZ:
case WasmOpcode.I64_CLZ: {
let a = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, Math.clz32(a.value)));
return WasmOpcode[opcode];
}
//CLZ
case WasmOpcode.I32_ROTL:
case WasmOpcode.I64_ROTL: {
// let a = this.context.stack.pop();
// this.context.stack.push(new WasmStackItem(type, rotl(a.value)));
return WasmOpcode[opcode];
}
//SHR
case WasmOpcode.I32_SHR_S:
case WasmOpcode.I32_SHR_U:
case WasmOpcode.I64_SHR_S:
case WasmOpcode.I64_SHR_U: {
// let a = this.context.stack.pop();
// this.context.stack.push(new WasmStackItem(type, shr(a.value)));
return WasmOpcode[opcode];
}
//SHR
case WasmOpcode.I32_SHL:
case WasmOpcode.I64_SHL: {
// let a = this.context.stack.pop();
// this.context.stack.push(new WasmStackItem(type, shl(a.value)));
return WasmOpcode[opcode];
}
//POPCNT
case WasmOpcode.I32_POPCNT:
case WasmOpcode.I64_POPCNT: {
// let a = this.context.stack.pop();
// this.context.stack.push(new WasmStackItem(type, popcnt(a.value)));
return WasmOpcode[opcode];
}
case WasmOpcode.F32_SQRT:
case WasmOpcode.F64_SQRT: {
let a = this.context.stack.pop();
this.context.stack.push(new WasmStackItem(a.type, Math.sqrt(a.value)));
return WasmOpcode[opcode];
}
//LOAD
case WasmOpcode.I32_LOAD:
case WasmOpcode.I64_LOAD:
case WasmOpcode.I32_LOAD8_U:
case WasmOpcode.I32_LOAD8_S:
case WasmOpcode.I64_LOAD8_U:
case WasmOpcode.I64_LOAD8_S:
case WasmOpcode.I32_LOAD16_U:
case WasmOpcode.I32_LOAD16_S:
case WasmOpcode.I64_LOAD16_U:
case WasmOpcode.I64_LOAD16_S:
case WasmOpcode.F32_LOAD:
case WasmOpcode.F64_LOAD: {
this.context.stack.pop();
this.context.stack.push(new WasmStackItem(type, 0));
this.context.lastOpcode = null;
return WasmOpcode[opcode];
}
//STORE
case WasmOpcode.I32_STORE:
case WasmOpcode.I64_STORE:
case WasmOpcode.I32_STORE8:
case WasmOpcode.I64_STORE8:
case WasmOpcode.I32_STORE16:
case WasmOpcode.I64_STORE16:
case WasmOpcode.F32_STORE:
case WasmOpcode.F64_STORE: {
let a = this.context.stack.pop(); // address
let b = this.context.stack.pop(); // offset
this.context.lastOpcode = null;
return WasmOpcode[opcode];
}
case WasmOpcode.IF: {
let a = this.context.stack.pop();
this.context.lastOpcode = null;
return WasmOpcode[opcode];
}
case WasmOpcode.BR_IF:
if (value !== undefined) {
let a = this.context.stack.pop();
this.context.lastOpcode = null;
return `${WasmOpcode[opcode]} ${value}`;
}
break;
case WasmOpcode.IF_ELSE:
case WasmOpcode.BLOCK:
case WasmOpcode.LOOP:
//ignore
return WasmOpcode[opcode];
case WasmOpcode.BR:
if (value !== undefined) {
return `${WasmOpcode[opcode]} ${value}`;
}
break;
case WasmOpcode.I32_WRAP_I64:
case WasmOpcode.I32_TRUNC_S_F32:
case WasmOpcode.I32_TRUNC_U_F32:
case WasmOpcode.I32_TRUNC_S_F64:
case WasmOpcode.I32_TRUNC_U_F64:
case WasmOpcode.I32_REINTERPRET_F32:
case WasmOpcode.I64_TRUNC_S_F32:
case WasmOpcode.I64_TRUNC_U_F32:
case WasmOpcode.I64_TRUNC_S_F64:
case WasmOpcode.I64_TRUNC_U_F64:
case WasmOpcode.I64_EXTEND_S_I32:
case WasmOpcode.I64_EXTEND_U_I32:
case WasmOpcode.F32_DEMOTE_F64:
case WasmOpcode.F32_TRUNC:
case WasmOpcode.F32_REINTERPRET_I32:
case WasmOpcode.F32_CONVERT_S_I32:
case WasmOpcode.F32_CONVERT_U_I32:
case WasmOpcode.F32_CONVERT_S_I64:
case WasmOpcode.F32_CONVERT_U_I64:
case WasmOpcode.F64_PROMOTE_F32:
case WasmOpcode.F64_TRUNC:
case WasmOpcode.F64_REINTERPRET_I64:
case WasmOpcode.F64_CONVERT_S_I32:
case WasmOpcode.F64_CONVERT_U_I32:
case WasmOpcode.F64_CONVERT_S_I64:
case WasmOpcode.F64_CONVERT_U_I64:
//ignore > pop > push
return WasmOpcode[opcode];
case null:
case undefined:
//ignore
break;
default:
Terminal.warn(`Unhandled Opcode ${opcode} => ${WasmOpcode[opcode]}`);
break;
}
return null;
}
}
function getOprandType(opcode: number): WasmType {
switch (opcode) {
// Int32
case WasmOpcode.I32_CONST:
case WasmOpcode.I32_ADD:
case WasmOpcode.I32_MUL:
case WasmOpcode.I32_SUB:
case WasmOpcode.I32_DIV_S:
case WasmOpcode.I32_DIV_U:
case WasmOpcode.I32_REM_S:
case WasmOpcode.I32_REM_U:
case WasmOpcode.I32_GE_S:
case WasmOpcode.I32_GE_U:
case WasmOpcode.I32_LE_S:
case WasmOpcode.I32_LE_U:
case WasmOpcode.I32_GT_S:
case WasmOpcode.I32_GT_U:
case WasmOpcode.I32_LT_S:
case WasmOpcode.I32_LT_U:
case WasmOpcode.I32_EQ:
case WasmOpcode.I32_NE:
case WasmOpcode.I32_EQZ:
case WasmOpcode.I32_AND:
case WasmOpcode.I32_OR:
case WasmOpcode.I32_XOR:
case WasmOpcode.I32_CTZ:
case WasmOpcode.I32_CLZ:
case WasmOpcode.I32_ROTL:
case WasmOpcode.I32_ROTR:
case WasmOpcode.I32_SHL:
case WasmOpcode.I32_SHR_S:
case WasmOpcode.I32_SHR_U:
case WasmOpcode.I32_POPCNT:
case WasmOpcode.I32_LOAD:
case WasmOpcode.I32_LOAD8_S:
case WasmOpcode.I32_LOAD8_U:
case WasmOpcode.I32_LOAD16_S:
case WasmOpcode.I32_LOAD16_U:
case WasmOpcode.I32_STORE16:
case WasmOpcode.I32_STORE8:
case WasmOpcode.I32_STORE:
case WasmOpcode.I32_REINTERPRET_F32:
case WasmOpcode.I32_TRUNC_S_F32:
case WasmOpcode.I32_TRUNC_U_F32:
case WasmOpcode.I32_TRUNC_S_F64:
case WasmOpcode.I32_TRUNC_U_F64:
case WasmOpcode.I32_WRAP_I64:
return WasmType.I32;
// Int64
case WasmOpcode.I64_CONST:
case WasmOpcode.I64_ADD:
case WasmOpcode.I64_MUL:
case WasmOpcode.I64_SUB:
case WasmOpcode.I64_DIV_S:
case WasmOpcode.I64_DIV_U:
case WasmOpcode.I64_CLZ:
case WasmOpcode.I64_ROTL:
case WasmOpcode.I64_AND:
case WasmOpcode.I64_CTZ:
case WasmOpcode.I64_EQ:
case WasmOpcode.I64_EQZ:
case WasmOpcode.I64_GE_S:
case WasmOpcode.I64_GE_U:
case WasmOpcode.I64_LE_S:
case WasmOpcode.I64_LE_U:
case WasmOpcode.I64_GT_S:
case WasmOpcode.I64_GT_U:
case WasmOpcode.I64_LT_S:
case WasmOpcode.I64_LT_U:
case WasmOpcode.I64_LOAD:
case WasmOpcode.I64_LOAD8_S:
case WasmOpcode.I64_LOAD8_U:
case WasmOpcode.I64_LOAD16_S:
case WasmOpcode.I64_LOAD16_U:
case WasmOpcode.I64_NE:
case WasmOpcode.I64_XOR:
case WasmOpcode.I64_STORE16:
case WasmOpcode.I64_STORE8:
case WasmOpcode.I64_STORE:
case WasmOpcode.I64_SHR_S:
case WasmOpcode.I64_SHR_U:
case WasmOpcode.I64_SHL:
case WasmOpcode.I64_ROTR:
case WasmOpcode.I64_REM_S:
case WasmOpcode.I64_REM_U:
case WasmOpcode.I64_POPCNT:
case WasmOpcode.I64_OR:
case WasmOpcode.I64_REINTERPRET_F64:
case WasmOpcode.I64_TRUNC_S_F32:
case WasmOpcode.I64_TRUNC_U_F32:
case WasmOpcode.I64_TRUNC_S_F64:
case WasmOpcode.I64_TRUNC_U_F64:
case WasmOpcode.I64_EXTEND_S_I32:
case WasmOpcode.I64_EXTEND_U_I32:
return WasmType.I64;
// Float32
case WasmOpcode.F32_CONST:
case WasmOpcode.F32_ADD:
case WasmOpcode.F32_SUB:
case WasmOpcode.F32_MUL:
case WasmOpcode.F32_DIV:
case WasmOpcode.F32_SQRT:
case WasmOpcode.F32_NEG:
case WasmOpcode.F32_NE:
case WasmOpcode.F32_ABS:
case WasmOpcode.F32_CEIL:
case WasmOpcode.F32_EQ:
case WasmOpcode.F32_FLOOR:
case WasmOpcode.F32_NEAREST:
case WasmOpcode.F32_MIN:
case WasmOpcode.F32_MAX:
case WasmOpcode.F32_GE:
case WasmOpcode.F32_GT:
case WasmOpcode.F32_LT:
case WasmOpcode.F32_LE:
case WasmOpcode.F32_COPYSIGN:
case WasmOpcode.F32_LOAD:
case WasmOpcode.F32_STORE:
case WasmOpcode.F32_TRUNC:
case WasmOpcode.F32_DEMOTE_F64:
case WasmOpcode.F32_CONVERT_S_I32:
case WasmOpcode.F32_CONVERT_U_I32:
case WasmOpcode.F32_CONVERT_S_I64:
case WasmOpcode.F32_CONVERT_U_I64:
case WasmOpcode.F32_REINTERPRET_I32:
return WasmType.F32;
// Float64
case WasmOpcode.F64_CONST:
case WasmOpcode.F64_ADD:
case WasmOpcode.F64_SUB:
case WasmOpcode.F64_MUL:
case WasmOpcode.F64_DIV:
case WasmOpcode.F64_SQRT:
case WasmOpcode.F64_NEG:
case WasmOpcode.F64_NE:
case WasmOpcode.F64_ABS:
case WasmOpcode.F64_CEIL:
case WasmOpcode.F64_EQ:
case WasmOpcode.F64_FLOOR:
case WasmOpcode.F64_NEAREST:
case WasmOpcode.F64_MIN:
case WasmOpcode.F64_MAX:
case WasmOpcode.F64_GE:
case WasmOpcode.F64_GT:
case WasmOpcode.F64_LT:
case WasmOpcode.F64_LE:
case WasmOpcode.F64_COPYSIGN:
case WasmOpcode.F64_LOAD:
case WasmOpcode.F64_STORE:
case WasmOpcode.F64_TRUNC:
case WasmOpcode.F64_PROMOTE_F32:
case WasmOpcode.F64_CONVERT_S_I32:
case WasmOpcode.F64_CONVERT_U_I32:
case WasmOpcode.F64_CONVERT_S_I64:
case WasmOpcode.F64_CONVERT_U_I64:
case WasmOpcode.F64_REINTERPRET_I64:
return WasmType.F64;
// No types
case WasmOpcode.CALL:
case WasmOpcode.END:
case WasmOpcode.RETURN:
case WasmOpcode.GET_GLOBAL:
case WasmOpcode.GET_LOCAL:
case WasmOpcode.SET_LOCAL:
case WasmOpcode.SET_GLOBAL:
case WasmOpcode.BLOCK:
case WasmOpcode.LOOP:
case WasmOpcode.IF:
case WasmOpcode.IF_ELSE:
case WasmOpcode.BR:
case WasmOpcode.BR_IF:
case WasmOpcode.BR_TABLE:
case WasmOpcode.NOP:
return null;
default:
Terminal.warn(`Unhandled Opcode ${opcode} => ${WasmOpcode[opcode]}`);
break;
}
return null;
} | the_stack |
import {
Schema, shapeExpr, ShapeOr, ShapeAnd, ShapeNot, ShapeExternal, shapeExprRef,
shapeExprLabel, NodeConstraint, xsFacet, stringFacet, numericFacet,
numericLiteral, valueSetValue, objectValue, ObjectLiteral, IriStem,
IriStemRange, LiteralStem, LiteralStemRange, Language, LanguageStem,
LanguageStemRange, Wildcard, Shape, tripleExpr, EachOf, OneOf,
TripleConstraint, tripleExprRef, tripleExprLabel, SemAct, Annotation, IRIREF,
STRING, LANGTAG
} from "shexj";
const base = 'http://a.example/some/path/';
const iri = (localName: string) => base + localName;
function test_pieces() {
const i1: IRIREF = iri('i1');
const i2: IRIREF = iri('i2');
const l1: STRING = 'literal 1';
const anotationIRI: Annotation = { type: "Annotation", predicate: i1, object: i2 };
// $ExpectError
const anotationIRI_e0: Annotation = { type: "Annotation999", predicate: i1, object: i2 };
// $ExpectError
const anotationIRI_e1: Annotation = { type: "Annotation", predicate999: i1, object: i2 };
// $ExpectError
const anotationIRI_e2: Annotation = { type: "Annotation", predicate: i1, object999: i2 };
const anotationLit: Annotation = { type: "Annotation", predicate: i1, object: l1 };
const anotation: Annotation = { type: "Annotation", predicate: i1, object: i2 };
const semAct1: SemAct = { type: "SemAct", name: i1 };
// // $ExpectError
// const semAct1_e0: SemAct = { type: "SemAct", name: l1 } // can typescript detect this?
// $ExpectError
const semAct1_e1: SemAct = { type: "SemAct", code: l1 };
const semAct2: SemAct = { type: "SemAct", name: i1, code: l1 };
// $ExpectError
const semAct2_e0: SemAct = { type: "Semact", name: i1, code: l1 };
const tel1: tripleExprLabel = i1;
const ter1: tripleExprRef = tel1;
const tc1: TripleConstraint = { type: "TripleConstraint", predicate: i1 };
const tc2: TripleConstraint = { id: i1, type: "TripleConstraint", inverse: true, predicate: i1, min: 1, max: -1, semActs: [semAct1, semAct2], annotations: [anotationIRI, anotationLit] };
const eo1: EachOf = { type: "EachOf", expressions: [tc1, tc2] };
const oo1: OneOf = { type: "OneOf", expressions: [tc1, eo1, ter1] };
// $ExpectError
const oo1_e1: OneOf = { type: "OneOf", expressions: [tc1, semAct1] };
const te1: tripleExpr = ter1;
const te2: tripleExpr = tc1;
const te3: tripleExpr = eo1;
const te4: tripleExpr = oo1;
// $ExpectError
const te_e1: tripleExpr = semAct1;
const sh1: Shape = { type: "Shape" };
const sh2: Shape = { type: "Shape", expression: te1, closed: true, extra: [i1, i2], semActs: [semAct1, semAct2], annotations: [anotationIRI, anotationLit] };
const lt1: LANGTAG = "en";
const lt2: LANGTAG = "en-fr";
const wi: Wildcard = { type: "Wildcard" };
const la1: Language = { type: "Language", languageTag: "en" };
const las1: LanguageStem = { type: "LanguageStem", stem: lt1 };
const lasr1: LanguageStemRange = { type: "LanguageStemRange", stem: lt1, exclusions: [lt2, las1] };
const lis1: LiteralStem = { type: "LiteralStem", stem: "abc" };
const lis2: LiteralStemRange = { type: "LiteralStemRange", stem: "ab", exclusions: ["abc", lis1] };
const irs1: IriStem = { type: "IriStem", stem: "abc" };
const irs2: IriStemRange = { type: "IriStemRange", stem: "ab", exclusions: ["abc", irs1] };
const oj1: ObjectLiteral = { value: "chat" };
const oj2: ObjectLiteral = { value: "chat", language: "en" };
const oj3: ObjectLiteral = { value: "ii", type: i1 };
const ov1: objectValue = i1;
const ov2: objectValue = oj1;
const vsv1: valueSetValue[] = [ov1, irs1, irs2, lis1, lis2, las1, lasr1];
const nf1: numericFacet = { mininclusive: 2.1, minexclusive: 2.0, maxinclusive: 3.0, maxexclusive: 3.1 };
const sf1: stringFacet = { length: 3, minlength: 2, maxlength: 4, pattern: "...", flags: "i" };
const xsf1: xsFacet[] = [nf1, sf1];
const nc1: NodeConstraint = { type: "NodeConstraint", nodeKind: "iri" };
// $ExpectError
const nc_e1: NodeConstraint = { type: "NodeConstraint", nodeKind: "iri999" };
const nc2: NodeConstraint = { type: "NodeConstraint", datatype: i2, values: vsv1, minlength: 2, minexclusive: 99 };
const sel1: shapeExprLabel = i1;
const ser1: shapeExprRef = tel1;
const ext1: ShapeExternal = { type: "ShapeExternal", id: sel1 };
const sn1: ShapeNot = { type: "ShapeNot", id: "sn1", shapeExpr: ext1 };
const sa1: ShapeAnd = { type: "ShapeAnd", id: "sa1", shapeExprs: [ext1, sn1] };
const so1: ShapeOr = { type: "ShapeOr", shapeExprs: [ext1, sn1, sa1] };
const s1: Schema = { type: "Schema" };
const s2: Schema = { type: "Schema", "@context": "http://www.w3.org/ns/shex.jsonld", startActs: [semAct1, semAct2], start: so1, imports: [i1, i2], shapes: [ext1, sn1, sa1] };
}
function test_kitchen_sink() {
const s1: Schema = {
type: "Schema",
startActs: [
{
type: "SemAct",
name: "http://ex.example/#foo",
code: " initializer for ignored extension "
}
],
start: "http://ex.example/S1",
shapes: [
{
type: "Shape",
id: "_:IDshape",
expression: {
id: "_:IDshapeE",
type: "OneOf",
expressions: [
{
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://ex.example/#code",
valueExpr: {
type: "NodeConstraint",
nodeKind: "literal"
}
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#system",
valueExpr: {
type: "NodeConstraint",
nodeKind: "iri"
}
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#literal",
valueExpr: {
type: "NodeConstraint",
values: [
{
value: "a"
},
{
value: "b",
type: "http://ex.example/#c"
},
{
value: "c",
language: "en"
},
{
value: "d",
language: "en-fr"
}
]
},
min: 2,
max: 3
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#misc",
valueExpr: {
type: "NodeConstraint",
nodeKind: "bnode"
},
semActs: [
{
type: "SemAct",
name: "http://ex.example/#foo",
code: " ignored "
},
{
type: "SemAct",
name: "http://ex.example/#bar",
code: " also ignored "
}
]
}
]
},
{
type: "EachOf",
expressions: [
{
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
inverse: true,
predicate: "http://ex.example/#ref",
valueExpr: {
type: "NodeConstraint",
values: [
{
value: "true",
type: "http://www.w3.org/2001/XMLSchema#boolean"
},
{
value: "false",
type: "http://www.w3.org/2001/XMLSchema#boolean"
}
]
}
},
{
type: "TripleConstraint",
inverse: true,
predicate: "http://ex.example/#miscRef"
}
]
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#issues",
valueExpr: "http://ex.example/S1",
min: 0,
max: -1
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#seeAlso",
valueExpr: "http://ex.example/S1",
min: 0,
max: -1
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#says",
valueExpr: "http://ex.example/#EmployeeShape",
min: 0,
max: -1
}
]
}
]
}
},
{
type: "Shape",
id: "http://ex.example/#EmployeeShape",
expression: {
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/givenName",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#string"
},
min: 1,
max: -1
},
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/familyName",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#string"
}
},
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/phone",
valueExpr: {
type: "NodeConstraint",
nodeKind: "iri"
},
min: 0,
max: -1
},
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/mbox",
valueExpr: {
type: "NodeConstraint",
nodeKind: "iri"
},
min: 0,
max: 1
}
]
}
},
{
type: "Shape",
id: "http://ex.example/#FooID",
closed: true,
expression: "_:IDshapeE",
extra: [
"http://ex.example/#code",
"http://ex.example/#system"
]
},
{
type: "Shape",
id: "http://ex.example/#UserShape",
expression: {
type: "EachOf",
expressions: [
{
type: "OneOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/name",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#string"
}
},
{
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/givenName",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#string"
},
min: 1,
max: -1
},
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/familyName",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#string"
}
}
]
}
]
},
{
type: "TripleConstraint",
predicate: "http://xmlns.com/foaf/mbox",
valueExpr: {
type: "NodeConstraint",
nodeKind: "iri",
pattern: "^mailto:"
}
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#id",
valueExpr: {
type: "ShapeAnd",
shapeExprs: [
{
type: "NodeConstraint",
nodeKind: "bnode"
},
"_:IDshape"
]
}
}
]
}
},
{
type: "Shape",
id: "http://ex.example/S1",
expression: {
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
valueExpr: {
type: "NodeConstraint",
values: [
"http://ex.example/#Issue"
]
},
min: 0,
max: 1
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#state",
valueExpr: {
type: "NodeConstraint",
values: [
{
type: "IriStemRange",
stem: "http://ex.example/#state",
exclusions: [
"http://ex.example/#state_resolved"
]
}
]
},
annotations: [
{
type: "Annotation",
predicate: "http://www.w3.org/2000/01/rdf-schem#label",
object: {
value: "State"
}
},
{
type: "Annotation",
predicate: "http://www.w3.org/2000/01/rdf-schem#description",
object: {
value: "the sit"
}
}
]
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#reportedBy",
valueExpr: {
type: "ShapeAnd",
shapeExprs: [
{
type: "NodeConstraint",
nodeKind: "iri"
},
"http://ex.example/#UserShape"
]
}
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#reportedOn",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#dateTime"
}
},
{
type: "EachOf",
expressions: [
{
type: "TripleConstraint",
predicate: "http://ex.example/#reproducedBy",
valueExpr: {
type: "ShapeAnd",
shapeExprs: [
{
type: "NodeConstraint",
nodeKind: "nonliteral"
},
"http://ex.example/#EmployeeShape"
]
}
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#reproducedOn",
valueExpr: {
type: "NodeConstraint",
datatype: "http://www.w3.org/2001/XMLSchema#dateTime"
}
}
],
min: 0,
max: 1,
semActs: [
{
type: "SemAct",
name: "http://ex.example/#foo",
code: " asdfasdf "
}
]
},
{
type: "TripleConstraint",
predicate: "http://ex.example/#related",
valueExpr: "http://ex.example/S1",
min: 0,
max: -1
}
]
}
}
],
"@context": "http://www.w3.org/ns/shex.jsonld"
};
} | the_stack |
import { hsv } from "@thi.ng/color/hsv/hsv";
import { downloadWithMime } from "@thi.ng/dl-asset/raw";
import { pathBuilder } from "@thi.ng/geom/path-builder";
import { points } from "@thi.ng/geom/points";
import { canvas, normalizeTree } from "@thi.ng/hdom-canvas";
import { dropdown } from "@thi.ng/hdom-components/dropdown";
import { svg } from "@thi.ng/hiccup-svg/svg";
import { COMMENT } from "@thi.ng/hiccup/api";
import { serialize } from "@thi.ng/hiccup/serialize";
import { sincos } from "@thi.ng/math/angle";
import { concat } from "@thi.ng/matrices/concat";
import { skewX23 } from "@thi.ng/matrices/skew";
import { translation23 } from "@thi.ng/matrices/translation";
import type { ISubscriber } from "@thi.ng/rstream";
import { fromRAF } from "@thi.ng/rstream/raf";
import { stream } from "@thi.ng/rstream/stream";
import { sync } from "@thi.ng/rstream/sync";
import { updateDOM } from "@thi.ng/transducers-hdom";
import { map } from "@thi.ng/transducers/map";
import { range } from "@thi.ng/transducers/range";
import { repeatedly } from "@thi.ng/transducers/repeatedly";
import { addN } from "@thi.ng/vectors/addn";
import logo from "./logo-64.png";
// for testing SVG conversion
// ignore error, resolved by parcel
// canvas size
const W = 300;
const W2 = W / 2;
const randpos = () => [Math.random() * W - W2, Math.random() * W - W2];
const randdir = (n = 1) => [
Math.random() * n * 2 - n,
Math.random() * n * 2 - n,
];
// various tests for different shapes & canvas drawing options
// each test is a standalone component (only one used at a time)
const TESTS: any = {
"dash offset": {
attribs: {},
desc: "Simple path w/ animated stroke dash pattern",
body: () =>
pathBuilder({
fill: "blue",
stroke: "#000",
weight: 3,
dash: [4, 8],
dashOffset: (Date.now() * 0.01) % 12,
})
.moveTo([10, 10])
.quadraticTo([W2, W2], [W2, W - 10])
.quadraticTo([W2, W2], [W - 10, 10])
.quadraticTo([W2, W2], [10, 10])
.current(),
},
"shape morph": {
attribs: { __clear: false },
desc: "Animated semi-transparent path, stroke dash pattern, transformed origin, non-clearing background",
body: () => {
const t = Date.now() * 0.01;
const a = 10 + 140 * (Math.sin(t * 0.33) * 0.5 + 0.5);
return pathBuilder({
fill: [1, 1, 1, 0.05],
stroke: "#000",
weight: 3,
miterLimit: 1,
dash: [20, 20],
dashOffset: (t * 5) % 40,
translate: [W2, W2],
rotate: (t * 0.05) % (2 * Math.PI),
})
.moveTo([-100, -100])
.quadraticTo([-a, 0], [0, 100])
.quadraticTo([a, 0], [100, -100])
.quadraticTo([0, -a], [-100, -100])
.current();
},
},
"points 1k": {
attribs: { __diff: false },
desc: "1,000 random circles",
body: () =>
points([...repeatedly(randpos, 1000)], {
fill: "#000",
stroke: "none",
size: 4,
shape: "circle",
translate: [W2, W2],
scale: 0.6 + 0.4 * Math.sin(Date.now() * 0.005),
}),
},
"points 10k": {
attribs: { __diff: false },
desc: "10,000 random rects",
body: () =>
points([...repeatedly(randpos, 10000)], {
fill: "#000",
stroke: "none",
translate: [W2, W2],
scale: 0.6 + 0.4 * Math.sin(Date.now() * 0.005),
}),
},
"points 50k": {
attribs: { __diff: false },
desc: "50,000 random rects",
body: () =>
points([...repeatedly(randpos, 50000)], {
fill: "#000",
stroke: "none",
translate: [W2, W2],
scale: 0.6 + 0.4 * Math.sin(Date.now() * 0.005),
}),
},
"rounded rects": {
attribs: {},
desc: "Rounded rects w/ animated corner radii",
body: () => {
const t = Date.now() * 0.01;
const r = 100 * (Math.sin(t * 0.5) * 0.5 + 0.5);
return [
"g",
{
weight: 1,
stroke: "#00f",
align: "center",
baseline: "middle",
font: "48px Menlo",
__normalize: false,
},
...map(
(i) => ["rect", null, [i, i], W - 2 * i, W - 2 * i, r],
range(10, 50, 5)
),
// ...map((i) => normalizedPath(roundedRect([i, i], [W - 2 * i, W - 2 * i], r)), range(10, 50, 5)),
["text", {}, [W2, W2], Math.round(r)],
];
},
},
"linear gradient": {
attribs: {},
desc: "Animated linear gradients",
body: () => [
[
"defs",
{},
[
"linearGradient",
{ id: "grad1", from: [0, 0], to: [W, W] },
[
[0, "#fc0"],
[1, "#0ef"],
],
],
[
"linearGradient",
{
id: "grad2",
from: [0, 0],
to: [W, W2 + W2 * Math.sin(Date.now() * 0.005)],
},
[
[0, "#700"],
[0.5, "#d0f"],
[1, "#fff"],
],
],
],
["circle", { fill: "$grad1" }, [W2, W2], W2 - 10],
["rect", { fill: "$grad2" }, [125, 0], 50, W],
["rect", { fill: "$grad2" }, [0, 125], W, 50],
],
},
"radial gradient": {
attribs: {},
desc: "Animated radial gradients (w/ alpha channel)",
body: () => {
const t = Date.now() * 0.01;
const x = W2 + 50 * Math.sin(t * 0.5);
const y = W2 + 20 * Math.sin(t * 0.3);
const spos = [110, 120];
return [
[
"defs",
{},
[
"radialGradient",
{
id: "bg",
from: [x, W - 20],
to: [W2, W],
r1: W,
r2: 100,
},
[
[0, "#07f"],
[0.5, "#0ef"],
[0.8, "#efe"],
[1, "#af0"],
],
],
[
"radialGradient",
{ id: "sun", from: spos, to: spos, r1: 5, r2: 50 },
[
[0, [1, 1, 1]],
[1, [1, 1, 0.75, 0]],
],
],
],
["circle", { fill: "$bg" }, [W2, y], W2 - 20],
["circle", { fill: "$sun" }, spos, 50],
];
},
},
"images 1k": {
attribs: {},
desc: "1,000 stateful image sprite components",
body: (() => {
const img = new Image();
img.src = logo;
const w = W - 64;
const ball = () => {
const p = randpos();
const v = randdir(4);
return () => {
let x = p[0] + v[0];
let y = p[1] + v[1];
x < 0 && ((x *= -1), (v[0] *= -1));
y < 0 && ((y *= -1), (v[1] *= -1));
x > w && ((x = w - (x - w)), (v[0] *= -1));
y > w && ((y = w - (y - w)), (v[1] *= -1));
p[0] = x;
p[1] = y;
return ["img", {}, img, p.slice()];
};
};
const body = ["g", {}, ...repeatedly(ball, 1000)];
return () => body;
})(),
},
static: {
attribs: {},
desc: "static scene (single draw) w/ skew matrix",
body: (() => {
const body = [
"g",
{
transform: concat(
[],
translation23([], [150, 150]),
skewX23([], -Math.PI / 6)
),
},
["rect", { fill: "#ff0" }, [-50, -50], 100, 100],
[
"text",
{
fill: "#00f",
font: "18px Menlo",
align: "center",
baseline: "middle",
},
[0, 0],
new Date().toISOString(),
],
];
return () => body;
})(),
},
ellipse: {
attribs: {},
desc: "ellipses",
body: () => {
const t = Date.now() * 0.005;
return [
"g",
{},
map(
(x) => [
"ellipse",
{ stroke: hsv(x / 20, 1, 1) },
[150, 150], // pos
addN(null, sincos(t + x * 0.1, 75), 75), // radii
Math.sin(t * 0.25), // axis
],
range(30)
),
];
},
},
};
// test case selection dropdown
const choices = (_: any, target: ISubscriber<string>, id: string) => [
dropdown,
{
class: "w4 ma2",
onchange: (e: Event) => {
const val = (<HTMLSelectElement>e.target).value;
window.location.hash = val.replace(/\s/g, "-");
target.next(val);
},
},
Object.keys(TESTS).map((k) => [k, k]),
id,
];
// event stream for triggering SVG conversion / export
const trigger = stream<boolean>();
// stream supplying current test ID
const selection = stream<string>();
// stream combinator updating & normalizing selected test component tree
// (one of the inputs is linked to RAF to trigger updates)
const scene = sync({
src: {
id: selection,
time: fromRAF(),
},
}).transform(
map(({ id }) => ({ id, shapes: normalizeTree({}, TESTS[id].body()) }))
);
// stream transformer to produce & update main user interface root component
scene.transform(
map(({ id, shapes }) => [
"div.vh-100.flex.flex-column.justify-center.items-center.code.f7",
[
"div",
[choices, selection, id],
[
"button.ml2",
{ onclick: () => trigger.next(true) },
"convert & export",
],
],
// hdom-canvas component w/ injected `scene` subtree
// turn __normalize off because `scene` already contains normalized tree
[
canvas,
{
class: "ma2",
width: 300,
height: 300,
__normalize: false,
...TESTS[id].attribs,
},
shapes,
],
["div.ma2.tc", TESTS[id].desc],
[
"a.link",
{
href: "https://github.com/thi-ng/umbrella/tree/develop/examples/hdom-canvas-shapes",
},
"Source code",
],
]),
updateDOM()
);
// stream combinator which triggers SVG conversion and file download
// when both inputs have triggered (one of them being linked to the export button)
sync({
src: { scene, trigger },
reset: true,
xform: map(({ scene }) =>
downloadWithMime(
new Date().toISOString().replace(/[:.-]/g, "") + ".svg",
serialize(
svg(
{
width: 300,
height: 300,
stroke: "none",
fill: "none",
convert: true,
},
[
COMMENT,
`generated by @thi.ng/hiccup-svg @ ${new Date()}`,
],
scene.shapes
)
),
{ mime: "image/svg+xml" }
)
),
});
// seed initial test selection
selection.next(
window.location.hash.length > 1
? window.location.hash.substr(1).replace(/-/g, " ")
: "shape morph"
);
// // HMR handling
// // terminate `scene` rstream to avoid multiple running instances after HMR
// // (this will also terminate all attached child streams/subscriptions)
// const hot = (<any>module).hot;
// if (hot) {
// hot.dispose(() => scene.done());
// } | the_stack |
////abstract class B {
//// private privateMethod() { }
//// protected protectedMethod() { };
//// static staticMethod() { }
//// abstract getValue(): number;
//// /*abstractClass*/
////}
////class C extends B {
//// /*classThatIsEmptyAndExtendingAnotherClass*/
////}
////class D extends B {
//// /*classThatHasAlreadyImplementedAnotherClassMethod*/
//// getValue() {
//// return 10;
//// }
//// /*classThatHasAlreadyImplementedAnotherClassMethodAfterMethod*/
////}
////class D1 extends B {
//// /*classThatHasDifferentMethodThanBase*/
//// getValue1() {
//// return 10;
//// }
//// /*classThatHasDifferentMethodThanBaseAfterMethod*/
////}
////class D2 extends B {
//// /*classThatHasAlreadyImplementedAnotherClassProtectedMethod*/
//// protectedMethod() {
//// }
//// /*classThatHasDifferentMethodThanBaseAfterProtectedMethod*/
////}
////class D3 extends D1 {
//// /*classThatExtendsClassExtendingAnotherClass*/
////}
////class D4 extends D1 {
//// static /*classThatExtendsClassExtendingAnotherClassAndTypesStatic*/
////}
////class D5 extends D2 {
//// /*classThatExtendsClassExtendingAnotherClassWithOverridingMember*/
////}
////class D6 extends D2 {
//// static /*classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic*/
////}
////class E {
//// /*classThatDoesNotExtendAnotherClass*/
////}
////class F extends B {
//// public /*classThatHasWrittenPublicKeyword*/
////}
////class F2 extends B {
//// private /*classThatHasWrittenPrivateKeyword*/
////}
////class G extends B {
//// static /*classElementContainingStatic*/
////}
////class G2 extends B {
//// private static /*classElementContainingPrivateStatic*/
////}
////class H extends B {
//// prop/*classThatStartedWritingIdentifier*/
////}
//////Class for location verification
////class I extends B {
//// prop0: number
//// /*propDeclarationWithoutSemicolon*/
//// prop: number;
//// /*propDeclarationWithSemicolon*/
//// prop1 = 10;
//// /*propAssignmentWithSemicolon*/
//// prop2 = 10
//// /*propAssignmentWithoutSemicolon*/
//// method(): number
//// /*methodSignatureWithoutSemicolon*/
//// method2(): number;
//// /*methodSignatureWithSemicolon*/
//// method3() {
//// /*InsideMethod*/
//// }
//// /*methodImplementation*/
//// get c()
//// /*accessorSignatureWithoutSemicolon*/
//// set c()
//// {
//// }
//// /*accessorSignatureImplementation*/
////}
////class J extends B {
//// get /*classThatHasWrittenGetKeyword*/
////}
////class K extends B {
//// set /*classThatHasWrittenSetKeyword*/
////}
////class J extends B {
//// get identi/*classThatStartedWritingIdentifierOfGetAccessor*/
////}
////class K extends B {
//// set identi/*classThatStartedWritingIdentifierOfSetAccessor*/
////}
////class L extends B {
//// public identi/*classThatStartedWritingIdentifierAfterModifier*/
////}
////class L2 extends B {
//// private identi/*classThatStartedWritingIdentifierAfterPrivateModifier*/
////}
////class M extends B {
//// static identi/*classThatStartedWritingIdentifierAfterStaticModifier*/
////}
////class M extends B {
//// private static identi/*classThatStartedWritingIdentifierAfterPrivateStaticModifier*/
////}
////class N extends B {
//// async /*classThatHasWrittenAsyncKeyword*/
////}
////class O extends B {
//// constructor(public a) {
//// },
//// /*classElementAfterConstructorSeparatedByComma*/
////}
const allowedKeywordCount = verify.allowedClassElementKeywords.length;
type CompletionInfo = [string, string];
type CompletionInfoVerifier = { validMembers: CompletionInfo[], invalidMembers: CompletionInfo[] };
function verifyClassElementLocations({ validMembers, invalidMembers }: CompletionInfoVerifier, classElementCompletionLocations: string[]) {
for (const marker of classElementCompletionLocations) {
goTo.marker(marker);
verifyCompletionInfo(validMembers, verify);
verifyCompletionInfo(invalidMembers, verify.not);
verify.completionListContainsClassElementKeywords();
verify.completionListCount(allowedKeywordCount + validMembers.length);
}
}
function verifyCompletionInfo(memberInfo: CompletionInfo[], verify: FourSlashInterface.verifyNegatable) {
for (const [symbol, text] of memberInfo) {
verify.completionListContains(symbol, text, /*documentation*/ undefined, "method");
}
}
const allMembersOfBase: CompletionInfo[] = [
["getValue", "(method) B.getValue(): number"],
["protectedMethod", "(method) B.protectedMethod(): void"],
["privateMethod", "(method) B.privateMethod(): void"],
["staticMethod", "(method) B.staticMethod(): void"]
];
const publicCompletionInfoOfD1: CompletionInfo[] = [
["getValue1", "(method) D1.getValue1(): number"]
];
const publicCompletionInfoOfD2: CompletionInfo[] = [
["protectedMethod", "(method) D2.protectedMethod(): void"]
];
function filterCompletionInfo(fn: (a: CompletionInfo) => boolean): CompletionInfoVerifier {
const validMembers: CompletionInfo[] = [];
const invalidMembers: CompletionInfo[] = [];
for (const member of allMembersOfBase) {
if (fn(member)) {
validMembers.push(member);
}
else {
invalidMembers.push(member);
}
}
return { validMembers, invalidMembers };
}
const instanceMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue" || a === "protectedMethod");
const staticMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "staticMethod");
const instanceWithoutProtectedMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "getValue");
const instanceWithoutPublicMemberInfo = filterCompletionInfo(([a]: CompletionInfo) => a === "protectedMethod");
const instanceMemberInfoD1: CompletionInfoVerifier = {
validMembers: instanceMemberInfo.validMembers.concat(publicCompletionInfoOfD1),
invalidMembers: instanceMemberInfo.invalidMembers
};
const instanceMemberInfoD2: CompletionInfoVerifier = {
validMembers: instanceWithoutProtectedMemberInfo.validMembers.concat(publicCompletionInfoOfD2),
invalidMembers: instanceWithoutProtectedMemberInfo.invalidMembers
};
const staticMemberInfoDn: CompletionInfoVerifier = {
validMembers: staticMemberInfo.validMembers,
invalidMembers: staticMemberInfo.invalidMembers.concat(publicCompletionInfoOfD1, publicCompletionInfoOfD2)
};
// Not a class element declaration location
const nonClassElementMarkers = [
"InsideMethod"
];
for (const marker of nonClassElementMarkers) {
goTo.marker(marker);
verifyCompletionInfo(allMembersOfBase, verify.not);
verify.not.completionListIsEmpty();
}
// Only keywords allowed at this position since they dont extend the class or are private
const onlyClassElementKeywordLocations = [
"abstractClass",
"classThatDoesNotExtendAnotherClass",
"classThatHasWrittenPrivateKeyword",
"classElementContainingPrivateStatic",
"classThatStartedWritingIdentifierAfterPrivateModifier",
"classThatStartedWritingIdentifierAfterPrivateStaticModifier"
];
verifyClassElementLocations({ validMembers: [], invalidMembers: allMembersOfBase }, onlyClassElementKeywordLocations);
// Instance base members and class member keywords allowed
const classInstanceElementLocations = [
"classThatIsEmptyAndExtendingAnotherClass",
"classThatHasDifferentMethodThanBase",
"classThatHasDifferentMethodThanBaseAfterMethod",
"classThatHasWrittenPublicKeyword",
"classThatStartedWritingIdentifier",
"propDeclarationWithoutSemicolon",
"propDeclarationWithSemicolon",
"propAssignmentWithSemicolon",
"propAssignmentWithoutSemicolon",
"methodSignatureWithoutSemicolon",
"methodSignatureWithSemicolon",
"methodImplementation",
"accessorSignatureWithoutSemicolon",
"accessorSignatureImplementation",
"classThatHasWrittenGetKeyword",
"classThatHasWrittenSetKeyword",
"classThatStartedWritingIdentifierOfGetAccessor",
"classThatStartedWritingIdentifierOfSetAccessor",
"classThatStartedWritingIdentifierAfterModifier",
"classThatHasWrittenAsyncKeyword",
"classElementAfterConstructorSeparatedByComma"
];
verifyClassElementLocations(instanceMemberInfo, classInstanceElementLocations);
// Static Base members and class member keywords allowed
const staticClassLocations = [
"classElementContainingStatic",
"classThatStartedWritingIdentifierAfterStaticModifier"
];
verifyClassElementLocations(staticMemberInfo, staticClassLocations);
const classInstanceElementWithoutPublicMethodLocations = [
"classThatHasAlreadyImplementedAnotherClassMethod",
"classThatHasAlreadyImplementedAnotherClassMethodAfterMethod",
];
verifyClassElementLocations(instanceWithoutPublicMemberInfo, classInstanceElementWithoutPublicMethodLocations);
const classInstanceElementWithoutProtectedMethodLocations = [
"classThatHasAlreadyImplementedAnotherClassProtectedMethod",
"classThatHasDifferentMethodThanBaseAfterProtectedMethod",
];
verifyClassElementLocations(instanceWithoutProtectedMemberInfo, classInstanceElementWithoutProtectedMethodLocations);
// instance memebers in D1 and base class are shown
verifyClassElementLocations(instanceMemberInfoD1, ["classThatExtendsClassExtendingAnotherClass"]);
// instance memebers in D2 and base class are shown
verifyClassElementLocations(instanceMemberInfoD2, ["classThatExtendsClassExtendingAnotherClassWithOverridingMember"]);
// static base members and class member keywords allowed
verifyClassElementLocations(staticMemberInfoDn, [
"classThatExtendsClassExtendingAnotherClassAndTypesStatic",
"classThatExtendsClassExtendingAnotherClassWithOverridingMemberAndTypesStatic"
]); | the_stack |
'use strict';
import { Logger, LogLevel } from 'chord/platform/log/common/log';
import { filenameToNodeName } from 'chord/platform/utils/common/paths';
const loggerWarning = new Logger(filenameToNodeName(__filename), LogLevel.Warning);
import { getRandomSample } from 'chord/base/node/random';
import { ASCII_LETTER_DIGIT } from 'chord/base/common/constants';
import { makeCookieJar, makeCookie, CookieJar } from 'chord/base/node/cookies';
import { querystringify } from 'chord/base/node/url';
import { request, IRequestOptions } from 'chord/base/node/_request';
import { IAudio } from 'chord/music/api/audio';
import { ISong } from 'chord/music/api/song';
import { ILyric } from 'chord/music/api/lyric';
import { IAlbum } from 'chord/music/api/album';
import { IArtist } from 'chord/music/api/artist';
import { ICollection } from 'chord/music/api/collection';
import { TMusicItems } from 'chord/music/api/items';
import { ESize, resizeImageUrl } from 'chord/music/common/size';
import {
makeSong,
makeLyric,
makeSongs,
makeAlbum,
makeAlbums,
makeArtist,
makeArtists,
makeCollection,
makeCollections,
} from "chord/music/kuwo/parser";
import { encryptQuery } from 'chord/music/kuwo/crypto';
const DOMAIN = 'kuwo.cn';
const LETTERS = Array.from(ASCII_LETTER_DIGIT);
/**
* Kuwo Music Api
*/
export class KuwoMusicApi {
static readonly HEADERS = {
'Pragma': 'no-cache',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'Accept': '*/*',
// Referer is needed
// 'Referer': 'http://h.kuwo.com/collect_detail.html?id=422425970&f=&from=&ch=',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
};
static readonly BASICURL = 'http://www.kuwo.cn/';
static readonly BASICURL_FLAC = 'http://mobi.kuwo.cn/';
static readonly NODE_MAP = {
audios: 'url',
audios_flac: 'mobi.s',
// No use this song node, it does not give audio url
song: 'api/www/music/musicInfo',
lyric: 'newh5/singles/songinfoandlrc',
album: 'api/www/album/albumInfo',
artist: 'api/www/artist/artist',
artistSongs: 'api/www/artist/artistMusic',
artistAlbums: 'api/www/artist/artistAlbum',
collection: 'api/www/playlist/playListInfo',
searchSongs: 'api/www/search/searchMusicBykeyWord',
searchAlbums: 'api/www/search/searchAlbumBykeyWord',
searchArtists: 'api/www/search/searchArtistBykeyWord',
searchCollections: 'api/www/search/searchPlayListBykeyWord',
}
private csrf_token: string;
private cookieJar: CookieJar;
constructor() {
this.reset();
}
public reset() {
let csrf_token = getRandomSample(LETTERS, 12).join('');
this.csrf_token = csrf_token;
let cookieJar = makeCookieJar();
let cookie = makeCookie('kw_token', csrf_token, DOMAIN);
cookieJar.setCookie(cookie, 'http://' + DOMAIN);
this.cookieJar = cookieJar;
}
/**
* Request
*/
public async request(node: string, apiParams: object, referer?: string, domain?: string): Promise<any | null> {
domain = domain || KuwoMusicApi.BASICURL;
let url = domain + node;
let params = apiParams ? querystringify(apiParams) : null;
let headers = !!referer ?
{ ...KuwoMusicApi.HEADERS, Referer: referer, csrf: this.csrf_token }
: { ...KuwoMusicApi.HEADERS, Referer: KuwoMusicApi.BASICURL, csrf: this.csrf_token };
url = url + '?' + params;
let options: IRequestOptions = {
method: 'GET',
url: url,
headers: headers,
jar: this.cookieJar || null,
gzip: true,
json: true,
resolveWithFullResponse: false,
};
let json: any = await request(options);
if (!(json.code == 200 || json.status == 200)) {
loggerWarning.warning('[KuwoMusicApi.request] [Error]: (params, response):', options, json);
}
return json;
}
/**
* Request flac audio
*/
public async request_audio_flac(songId: string): Promise<any | null> {
let domain = KuwoMusicApi.BASICURL_FLAC;
let url = domain + KuwoMusicApi.NODE_MAP.audios_flac;
let apiParams = {
f: 'kuwo',
q: encryptQuery('corp=kuwo&p2p=1&type=convert_url2&sig=0&format=flac&rid=' + songId),
};
let params = querystringify(apiParams);
let headers = {
'user-agent': 'okhttp/3.10.0',
};
url = url + '?' + params;
let options: IRequestOptions = {
method: 'GET',
url: url,
headers: headers,
jar: null,
gzip: true,
resolveWithFullResponse: false,
};
let info: any;
try {
info = await request(options);
} catch (e) {
return null;
}
if (info && info.startsWith('format=flac')) {
let kbps = /bitrate=(\d+)/.exec(info)[1];
let url = /url=([^\s]+)/.exec(info)[1];
return {
kbps: Number.parseInt(kbps),
url,
}
} else {
return null;
}
}
/**
* Get audio urls, the songId must be number string
*/
public async audios(songId: string, supKbps?: number): Promise<Array<IAudio>> {
let br: string;
let kbps: number;
if (supKbps <= 128) {
br = '128kmp3';
kbps = 128;
} else if (supKbps <= 192) {
br = '192kmp3';
kbps = 192;
} else if (supKbps <= 320) {
br = '320kmp3';
kbps = 320;
} else {
kbps = 720;
}
// flac
if (supKbps > 320) {
let info = await this.request_audio_flac(songId);
if (info) {
let audios = [
{
format: 'flac',
size: null,
kbps: info['kbps'],
url: info['url'],
path: null,
}
];
return audios;
} else {
br = '320kmp3';
kbps = 320;
}
}
let info = await this.request(
KuwoMusicApi.NODE_MAP.audios,
{
format: 'mp3',
rid: songId,
response: 'url',
type: 'convert_url3',
br,
from: 'web',
t: Date.now(),
},
);
let audios = [
{
format: 'mp3',
size: null,
kbps,
url: info['url'],
path: null,
}
];
return audios;
}
/**
* Get a song, the songId must be number string
*/
public async song(songId: string): Promise<ISong> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.song,
{ mid: songId },
);
let info = json.data;
let song = makeSong(info);
return song;
}
public async lyric(songId: string): Promise<ILyric> {
let info = await this.request(
KuwoMusicApi.NODE_MAP.lyric,
{ musicId: songId },
null,
'http://m.kuwo.cn/'
)
return makeLyric(songId, info.data.lrclist);
}
/**
* Get an album, the albumId must be number string
*/
public async album(albumId: string): Promise<IAlbum> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.album,
{
albumId,
pn: 1,
rn: 1000,
},
);
let info = json.data;
let album = makeAlbum(info);
return album;
}
/**
* Get an artist, the artistId must be number string
*/
public async artist(artistId: string): Promise<IArtist> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.artist,
{ artistid: artistId },
);
let info = json.data;
let artist = makeArtist(info);
return artist;
}
/**
* Get songs of an artist, the artistId must be number string
*/
public async artistSongs(artistId: string, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.artistSongs,
{
artistid: artistId,
pn: page,
rn: size,
},
);
let info = json.data.list;
let songs = makeSongs(info);
return songs;
}
/**
* Get albums of an artist, the artistId must be number string
*/
public async artistAlbums(artistId: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.artistAlbums,
{
artistid: artistId,
pn: page,
rn: size,
},
);
let info = json.data.albumList;
let albums = makeAlbums(info);
return albums;
}
/**
* Get a collection, the collectionId must be number string
*/
public async collection(collectionId: string, page: number = 1, size: number = 100): Promise<ICollection> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.collection,
{
pid: collectionId,
pn: page,
rn: size,
},
);
let info = json && json.data;
let collection = makeCollection(info);
return collection;
}
/**
* Search Songs
*/
public async searchSongs(keyword: string, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.searchSongs,
{
key: keyword.replace(/\s+/g, '+'),
pn: page,
rn: size,
},
);
let info = json && json.data && json.data.list;
let songs = makeSongs(info);
return songs;
}
/**
* Search albums
*/
public async searchAlbums(keyword: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.searchAlbums,
{
key: keyword.replace(/\s+/g, '+'),
pn: page,
rn: size,
},
);
let info = json && json.data && json.data.albumList;
let albums = makeAlbums(info);
return albums;
}
public async searchArtists(keyword: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.searchArtists,
{
key: keyword.replace(/\s+/g, '+'),
pn: page,
rn: size,
},
);
let info = json && json.data && json.data.artistList;
let artists = makeArtists(info);
return artists;
}
public async searchCollections(keyword: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> {
let json = await this.request(
KuwoMusicApi.NODE_MAP.searchCollections,
{
key: keyword.replace(/\s+/g, '+'),
pn: page,
rn: size,
},
);
let info = json && json.data && json.data.list;
let collections = makeCollections(info);
return collections;
}
/**
* Record played song
*/
public async playLog(songId: string, seek: number): Promise<boolean> {
return false;
}
public resizeImageUrl(url: string, size: ESize | number): string {
return resizeImageUrl(url, size, (url, size) => {
if (url.match('/userp')) {
if (size <= 150) {
size = 150;
} else if (size > 150 && size <= 300) {
size = 300;
} else if (size > 300 && size <= 500) {
size = 500;
} else if (size > 500) {
size = 700;
}
url = url.replace(/_\d{3}\.jpg/, '.jpg')
.replace('.jpg', size.toString());
} else {
if (size <= 120) {
size = 120;
} else if (size > 120 && size <= 300) {
size = 300;
} else if (size > 300) {
size = 500;
}
url = url.replace(/starheads\/\d{3}/, 'starheads/' + size.toString())
.replace(/albumcover\/\d{3}/, 'albumcover/' + size.toString());
}
return url;
});
}
public async fromURL(input: string): Promise<Array<TMusicItems>> {
let chunks = input.split(' ');
let items = [];
for (let chunk of chunks) {
let originId: string;
let type: string;
let matchList = [
// song
[/play_detail\/(\d+)/, 'song'],
// artist
[/singer_detail\/(\d+)/, 'artist'],
// album
[/album_detail\/(\d+)/, 'album'],
// collection
[/playlist_detail\/(\d+)/, 'collect'],
];
for (let [re, tp] of matchList) {
let m = (re as RegExp).exec(chunk);
if (m) {
originId = m[1];
type = tp as string;
break;
}
}
if (originId) {
let item: any;
switch (type) {
case 'song':
item = await this.song(originId);
items.push(item);
break;
case 'artist':
item = await this.artist(originId);
items.push(item);
break;
case 'album':
item = await this.album(originId);
items.push(item);
break;
case 'collect':
item = await this.collection(originId);
items.push(item);
break;
default:
break;
}
}
}
return items;
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { NotificationChannels } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { DevTestLabsClient } from "../devTestLabsClient";
import {
NotificationChannel,
NotificationChannelsListNextOptionalParams,
NotificationChannelsListOptionalParams,
NotificationChannelsListResponse,
NotificationChannelsGetOptionalParams,
NotificationChannelsGetResponse,
NotificationChannelsCreateOrUpdateOptionalParams,
NotificationChannelsCreateOrUpdateResponse,
NotificationChannelsDeleteOptionalParams,
NotificationChannelFragment,
NotificationChannelsUpdateOptionalParams,
NotificationChannelsUpdateResponse,
NotifyParameters,
NotificationChannelsNotifyOptionalParams,
NotificationChannelsListNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing NotificationChannels operations. */
export class NotificationChannelsImpl implements NotificationChannels {
private readonly client: DevTestLabsClient;
/**
* Initialize a new instance of the class NotificationChannels class.
* @param client Reference to the service client
*/
constructor(client: DevTestLabsClient) {
this.client = client;
}
/**
* List notification channels in a given lab.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param options The options parameters.
*/
public list(
resourceGroupName: string,
labName: string,
options?: NotificationChannelsListOptionalParams
): PagedAsyncIterableIterator<NotificationChannel> {
const iter = this.listPagingAll(resourceGroupName, labName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(resourceGroupName, labName, options);
}
};
}
private async *listPagingPage(
resourceGroupName: string,
labName: string,
options?: NotificationChannelsListOptionalParams
): AsyncIterableIterator<NotificationChannel[]> {
let result = await this._list(resourceGroupName, labName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(
resourceGroupName,
labName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
resourceGroupName: string,
labName: string,
options?: NotificationChannelsListOptionalParams
): AsyncIterableIterator<NotificationChannel> {
for await (const page of this.listPagingPage(
resourceGroupName,
labName,
options
)) {
yield* page;
}
}
/**
* List notification channels in a given lab.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param options The options parameters.
*/
private _list(
resourceGroupName: string,
labName: string,
options?: NotificationChannelsListOptionalParams
): Promise<NotificationChannelsListResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, options },
listOperationSpec
);
}
/**
* Get notification channel.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param name The name of the notification channel.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
labName: string,
name: string,
options?: NotificationChannelsGetOptionalParams
): Promise<NotificationChannelsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, name, options },
getOperationSpec
);
}
/**
* Create or replace an existing notification channel.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param name The name of the notification channel.
* @param notificationChannel A notification.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
labName: string,
name: string,
notificationChannel: NotificationChannel,
options?: NotificationChannelsCreateOrUpdateOptionalParams
): Promise<NotificationChannelsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, name, notificationChannel, options },
createOrUpdateOperationSpec
);
}
/**
* Delete notification channel.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param name The name of the notification channel.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
labName: string,
name: string,
options?: NotificationChannelsDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, name, options },
deleteOperationSpec
);
}
/**
* Allows modifying tags of notification channels. All other properties will be ignored.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param name The name of the notification channel.
* @param notificationChannel A notification.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
labName: string,
name: string,
notificationChannel: NotificationChannelFragment,
options?: NotificationChannelsUpdateOptionalParams
): Promise<NotificationChannelsUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, name, notificationChannel, options },
updateOperationSpec
);
}
/**
* Send notification to provided channel.
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param name The name of the notification channel.
* @param notifyParameters Properties for generating a Notification.
* @param options The options parameters.
*/
notify(
resourceGroupName: string,
labName: string,
name: string,
notifyParameters: NotifyParameters,
options?: NotificationChannelsNotifyOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, name, notifyParameters, options },
notifyOperationSpec
);
}
/**
* ListNext
* @param resourceGroupName The name of the resource group.
* @param labName The name of the lab.
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
resourceGroupName: string,
labName: string,
nextLink: string,
options?: NotificationChannelsListNextOptionalParams
): Promise<NotificationChannelsListNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, labName, nextLink, options },
listNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.NotificationChannelList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.expand,
Parameters.filter,
Parameters.top,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.NotificationChannel
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion, Parameters.expand],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.labName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.NotificationChannel
},
201: {
bodyMapper: Mappers.NotificationChannel
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.notificationChannel,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.labName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.labName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.NotificationChannel
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.notificationChannel1,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.labName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const notifyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/notificationchannels/{name}/notify",
httpMethod: "POST",
responses: {
200: {},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.notifyParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.name,
Parameters.labName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.NotificationChannelList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.expand,
Parameters.filter,
Parameters.top,
Parameters.orderby
],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.labName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
/**
*
* @module Kiwi
* @submodule Utils.
*
*/
module Kiwi.Utils {
/**
* A utilty class used to add management functionality to common console methods.
* You can use this class by either creating a new instance, or using the instance at the namespace 'Kiwi.Log'.
*
* log/error/warn methods contained on this class function just like their 'console' equivalents except that:
* - You can assign a tag to message by adding a '#' symbol to the front of a parameter. Example: this.log('Hi', '#welcome');
* - Messages can have multiple tags. Example: this.log('Hi', '#welcome', '#greeting');
* - Messages are recorded (by default) and you can then search through any messages saved.
*
* You can use the 'show' commands to search through recordings and find specific messages.
*
*
* @class Log
* @namespace Kiwi.Utils
* @constructor
* @param [params] {Object}
* @param [options.recording=true] {Boolean} If the logs should be recorded.
* @param [options.display=true] {Boolean} If the logs should be displayed or not.
* @param [options.enabled=true] {Boolean} If the Logger is enabled at all.
* @param [options.maxRecordings=Infinity] {Number} The maximum number of recordings to have at a single time.
*/
export class Log {
constructor(params: any= {}) {
this.setDefaultsFromParams(params);
}
/**
* Sets the log properties based on a object passed.
* This method is used to set the properties on the Log based on
* gameoptions passed at game creation.
*
* @method setDefaultsFromParams
* @param [params] {Object}
* @param [options.recording=true] {Boolean} If the logs should be recorded.
* @param [options.display=true] {Boolean} If the logs should be displayed or not.
* @param [options.enabled=true] {Boolean} If the Logger is enabled at all.
* @param [options.maxRecordings=Infinity] {Number} The maximum number of recordings to have at a single time.
* @public
*/
public setDefaultsFromParams(params: any= {}) {
if (!Kiwi.Utils.Common.isUndefined(params.enabled)) {
this.enabled = params.enabled;
}
if (!Kiwi.Utils.Common.isUndefined(params.recording)) {
this.recording = params.recording;
}
if (!Kiwi.Utils.Common.isUndefined(params.display)) {
this.display = params.display;
}
if (!Kiwi.Utils.Common.isUndefined(params.maxRecordings)) {
this.maxRecordings = params.maxRecordings;
}
if (Kiwi.Utils.Common.isArray(params.tagFilters)) {
this.tagFilters = params.tagFilters;
}
}
/**
* If the log, warn, or error messages should function at all.
* When set to false messages won't display or be recorded.
*
* @property enabled
* @type Boolean
* @default true
* @public
*/
public enabled: boolean = true;
/**
* If messages should be recorded or not.
*
* @property record
* @type Boolean
* @default true
* @public
*/
public recording: boolean = true;
/**
* If the log, warn, and error methods should display when executed or not.
* You may want to set this to 'false' when releasing a game.
*
* @property display
* @type Boolean
* @default true
* @public
*/
public display: boolean = true;
/**
* A list of tags which any message recorded needs to match in-order to be displayed.
* This helps when debugging systems with lots of messages, without removing every log.
*
* @property tagFilters
* @type Array
* @since 1.3.0
* @public
*/
public tagFilters: string[] = [];
/**
* The maximum number of recordings to be kept at once.
*
* @property maxRecordings
* @type Number
* @default Infinity
* @public
*/
public maxRecordings: number = Infinity;
/**
* A list containing all messages recorded.
*
* @property recordings
* @type Array
* @private
*/
private recordings: any[] = [];
/**
* The time (in milliseconds) of the last recording.
*
* @property lastMessageTime
* @type Number
* @readOnly
* @public
*/
public get lastMessageTime():number {
if (this.recordings.length > 0) {
return this.recordings[this.recordings.length - 1].time;
}
return 0;
}
/**
* The number of recordings that have been saved.
* Same as the recordings length, and won't go above the 'maxRecordings'.
*
* @property numRecordings
* @type Number
* @readOnly
* @public
*/
public get numRecordings():number {
return this.recordings.length;
}
/**
* Saves a message to the 'recordings' array.
* That message can then be retrieved later using the 'show' methods.
*
* @method recordMessage
* @param message {String}
* @param [tags=[]] {String}
* @param [logMethod=console.log] {String}
* @public
*/
public record(messages: string[], tags:string[]=[], logMethod:any=console.log) {
if (this.recording) {
var recording = {
messages: messages,
time: Date.now(),
tags: tags,
logMethod: logMethod
};
if (this.recordings.push(recording) > this.maxRecordings) {
this.recordings.shift();
}
}
}
/**
* Removes recordings from the list. Goes from the oldest to newest.
* By not passing any parameters, the entire log will be cleared.
*
* @method clearRecordings
* @param [start=0] {Number}
* @param [end] {Number}
* @public
*/
public clearRecordings(start: number=0, end: number=this.recordings.length) {
this.recordings.splice(start, end);
}
/**
* Executes a particular array of messages using a method passed.
* Takes into account the 'display' property before executing.
*
* @method _execute
* @param method {Any} The method that should be used to log the messages. Generally a console method.
* @param context {Any} The context that the method should be executed in. Generally set to the console.
* @param messages {Array}
* @param [force=false] {Array}
* @private
*/
private _execute(method:any, context: any, messages:string[], force:boolean=false) {
if (this.display || force) {
method.apply(context, messages);
}
}
/**
* Accepts an array of strings and returns a new array consisting of all elements considered as a tag.
*
* @method getTagsFromArray
* @param strings {Array}
* @return {Array} Elements of the array considered as tags
* @public
*/
public getTagsFromArray(array: string[]) {
var i = 0,
tags = [];
while (i < array.length) {
if (typeof array[i] === "string") {
if (array[i].charAt(0) === "#") {
tags.push(array[i]);
}
}
i++;
}
return tags;
}
/**
* Returns true if the all of the tags passed also occur in the tag filters.
* This is used to filter out messages by their tags.
*
* @method _filterTags
* @param tags {Array} A list of tags, which need to occur in the tag filters
* @param [tagFilters=this.tagFilters] {Array} A list of tags. Tags need to
* @return {Boolean} Tags match the tag filters, and so if the message would be allowed to execute.
* @since 1.3.0
* @private
*/
private _filterTags(tags: string[], tagFilters:string[] = this.tagFilters): boolean {
//No filters, then allow
if (tagFilters.length === 0) {
return true;
}
if (tags.length == 0) {
return false;
}
var i = 0;
while (i < tags.length) {
//If the tag does not appear in the filter list
if (tagFilters.indexOf(tags[i]) === -1) {
return false;
}
i++;
}
return true;
}
/**
* Logs a message using the 'console.log' method.
* Arguments starting with a '#' symbol are given that value as a tag.
*
* @method log
* @param [..args] {Any} The data you would like to log.
* @public
*/
public log(...args:any[]) {
if (!this.enabled) {
return;
}
var tags = this.getTagsFromArray(args);
this.record(args, tags, console.log);
if (this._filterTags(tags)) {
this._execute(console.log, console, args);
}
}
/**
* Logs a message using the 'console.warn' method.
* Arguments starting with a '#' symbol are given that value as a tag.
*
* @method warn
* @param [..args] {Any} The data you would like to log.
* @public
*/
public warn(...args: any[]) {
if (!this.enabled) {
return;
}
var tags = this.getTagsFromArray(args);
this.record(args, tags, console.warn);
if (this._filterTags(tags)) {
this._execute(console.warn, console, args);
}
}
/**
* Logs a message using the 'console.error' method.
* Arguments starting with a '#' symbol are given that value as a tag.
*
* @method error
* @param [..args] {Any} The data you would like to log.
* @public
*/
public error(...args: any[]) {
if (!this.enabled) {
return;
}
var tags = this.getTagsFromArray(args);
this.record(args, tags, console.error);
if (this._filterTags(tags)) {
this._execute(console.error, console, args);
}
}
/**
* Method that displays a particular recording passed.
*
* @method _show
* @param recording {Object}
* @param tags {Array}
* @return {Boolean} If the recording was displayed or not.
* @private
*/
private _show( recording, tags:string[] ) {
if (!recording.logMethod) {
return false;
}
//Check that the tags match
var n = tags.length;
while( n-- ) {
if ( recording.tags.indexOf( tags[ n ] ) == -1 ) {
return false;
}
}
this._execute(recording.logMethod, console, recording.messages, true );
return true;
}
/**
* Displays the last recording matching the tags passed.
* Ignores the tag filters.
*
* @method showLast
* @param [...args] {Any} Any tags that the recordings must have.
* @public
*/
public showLast(...args:any[]) {
var i = this.recordings.length;
while(i--) {
if (this._show(this.recordings[i], args)) {
return;
}
}
}
/**
* Displays all recordings.
* Ignores the tag filters.
*
* @method showAll
* @param [...args] {Any} Any tags that the recordings must have.
* @public
*/
public showAll(...args: any[]) {
for (var i = 0; i < this.recordings.length; i++) {
this._show(this.recordings[i], args );
}
}
/**
* Displays all logs recorded.
* Ignores the tag filters.
*
* @method showLogs
* @param [...args] {Any} Any tags that the recordings must have.
* @public
*/
public showLogs(...args: any[]) {
for (var i = 0; i < this.recordings.length; i++) {
if (this.recordings[i].logMethod === console.log) {
this._show(this.recordings[i], args);
}
}
}
/**
* Displays all errors recorded.
* Ignores the tag filters.
*
* @method showErrors
* @param [...args] {Any} Any tags that the recordings must have.
* @public
*/
public showErrors(...args: any[]) {
for (var i = 0; i < this.recordings.length; i++) {
if (this.recordings[i].logMethod === console.error) {
this._show(this.recordings[i], args);
}
}
}
/**
* Displays all warnings recorded.
* Ignores the tag filters.
*
* @method showWarnings
* @param [...args] {Any} Any tags that the recordings must have.
* @public
*/
public showWarnings(...args: any[]) {
for (var i = 0; i < this.recordings.length; i++) {
if (this.recordings[i].logMethod === console.warn) {
this._show(this.recordings[i], args);
}
}
}
/**
* Displays a series of recordings within a time period passed.
* Time recorded is in milliseconds.
* Ignores the tag filters.
*
* @method showTimePeriod
* @param [start=0] {Number}
* @param [end=Infinity] {Number}
* @param [tags] {Array} An tags that the recordings must have.
* @public
*/
public showTimePeriod(start: number=0, end: number=Infinity, tags:string[]=[]) {
var recording;
for (var i = 0; i < this.recordings.length; i++) {
recording = this.recordings[i];
if (start < recording.time && end > recording.time) {
this._show(recording, tags);
}
}
}
/**
* Adds a tag to the list of tag filters.
* Any messages that do not have the tags in the tagFilters list will not be displayed.
*
* @method addFilter
* @param [...args] {Any} Tags to add to the filters list.
* @since 1.3.0
* @public
*/
public addFilter(...args: any[]) {
this.tagFilters = this.tagFilters.concat(args);
}
/**
* Removes a tag to the list of tag filters.
* Any messages that do not have the tags in the tagFilters list will not be displayed.
*
* @method removeFilter
* @param [...args] {Any} Tags to be remove from the filters list.
* @since 1.3.0
* @public
*/
public removeFilter(...args: any[]) {
var i = 0,
index;
while (i < args.length) {
index = this.tagFilters.indexOf(args[i]);
if (index !== -1) {
this.tagFilters.splice(index, 1);
}
i++;
}
}
}
} | the_stack |
import { strict as assert } from "assert";
import {
createFromKey,
BspSet,
compare,
union,
intersect,
except,
dense,
empty,
symmetricDiff,
complement,
SetOperations,
forEachKey,
Dense,
meets,
pair,
Pair,
} from "../bspSet";
import { Ivl, ivlMeets, ivlCompare, ivlMeetsOrTouches, ivlJoin, ivlExcept } from "../split";
/** Represents a half-open 2D rectangle [xa,xb) x [ya,yb) */
type Rect2D = [Ivl, Ivl];
function rect2DMeets(rect1: Rect2D, rect2: Rect2D): boolean {
const [ivl1a, ivl1b] = rect1;
const [ivl2a, ivl2b] = rect2;
return ivlMeets(ivl1a, ivl2a) && ivlMeets(ivl1b, ivl2b);
}
function rect2DCompare(rect1: Rect2D, rect2: Rect2D) {
const [ivl1a, ivl1b] = rect1;
const [ivl2a, ivl2b] = rect2;
const cmpa = ivlCompare(ivl1a, ivl2a);
if (cmpa === undefined) { return undefined; }
const cmpb = ivlCompare(ivl1b, ivl2b);
if (cmpa === 0) { return cmpb; }
if (cmpb === 0) { return cmpa; }
return cmpa === cmpb ? cmpa : undefined;
}
export function splitIvl(key: Ivl): Pair<Ivl> {
const [x1, x2] = key;
// Exponentially growing
if (x2 === Infinity) {
return pair<Ivl>([x1, 2 * (x1 + 1) - 1], [2 * (x1 + 1) - 1, Infinity]);
}
// binary searching
// eslint-disable-next-line no-bitwise
const median = (x1 + x2) >> 1;
return pair<Ivl>([x1, median], [median, x2]);
}
describe("BSP-set tests", () => {
function split(key: Rect2D): Pair<Rect2D> {
const [[x1, x2]] = key;
if (x2 > x1 + 1) {
const [xLeft, xRight] = splitIvl(key[0]);
return [
[xLeft, key[1]],
[xRight, key[1]],
];
}
const [yLeft, yRight] = splitIvl(key[1]);
return [
[key[0], yLeft],
[key[0], yRight],
];
}
const top: Rect2D = [
[0, Infinity],
[0, Infinity],
];
const intersectRect2D = (
[[leftRowMin, leftRowMax], [leftColMin, leftColMax]]: Rect2D,
[[rightRowMin, rightRowMax], [rightColMin, rightColMax]]: Rect2D,
): Rect2D => [
[
Math.max(leftRowMin, rightRowMin),
Math.min(leftRowMax, rightRowMax),
],
[
Math.max(leftColMin, rightColMin),
Math.min(leftColMax, rightColMax),
],
];
function unionRect2D(
[leftRowIvl, leftColIvl]: Rect2D,
[rightRowIvl, rightColIvl]: Rect2D,
): Rect2D | undefined {
if (
ivlCompare(leftRowIvl, rightRowIvl) === 0 &&
ivlMeetsOrTouches(leftColIvl, rightColIvl)
) {
return [leftRowIvl, ivlJoin(leftColIvl, rightColIvl)];
}
if (
ivlCompare(leftColIvl, rightColIvl) === 0 &&
ivlMeetsOrTouches(leftRowIvl, rightRowIvl)
) {
return [ivlJoin(leftRowIvl, rightRowIvl), leftColIvl];
}
return undefined;
}
function exceptRect2D(
[leftRowIvl, leftColIvl]: Rect2D,
[rightRowIvl, rightColIvl]: Rect2D,
): Rect2D | undefined {
const rowCmp = ivlCompare(leftRowIvl, rightRowIvl);
const colCmp = ivlCompare(leftColIvl, rightColIvl);
if (rowCmp !== undefined && rowCmp <= 0) {
const newCols = ivlExcept(leftColIvl, rightColIvl);
if (newCols !== undefined) { return [leftRowIvl, newCols]; }
}
if (colCmp !== undefined && colCmp <= 0) {
const newRows = ivlExcept(leftRowIvl, rightRowIvl);
if (newRows !== undefined) { return [newRows, leftColIvl]; }
}
return undefined;
}
const simpleOperations: SetOperations<Rect2D, "simple id"> = {
split(key: Rect2D): Pair<[Rect2D, number]> {
const [left, right] = split(key);
return [
[left, NaN],
[right, NaN],
];
},
canSplit: () => true,
meets: rect2DMeets,
compare: rect2DCompare,
intersect: intersectRect2D,
union: unionRect2D,
except: exceptRect2D,
top,
id: "simple id" as const,
};
it("Split ivl tests, trying to reach 10", () => {
let myPair = splitIvl([0, Infinity]);
assert.deepStrictEqual(myPair[0], [0, 1]);
assert.deepStrictEqual(myPair[1], [1, Infinity]);
myPair = splitIvl(myPair[1]);
assert.deepStrictEqual(myPair[0], [1, 3]);
assert.deepStrictEqual(myPair[1], [3, Infinity]);
myPair = splitIvl(myPair[1]);
assert.deepStrictEqual(myPair[0], [3, 7]);
assert.deepStrictEqual(myPair[1], [7, Infinity]);
myPair = splitIvl(myPair[1]);
assert.deepStrictEqual(myPair[0], [7, 15]);
assert.deepStrictEqual(myPair[1], [15, Infinity]);
myPair = splitIvl(myPair[0]);
assert.deepStrictEqual(myPair[0], [7, 11]);
assert.deepStrictEqual(myPair[1], [11, 15]);
myPair = splitIvl(myPair[0]);
assert.deepStrictEqual(myPair[0], [7, 9]);
assert.deepStrictEqual(myPair[1], [9, 11]);
myPair = splitIvl(myPair[1]);
assert.deepStrictEqual(myPair[0], [9, 10]);
assert.deepStrictEqual(myPair[1], [10, 11]);
});
it("split tests, trying to reach 3, 3", () => {
let myPair = split([
[0, Infinity],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[0], [
[0, 1],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[1], [
[1, Infinity],
[0, Infinity],
]);
myPair = split(myPair[1]);
assert.deepStrictEqual(myPair[0], [
[1, 3],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[1], [
[3, Infinity],
[0, Infinity],
]);
myPair = split(myPair[1]);
assert.deepStrictEqual(myPair[0], [
[3, 7],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[1], [
[7, Infinity],
[0, Infinity],
]);
myPair = split(myPair[0]);
assert.deepStrictEqual(myPair[0], [
[3, 5],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[1], [
[5, 7],
[0, Infinity],
]);
myPair = split(myPair[0]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[0, Infinity],
]);
assert.deepStrictEqual(myPair[1], [
[4, 5],
[0, Infinity],
]);
myPair = split(myPair[0]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[0, 1],
]);
assert.deepStrictEqual(myPair[1], [
[3, 4],
[1, Infinity],
]);
myPair = split(myPair[1]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[1, 3],
]);
assert.deepStrictEqual(myPair[1], [
[3, 4],
[3, Infinity],
]);
myPair = split(myPair[1]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[3, 7],
]);
assert.deepStrictEqual(myPair[1], [
[3, 4],
[7, Infinity],
]);
myPair = split(myPair[0]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[3, 5],
]);
assert.deepStrictEqual(myPair[1], [
[3, 4],
[5, 7],
]);
myPair = split(myPair[0]);
assert.deepStrictEqual(myPair[0], [
[3, 4],
[3, 4],
]);
assert.deepStrictEqual(myPair[1], [
[3, 4],
[4, 5],
]);
});
it("meets repro", () => {
assert.deepStrictEqual(ivlMeets([4, 5], [3, 6]), true);
assert.deepStrictEqual(ivlMeets([0, Infinity], [3, 5]), true);
assert.deepStrictEqual(
rect2DMeets(
[
[4, 5],
[0, Infinity],
],
[
[3, 6],
[3, 5],
],
), true);
});
it("Build up a big set out of many small ones", () => {
const rectangles: Rect2D[] = [];
for (let i = 3; i < 7; i += 1) {
for (let j = 3; j < 7; j += 1) {
rectangles.push([
[i, Math.min(i + j, 7)],
[j, Math.max(j + 1, Math.min(i - j + 5, 7))],
]);
}
}
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const sets = rectangles.map(createFromKey_inner);
const expected = createFromKey_inner([
[3, 7],
[3, 7],
]);
for (const set of sets) {
const cmp = compare(set, expected);
assert.equal(cmp !== undefined && cmp < 0, true);
}
const actual = sets.reduce(union);
assert.equal(compare(actual, expected), 0);
}
test(createFromKey(simpleOperations));
});
it("union repro", () => {
const rectangles: Rect2D[] = [
[
[0, 1],
[0, 2],
],
[
[1, 2],
[0, 1],
],
[
[1, 2],
[1, 2],
],
];
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const sets = rectangles.map(createFromKey_inner);
const expected = createFromKey_inner([
[0, 2],
[0, 2],
]);
for (const set of sets) {
const cmp = compare(set, expected);
assert.equal(cmp !== undefined && cmp < 0, true);
}
const actual = sets.reduce(union);
assert.equal(compare(actual, expected), 0);
}
test(createFromKey(simpleOperations));
});
it("Compute a large intersection", () => {
const rectangles: Rect2D[] = [];
for (let i = 3; i < 7; i += 1) {
for (let j = 3; j < 7; j += 1) {
rectangles.push([
[i, Math.max(i + j, 8)],
[j, Math.max(8, i - j + 10)],
]);
}
}
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const sets = rectangles.map(createFromKey_inner);
const expected = createFromKey_inner([
[6, 8],
[6, 8],
]);
for (const set of sets) {
const cmp = compare(set, expected);
assert.equal(cmp !== undefined && cmp > 0, true);
}
const actual = sets.reduce(intersect);
assert.equal(compare(actual, expected), 0);
}
test(createFromKey(simpleOperations));
});
it("Compute a large set difference", () => {
const rectangles: Rect2D[] = [];
for (let i = 3; i < 7; i += 1) {
for (let j = 3; j < 7; j += 1) {
rectangles.push([
[i, Math.max(8, i + j)],
[j + 2, Math.max(9, i - j + 10)],
]);
rectangles.push([
[i + 2, Math.max(8, i + j)],
[j, Math.max(9, i - j + 10)],
]);
}
}
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const sets = rectangles.map(createFromKey_inner);
const expected = createFromKey_inner([
[3, 5],
[3, 5],
]);
for (const set of sets) {
assert.equal(compare(set, expected), undefined);
}
const actual = sets.reduce(
except,
createFromKey_inner([
[3, 8],
[3, 8],
]),
);
assert.equal(compare(actual, expected), 0);
}
test(createFromKey(simpleOperations));
});
it("Symmetric difference", () => {
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const a = createFromKey_inner([
[1, 3],
[1, 3],
]);
const b = createFromKey_inner([
[2, 4],
[2, 4],
]);
const actual = symmetricDiff(a, b);
const points: [number, number][] = [
[1, 1],
[1, 2],
[2, 1],
[3, 2],
[3, 3],
[2, 3],
];
const expected = points
.map(([x, y]) =>
createFromKey_inner([
[x, x + 1],
[y, y + 1],
]),
)
.reduce(union);
assert.equal(compare(actual, expected), 0);
}
test(createFromKey(simpleOperations));
});
it("Meets", () => {
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const a = createFromKey_inner([
[1, 3],
[1, 3],
]);
const b = createFromKey_inner([
[2, 4],
[2, 4],
]);
const actual = meets(a, b);
assert.equal(actual, true);
}
test(createFromKey(simpleOperations));
});
it("Complement", () => {
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const a = createFromKey_inner([
[1, 3],
[1, 3],
]);
const expected = except(dense, a);
const actual = complement(a);
assert.deepStrictEqual(actual, expected);
assert.equal(compare(actual, expected), 0);
assert.equal(compare(intersect(actual, a), empty), 0);
assert.equal(complement(empty), dense);
assert.equal(complement(dense), empty);
}
test(createFromKey(simpleOperations));
});
it("Test empty set as result", () => {
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const a = createFromKey_inner([
[1, 1],
[2, 2],
]);
const b = createFromKey_inner([
[2, 2],
[1, 1],
]);
const actual = intersect(a, b);
assert.equal(actual, empty);
assert.equal(compare(actual, empty), 0);
}
test(createFromKey(simpleOperations));
});
it("forEachKey", () => {
assert.doesNotThrow(() =>
forEachKey(empty, () => {
throw new Error("should not be called");
}),
);
function test<T>(createFromKey_inner: (key: Rect2D) => BspSet<Rect2D, T>) {
const a = createFromKey_inner([
[1, 3],
[1, 3],
]) as Exclude<BspSet<Rect2D, T>, Dense>;
const b = createFromKey_inner([
[2, 4],
[2, 4],
]) as Exclude<BspSet<Rect2D, T>, Dense>;
const u = union(a, b) as Exclude<BspSet<Rect2D, T>, Dense>;
let n = 0;
forEachKey(a, (key) => {
assert.deepEqual(key, [
[1, 3],
[1, 3],
]);
n += 1;
return true;
});
assert.equal(n, 1);
let v: BspSet<Rect2D, T> = empty;
n = 0;
forEachKey(u, (key) => {
v = union(v, createFromKey_inner(key));
n += 1;
return true;
});
assert.equal(compare(u, v), 0);
assert.equal(n > 2, true);
}
test(createFromKey(simpleOperations));
});
}); | the_stack |
import { GraphQLInputObjectType } from './graphql';
import { resolveMaybeThunk, upperFirst, inspect, mapEachKey } from './utils/misc';
import { isObject, isFunction, isString } from './utils/is';
import { typeByPath, TypeInPath } from './utils/typeByPath';
import type {
Thunk,
ThunkWithSchemaComposer,
ObjMap,
Extensions,
Directive,
DirectiveArgs,
} from './utils/definitions';
import { SchemaComposer } from './SchemaComposer';
import { ListComposer } from './ListComposer';
import { NonNullComposer } from './NonNullComposer';
import type { ThunkComposer } from './ThunkComposer';
import type { TypeAsString, TypeDefinitionString } from './TypeMapper';
import type {
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap,
GraphQLInputType,
InputValueDefinitionNode,
} from './graphql';
import { graphqlVersion } from './utils/graphqlVersion';
import { defineInputFieldMap, convertInputFieldMapToConfig } from './utils/configToDefine';
import {
unwrapInputTC,
isTypeNameString,
cloneTypeTo,
NamedTypeComposer,
ComposeInputType,
ComposeNamedInputType,
ComposeInputTypeDefinition,
} from './utils/typeHelpers';
import { printInputObject, SchemaPrinterOptions } from './utils/schemaPrinter';
import { getInputObjectTypeDefinitionNode } from './utils/definitionNode';
import { getSortMethodFromOption } from './utils/schemaPrinterSortTypes';
export type InputTypeComposerDefinition =
| TypeAsString
| TypeDefinitionString
| InputTypeComposerAsObjectDefinition
| Readonly<GraphQLInputObjectType>;
export type InputTypeComposerAsObjectDefinition = {
name: string;
fields: ThunkWithSchemaComposer<InputTypeComposerFieldConfigMapDefinition, SchemaComposer<any>>;
description?: null | string;
extensions?: Extensions;
directives?: Directive[];
};
export type InputTypeComposerFieldConfigMap = ObjMap<InputTypeComposerFieldConfig>;
export type InputTypeComposerFieldConfigMapDefinition =
ObjMap<InputTypeComposerFieldConfigDefinition>;
export type InputTypeComposerFieldConfigDefinition =
| ThunkWithSchemaComposer<InputTypeComposerFieldConfigAsObjectDefinition, SchemaComposer<any>>
| ThunkWithSchemaComposer<ComposeInputTypeDefinition, SchemaComposer<any>>;
export type InputTypeComposerFieldConfigAsObjectDefinition = {
type: ThunkWithSchemaComposer<ComposeInputTypeDefinition, SchemaComposer<any>>;
defaultValue?: unknown;
description?: string | null;
extensions?: Extensions;
directives?: Directive[];
[key: string]: unknown;
};
export type InputTypeComposerFieldConfig = {
type: ComposeInputType;
defaultValue?: unknown;
description?: string | null;
astNode?: InputValueDefinitionNode | null;
extensions?: Extensions;
directives?: Directive[];
[key: string]: unknown;
};
export type InputTypeComposerThunked<TContext> =
| InputTypeComposer<TContext>
| ThunkComposer<InputTypeComposer<TContext>, GraphQLInputType>;
export class InputTypeComposer<TContext = any> {
schemaComposer: SchemaComposer<TContext>;
_gqType: GraphQLInputObjectType;
_gqcFields: InputTypeComposerFieldConfigMap;
_gqcExtensions?: Extensions;
_gqcDirectives?: Directive[];
_gqcIsModified?: boolean;
/**
* Create `InputTypeComposer` with adding it by name to the `SchemaComposer`.
*/
static create<TCtx = any>(
typeDef: InputTypeComposerDefinition,
schemaComposer: SchemaComposer<TCtx>
): InputTypeComposer<TCtx> {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `InputTypeComposer.create(typeDef, schemaComposer)`'
);
}
if (schemaComposer.hasInstance(typeDef, InputTypeComposer)) {
return schemaComposer.getITC(typeDef);
}
const itc = this.createTemp(typeDef, schemaComposer);
schemaComposer.add(itc);
return itc;
}
/**
* Create `InputTypeComposer` without adding it to the `SchemaComposer`. This method may be useful in plugins, when you need to create type temporary.
*/
static createTemp<TCtx = any>(
typeDef: InputTypeComposerDefinition,
schemaComposer?: SchemaComposer<TCtx>
): InputTypeComposer<TCtx> {
const sc = schemaComposer || new SchemaComposer();
let ITC;
if (isString(typeDef)) {
const typeName: string = typeDef;
if (isTypeNameString(typeName)) {
ITC = new InputTypeComposer(
new GraphQLInputObjectType({
name: typeName,
fields: () => ({}),
}),
sc
);
} else {
ITC = sc.typeMapper.convertSDLTypeDefinition(typeName);
if (!(ITC instanceof InputTypeComposer)) {
throw new Error(
'You should provide correct GraphQLInputObjectType type definition. ' +
'Eg. `input MyInputType { name: String! }`'
);
}
}
} else if (typeDef instanceof GraphQLInputObjectType) {
ITC = new InputTypeComposer(typeDef, sc);
} else if (isObject(typeDef)) {
const type = new GraphQLInputObjectType({
name: typeDef.name,
description: typeDef.description,
fields: () => ({}),
});
ITC = new InputTypeComposer(type, sc);
const fields = (typeDef as any).fields;
if (isFunction(fields)) {
// `convertInputFieldMapToConfig` helps to solve hoisting problems
// rewrap fields `() => { f1: { type: A } }` -> `{ f1: { type: () => A } }`
ITC.addFields(convertInputFieldMapToConfig(fields, sc));
}
if (isObject(fields)) ITC.addFields(fields);
ITC.setExtensions(typeDef.extensions || undefined);
if (Array.isArray((typeDef as any)?.directives)) {
ITC.setDirectives((typeDef as any).directives);
}
} else {
throw new Error(
`You should provide InputObjectConfig or string with type name to InputTypeComposer.create(typeDef). Provided:\n${inspect(
typeDef
)}`
);
}
return ITC;
}
constructor(graphqlType: GraphQLInputObjectType, schemaComposer: SchemaComposer<TContext>) {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `new InputTypeComposer(GraphQLInputType, SchemaComposer)`'
);
}
if (!(graphqlType instanceof GraphQLInputObjectType)) {
throw new Error('InputTypeComposer accept only GraphQLInputObjectType in constructor');
}
this.schemaComposer = schemaComposer;
this._gqType = graphqlType;
// add itself to TypeStorage on create
// it avoids recursive type use errors
this.schemaComposer.set(graphqlType, this);
this.schemaComposer.set(graphqlType.name, this);
if (graphqlVersion >= 14) {
this._gqcFields = convertInputFieldMapToConfig(
(this._gqType as any)._fields,
this.schemaComposer
);
} else {
const fields: Thunk<GraphQLInputFieldConfigMap> = (this._gqType as any)._typeConfig.fields;
this._gqcFields = this.schemaComposer.typeMapper.convertInputFieldConfigMap(
(resolveMaybeThunk(fields) as any) || {},
this.getTypeName()
);
}
if (!this._gqType.astNode) {
this._gqType.astNode = getInputObjectTypeDefinitionNode(this);
}
this._gqcIsModified = false;
}
// -----------------------------------------------
// Field methods
// -----------------------------------------------
getFields(): InputTypeComposerFieldConfigMap {
return this._gqcFields;
}
getFieldNames(): string[] {
return Object.keys(this._gqcFields);
}
hasField(fieldName: string): boolean {
return !!this._gqcFields[fieldName];
}
setFields(fields: InputTypeComposerFieldConfigMapDefinition): this {
this._gqcFields = {};
Object.keys(fields).forEach((name) => {
this.setField(name, fields[name]);
});
return this;
}
setField(fieldName: string, fieldConfig: InputTypeComposerFieldConfigDefinition): this {
this._gqcFields[fieldName] = isFunction(fieldConfig)
? (fieldConfig as any)
: this.schemaComposer.typeMapper.convertInputFieldConfig(
fieldConfig,
fieldName,
this.getTypeName()
);
this._gqcIsModified = true;
return this;
}
/**
* Add new fields or replace existed in a GraphQL type
*/
addFields(newFields: InputTypeComposerFieldConfigMapDefinition): this {
Object.keys(newFields).forEach((name) => {
this.setField(name, newFields[name]);
});
return this;
}
/**
* Add new fields or replace existed (where field name may have dots)
*/
addNestedFields(newFields: InputTypeComposerFieldConfigMapDefinition): this {
Object.keys(newFields).forEach((fieldName) => {
const fc = newFields[fieldName];
const names = fieldName.split('.');
const name = names.shift();
if (!name) {
throw new Error(`Type ${this.getTypeName()} has invalid field name: ${fieldName}`);
}
if (names.length === 0) {
// single field
this.setField(name, fc);
} else {
// nested field
let childTC;
if (!this.hasField(name)) {
childTC = InputTypeComposer.create(
`${this.getTypeName()}${upperFirst(name)}`,
this.schemaComposer
);
this.setField(name, childTC);
} else {
childTC = this.getFieldTC(name);
}
if (childTC instanceof InputTypeComposer) {
childTC.addNestedFields({ [names.join('.')]: fc });
}
}
});
return this;
}
getField(fieldName: string): InputTypeComposerFieldConfig {
// If FieldConfig is a Thunk then unwrap it on first read.
// In most cases FieldConfig is an object,
// but for solving hoisting problems it's quite good to wrap it in function.
if (isFunction(this._gqcFields[fieldName])) {
const unwrappedFieldConfig = (this._gqcFields as any)[fieldName](this.schemaComposer);
this.setField(fieldName, unwrappedFieldConfig);
}
const field = this._gqcFields[fieldName];
if (!field) {
throw new Error(
`Cannot get field '${fieldName}' from input type '${this.getTypeName()}'. Field does not exist.`
);
}
return field;
}
/**
* Remove fields from type by name or array of names.
* You also may pass name in dot-notation, in such case will be removed nested field.
*
* @example
* removeField('field1'); // remove 1 field
* removeField(['field1', 'field2']); // remove 2 fields
* removeField('field1.subField1'); // remove 1 nested field
*/
removeField(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const names = fieldName.split('.');
const name = names.shift();
if (!name) return;
if (names.length === 0) {
// single field
delete this._gqcFields[name];
this._gqcIsModified = true;
} else {
// nested field
// eslint-disable-next-line no-lonely-if
if (this.hasField(name)) {
const subTC = this.getFieldTC(name);
if (subTC instanceof InputTypeComposer) {
subTC.removeField(names.join('.'));
}
}
}
});
return this;
}
removeOtherFields(fieldNameOrArray: string | string[]): this {
const keepFieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
Object.keys(this._gqcFields).forEach((fieldName) => {
if (keepFieldNames.indexOf(fieldName) === -1) {
delete this._gqcFields[fieldName];
this._gqcIsModified = true;
}
});
return this;
}
extendField(
fieldName: string,
partialFieldConfig: Partial<InputTypeComposerFieldConfigAsObjectDefinition>
): this {
let prevFieldConfig;
try {
prevFieldConfig = this.getField(fieldName);
} catch (e) {
throw new Error(
`Cannot extend field '${fieldName}' from input type '${this.getTypeName()}'. Field does not exist.`
);
}
this.setField(fieldName, {
...prevFieldConfig,
...partialFieldConfig,
extensions: {
...(prevFieldConfig.extensions || {}),
...(partialFieldConfig.extensions || {}),
},
directives: [...(prevFieldConfig.directives || []), ...(partialFieldConfig.directives || [])],
});
return this;
}
reorderFields(names: string[]): this {
const orderedFields = {} as InputTypeComposerFieldConfigMap;
const fields = this._gqcFields;
names.forEach((name) => {
if (fields[name]) {
orderedFields[name] = fields[name];
delete fields[name];
}
});
this._gqcFields = { ...orderedFields, ...fields };
this._gqcIsModified = true;
return this;
}
getFieldConfig(fieldName: string): GraphQLInputFieldConfig {
const { type, ...rest } = this.getField(fieldName);
return {
type: type.getType(),
...rest,
};
}
getFieldType(fieldName: string): GraphQLInputType {
return this.getField(fieldName).type.getType();
}
getFieldTypeName(fieldName: string): string {
return this.getField(fieldName).type.getTypeName();
}
/**
* Automatically unwrap from List, NonNull, ThunkComposer
* It's important! Cause greatly helps to modify fields types in a real code
* without manual unwrap writing.
*
* If you need to work with wrappers, you may use the following code:
* - `TC.getField().type` // returns real wrapped TypeComposer
* - `TC.isFieldNonNull()` // checks is field NonNull or not
* - `TC.makeFieldNonNull()` // for wrapping in NonNullComposer
* - `TC.makeFieldNullable()` // for unwrapping from NonNullComposer
* - `TC.isFieldPlural()` // checks is field wrapped in ListComposer or not
* - `TC.makeFieldPlural()` // for wrapping in ListComposer
* - `TC.makeFieldNonPlural()` // for unwrapping from ListComposer
*/
getFieldTC(fieldName: string): ComposeNamedInputType<TContext> {
const anyTC = this.getField(fieldName).type;
return unwrapInputTC(anyTC);
}
/**
* Alias for `getFieldTC()` but returns statically checked InputTypeComposer.
* If field have other type then error will be thrown.
*/
getFieldITC(fieldName: string): InputTypeComposer<TContext> {
const tc = this.getFieldTC(fieldName);
if (!(tc instanceof InputTypeComposer)) {
throw new Error(
`${this.getTypeName()}.getFieldITC('${fieldName}') must be InputTypeComposer, but received ${
tc.constructor.name
}. Maybe you need to use 'getFieldTC()' method which returns any type composer?`
);
}
return tc;
}
// alias for `isFieldNonNull()` (may be deprecated in future)
isRequired(fieldName: string): boolean {
return this.isFieldNonNull(fieldName);
}
isFieldNonNull(fieldName: string): boolean {
return this.getField(fieldName).type instanceof NonNullComposer;
}
makeFieldNonNull(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof NonNullComposer)) {
fc.type = new NonNullComposer(fc.type);
this._gqcIsModified = true;
}
});
return this;
}
/**
* An alias for `makeFieldNonNull()`
*/
makeRequired(fieldNameOrArray: string | string[]): this {
return this.makeFieldNonNull(fieldNameOrArray);
}
makeFieldNullable(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && fc.type instanceof NonNullComposer) {
fc.type = fc.type.ofType;
this._gqcIsModified = true;
}
});
return this;
}
/**
* An alias for `makeFieldNullable()`
*/
makeOptional(fieldNameOrArray: string | string[]): this {
return this.makeFieldNullable(fieldNameOrArray);
}
isFieldPlural(fieldName: string): boolean {
const type = this.getField(fieldName).type;
return (
type instanceof ListComposer ||
(type instanceof NonNullComposer && type.ofType instanceof ListComposer)
);
}
makeFieldPlural(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof ListComposer)) {
fc.type = new ListComposer(fc.type);
this._gqcIsModified = true;
}
});
return this;
}
makeFieldNonPlural(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc) {
if (fc.type instanceof ListComposer) {
fc.type = fc.type.ofType;
this._gqcIsModified = true;
} else if (fc.type instanceof NonNullComposer && fc.type.ofType instanceof ListComposer) {
fc.type =
fc.type.ofType.ofType instanceof NonNullComposer
? fc.type.ofType.ofType
: new NonNullComposer(fc.type.ofType.ofType);
this._gqcIsModified = true;
}
}
});
return this;
}
// -----------------------------------------------
// Type methods
// -----------------------------------------------
getType(): GraphQLInputObjectType {
if (this._gqcIsModified) {
this._gqcIsModified = false;
this._gqType.astNode = getInputObjectTypeDefinitionNode(this);
if (graphqlVersion >= 14) {
(this._gqType as any)._fields = () => {
return defineInputFieldMap(
this._gqType,
mapEachKey(this._gqcFields, (_, name) => this.getFieldConfig(name)) as any,
this._gqType.astNode
);
};
} else {
(this._gqType as any)._typeConfig.fields = () => {
return mapEachKey(this._gqcFields, (_, name) => this.getFieldConfig(name));
};
delete (this._gqType as any)._fields;
}
}
return this._gqType;
}
getTypePlural(): ListComposer<InputTypeComposer<TContext>> {
return new ListComposer(this);
}
getTypeNonNull(): NonNullComposer<InputTypeComposer<TContext>> {
return new NonNullComposer(this);
}
/**
* Get Type wrapped in List modifier
*
* @example
* const UserTC = schemaComposer.createInputTC(`input UserInput { name: String }`);
* schemaComposer.Mutation.addFields({
* add: {
* args: {
* users1: UserTC.List, // in SDL: users1: [UserInput]
* users2: UserTC.NonNull.List, // in SDL: users2: [UserInput!]
* users3: UserTC.NonNull.List.NonNull, // in SDL: users2: [UserInput!]!
* }
* }
* })
*/
get List(): ListComposer<InputTypeComposer<TContext>> {
return new ListComposer(this);
}
/**
* Get Type wrapped in NonNull modifier
*
* @example
* const UserTC = schemaComposer.createInputTC(`input UserInput { name: String }`);
* schemaComposer.Mutation.addFields({
* add: {
* args: {
* users1: UserTC.List, // in SDL: users1: [UserInput]
* users2: UserTC.NonNull.List, // in SDL: users2: [UserInput!]
* users3: UserTC.NonNull.List.NonNull, // in SDL: users2: [UserInput!]!
* }
* }
* })
*/
get NonNull(): NonNullComposer<InputTypeComposer<TContext>> {
return new NonNullComposer(this);
}
getTypeName(): string {
return this._gqType.name;
}
setTypeName(name: string): this {
this._gqType.name = name;
this._gqcIsModified = true;
this.schemaComposer.set(name, this);
return this;
}
getDescription(): string {
return this._gqType.description || '';
}
setDescription(description: string): this {
this._gqType.description = description;
this._gqcIsModified = true;
return this;
}
/**
* You may clone this type with a new provided name as string.
* Or you may provide a new TypeComposer which will get all cloned
* settings from this type.
*/
clone(newTypeNameOrTC: string | InputTypeComposer<any>): InputTypeComposer<TContext> {
if (!newTypeNameOrTC) {
throw new Error('You should provide new type name for clone() method');
}
const cloned =
newTypeNameOrTC instanceof InputTypeComposer
? newTypeNameOrTC
: InputTypeComposer.create(newTypeNameOrTC, this.schemaComposer);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
extensions: { ...fieldConfig.extensions },
directives: fieldConfig.directives && [...(fieldConfig.directives || [])],
}));
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
cloned.setDirectives(this.getDirectives());
return cloned;
}
/**
* Clone this type to another SchemaComposer.
* Also will be cloned all sub-types.
*/
cloneTo(
anotherSchemaComposer: SchemaComposer<any>,
cloneMap: Map<any, any> = new Map()
): InputTypeComposer<any> {
if (!anotherSchemaComposer) {
throw new Error('You should provide SchemaComposer for InputTypeComposer.cloneTo()');
}
if (cloneMap.has(this)) return cloneMap.get(this);
const cloned = InputTypeComposer.create(this.getTypeName(), anotherSchemaComposer);
cloneMap.set(this, cloned);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
type: cloneTypeTo(fieldConfig.type, anotherSchemaComposer, cloneMap) as ComposeInputType,
extensions: { ...fieldConfig.extensions },
}));
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
return cloned;
}
merge(type: GraphQLInputObjectType | InputTypeComposer<any>): this {
let tc: InputTypeComposer<any>;
if (type instanceof GraphQLInputObjectType) {
tc = InputTypeComposer.createTemp(type, this.schemaComposer);
} else if (type instanceof InputTypeComposer) {
tc = type;
} else {
throw new Error(
`Cannot merge ${inspect(
type
)} with InputObjectType(${this.getTypeName()}). Provided type should be GraphQLInputObjectType or InputTypeComposer.`
);
}
// deep clone all fields
const fields = { ...tc.getFields() } as InputTypeComposerFieldConfigMapDefinition;
Object.keys(fields).forEach((fieldName) => {
fields[fieldName] = {
...(fields[fieldName] as any),
// set type as SDL string, it automatically will be remapped to the correct type instance in the current schema
type: tc.getFieldTypeName(fieldName),
};
});
this.addFields(fields);
return this;
}
// -----------------------------------------------
// Extensions methods
//
// `Extensions` is a property on type/field/arg definitions to pass private extra metadata.
// It's used only on the server-side with the Code-First approach,
// mostly for 3rd party server middlewares & plugins.
// Property `extensions` may contain private server metadata of any type (even functions)
// and does not available via SDL.
//
// @see https://github.com/graphql/graphql-js/issues/1527
// @note
// If you need to provide public metadata to clients then use `directives` instead.
// -----------------------------------------------
getExtensions(): Extensions {
if (!this._gqcExtensions) {
return {};
} else {
return this._gqcExtensions;
}
}
setExtensions(extensions: Extensions | undefined): this {
this._gqcExtensions = extensions || undefined;
this._gqcIsModified = true;
return this;
}
extendExtensions(extensions: Extensions): this {
const current = this.getExtensions();
this.setExtensions({
...current,
...extensions,
});
return this;
}
clearExtensions(): this {
this.setExtensions({});
return this;
}
getExtension(extensionName: string): unknown {
const extensions = this.getExtensions();
return extensions[extensionName];
}
hasExtension(extensionName: string): boolean {
const extensions = this.getExtensions();
return extensionName in extensions;
}
setExtension(extensionName: string, value: unknown): this {
this.extendExtensions({
[extensionName]: value,
});
return this;
}
removeExtension(extensionName: string): this {
const extensions = { ...this.getExtensions() };
delete extensions[extensionName];
this.setExtensions(extensions);
return this;
}
getFieldExtensions(fieldName: string): Extensions {
const field = this.getField(fieldName);
return field.extensions || {};
}
setFieldExtensions(fieldName: string, extensions: Extensions): this {
const field = this.getField(fieldName);
this.setField(fieldName, { ...field, extensions });
return this;
}
extendFieldExtensions(fieldName: string, extensions: Extensions): this {
const current = this.getFieldExtensions(fieldName);
this.setFieldExtensions(fieldName, {
...current,
...extensions,
});
return this;
}
clearFieldExtensions(fieldName: string): this {
this.setFieldExtensions(fieldName, {});
return this;
}
getFieldExtension(fieldName: string, extensionName: string): unknown {
const extensions = this.getFieldExtensions(fieldName);
return extensions[extensionName];
}
hasFieldExtension(fieldName: string, extensionName: string): boolean {
const extensions = this.getFieldExtensions(fieldName);
return extensionName in extensions;
}
setFieldExtension(fieldName: string, extensionName: string, value: unknown): this {
this.extendFieldExtensions(fieldName, {
[extensionName]: value,
});
return this;
}
removeFieldExtension(fieldName: string, extensionName: string): this {
const extensions = { ...this.getFieldExtensions(fieldName) };
delete extensions[extensionName];
this.setFieldExtensions(fieldName, extensions);
return this;
}
// -----------------------------------------------
// Directive methods
//
// Directives provide the ability to work with public metadata which is available via SDL.
// Directives can be used on type/field/arg definitions. The most famous directives are
// `@deprecated(reason: "...")` and `@specifiedBy(url: "...")` which are present in GraphQL spec.
// GraphQL spec allows to you add any own directives.
//
// @example
// type Article @directive1 {
// name @directive2
// comments(limit: Int @directive3)
// }
//
// @note
// If you need private metadata then use `extensions` instead.
// -----------------------------------------------
getDirectives(): Array<Directive> {
return this._gqcDirectives || [];
}
setDirectives(directives: Array<Directive>): this {
this._gqcDirectives = directives;
this._gqcIsModified = true;
return this;
}
getDirectiveNames(): string[] {
return this.getDirectives().map((d) => d.name);
}
/**
* Returns arguments of first found directive by name.
* If directive does not exists then will be returned undefined.
*/
getDirectiveByName(directiveName: string): DirectiveArgs | undefined {
const directive = this.getDirectives().find((d) => d.name === directiveName);
if (!directive) return undefined;
return directive.args;
}
/**
* Set arguments of first found directive by name.
* If directive does not exists then will be created new one.
*/
setDirectiveByName(directiveName: string, args?: DirectiveArgs): this {
const directives = this.getDirectives();
const idx = directives.findIndex((d) => d.name === directiveName);
if (idx >= 0) {
directives[idx].args = args;
} else {
directives.push({ name: directiveName, args });
}
this.setDirectives(directives);
return this;
}
getDirectiveById(idx: number): DirectiveArgs | undefined {
const directive = this.getDirectives()[idx];
if (!directive) return undefined;
return directive.args;
}
getFieldDirectives(fieldName: string): Array<Directive> {
return this.getField(fieldName).directives || [];
}
setFieldDirectives(fieldName: string, directives: Array<Directive> | undefined): this {
const fc = this.getField(fieldName);
fc.directives = directives;
this._gqcIsModified = true;
return this;
}
getFieldDirectiveNames(fieldName: string): string[] {
return this.getFieldDirectives(fieldName).map((d) => d.name);
}
/**
* Returns arguments of first found directive by name.
* If directive does not exists then will be returned undefined.
*/
getFieldDirectiveByName(fieldName: string, directiveName: string): DirectiveArgs | undefined {
const directive = this.getFieldDirectives(fieldName).find((d) => d.name === directiveName);
if (!directive) return undefined;
return directive.args;
}
/**
* Set arguments of first found directive by name.
* If directive does not exists then will be created new one.
*/
setFieldDirectiveByName(fieldName: string, directiveName: string, args?: DirectiveArgs): this {
const directives = this.getFieldDirectives(fieldName);
const idx = directives.findIndex((d) => d.name === directiveName);
if (idx >= 0) {
directives[idx].args = args;
} else {
directives.push({ name: directiveName, args });
}
this.setFieldDirectives(fieldName, directives);
return this;
}
getFieldDirectiveById(fieldName: string, idx: number): DirectiveArgs | undefined {
const directive = this.getFieldDirectives(fieldName)[idx];
if (!directive) return undefined;
return directive.args;
}
// -----------------------------------------------
// Misc methods
// -----------------------------------------------
get(path: string | string[]): TypeInPath<TContext> | void {
return typeByPath(this, path);
}
/**
* Returns all types which are used inside the current type
*/
getNestedTCs(
opts: {
exclude?: string[] | null;
} = {},
passedTypes: Set<NamedTypeComposer<any>> = new Set()
): Set<NamedTypeComposer<any>> {
const exclude = Array.isArray(opts.exclude) ? opts.exclude : [];
this.getFieldNames().forEach((fieldName) => {
const itc = this.getFieldTC(fieldName);
if (!passedTypes.has(itc) && !exclude.includes(itc.getTypeName())) {
passedTypes.add(itc);
if (itc instanceof InputTypeComposer) {
itc.getNestedTCs(opts, passedTypes);
}
}
});
return passedTypes;
}
/**
* Prints SDL for current type. Or print with all used types if `deep: true` option was provided.
*/
toSDL(
opts?: SchemaPrinterOptions & {
deep?: boolean;
exclude?: string[];
}
): string {
const { deep, ...innerOpts } = opts || {};
innerOpts.sortTypes = innerOpts.sortTypes || false;
const exclude = Array.isArray(innerOpts.exclude) ? innerOpts.exclude : [];
if (deep) {
let r = '';
r += printInputObject(this.getType(), innerOpts);
const nestedTypes = Array.from(this.getNestedTCs({ exclude }));
const sortMethod = getSortMethodFromOption(innerOpts.sortAll || innerOpts.sortTypes);
if (sortMethod) {
nestedTypes.sort(sortMethod);
}
nestedTypes.forEach((t) => {
if (t !== this && !exclude.includes(t.getTypeName())) {
const sdl = t.toSDL(innerOpts);
if (sdl) r += `\n\n${sdl}`;
}
});
return r;
}
return printInputObject(this.getType(), innerOpts);
}
} | the_stack |
* @file Coordinate space transform editor widget.
*/
import './coordinate_transform.css';
import svg_updateArrow from 'ikonate/icons/arrow-up.svg';
import svg_plus from 'ikonate/icons/plus.svg';
import {CoordinateSpace, CoordinateSpaceCombiner, CoordinateSpaceTransform, coordinateSpaceTransformsEquivalent, extendTransformedBoundingBoxUpToRank, getDefaultInputScale, getDimensionNameValidity, getInferredOutputScale, homogeneousTransformSubmatrix, isLocalDimension, makeCoordinateSpace, makeSingletonDimTransformedBoundingBox, newDimensionId, permuteCoordinateSpace, validateDimensionNames, WatchableCoordinateSpaceTransform} from 'neuroglancer/coordinate_transform';
import {WatchableValueInterface} from 'neuroglancer/trackable_value';
import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce';
import {arraysEqual} from 'neuroglancer/util/array';
import {RefCounted} from 'neuroglancer/util/disposable';
import {removeChildren, removeFromParent} from 'neuroglancer/util/dom';
import {ActionEvent, KeyboardEventBinder, registerActionListener} from 'neuroglancer/util/keyboard_bindings';
import {createIdentity, extendHomogeneousTransform, isIdentity} from 'neuroglancer/util/matrix';
import {EventActionMap, MouseEventBinder} from 'neuroglancer/util/mouse_bindings';
import {formatScaleWithUnitAsString, parseScale} from 'neuroglancer/util/si_units';
import {makeIcon} from 'neuroglancer/widget/icon';
function updateInputFieldWidth(element: HTMLInputElement, value: string = element.value) {
element.style.minWidth = (value.length + 1) + 'ch';
}
const singletonClassName = 'neuroglancer-coordinate-space-transform-singleton';
function formatBounds(lower: number, upper: number) {
let lowerString: string;
if (lower === Number.NEGATIVE_INFINITY) {
lowerString = '(-∞,';
} else {
lowerString = `[${Math.floor(lower)},`;
}
let upperString: string;
if (upper === Number.POSITIVE_INFINITY) {
upperString = '+∞)';
} else {
upperString = `${Math.floor(upper)})`;
}
return {lower: lowerString, upper: upperString};
}
const inputEventMap = EventActionMap.fromObject({
'arrowup': {action: 'move-up'},
'arrowdown': {action: 'move-down'},
'arrowleft': {action: 'move-left', preventDefault: false},
'arrowright': {action: 'move-right', preventDefault: false},
'enter': {action: 'commit'},
'escape': {action: 'cancel'},
});
function makeScaleElement() {
const cellElement = document.createElement('div');
const inputElement = document.createElement('input');
cellElement.classList.add('neuroglancer-coordinate-space-transform-scale-container');
inputElement.spellcheck = false;
inputElement.autocomplete = 'off';
inputElement.size = 1;
inputElement.classList.add('neuroglancer-coordinate-space-transform-scale');
cellElement.appendChild(inputElement);
const suggestionElement = document.createElement('div');
const suggestionArrow = document.createElement('span');
suggestionArrow.innerHTML = svg_updateArrow;
suggestionElement.appendChild(suggestionArrow);
const textNode = document.createTextNode('');
suggestionElement.appendChild(textNode);
suggestionElement.classList.add('neuroglancer-coordinate-space-transform-scale-suggestion');
cellElement.appendChild(suggestionElement);
return {cellElement, inputElement, suggestionElement};
}
function updateScaleSuggestionElement(
suggestionElement: HTMLElement, suggested: {unit: string, scale: number}|undefined,
existingScale: number, existingUnit: string, prefix: string) {
if (suggested === undefined ||
(suggested.scale === existingScale && suggested.unit === existingUnit)) {
suggestionElement.style.display = 'none';
} else {
suggestionElement.style.display = '';
const suggestedString =
formatScaleWithUnitAsString(suggested.scale, suggested.unit, {elide1: false});
suggestionElement.lastChild!.textContent = suggestedString;
suggestionElement.title = `${prefix}${suggestedString}`;
}
}
function makeOutputNameElement() {
const inputElement = document.createElement('input');
inputElement.spellcheck = false;
inputElement.autocomplete = 'off';
inputElement.size = 1;
inputElement.placeholder = ' ';
inputElement.classList.add('neuroglancer-coordinate-space-transform-output-name');
return inputElement;
}
function updateCoordinateSpaceScales(
scaleElements: HTMLInputElement[], modified: boolean[],
watchable: WatchableValueInterface<CoordinateSpace>): boolean {
const scalesAndUnits = scaleElements.map(x => parseScale(x.value));
if (scalesAndUnits.includes(undefined)) {
return false;
}
const newScales = Float64Array.from(scalesAndUnits, x => x!.scale);
const newUnits = Array.from(scalesAndUnits, x => x!.unit);
const existing = watchable.value;
const {scales, units, rank} = existing;
for (let i = 0; i < rank; ++i) {
if (!modified[i]) {
newScales[i] = scales[i];
newUnits[i] = units[i];
}
}
if (arraysEqual(scales, newScales) && arraysEqual(units, newUnits)) return false;
const timestamps = existing.timestamps.map(
(t, i) => (newScales[i] === scales[i] && newUnits[i] === units[i]) ? t : Date.now());
const newSpace = makeCoordinateSpace({
valid: existing.valid,
rank: existing.rank,
scales: newScales,
units: newUnits,
timestamps,
ids: existing.ids,
names: existing.names,
boundingBoxes: existing.boundingBoxes,
coordinateArrays: existing.coordinateArrays,
});
watchable.value = newSpace;
return true;
}
function updateCoordinateSpaceSingleDimensionScale(
space: CoordinateSpace, dimIndex: number, scale: number, unit: string): CoordinateSpace {
const scales = new Float64Array(space.scales);
const units = Array.from(space.units);
if (scales[dimIndex] === scale && units[dimIndex] === unit) return space;
const timestamps = Array.from(space.timestamps);
scales[dimIndex] = scale;
units[dimIndex] = unit;
timestamps[dimIndex] = Date.now();
return {...space, scales, units, timestamps};
}
export class CoordinateSpaceTransformWidget extends RefCounted {
element = document.createElement('div');
private coefficientContainer = document.createElement('div');
private translationContainer = document.createElement('div');
private outputNameContainer = document.createElement('div');
private outputScaleContainer = document.createElement('div');
private inputNameContainer = document.createElement('div');
private inputScaleContainer = document.createElement('div');
private inputLowerBoundsContainer = document.createElement('div');
private inputUpperBoundsContainer = document.createElement('div');
private coefficientElements: HTMLInputElement[] = [];
private inputNameElements: HTMLElement[] = [];
private outputNameElements: HTMLInputElement[] = [];
private outputScaleElements: HTMLInputElement[] = [];
private outputScaleSuggestionElements: HTMLElement[] = [];
private inputScaleSuggestionElements: HTMLElement[] = [];
private inputScaleElements: HTMLInputElement[] = [];
private inputBoundsElements: {lower: HTMLDivElement, upper: HTMLDivElement}[] = [];
private outputBoundsElements: {lower: HTMLDivElement, upper: HTMLDivElement}[] = [];
private addSourceDimensionIcon = makeIcon({svg: svg_plus, text: 'S'});
private addOutputDimensionIcon = makeIcon({svg: svg_plus, text: 'V'});
private addOutputDimensionCell = document.createElement('div');
private addOutputDimensionInput = makeOutputNameElement();
private inputScaleModified: boolean[] = [];
private outputScaleModified: boolean[] = [];
private curSourceRank: number = -1;
private curRank: number = -1;
private curTransform: CoordinateSpaceTransform|undefined = undefined;
private addingSourceDimension = false;
private resetToIdentityButton = makeIcon({
text: 'Set to identity',
title: 'Reset to identity transform',
onClick:
() => {
const {transform} = this;
const rank = transform.value.rank;
transform.transform = createIdentity(Float64Array, rank + 1);
}
});
private resetToDefaultButton = makeIcon({
text: 'Reset to default',
title: 'Reset to default input scales, transform, and output dimensions.',
onClick:
() => {
const {transform} = this;
if (transform.mutableSourceRank) return;
const {defaultTransform} = transform;
let {outputSpace: newOutputSpace} = defaultTransform;
const ids = newOutputSpace.ids.map(() => newDimensionId());
transform.value = {
...defaultTransform,
outputSpace: {
...newOutputSpace,
ids,
},
};
}
});
constructor(
public transform: WatchableCoordinateSpaceTransform,
public localCombiner: CoordinateSpaceCombiner,
public globalCombiner: CoordinateSpaceCombiner) {
super();
const {element} = this;
const keyboardHandler = this.registerDisposer(new KeyboardEventBinder(element, inputEventMap));
keyboardHandler.allShortcutsAreGlobal = true;
element.classList.add('neuroglancer-coordinate-space-transform-widget');
this.registerDisposer(new MouseEventBinder(element, inputEventMap));
const updateView = animationFrameDebounce(() => this.updateView());
this.registerDisposer(transform.changed.add(updateView));
const {
coefficientContainer,
translationContainer,
outputNameContainer,
inputNameContainer,
inputScaleContainer,
inputLowerBoundsContainer,
inputUpperBoundsContainer,
outputScaleContainer,
addOutputDimensionCell,
addOutputDimensionIcon,
addSourceDimensionIcon,
resetToIdentityButton,
resetToDefaultButton,
} = this;
coefficientContainer.style.display = 'contents';
translationContainer.style.display = 'contents';
outputNameContainer.style.display = 'contents';
inputNameContainer.style.display = 'contents';
inputScaleContainer.style.display = 'contents';
outputScaleContainer.style.display = 'contents';
inputLowerBoundsContainer.style.display = 'contents';
inputUpperBoundsContainer.style.display = 'contents';
const resetButtons = document.createElement('div');
resetButtons.classList.add('neuroglancer-coordinate-space-transform-widget-reset-buttons');
resetToIdentityButton.classList.add(
'neuroglancer-coordinate-space-transform-widget-reset-to-identity');
resetToDefaultButton.classList.add(
'neuroglancer-coordinate-space-transform-widget-reset-to-default');
resetButtons.appendChild(resetToIdentityButton);
resetButtons.appendChild(resetToDefaultButton);
element.appendChild(resetButtons);
for (const [className, textContent] of [
['source', 'Source dimensions'],
['output', 'Output dimensions'],
['input-lower', 'Lower'],
['input-upper', 'Upper'],
['input-scale', 'Scale'],
['translation', 'Translation'],
]) {
const label = document.createElement('div');
label.classList.add(`neuroglancer-coordinate-space-transform-${className}-label`);
label.classList.add(`neuroglancer-coordinate-space-transform-label`);
label.textContent = textContent;
element.appendChild(label);
}
if (transform.mutableSourceRank) {
addOutputDimensionCell.appendChild(addSourceDimensionIcon);
}
addOutputDimensionCell.appendChild(addOutputDimensionIcon);
addOutputDimensionCell.classList.add('neuroglancer-coordinate-space-transform-output-extend');
const extendOutputDimensionsTitle = 'Embed in additional output dimension';
const extendSourceDimensionsTitle = 'Extend to additional source dimension';
addOutputDimensionIcon.title = extendOutputDimensionsTitle;
addSourceDimensionIcon.title = extendSourceDimensionsTitle;
addOutputDimensionCell.appendChild(this.addOutputDimensionInput);
addOutputDimensionCell.dataset.isActive = 'false';
addOutputDimensionIcon.addEventListener('click', () => {
this.addingSourceDimension = false;
this.addOutputDimensionInput.title = extendOutputDimensionsTitle;
this.addOutputDimensionCell.dataset.isActive = 'true';
this.addOutputDimensionInput.focus();
});
addSourceDimensionIcon.addEventListener('click', () => {
this.addingSourceDimension = true;
this.addOutputDimensionInput.title = extendSourceDimensionsTitle;
;
this.addOutputDimensionCell.dataset.isActive = 'true';
this.addOutputDimensionInput.focus();
});
this.addOutputDimensionInput.addEventListener('blur', () => {
this.updateAddOutputDimensionCellStyle();
});
element.appendChild(coefficientContainer);
element.appendChild(outputNameContainer);
element.appendChild(inputNameContainer);
element.appendChild(inputScaleContainer);
element.appendChild(outputScaleContainer);
element.appendChild(inputLowerBoundsContainer);
element.appendChild(inputUpperBoundsContainer);
coefficientContainer.appendChild(translationContainer);
element.addEventListener('input', (event: UIEvent) => {
const {target} = event;
if (target instanceof HTMLInputElement) {
updateInputFieldWidth(target);
let index = this.inputScaleElements.indexOf(target);
if (index !== -1) {
this.inputScaleModified[index] = true;
this.updateScaleValidity(target);
return;
}
index = this.outputScaleElements.indexOf(target);
if (index !== -1) {
this.outputScaleModified[index] = true;
this.updateScaleValidity(target);
return;
}
index = this.outputNameElements.indexOf(target);
if (index !== -1) {
this.updateOutputNameValidity();
return;
}
if (this.coefficientContainer.contains(target)) {
this.updateCoefficientValidity(target);
return;
}
}
});
const registerMoveUpDown = (action: string, rowDelta: number, colDelta: number) => {
registerActionListener<Event>(element, action, (event: ActionEvent<Event>) => {
event.stopPropagation();
const target = event.target;
if (!(target instanceof HTMLInputElement)) return;
if (colDelta !== 0) {
// Only move to another column if the selection is in the correct state.
if (target.selectionStart !== target.selectionEnd ||
target.selectionStart !== (colDelta === 1 ? target.value.length : 0)) {
return;
}
}
const gridPos = this.getElementGridPosition(target);
if (gridPos === undefined) return;
const newElement =
this.getElementByGridPosition(gridPos.row + rowDelta, gridPos.col + colDelta);
if (newElement !== null) {
newElement.focus();
event.preventDefault();
}
});
};
registerMoveUpDown('move-up', -1, 0);
registerMoveUpDown('move-down', +1, 0);
registerMoveUpDown('move-left', 0, -1);
registerMoveUpDown('move-right', 0, +1);
const registerFocusout = (container: HTMLDivElement, handler: (event: FocusEvent) => void) => {
container.addEventListener('focusout', (event: FocusEvent) => {
const {relatedTarget} = event;
if ((relatedTarget instanceof Node) && container.contains(relatedTarget)) {
return;
}
handler(event);
});
};
registerFocusout(coefficientContainer, () => {
if (!this.updateModelTransform()) {
this.updateViewTransformCoefficients();
}
});
registerFocusout(outputNameContainer, () => {
if (!this.updateModelOutputNames()) {
this.updateViewOutputNames();
}
});
registerFocusout(inputScaleContainer, () => {
if (!this.updateModelInputScales()) {
this.updateViewInputScales();
}
});
registerFocusout(outputScaleContainer, () => {
if (!this.updateModelOutputScales()) {
this.updateViewOutputScales();
}
});
registerActionListener(element, 'cancel', event => {
this.curTransform = undefined;
this.updateView();
(event.target! as HTMLElement).blur();
});
registerActionListener(coefficientContainer, 'commit', () => {
this.updateModelTransform();
});
registerActionListener(outputNameContainer, 'commit', () => {
this.updateModelOutputNames();
});
registerActionListener(inputScaleContainer, 'commit', () => {
this.updateModelInputScales();
});
registerActionListener(outputScaleContainer, 'commit', () => {
this.updateModelOutputScales();
});
element.addEventListener('focusin', (event: FocusEvent) => {
const {target} = event;
if (target instanceof HTMLInputElement) {
target.select();
}
});
this.updateView();
}
private updateWillBeDeletedAttributes(dimensionWillBeDeleted?: boolean[]) {
const {rank} = this.transform.value;
if (dimensionWillBeDeleted === undefined) {
dimensionWillBeDeleted = new Array<boolean>(rank);
dimensionWillBeDeleted.fill(false);
}
const {coefficientElements, inputBoundsElements, inputScaleElements} = this;
for (let row = 0; row < rank; ++row) {
const rowDeleted = dimensionWillBeDeleted[row];
for (let col = 0; col <= rank; ++col) {
const element = coefficientElements[rank * col + row];
const colDeleted = col < rank && dimensionWillBeDeleted[col];
element.dataset.willBeDeleted = (rowDeleted || colDeleted).toString();
}
inputScaleElements[row].dataset.willBeDeleted = rowDeleted.toString();
const {lower, upper} = inputBoundsElements[row];
lower.dataset.willBeDeleted = rowDeleted.toString();
upper.dataset.willBeDeleted = rowDeleted.toString();
}
}
private updateAddOutputDimensionCellStyle() {
const {addOutputDimensionInput} = this;
this.addOutputDimensionCell.dataset.isActive =
(addOutputDimensionInput.value.length !== 0 ||
document.activeElement === addOutputDimensionInput)
.toString();
}
private updateOutputNameValidity() {
const {outputNameElements} = this;
const names = outputNameElements.map(x => x.value);
const {value: {sourceRank, rank}, mutableSourceRank} = this.transform;
if (outputNameElements.length !== rank + 1) return;
const isValid = getDimensionNameValidity(names);
let dimensionWillBeDeleted = new Array<boolean>(rank);
dimensionWillBeDeleted.fill(false);
for (let i = 0; i <= rank; ++i) {
let valid = isValid[i];
if (names[i].length === 0 && (mutableSourceRank || i >= sourceRank)) {
valid = true;
dimensionWillBeDeleted[i] = true;
}
outputNameElements[i].dataset.isValid = valid.toString();
}
this.updateWillBeDeletedAttributes(dimensionWillBeDeleted);
this.updateAddOutputDimensionCellStyle();
}
private updateScaleValidity(element: HTMLInputElement) {
const isValid = parseScale(element.value) !== undefined;
element.dataset.isValid = isValid.toString();
}
private updateCoefficientValidity(element: HTMLInputElement) {
const isValid = Number.isFinite(Number(element.value));
element.dataset.isValid = isValid.toString();
}
private getElementGridPosition(element: HTMLInputElement) {
{
const i = this.outputNameElements.indexOf(element);
if (i !== -1) {
return {row: i, col: -2};
}
}
{
const i = this.inputScaleElements.indexOf(element);
if (i !== -1) {
return {row: -1, col: i};
}
}
{
const i = this.coefficientElements.indexOf(element);
const {rank} = this.transform.value;
if (i !== -1) {
return {row: i % rank, col: Math.floor(i / rank)};
}
}
{
const i = this.outputScaleElements.indexOf(element);
if (i !== -1) {
return {row: i, col: -1};
}
}
return undefined;
}
private getElementByGridPosition(row: number, col: number) {
const {rank} = this.transform.value;
if (row === -1) {
if (col < 0 || col >= rank) return null;
return this.inputScaleElements[col];
}
if (col === -2) {
if (row < 0 || row > rank) return null;
return this.outputNameElements[row];
}
if (col === -1) {
if (row < 0 || row >= rank) return null;
return this.outputScaleElements[row];
}
if (row < 0 || row >= rank || col < 0 || col > rank) return null;
return this.coefficientElements[col * rank + row];
}
private dimensionRefCount(name: string) {
const combiner = isLocalDimension(name) ? this.localCombiner : this.globalCombiner;
return combiner.dimensionRefCounts.get(name) || 0;
}
private updateModelInputScales() {
return updateCoordinateSpaceScales(
this.inputScaleElements, this.inputScaleModified, this.transform.inputSpace);
}
private updateModelOutputScales() {
return updateCoordinateSpaceScales(
this.outputScaleElements, this.outputScaleModified, this.transform.outputSpace);
}
private updateModelOutputNames() {
const outputNames = this.outputNameElements.map(e => e.value);
const {value: existingValue, mutableSourceRank} = this.transform;
const {outputSpace, rank, sourceRank} = existingValue;
if (outputNames.length !== rank + 1) return;
const newToOldDimensionIndices: number[] = [];
const newNames: string[] = [];
const add = outputNames[rank].length !== 0;
let newSourceRank = sourceRank;
for (let i = 0; i <= rank; ++i) {
const name = outputNames[i];
if (name.length === 0) {
if (i < sourceRank) {
if (!mutableSourceRank) return false;
--newSourceRank;
}
continue;
}
newNames.push(name);
newToOldDimensionIndices.push(i);
}
if (!validateDimensionNames(newNames)) return false;
const existingNames = outputSpace.names;
if (!add && arraysEqual(existingNames, newNames)) {
// No change.
return true;
}
let newInputSpace = existingValue.inputSpace;
let newOutputSpace = existingValue.outputSpace;
let newTransform = existingValue.transform;
if (add) {
if (this.addingSourceDimension) ++newSourceRank;
const newName = outputNames[rank];
const space =
(isLocalDimension(newName) ? this.localCombiner : this.globalCombiner).combined.value;
const existingIndex = space.names.indexOf(newName);
let unit: string;
let scale: number;
if (existingIndex !== -1) {
unit = space.units[existingIndex];
scale = space.scales[existingIndex];
} else {
unit = '';
scale = 1;
}
const boundingBoxes = newInputSpace.boundingBoxes.map(
boundingBox => extendTransformedBoundingBoxUpToRank(boundingBox, rank, rank + 1));
if (!this.addingSourceDimension) {
boundingBoxes.push(makeSingletonDimTransformedBoundingBox(rank + 1, rank));
}
newInputSpace = makeCoordinateSpace({
valid: newInputSpace.valid,
rank: rank + 1,
names: [...newInputSpace.names, ''],
ids: [...newInputSpace.ids, newDimensionId()],
timestamps: [...newInputSpace.timestamps, Date.now()],
scales: Float64Array.from([...newInputSpace.scales, scale]),
units: [...newInputSpace.units, unit],
boundingBoxes,
coordinateArrays: [...newInputSpace.coordinateArrays, undefined],
});
newOutputSpace = makeCoordinateSpace({
valid: outputSpace.valid,
rank: rank + 1,
names: [...outputSpace.names, newName],
ids: [...outputSpace.ids, newDimensionId()],
timestamps: [...outputSpace.timestamps, Date.now()],
scales: Float64Array.from([...outputSpace.scales, scale]),
units: [...outputSpace.units, unit],
coordinateArrays: [...outputSpace.coordinateArrays, undefined],
});
newTransform = extendHomogeneousTransform(
new Float64Array((rank + 2) ** 2), rank + 1, newTransform, rank);
}
newTransform = homogeneousTransformSubmatrix(
Float64Array, newTransform, newInputSpace.rank, newToOldDimensionIndices,
newToOldDimensionIndices);
newInputSpace = permuteCoordinateSpace(newInputSpace, newToOldDimensionIndices);
newOutputSpace = permuteCoordinateSpace(newOutputSpace, newToOldDimensionIndices);
const ids = newOutputSpace.ids.map((id, i) => {
const oldIndex = newToOldDimensionIndices[i];
if (oldIndex === rank) return id;
const newName = newNames[i];
const existingName = existingNames[oldIndex];
return ((newName === existingName) ||
(this.dimensionRefCount(existingName) === 1 &&
(this.dimensionRefCount(newName) === (existingNames.includes(newName) ? 1 : 0)))) ?
id :
newDimensionId();
});
const timestamps = newOutputSpace.timestamps.map((t, i) => {
const oldIndex = newToOldDimensionIndices[i];
return (oldIndex === rank || newNames[i] === existingNames[oldIndex]) ? t : Date.now();
});
newOutputSpace = {
...newOutputSpace,
names: newNames,
ids,
timestamps,
};
let newValue = {
rank: newOutputSpace.rank,
sourceRank: newSourceRank,
outputSpace: newOutputSpace,
inputSpace: newInputSpace,
transform: newTransform
};
this.transform.value = newValue;
return true;
}
private updateModelTransform(): boolean {
const coefficientElements = this.coefficientElements;
const {rank} = this.transform.value;
const newTransform = new Float64Array((rank + 1) ** 2);
newTransform[newTransform.length - 1] = 1;
for (let row = 0; row < rank; ++row) {
for (let col = 0; col <= rank; ++col) {
const e = coefficientElements[col * rank + row];
const v = parseFloat(e.value);
if (!Number.isFinite(v)) {
return false;
}
newTransform[col * (rank + 1) + row] = v;
}
}
this.transform.transform = newTransform;
return true;
}
private updateViewOutputNames() {
const {transform: {value: {outputSpace, rank}}} = this;
if (rank !== this.curRank) return;
const {outputNameElements} = this;
const {names: outputNames} = outputSpace;
for (let outputDim = 0; outputDim < rank; ++outputDim) {
const outputNameElement = outputNameElements[outputDim];
outputNameElement.value = outputNames[outputDim];
outputNameElement.dataset.isValid = 'true';
updateInputFieldWidth(outputNameElement);
}
outputNameElements[rank].value = '';
this.updateWillBeDeletedAttributes();
}
private updateViewTransformCoefficients() {
const {transform: {value: {transform, rank}}} = this;
const {coefficientElements} = this;
for (let outputDim = 0; outputDim < rank; ++outputDim) {
for (let inputDim = 0; inputDim <= rank; ++inputDim) {
const coeffElement = coefficientElements[inputDim * rank + outputDim];
coeffElement.value = transform[inputDim * (rank + 1) + outputDim].toString();
coeffElement.dataset.isValid = 'true';
updateInputFieldWidth(coeffElement);
}
}
}
private ensureViewRankUpdated() {
const transform = this.transform.value;
const {rank} = transform;
const sourceRank = transform.sourceRank;
if (this.curSourceRank === sourceRank && this.curRank === rank) {
return;
}
const {
inputBoundsElements,
inputNameElements,
inputScaleElements,
} = this;
const {
element,
coefficientElements,
outputNameElements,
outputScaleElements,
outputScaleSuggestionElements,
inputScaleSuggestionElements,
outputBoundsElements,
coefficientContainer,
translationContainer,
outputNameContainer,
inputNameContainer,
inputScaleContainer,
inputLowerBoundsContainer,
inputUpperBoundsContainer,
outputScaleContainer,
} = this;
element.style.gridTemplateColumns =
`[outputLabel headerStart] min-content [outputNames] 1fr [outputScales] 1fr [headerEnd] ` +
`repeat(${Math.max(1, rank) + 1}, [sourceDim] 1fr)`;
element.style.gridTemplateRows = `[sourceLabel headerStart] auto [sourceNames] ` +
`auto [sourceLower] auto [sourceUpper] auto [sourceScales] auto [headerEnd]` +
`repeat(${rank + 1}, [outputDim] auto)`;
removeChildren(coefficientContainer);
removeChildren(translationContainer);
coefficientContainer.appendChild(translationContainer);
removeChildren(outputNameContainer);
removeChildren(inputNameContainer);
removeChildren(inputScaleContainer);
removeChildren(inputLowerBoundsContainer);
removeChildren(inputUpperBoundsContainer);
removeChildren(outputScaleContainer);
inputNameElements.length = 0;
inputScaleElements.length = 0;
inputBoundsElements.length = 0;
outputScaleElements.length = 0;
outputScaleSuggestionElements.length = 0;
inputScaleSuggestionElements.length = 0;
coefficientElements.length = 0;
outputNameElements.length = 0;
outputBoundsElements.length = 0;
for (let inputDim = 0; inputDim < rank; ++inputDim) {
const addClasses = (element: HTMLElement) => {
element.classList.add('neuroglancer-coordinate-space-transform-input');
if (inputDim >= sourceRank) {
element.classList.add(singletonClassName);
}
};
{
const cellElement = document.createElement('div');
cellElement.classList.add('neuroglancer-coordinate-space-transform-input-name');
addClasses(cellElement);
cellElement.style.gridRowStart = 'sourceNames';
cellElement.style.gridColumnStart = `sourceDim ${inputDim + 1}`;
inputNameContainer.appendChild(cellElement);
inputNameElements.push(cellElement);
}
{
const {cellElement, inputElement, suggestionElement} = makeScaleElement();
cellElement.classList.add('neuroglancer-coordinate-space-transform-input-scale-container');
addClasses(cellElement);
cellElement.style.gridRowStart = `sourceScales`;
cellElement.style.gridColumnStart = `sourceDim ${inputDim + 1}`;
inputScaleContainer.appendChild(cellElement);
inputScaleElements.push(inputElement);
inputScaleSuggestionElements.push(suggestionElement);
const dim = inputDim;
suggestionElement.addEventListener('click', () => {
const suggested = getDefaultInputScale(this.transform, dim);
if (suggested === undefined) return;
this.transform.inputSpace.value = updateCoordinateSpaceSingleDimensionScale(
this.transform.inputSpace.value, dim, suggested.scale, suggested.unit);
});
}
{
const lower = document.createElement('div');
addClasses(lower);
lower.classList.add('neuroglancer-coordinate-space-transform-input-bounds');
lower.style.gridRowStart = `sourceLower`;
lower.style.gridColumnStart = `sourceDim ${inputDim + 1}`;
inputLowerBoundsContainer.appendChild(lower);
const upper = document.createElement('div');
addClasses(upper);
upper.classList.add('neuroglancer-coordinate-space-transform-input-bounds');
upper.style.gridRowStart = `sourceUpper`;
upper.style.gridColumnStart = `sourceDim ${inputDim + 1}`;
inputUpperBoundsContainer.appendChild(upper);
inputBoundsElements.push({lower, upper});
}
}
for (let outputDim = 0; outputDim < rank; ++outputDim) {
for (let inputDim = 0; inputDim <= rank; ++inputDim) {
const cellElement = document.createElement('input');
cellElement.classList.add('neuroglancer-coordinate-space-transform-coeff');
cellElement.spellcheck = false;
cellElement.autocomplete = 'off';
cellElement.size = 1;
cellElement.style.gridRowStart = `outputDim ${outputDim + 1}`;
cellElement.placeholder = ' ';
cellElement.style.gridColumnStart = `sourceDim ${inputDim + 1}`;
coefficientElements[inputDim * rank + outputDim] = cellElement;
if (inputDim === rank) {
cellElement.classList.add('neuroglancer-coordinate-space-transform-translation-coeff');
} else if (inputDim == sourceRank) {
cellElement.classList.add(singletonClassName);
}
((inputDim === rank) ? translationContainer : coefficientContainer)
.appendChild(cellElement);
}
{
const {cellElement, suggestionElement, inputElement} = makeScaleElement();
cellElement.classList.add('neuroglancer-coordinate-space-transform-output-scale-container');
cellElement.style.gridRowStart = `outputDim ${outputDim + 1}`;
cellElement.style.gridColumnStart = `outputScales`;
const dim = outputDim;
suggestionElement.addEventListener('click', () => {
const {value: transform} = this.transform;
const suggested = getInferredOutputScale(transform, dim);
if (suggested === undefined) return;
this.transform.outputSpace.value = updateCoordinateSpaceSingleDimensionScale(
transform.outputSpace, dim, suggested.scale, suggested.unit);
});
outputScaleSuggestionElements.push(suggestionElement);
outputScaleContainer.appendChild(cellElement);
outputScaleElements.push(inputElement);
}
{
const cellElement = document.createElement('div');
cellElement.classList.add('neuroglancer-coordinate-space-transform-output-name-container');
cellElement.style.gridRowStart = `outputDim ${outputDim + 1}`;
cellElement.style.gridColumnStart = `outputNames`;
const nameInput = makeOutputNameElement();
nameInput.title = 'Rebind to a different dimension';
if (outputDim >= sourceRank) {
nameInput.title += `, or delete to remove singleton dimension`;
} else if (this.transform.mutableSourceRank) {
nameInput.title += `, or delete to remove source dimension`;
}
nameInput.title +=
`. Names ending in ' or ^ indicate dimensions local to the layer; names ending in ^ indicate channel dimensions (image layers only).`;
outputNameElements.push(nameInput);
outputNameContainer.appendChild(cellElement);
cellElement.appendChild(nameInput);
const lower = document.createElement('div');
lower.classList.add('neuroglancer-coordinate-space-transform-output-bounds');
cellElement.appendChild(lower);
const upper = document.createElement('div');
upper.classList.add('neuroglancer-coordinate-space-transform-output-bounds');
cellElement.appendChild(upper);
outputBoundsElements.push({lower, upper});
cellElement.addEventListener('mousedown', event => {
if (event.target === nameInput) return;
nameInput.focus();
event.preventDefault();
});
}
}
outputNameElements.push(this.addOutputDimensionInput);
this.addOutputDimensionInput.value = '';
outputNameContainer.appendChild(this.addOutputDimensionCell);
this.curSourceRank = sourceRank;
this.curRank = rank;
}
private updateViewInputScales() {
this.ensureViewRankUpdated();
this.inputScaleModified.length = 0;
const {inputSpace, rank, sourceRank} = this.transform.value;
const {
inputBoundsElements,
inputNameElements,
inputScaleElements,
inputScaleSuggestionElements,
} = this;
const {
names: inputNames,
scales: inputScales,
units: inputUnits,
bounds: {lowerBounds: inputLowerBounds, upperBounds: inputUpperBounds}
} = inputSpace;
for (let inputDim = 0; inputDim < rank; ++inputDim) {
const inputScaleElement = inputScaleElements[inputDim];
const scale = inputScales[inputDim];
const unit = inputUnits[inputDim];
inputScaleElement.value = formatScaleWithUnitAsString(scale, unit, {elide1: false});
inputScaleElement.dataset.isValid = 'true';
updateInputFieldWidth(inputScaleElement);
let dimensionNameString: string;
if (inputDim < sourceRank) {
let name = inputNames[inputDim];
if (!name) name = `${inputDim}`;
inputNameElements[inputDim].textContent = name;
dimensionNameString = `source dimension ${name}`;
inputScaleElement.title = `Override scale of ${dimensionNameString}`;
} else {
dimensionNameString = `singleton dimension`;
inputScaleElement.title = `Set extent of ${dimensionNameString}`;
}
const {lower, upper} = formatBounds(inputLowerBounds[inputDim], inputUpperBounds[inputDim]);
const elements = inputBoundsElements[inputDim];
elements.lower.textContent = lower;
elements.lower.title = `Lower bound of ${dimensionNameString}`;
elements.upper.title = `Upper bound of ${dimensionNameString}`;
elements.upper.textContent = upper;
updateScaleSuggestionElement(
inputScaleSuggestionElements[inputDim], getDefaultInputScale(this.transform, inputDim),
scale, unit, `Revert scale of ${dimensionNameString} to `);
}
}
private updateViewOutputScales() {
const {value: transform} = this.transform;
const {
rank,
names,
units: outputUnits,
scales: outputScales,
bounds: {lowerBounds: outputLowerBounds, upperBounds: outputUpperBounds}
} = transform.outputSpace;
const {outputScaleElements, outputBoundsElements, outputScaleSuggestionElements} = this;
for (let outputDim = 0; outputDim < rank; ++outputDim) {
const scaleElement = outputScaleElements[outputDim];
const scale = outputScales[outputDim];
const unit = outputUnits[outputDim];
scaleElement.value = formatScaleWithUnitAsString(scale, unit, {elide1: false});
updateInputFieldWidth(scaleElement);
const name = names[outputDim];
scaleElement.dataset.isValid = 'true';
const titlePrefix =
`Change coordinates of ${isLocalDimension(name) ? 'local' : 'global'} dimension ${name}`;
scaleElement.title = `${titlePrefix} (does not rescale the source)`;
const {lower, upper} =
formatBounds(outputLowerBounds[outputDim], outputUpperBounds[outputDim]);
const elements = outputBoundsElements[outputDim];
elements.lower.textContent = lower;
elements.upper.textContent = upper;
updateScaleSuggestionElement(
outputScaleSuggestionElements[outputDim], getInferredOutputScale(transform, outputDim),
scale, unit, `${titlePrefix} to inferred scale of `);
}
}
private updateResetButtonVisibility(coefficientsModified = false, dimensionsModified = false) {
const {transform: {value: transform, mutableSourceRank, defaultTransform}} = this;
const {rank} = transform;
this.resetToIdentityButton.style.visibility =
(coefficientsModified || !isIdentity(transform.transform, rank + 1, rank + 1)) ? 'visible' :
'hidden';
this.resetToDefaultButton.style.visibility =
(!mutableSourceRank &&
(coefficientsModified || dimensionsModified ||
!coordinateSpaceTransformsEquivalent(defaultTransform, transform))) ?
'visible' :
'hidden';
}
updateView() {
const transform = this.transform.value;
if (this.curTransform === transform) return;
this.curTransform = transform;
this.ensureViewRankUpdated();
this.updateViewInputScales();
this.updateViewOutputNames();
this.updateViewTransformCoefficients();
this.updateViewOutputScales();
this.updateAddOutputDimensionCellStyle();
this.updateResetButtonVisibility();
}
disposed() {
removeFromParent(this.element);
super.disposed();
}
} | the_stack |
import { dynamicElevationOffsetProperty, elevationProperty, getRippleColor, rippleColorProperty, shapeProperty, themer } from '@nativescript-community/ui-material-core';
import {
Background,
Color,
CoreTypes,
Font,
ImageSource,
Screen,
Utils,
backgroundInternalProperty,
borderBottomLeftRadiusProperty,
borderBottomRightRadiusProperty,
borderTopLeftRadiusProperty,
borderTopRightRadiusProperty,
colorProperty,
fontInternalProperty
} from '@nativescript/core';
import { textTransformProperty } from '@nativescript/core/ui/text-base';
import { ButtonBase, imageSourceProperty, srcProperty } from './button-common';
let buttonScheme: MDCContainerScheme;
function getButtonScheme() {
if (!buttonScheme) {
buttonScheme = MDCContainerScheme.new();
}
return buttonScheme;
}
declare class IObserverClass extends NSObject {
static new(): IObserverClass;
static alloc(): IObserverClass;
_owner: WeakRef<Button>;
}
@NativeClass
class MDButtonObserverClass extends NSObject {
_owner: WeakRef<Button>;
public static initWithOwner(owner: Button) {
const delegate = MDButtonObserverClass.new() as MDButtonObserverClass;
delegate._owner = new WeakRef(owner);
return delegate;
}
observeValueForKeyPathOfObjectChangeContext(path: string, tv: UITextView) {
if (path === 'contentSize') {
const owner = this._owner && this._owner.get();
if (owner) {
const inset = owner.nativeViewProtected.titleEdgeInsets;
const top = Utils.layout.toDeviceIndependentPixels(owner.effectivePaddingTop + owner.effectiveBorderTopWidth);
switch (owner.verticalTextAlignment) {
case 'initial': // not supported
case 'top':
owner.nativeViewProtected.titleEdgeInsets = {
top,
left: inset.left,
bottom: inset.bottom,
right: inset.right
};
break;
case 'middle': {
const height = tv.sizeThatFits(CGSizeMake(tv.bounds.size.width, 10000)).height;
let topCorrect = (tv.bounds.size.height - height * tv.zoomScale) / 2.0;
topCorrect = topCorrect < 0.0 ? 0.0 : topCorrect;
// tv.contentOffset = CGPointMake(0, -topCorrect);
owner.nativeViewProtected.titleEdgeInsets = {
top: top + topCorrect,
left: inset.left,
bottom: inset.bottom,
right: inset.right
};
break;
}
case 'bottom': {
const height = tv.sizeThatFits(CGSizeMake(tv.bounds.size.width, 10000)).height;
let bottomCorrect = tv.bounds.size.height - height * tv.zoomScale;
bottomCorrect = bottomCorrect < 0.0 ? 0.0 : bottomCorrect;
// tv.contentOffset = CGPointMake(0, -bottomCorrect);
owner.nativeViewProtected.titleEdgeInsets = {
top: top + bottomCorrect,
left: inset.left,
bottom: inset.bottom,
right: inset.right
};
break;
}
}
}
}
}
}
export class Button extends ButtonBase {
private _observer: IObserverClass;
nativeViewProtected: MDCButton;
_ios: MDCButton;
getDefaultElevation(): number {
return 2;
}
getDefaultDynamicElevationOffset() {
return 6;
}
applyShapeScheme() {
MDCButtonShapeThemer.applyShapeSchemeToButton(this.shapeScheme, this.nativeViewProtected);
}
[borderBottomLeftRadiusProperty.setNative](value) {
this.setBottomLeftCornerRadius(value);
this.applyShapeScheme();
}
[borderBottomRightRadiusProperty.setNative](value) {
this.setBottomRightCornerRadius(value);
this.applyShapeScheme();
}
[borderTopLeftRadiusProperty.setNative](value) {
this.setTopLeftCornerRadius(value);
this.applyShapeScheme();
}
[borderTopRightRadiusProperty.setNative](value) {
this.setTopRightCornerRadius(value);
this.applyShapeScheme();
}
shapeScheme: MDCShapeScheme;
private getShapeScheme() {
if (!this.shapeScheme) {
if (this.shape) {
// we need to copy it as if we change border radius on this view
// it will change for everyone else
this.shapeScheme = MDCShapeScheme.new();
const shapeScheme = themer.getShape(this.shape);
this.shapeScheme.smallComponentShape = shapeScheme.smallComponentShape.copy();
} else {
this.shapeScheme = MDCShapeScheme.new();
const shapeCategory = MDCShapeCategory.new();
this.shapeScheme.smallComponentShape = shapeCategory;
}
}
return this.shapeScheme;
}
private setBottomLeftCornerRadius(value: number) {
const shapeScheme = this.getShapeScheme();
const current = shapeScheme.smallComponentShape.bottomLeftCorner;
if (current instanceof MDCCutCornerTreatment) {
shapeScheme.smallComponentShape.bottomLeftCorner = MDCCornerTreatment.cornerWithCut(value);
} else {
shapeScheme.smallComponentShape.bottomLeftCorner = MDCCornerTreatment.cornerWithRadius(value);
}
}
private setBottomRightCornerRadius(value: number) {
const shapeScheme = this.getShapeScheme();
const current = shapeScheme.smallComponentShape.bottomRightCorner;
if (current instanceof MDCCutCornerTreatment) {
shapeScheme.smallComponentShape.bottomRightCorner = MDCCornerTreatment.cornerWithCut(value);
} else {
shapeScheme.smallComponentShape.bottomRightCorner = MDCCornerTreatment.cornerWithRadius(value);
}
}
private setTopLeftCornerRadius(value: number) {
const shapeScheme = this.getShapeScheme();
const current = shapeScheme.smallComponentShape.topLeftCorner;
if (current instanceof MDCCutCornerTreatment) {
shapeScheme.smallComponentShape.topLeftCorner = MDCCornerTreatment.cornerWithCut(value);
} else {
shapeScheme.smallComponentShape.topLeftCorner = MDCCornerTreatment.cornerWithRadius(value);
}
}
private setTopRightCornerRadius(value: number) {
const shapeScheme = this.getShapeScheme();
const current = shapeScheme.smallComponentShape.topRightCorner;
if (current instanceof MDCCutCornerTreatment) {
shapeScheme.smallComponentShape.topRightCorner = MDCCornerTreatment.cornerWithCut(value);
} else {
shapeScheme.smallComponentShape.topRightCorner = MDCCornerTreatment.cornerWithRadius(value);
}
}
public createNativeView() {
const view = MDCButton.new();
view.imageView.contentMode = UIViewContentMode.ScaleAspectFit;
const colorScheme = themer.getAppColorScheme() as MDCSemanticColorScheme;
const scheme = MDCContainerScheme.new();
scheme.colorScheme = colorScheme;
if (this.variant === 'text') {
// fixes a bug where N would set default UILabel system color
// if no color in style which would break theming
this.style['css:color'] = themer.getPrimaryColor() as Color;
view.applyTextThemeWithScheme(scheme);
} else if (this.variant === 'flat') {
if (colorScheme) {
MDCButtonColorThemer.applySemanticColorSchemeToButton(colorScheme, view);
}
} else if (this.variant === 'outline') {
view.applyOutlinedThemeWithScheme(scheme);
} else {
// contained
view.applyContainedThemeWithScheme(scheme);
// we need to set the default through css or user would not be able to overload it through css...
this.style['css:margin-left'] = 10;
this.style['css:margin-right'] = 10;
this.style['css:margin-top'] = 12;
this.style['css:margin-bottom'] = 12;
}
return view;
}
initNativeView() {
super.initNativeView();
this._observer = MDButtonObserverClass.initWithOwner(this);
this.nativeViewProtected.addObserverForKeyPathOptionsContext(this._observer, 'contentSize', NSKeyValueObservingOptions.New, null);
}
disposeNativeView() {
super.disposeNativeView();
if (this._observer) {
this.nativeViewProtected.removeObserverForKeyPath(this._observer, 'contentSize');
this._observer = null;
}
}
[textTransformProperty.setNative](value: CoreTypes.TextTransformType) {
this.nativeViewProtected.uppercaseTitle = value !== 'none';
}
[rippleColorProperty.setNative](color: Color) {
this.nativeViewProtected.inkColor = getRippleColor(color);
}
[elevationProperty.setNative](value: number) {
this.nativeViewProtected.setElevationForState(value, UIControlState.Normal);
let dynamicElevationOffset = this.dynamicElevationOffset;
if (typeof dynamicElevationOffset === 'undefined' || dynamicElevationOffset === null) {
dynamicElevationOffset = this.getDefaultDynamicElevationOffset();
}
if (this.dynamicElevationOffset === undefined) {
this.nativeViewProtected.setElevationForState(value + dynamicElevationOffset, UIControlState.Highlighted);
}
}
[dynamicElevationOffsetProperty.setNative](value: number) {
let elevation = this.elevation;
if (typeof elevation === 'undefined' || elevation === null) {
elevation = this.getDefaultElevation();
}
this.nativeViewProtected.setElevationForState(value + elevation, UIControlState.Highlighted);
}
[backgroundInternalProperty.setNative](value: Background) {
if (this.nativeViewProtected) {
const scale = Screen.mainScreen.scale;
// this.nativeViewProtected.backgroundColor = value.color ? value.color.ios : null;
if (value.color) {
this.nativeViewProtected.setBackgroundColorForState(value.color ? value.color.ios : null, UIControlState.Normal);
if (this.variant === 'outline') {
this.nativeViewProtected.setBackgroundColorForState(new Color('transparent').ios, UIControlState.Disabled);
}
}
this.nativeViewProtected.setBorderWidthForState(value.borderLeftWidth / scale, UIControlState.Normal);
this.nativeViewProtected.setBorderColorForState(value.borderTopColor ? value.borderTopColor.ios : null, UIControlState.Normal);
this.nativeViewProtected.layer.cornerRadius = value.borderTopLeftRadius / scale;
}
}
_setNativeClipToBounds() {
// const backgroundInternal = this.style.backgroundInternal;
// this.nativeViewProtected.clipsToBounds =
// this.nativeViewProtected instanceof UIScrollView ||
// backgroundInternal.hasBorderWidth() ||
// backgroundInternal.hasBorderRadius();
}
[fontInternalProperty.setNative](value: Font | UIFont) {
if (!(value instanceof Font) || !this.formattedText) {
const nativeView = this.nativeViewProtected;
const font = value instanceof Font ? value.getUIFont(nativeView.font) : value;
nativeView.setTitleFontForState(font, UIControlState.Normal);
}
}
public _setNativeImage(nativeImage: UIImage) {
this.nativeViewProtected.setImageForState(nativeImage ? nativeImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) : nativeImage, UIControlState.Normal);
}
[imageSourceProperty.setNative](value: ImageSource) {
this._setNativeImage(value ? value.ios : null);
}
[srcProperty.setNative](value: any) {
this._createImageSourceFromSrc(value);
}
[colorProperty.setNative](value) {
const color = value instanceof Color ? value.ios : value;
super[colorProperty.setNative](value);
this.nativeViewProtected.setImageTintColorForState(color, UIControlState.Normal);
}
[shapeProperty.setNative](shape: string) {
// TODO: for now we cant change after set
// this.shapeScheme = null;
this.getShapeScheme();
this.applyShapeScheme();
}
} | the_stack |
import { deriveKey as pbkdf2 } from "@stablelib/pbkdf2";
import { SHA256 } from "@stablelib/sha256";
import { isInteger } from "@stablelib/int";
import { readUint32LE, writeUint32LE } from "@stablelib/binary";
import { wipe } from "@stablelib/wipe";
export class Scrypt {
private _XY: Int32Array;
private _V: Int32Array;
private _step = 256; // initial step for non-blocking calculation
readonly N: number;
readonly r: number;
readonly p: number;
constructor(N: number, r: number, p: number) {
// Check parallelization parameter.
if (p <= 0) {
throw new Error("scrypt: incorrect p");
}
// Check r parameter.
if (r <= 0) {
throw new Error("scrypt: incorrect r");
}
// Check that N is within supported range.
if (N < 1 || N > Math.pow(2, 31)) {
throw new Error('scrypt: N must be between 2 and 2^31');
}
// Check that N is a power of two.
if (!isInteger(N) || (N & (N - 1)) !== 0) {
throw new Error("scrypt: N must be a power of 2");
}
const MAX_INT = (1 << 31) >>> 0;
if (r * p >= 1 << 30 || r > MAX_INT / 128 / p || r > MAX_INT / 256 || N > MAX_INT / 128 / r) {
throw new Error("scrypt: parameters are too large");
}
// XXX we can use Uint32Array, but Int32Array is faster, especially in Safari.
this._V = new Int32Array(32 * (N + 2) * r);
this._XY = this._V.subarray(32 * N * r);
this.N = N;
this.r = r;
this.p = p;
}
deriveKey(password: Uint8Array, salt: Uint8Array, dkLen: number): Uint8Array {
const B = pbkdf2(SHA256, password, salt, 1, this.p * 128 * this.r);
for (let i = 0; i < this.p; i++) {
smix(B.subarray(i * 128 * this.r), this.r, this.N, this._V, this._XY);
}
const result = pbkdf2(SHA256, password, B, 1, dkLen);
wipe(B);
return result;
}
deriveKeyNonBlocking(password: Uint8Array, salt: Uint8Array, dkLen: number): Promise<Uint8Array> {
const B = pbkdf2(SHA256, password, salt, 1, this.p * 128 * this.r);
let tail = Promise.resolve(this._step);
for (let i = 0; i < this.p; i++) {
tail = tail.then(step => smixAsync(B.subarray(i * 128 * this.r), this.r, this.N, this._V, this._XY, step));
}
return tail.then(step => {
const result = pbkdf2(SHA256, password, B, 1, dkLen);
wipe(B);
this._step = step;
return result;
});
}
clean() {
wipe(this._V);
}
}
/**
* Derives a key from password and salt with parameters
* N — CPU/memory cost, r — block size, p — parallelization,
* containing dkLen bytes.
*/
export function deriveKey(password: Uint8Array, salt: Uint8Array,
N: number, r: number, p: number, dkLen: number): Uint8Array {
return new Scrypt(N, r, p).deriveKey(password, salt, dkLen);
}
/**
* Same as deriveKey, but performs calculation in a non-blocking way,
* making sure to not take more than 100 ms per blocking calculation.
*/
export function deriveKeyNonBlocking(password: Uint8Array, salt: Uint8Array,
N: number, r: number, p: number, dkLen: number): Promise<Uint8Array> {
return new Scrypt(N, r, p).deriveKeyNonBlocking(password, salt, dkLen);
}
function smix(B: Uint8Array, r: number, N: number, V: Int32Array, XY: Int32Array) {
const xi = 0;
const yi = 32 * r;
const tmp = new Int32Array(16);
for (let i = 0; i < 32 * r; i++) {
V[i] = readUint32LE(B, i * 4);
}
for (let i = 0; i < N; i++) {
blockMix(tmp, V, i * (32 * r), (i + 1) * (32 * r), r);
}
for (let i = 0; i < N; i += 2) {
let j = integerify(XY, xi, r) & (N - 1);
blockXOR(XY, xi, V, j * (32 * r), 32 * r);
blockMix(tmp, XY, xi, yi, r);
j = integerify(XY, yi, r) & (N - 1);
blockXOR(XY, yi, V, j * (32 * r), 32 * r);
blockMix(tmp, XY, yi, xi, r);
}
for (let i = 0; i < 32 * r; i++) {
writeUint32LE(XY[xi + i], B, i * 4);
}
wipe(tmp);
}
const nextTick = (typeof setImmediate !== 'undefined') ? setImmediate : (setTimeout as unknown as () => void);
function splitCalc(start: number, end: number, step: number, fn: (s: number, e: number) => number): Promise<number> {
return new Promise<number>(fulfill => {
let adjusted = false;
let startTime: number;
const TARGET_MS = 100; // target milliseconds per calculation
function nextStep() {
if (!adjusted) {
// Get current time.
startTime = Date.now();
}
// Perform the next step of calculation.
start = fn(start, start + step < end ? start + step : end);
if (start < end) {
if (!adjusted) {
// There are more steps to do.
// Measure the time it took for calculation and decide
// if we should increase the step.
const dur = Date.now() - startTime;
if (dur < TARGET_MS) {
if (dur <= 0) {
// Double the steps if duration is too small or negative.
step *= 2;
} else {
step = Math.floor(step * 100 / dur);
}
} else {
// Don't bother with adjusting steps anymore.
adjusted = true;
}
}
nextTick(() => { nextStep(); });
} else {
fulfill(step);
}
}
nextStep();
});
}
function smixAsync(B: Uint8Array, r: number, N: number, V: Int32Array, XY: Int32Array, initialStep: number): Promise<number> {
const xi = 0;
const yi = 32 * r;
const tmp = new Int32Array(16);
for (let i = 0; i < 32 * r; i++) {
V[i] = readUint32LE(B, i * 4);
}
return Promise.resolve(initialStep)
.then(step => splitCalc(0, N, step, (i: number, end: number): number => {
for (; i < end; i++) {
blockMix(tmp, V, i * (32 * r), (i + 1) * (32 * r), r);
}
return i;
}))
.then(step => splitCalc(0, N, step, (i: number, end: number): number => {
for (; i < end; i += 2) {
let j = integerify(XY, xi, r) & (N - 1);
blockXOR(XY, xi, V, j * (32 * r), 32 * r);
blockMix(tmp, XY, xi, yi, r);
j = integerify(XY, yi, r) & (N - 1);
blockXOR(XY, yi, V, j * (32 * r), 32 * r);
blockMix(tmp, XY, yi, xi, r);
}
return i;
}))
.then(step => {
for (let i = 0; i < 32 * r; i++) {
writeUint32LE(XY[xi + i], B, i * 4);
}
wipe(tmp);
return step;
});
}
function salsaXOR(tmp: Int32Array, B: Int32Array, bin: number, bout: number) {
const j0 = tmp[0] ^ B[bin++],
j1 = tmp[1] ^ B[bin++],
j2 = tmp[2] ^ B[bin++],
j3 = tmp[3] ^ B[bin++],
j4 = tmp[4] ^ B[bin++],
j5 = tmp[5] ^ B[bin++],
j6 = tmp[6] ^ B[bin++],
j7 = tmp[7] ^ B[bin++],
j8 = tmp[8] ^ B[bin++],
j9 = tmp[9] ^ B[bin++],
j10 = tmp[10] ^ B[bin++],
j11 = tmp[11] ^ B[bin++],
j12 = tmp[12] ^ B[bin++],
j13 = tmp[13] ^ B[bin++],
j14 = tmp[14] ^ B[bin++],
j15 = tmp[15] ^ B[bin++];
let x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
x15 = j15;
let u: number;
for (let i = 0; i < 8; i += 2) {
u = x0 + x12; x4 ^= u << 7 | u >>> (32 - 7);
u = x4 + x0; x8 ^= u << 9 | u >>> (32 - 9);
u = x8 + x4; x12 ^= u << 13 | u >>> (32 - 13);
u = x12 + x8; x0 ^= u << 18 | u >>> (32 - 18);
u = x5 + x1; x9 ^= u << 7 | u >>> (32 - 7);
u = x9 + x5; x13 ^= u << 9 | u >>> (32 - 9);
u = x13 + x9; x1 ^= u << 13 | u >>> (32 - 13);
u = x1 + x13; x5 ^= u << 18 | u >>> (32 - 18);
u = x10 + x6; x14 ^= u << 7 | u >>> (32 - 7);
u = x14 + x10; x2 ^= u << 9 | u >>> (32 - 9);
u = x2 + x14; x6 ^= u << 13 | u >>> (32 - 13);
u = x6 + x2; x10 ^= u << 18 | u >>> (32 - 18);
u = x15 + x11; x3 ^= u << 7 | u >>> (32 - 7);
u = x3 + x15; x7 ^= u << 9 | u >>> (32 - 9);
u = x7 + x3; x11 ^= u << 13 | u >>> (32 - 13);
u = x11 + x7; x15 ^= u << 18 | u >>> (32 - 18);
u = x0 + x3; x1 ^= u << 7 | u >>> (32 - 7);
u = x1 + x0; x2 ^= u << 9 | u >>> (32 - 9);
u = x2 + x1; x3 ^= u << 13 | u >>> (32 - 13);
u = x3 + x2; x0 ^= u << 18 | u >>> (32 - 18);
u = x5 + x4; x6 ^= u << 7 | u >>> (32 - 7);
u = x6 + x5; x7 ^= u << 9 | u >>> (32 - 9);
u = x7 + x6; x4 ^= u << 13 | u >>> (32 - 13);
u = x4 + x7; x5 ^= u << 18 | u >>> (32 - 18);
u = x10 + x9; x11 ^= u << 7 | u >>> (32 - 7);
u = x11 + x10; x8 ^= u << 9 | u >>> (32 - 9);
u = x8 + x11; x9 ^= u << 13 | u >>> (32 - 13);
u = x9 + x8; x10 ^= u << 18 | u >>> (32 - 18);
u = x15 + x14; x12 ^= u << 7 | u >>> (32 - 7);
u = x12 + x15; x13 ^= u << 9 | u >>> (32 - 9);
u = x13 + x12; x14 ^= u << 13 | u >>> (32 - 13);
u = x14 + x13; x15 ^= u << 18 | u >>> (32 - 18);
}
B[bout++] = tmp[0] = (x0 + j0) | 0;
B[bout++] = tmp[1] = (x1 + j1) | 0;
B[bout++] = tmp[2] = (x2 + j2) | 0;
B[bout++] = tmp[3] = (x3 + j3) | 0;
B[bout++] = tmp[4] = (x4 + j4) | 0;
B[bout++] = tmp[5] = (x5 + j5) | 0;
B[bout++] = tmp[6] = (x6 + j6) | 0;
B[bout++] = tmp[7] = (x7 + j7) | 0;
B[bout++] = tmp[8] = (x8 + j8) | 0;
B[bout++] = tmp[9] = (x9 + j9) | 0;
B[bout++] = tmp[10] = (x10 + j10) | 0;
B[bout++] = tmp[11] = (x11 + j11) | 0;
B[bout++] = tmp[12] = (x12 + j12) | 0;
B[bout++] = tmp[13] = (x13 + j13) | 0;
B[bout++] = tmp[14] = (x14 + j14) | 0;
B[bout++] = tmp[15] = (x15 + j15) | 0;
}
function blockCopy(dst: Int32Array, di: number, src: Int32Array, si: number, len: number) {
while (len--) {
dst[di++] = src[si++];
}
}
function blockXOR(dst: Int32Array, di: number, src: Int32Array, si: number, len: number) {
while (len--) {
dst[di++] ^= src[si++];
}
}
function blockMix(tmp: Int32Array, B: Int32Array, bin: number, bout: number, r: number) {
blockCopy(tmp, 0, B, bin + (2 * r - 1) * 16, 16);
for (let i = 0; i < 2 * r; i += 2) {
salsaXOR(tmp, B, bin + i * 16, bout + i * 8);
salsaXOR(tmp, B, bin + i * 16 + 16, bout + i * 8 + r * 16);
}
}
function integerify(B: Int32Array, bi: number, r: number): number {
return B[bi + (2 * r - 1) * 16];
} | the_stack |
import {
SchemaInput,
Datatype,
Datatypes,
Attribute,
Schema,
Relation,
} from "../";
import { inflateSchema, buildRelations } from "./inflate";
import { ProjectInput } from "../project";
// // // //
export type PreviewOutputType = "json" | "typescript" | "graphql";
export enum PreviewOutputTypes {
json = "json",
typescript = "typescript",
graphql = "graphql",
}
// CLEANUP - document this function, write better tests
// CLEANUP - add a type that maps each value in Datatypes enum to a string,
// and create an instances for each PreviewOutputType
export const getDatatypeValueJson = ({
datatype,
}: {
datatype: Datatype;
}): string => {
switch (datatype) {
case Datatypes.ID:
return "1";
case Datatypes.AUTO_INCREMENTED_ID:
return "1";
case Datatypes.UUID:
return `"00112233-4455-6677-8899-aabbccddeeff"`;
case Datatypes.STRING:
return `"string"`;
case Datatypes.TEXT:
return `"longer string for text"`;
case Datatypes.INT:
return `128`;
case Datatypes.BIGINT:
return `12378971290123987`;
case Datatypes.FLOAT:
return `3.14159`;
case Datatypes.DECIMAL:
return `3.14159`;
case Datatypes.NUMBER:
return `3.14159`;
case Datatypes.BOOLEAN:
return `true`;
case Datatypes.JSON:
return `{}`;
case Datatypes.JSONB:
return `{}`;
case Datatypes.DATE:
return `"2019-03-11"`;
case Datatypes.TIME:
return `"17:04:14 GMT-0400"`;
case Datatypes.DATETIME:
return `"3/18/2019, 5:04:51 PM"`;
case Datatypes.TIMESTAMP:
return `"3/18/2019, 5:04:51 PM"`;
case Datatypes.UUID_ARRAY:
return `["00112233-4455-6677-8899-aabbccddeeff"]`;
case Datatypes.STRING_ARRAY:
return `["string", "array"]`;
case Datatypes.TEXT_ARRAY:
return `["text", "array"]`;
case Datatypes.INT_ARRAY:
return `[128, 256]`;
case Datatypes.BIGINT_ARRAY:
return `[128128309810198, 128128309810198]`;
case Datatypes.FLOAT_ARRAY:
return `[3.14156, 64.23012]`;
case Datatypes.DECIMAL_ARRAY:
return `[0.12390123, 0.12312442]`;
case Datatypes.NUMBER_ARRAY:
return `[128, 255.9]`;
case Datatypes.BOOLEAN_ARRAY:
return `[true, false, true]`;
case Datatypes.DATE_ARRAY:
return `["2019-03-11", "2020-03-11]`;
case Datatypes.TIME_ARRAY:
return `["17:04:14 GMT-0400", "12:04:14 GMT-0400"]`;
case Datatypes.DATETIME_ARRAY:
return `[128]`;
case Datatypes.TIMESTAMP_ARRAY:
return `["3/18/2019, 5:04:51 PM", "3/20/2019, 1:04:51 PM"]`;
}
};
export function renderSchemaJson({
schemaInput,
projectInput,
}: {
projectInput: ProjectInput;
schemaInput: SchemaInput;
}): string {
const inflatedSchema: Schema = inflateSchema({
schemaInput,
relations: buildRelations({
schemaInputs: projectInput.schemas,
relationInputs: projectInput.relations,
}),
});
// Define + open JSON output
let jsonOutput: string[] = [
"{", // Open JSON output
// Map each property
[
...schemaInput.attributes.map((attr: Attribute) => {
return ` "${attr.identifiers.snake}": ${getDatatypeValueJson({
datatype: attr.datatype,
})}`;
}),
...inflatedSchema.relations.map((r: Relation): string => {
return ` "${r.identifiers.destination.alias.singular.camel}": "${r.identifiers.destination.canonical.singular.pascal} ID"`;
}),
].join(",\n"),
"}", // Close JSON output
];
// Joins lines
return jsonOutput.join("\n");
}
// // // //
// CLEANUP - document this function, write better tests
export const getDatatypeValueGraphQL = ({
datatype,
}: {
datatype: Datatype;
}): string => {
switch (datatype) {
case Datatypes.ID:
return `ID`;
case Datatypes.AUTO_INCREMENTED_ID:
return `Number`;
case Datatypes.UUID:
return `String`;
case Datatypes.STRING:
return `String`;
case Datatypes.TEXT:
return `String`;
case Datatypes.INT:
return `Number`;
case Datatypes.BIGINT:
return `Number`;
case Datatypes.FLOAT:
return `Number`;
case Datatypes.DECIMAL:
return `Number`;
case Datatypes.NUMBER:
return `Number`;
case Datatypes.BOOLEAN:
return `Boolean`;
case Datatypes.JSON:
return `"{}"`;
case Datatypes.JSONB:
return `"{}"`;
case Datatypes.DATE:
return `Date`;
case Datatypes.TIME:
return `Time`;
case Datatypes.DATETIME:
return `Date`;
case Datatypes.TIMESTAMP:
return `Date`;
case Datatypes.UUID_ARRAY:
return `[String]`;
case Datatypes.STRING_ARRAY:
return `[String]`;
case Datatypes.TEXT_ARRAY:
return `[String]`;
case Datatypes.INT_ARRAY:
return `[Number]`;
case Datatypes.BIGINT_ARRAY:
return `[Number]`;
case Datatypes.FLOAT_ARRAY:
return `[Number]`;
case Datatypes.DECIMAL_ARRAY:
return `[Number]`;
case Datatypes.NUMBER_ARRAY:
return `[Number]`;
case Datatypes.BOOLEAN_ARRAY:
return `[Boolean]`;
case Datatypes.DATE_ARRAY:
return `[Date]`;
case Datatypes.TIME_ARRAY:
return `[Time]`;
case Datatypes.DATETIME_ARRAY:
return `[Date]`;
case Datatypes.TIMESTAMP_ARRAY:
return `[Date]`;
}
};
export function renderSchemaGrapqhQL({
schemaInput,
projectInput,
}: {
projectInput: ProjectInput;
schemaInput: SchemaInput;
}): string {
const inflatedSchema: Schema = inflateSchema({
schemaInput,
relations: buildRelations({
schemaInputs: projectInput.schemas,
relationInputs: projectInput.relations,
}),
});
// Define + open JSON output
let jsonOutput: string[] = [
`type ${schemaInput.identifiers.singular.pascal} {`, // Open JSON output
// Map each property
...schemaInput.attributes.map((attr: Attribute) => {
return ` ${attr.identifiers.snake}: ${getDatatypeValueGraphQL({
datatype: attr.datatype,
})}!`;
}),
...inflatedSchema.relations.map((r: Relation): string => {
return ` ${r.identifiers.destination.alias.singular.camel}: ${r.identifiers.destination.canonical.singular.pascal}!`;
}),
"}", // Close JSON output
];
// Joins lines
return jsonOutput.join("\n");
}
// // // //
// CLEANUP - document this function, write better tests
export const getDatatypeValueTypeScript = ({
datatype,
}: {
datatype: Datatype;
}): string => {
switch (datatype) {
case Datatypes.ID:
return `ID`;
case Datatypes.AUTO_INCREMENTED_ID:
return `number`;
case Datatypes.UUID:
return `string`;
case Datatypes.STRING:
return `string`;
case Datatypes.TEXT:
return `string`;
case Datatypes.INT:
return `number`;
case Datatypes.BIGINT:
return `"number`;
case Datatypes.FLOAT:
return `number`;
case Datatypes.DECIMAL:
return `number`;
case Datatypes.NUMBER:
return `number`;
case Datatypes.BOOLEAN:
return `boolean`;
case Datatypes.JSON:
return `"{}"`;
case Datatypes.JSONB:
return `"{}"`;
case Datatypes.DATE:
return `string`;
case Datatypes.TIME:
return `string`;
case Datatypes.DATETIME:
return `string`;
case Datatypes.TIMESTAMP:
return `string`;
case Datatypes.UUID_ARRAY:
return `string[]`;
case Datatypes.STRING_ARRAY:
return `string[]`;
case Datatypes.TEXT_ARRAY:
return `string[]`;
case Datatypes.INT_ARRAY:
return `number[]`;
case Datatypes.BIGINT_ARRAY:
return `number[]`;
case Datatypes.FLOAT_ARRAY:
return `number[]`;
case Datatypes.DECIMAL_ARRAY:
return `number[]`;
case Datatypes.NUMBER_ARRAY:
return `number[]`;
case Datatypes.BOOLEAN_ARRAY:
return `boolean[]`;
case Datatypes.DATE_ARRAY:
return `string[]`;
case Datatypes.TIME_ARRAY:
return `string[]`;
case Datatypes.DATETIME_ARRAY:
return `string[]`;
case Datatypes.TIMESTAMP_ARRAY:
return `string[]`;
}
};
export function renderSchemaTypeScript({
schemaInput,
projectInput,
}: {
projectInput: ProjectInput;
schemaInput: SchemaInput;
}): string {
const inflatedSchema: Schema = inflateSchema({
schemaInput,
relations: buildRelations({
schemaInputs: projectInput.schemas,
relationInputs: projectInput.relations,
}),
});
// Define + open JSON output
let output: string[] = [
`interface ${schemaInput.identifiers.singular.pascal} {`, // Open JSON output
// Map each property
...schemaInput.attributes.map((attr: Attribute) => {
return ` ${attr.identifiers.snake}: ${getDatatypeValueTypeScript({
datatype: attr.datatype,
})};`;
}),
...inflatedSchema.relations.map((r: Relation): string => {
return ` ${r.identifiers.destination.alias.singular.camel}Id: ${r.identifiers.destination.canonical.singular.pascal};`;
}),
"}", // Close JSON output
];
// Joins lines
return output.join("\n");
}
// // // //
// CLEANUP - document this function, write better tests
// FEATURE - update this to include optional header text? i.e. import statements when exporting "typescript" preview
export function schemaPreviewContent(props: {
schemaInput: SchemaInput;
projectInput: ProjectInput;
previewOutputType: PreviewOutputType;
}) {
const { schemaInput, projectInput, previewOutputType } = props;
if (previewOutputType === PreviewOutputTypes.json) {
return renderSchemaJson({ schemaInput, projectInput });
}
if (previewOutputType === PreviewOutputTypes.typescript) {
return renderSchemaTypeScript({ schemaInput, projectInput });
}
if (previewOutputType === PreviewOutputTypes.graphql) {
return renderSchemaGrapqhQL({ schemaInput, projectInput });
}
// Return null if no match
return null;
} | the_stack |
import * as React from "react";
import { useId } from "@reach/auto-id";
import { Popover } from "@reach/popover";
import {
createDescendantContext,
DescendantProvider,
useDescendant,
useDescendants,
useDescendantsInit,
useDescendantKeyDown,
} from "@reach/descendants";
import { isRightClick } from "@reach/utils/is-right-click";
import { usePrevious } from "@reach/utils/use-previous";
import { getOwnerDocument } from "@reach/utils/owner-document";
import { createNamedContext } from "@reach/utils/context";
import { isFunction, isString } from "@reach/utils/type-check";
import { makeId } from "@reach/utils/make-id";
import { useStatefulRefValue } from "@reach/utils/use-stateful-ref-value";
import { useComposedRefs } from "@reach/utils/compose-refs";
import { composeEventHandlers } from "@reach/utils/compose-event-handlers";
import type { Descendant } from "@reach/descendants";
import type { Position } from "@reach/popover";
import type * as Polymorphic from "@reach/utils/polymorphic";
////////////////////////////////////////////////////////////////////////////////
// Actions
const CLEAR_SELECTION_INDEX = "CLEAR_SELECTION_INDEX";
const CLICK_MENU_ITEM = "CLICK_MENU_ITEM";
const CLOSE_MENU = "CLOSE_MENU";
const OPEN_MENU_AT_FIRST_ITEM = "OPEN_MENU_AT_FIRST_ITEM";
const OPEN_MENU_AT_INDEX = "OPEN_MENU_AT_INDEX";
const OPEN_MENU_CLEARED = "OPEN_MENU_CLEARED";
const SEARCH_FOR_ITEM = "SEARCH_FOR_ITEM";
const SELECT_ITEM_AT_INDEX = "SELECT_ITEM_AT_INDEX";
const SET_BUTTON_ID = "SET_BUTTON_ID";
const DropdownDescendantContext = createDescendantContext<DropdownDescendant>(
"DropdownDescendantContext"
);
const DropdownContext = createNamedContext<InternalDropdownContextValue>(
"DropdownContext",
{} as InternalDropdownContextValue
);
const initialState: DropdownState = {
// The button ID is needed for aria controls and can be set directly and
// updated for top-level use via context. Otherwise a default is set by useId.
// TODO: Consider deprecating direct ID in 1.0 in favor of id at the top level
// for passing deterministic IDs to descendent components.
triggerId: null,
// Whether or not the dropdown is expanded
isExpanded: false,
// When a user begins typing a character string, the selection will change if
// a matching item is found
typeaheadQuery: "",
// The index of the current selected item. When the selection is cleared a
// value of -1 is used.
selectionIndex: -1,
};
////////////////////////////////////////////////////////////////////////////////
// Dropdown!
const DropdownProvider: React.FC<DropdownProviderProps> = ({
id,
children,
}) => {
let triggerRef = React.useRef(null);
let dropdownRef = React.useRef(null);
let popoverRef = React.useRef(null);
let [descendants, setDescendants] = useDescendantsInit<DropdownDescendant>();
let _id = useId(id);
let dropdownId = id || makeId("menu", _id);
let triggerId = makeId("menu-button", dropdownId);
let [state, dispatch] = React.useReducer(reducer, {
...initialState,
triggerId,
});
// We use an event listener attached to the window to capture outside clicks
// that close the dropdown. We don't want the initial button click to trigger
// this when a dropdown is closed, so we can track this behavior in a ref for
// now. We shouldn't need this when we rewrite with state machine logic.
let triggerClickedRef = React.useRef(false);
// We will put children callbacks in a ref to avoid triggering endless render
// loops when using render props if the app code doesn't useCallback
// https://github.com/reach/reach-ui/issues/523
let selectCallbacks = React.useRef([]);
// If the popover's position overlaps with an option when the popover
// initially opens, the mouseup event will trigger a select. To prevent that,
// we decide the control is only ready to make a selection if the pointer
// moves a certain distance OR if the mouse button is pressed for a certain
// length of time, otherwise the user is just registering the initial button
// click rather than selecting an item.
// For context on some implementation details, see https://github.com/reach/reach-ui/issues/563
let readyToSelect = React.useRef(false);
let mouseDownStartPosRef = React.useRef({ x: 0, y: 0 });
// Trying a new approach for splitting up contexts by stable/unstable
// references. We'll see how it goes!
let context: InternalDropdownContextValue = {
dispatch,
dropdownId,
dropdownRef,
mouseDownStartPosRef,
popoverRef,
readyToSelect,
selectCallbacks,
state,
triggerClickedRef,
triggerRef,
};
// When the dropdown is open, focus is placed on the dropdown itself so that
// keyboard navigation is still possible.
React.useEffect(() => {
if (state.isExpanded) {
// @ts-ignore
window.__REACH_DISABLE_TOOLTIPS = true;
window.requestAnimationFrame(() => {
focus(dropdownRef.current);
});
} else {
// We want to ignore the immediate focus of a tooltip so it doesn't pop up
// again when the dropdown closes, only pops up when focus returns again
// to the tooltip (like native OS tooltips).
// @ts-ignore
window.__REACH_DISABLE_TOOLTIPS = false;
}
}, [state.isExpanded]);
return (
<DescendantProvider
context={DropdownDescendantContext}
items={descendants}
set={setDescendants}
>
<DropdownContext.Provider value={context}>
{isFunction(children)
? children({
isExpanded: state.isExpanded,
// TODO: Remove in 1.0
isOpen: state.isExpanded,
})
: children}
</DropdownContext.Provider>
</DescendantProvider>
);
};
interface DropdownProviderProps {
children:
| React.ReactNode
| ((
props: DropdownContextValue & {
// TODO: Remove in 1.0
isOpen: boolean;
}
) => React.ReactNode);
id?: string;
}
if (__DEV__) {
DropdownProvider.displayName = "DropdownProvider";
}
////////////////////////////////////////////////////////////////////////////////
function useDropdownTrigger({
onKeyDown,
onMouseDown,
id,
ref: forwardedRef,
...props
}: DropdownTriggerProps &
React.ComponentPropsWithoutRef<"button"> & {
ref: React.ForwardedRef<HTMLButtonElement>;
}) {
let {
dispatch,
dropdownId,
mouseDownStartPosRef,
triggerClickedRef,
triggerRef,
state: { triggerId, isExpanded },
} = useDropdownContext();
let ref = useComposedRefs(triggerRef, forwardedRef);
let items = useDropdownDescendants();
let firstNonDisabledIndex = React.useMemo(
() => items.findIndex((item) => !item.disabled),
[items]
);
React.useEffect(() => {
if (id != null && id !== triggerId) {
dispatch({
type: SET_BUTTON_ID,
payload: id,
});
}
}, [triggerId, dispatch, id]);
function handleKeyDown(event: React.KeyboardEvent) {
switch (event.key) {
case "ArrowDown":
case "ArrowUp":
event.preventDefault(); // prevent scroll
dispatch({
type: OPEN_MENU_AT_INDEX,
payload: { index: firstNonDisabledIndex },
});
break;
case "Enter":
case " ":
dispatch({
type: OPEN_MENU_AT_INDEX,
payload: { index: firstNonDisabledIndex },
});
break;
default:
break;
}
}
function handleMouseDown(event: React.MouseEvent) {
if (isRightClick(event.nativeEvent)) {
return;
}
mouseDownStartPosRef.current = {
x: event.clientX,
y: event.clientY,
};
if (!isExpanded) {
triggerClickedRef.current = true;
}
if (isExpanded) {
dispatch({ type: CLOSE_MENU });
} else {
dispatch({ type: OPEN_MENU_CLEARED });
}
}
return {
data: {
isExpanded,
controls: dropdownId,
},
props: {
...props,
ref,
id: triggerId || undefined,
onKeyDown: composeEventHandlers(onKeyDown, handleKeyDown),
onMouseDown: composeEventHandlers(onMouseDown, handleMouseDown),
type: "button" as const,
},
};
}
const DropdownTrigger = React.forwardRef(
({ as: Comp = "button", ...rest }, forwardedRef) => {
let { props } = useDropdownTrigger({ ...rest, ref: forwardedRef });
return <Comp data-reach-dropdown-trigger="" {...props} />;
}
) as Polymorphic.ForwardRefComponent<"button", DropdownTriggerProps>;
interface DropdownTriggerProps {
children: React.ReactNode;
}
if (__DEV__) {
DropdownTrigger.displayName = "DropdownTrigger";
}
////////////////////////////////////////////////////////////////////////////////
function useDropdownItem({
index: indexProp,
isLink = false,
onClick,
onDragStart,
onMouseDown,
onMouseEnter,
onMouseLeave,
onMouseMove,
onMouseUp,
onSelect,
disabled,
onFocus,
valueText: valueTextProp,
ref: forwardedRef,
...props
}: DropdownItemProps &
React.ComponentPropsWithoutRef<"div"> & {
ref: React.ForwardedRef<HTMLDivElement>;
}) {
let {
dispatch,
dropdownRef,
mouseDownStartPosRef,
readyToSelect,
selectCallbacks,
triggerRef,
state: { selectionIndex, isExpanded },
} = useDropdownContext();
let ownRef = React.useRef<HTMLElement | null>(null);
// After the ref is mounted to the DOM node, we check to see if we have an
// explicit valueText prop before looking for the node's textContent for
// typeahead functionality.
let [valueText, setValueText] = React.useState(valueTextProp || "");
let setValueTextFromDOM = React.useCallback(
(node: HTMLElement) => {
if (!valueTextProp && node?.textContent) {
setValueText(node.textContent);
}
},
[valueTextProp]
);
let mouseEventStarted = React.useRef(false);
let [element, handleRefSet] = useStatefulRefValue<HTMLElement | null>(
ownRef,
null
);
let descendant = React.useMemo(() => {
return {
element,
key: valueText,
disabled,
isLink,
};
}, [disabled, element, isLink, valueText]);
let index = useDescendant(descendant, DropdownDescendantContext, indexProp);
let isSelected = index === selectionIndex && !disabled;
let ref = useComposedRefs(forwardedRef, handleRefSet, setValueTextFromDOM);
// Update the callback ref array on every render
selectCallbacks.current[index] = onSelect;
function select() {
focus(triggerRef.current);
onSelect && onSelect();
dispatch({ type: CLICK_MENU_ITEM });
}
function handleClick(event: React.MouseEvent) {
if (isRightClick(event.nativeEvent)) {
return;
}
if (isLink) {
if (disabled) {
event.preventDefault();
} else {
select();
}
}
}
function handleDragStart(event: React.MouseEvent) {
// Because we don't preventDefault on mousedown for links (we need the
// native click event), clicking and holding on a link triggers a
// dragstart which we don't want.
if (isLink) {
event.preventDefault();
}
}
function handleMouseDown(event: React.MouseEvent) {
if (isRightClick(event.nativeEvent)) {
return;
}
if (isLink) {
// Signal that the mouse is down so we can call the right function if the
// user is clicking on a link.
mouseEventStarted.current = true;
} else {
event.preventDefault();
}
}
function handleMouseEnter(event: React.MouseEvent) {
let doc = getOwnerDocument(dropdownRef.current)!;
if (!isSelected && index != null && !disabled) {
if (
dropdownRef?.current &&
dropdownRef.current !== doc.activeElement &&
ownRef.current !== doc.activeElement
) {
dropdownRef.current.focus();
}
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index,
},
});
}
}
function handleMouseLeave(event: React.MouseEvent) {
// Clear out selection when mouse over a non-dropdown-item child.
dispatch({ type: CLEAR_SELECTION_INDEX });
}
function handleMouseMove(event: React.MouseEvent) {
if (!readyToSelect.current) {
let threshold = 8;
let deltaX = Math.abs(event.clientX - mouseDownStartPosRef.current.x);
let deltaY = Math.abs(event.clientY - mouseDownStartPosRef.current.y);
if (deltaX > threshold || deltaY > threshold) {
readyToSelect.current = true;
}
}
if (!isSelected && index != null && !disabled) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index,
dropdownRef,
},
});
}
}
function handleFocus() {
readyToSelect.current = true;
if (!isSelected && index != null && !disabled) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index,
},
});
}
}
function handleMouseUp(event: React.MouseEvent) {
if (isRightClick(event.nativeEvent)) {
return;
}
if (!readyToSelect.current) {
readyToSelect.current = true;
return;
}
if (isLink) {
// If a mousedown event was initiated on a link item followed by a mouseup
// event on the same link, we do nothing; a click event will come next and
// handle selection. Otherwise, we trigger a click event.
if (mouseEventStarted.current) {
mouseEventStarted.current = false;
} else if (ownRef.current) {
ownRef.current.click();
}
} else {
if (!disabled) {
select();
}
}
}
React.useEffect(() => {
if (isExpanded) {
// When the dropdown opens, wait for about half a second before enabling
// selection. This is designed to mirror dropdown menus on macOS, where
// opening a menu on top of a trigger would otherwise result in an
// immediate accidental selection once the click trigger is released.
let id = window.setTimeout(() => {
readyToSelect.current = true;
}, 400);
return () => {
window.clearTimeout(id);
};
} else {
// When the dropdown closes, reset readyToSelect for the next interaction.
readyToSelect.current = false;
}
}, [isExpanded, readyToSelect]);
// Any time a mouseup event occurs anywhere in the document, we reset the
// mouseEventStarted ref so we can check it again when needed.
React.useEffect(() => {
let ownerDocument = getOwnerDocument(ownRef.current)!;
ownerDocument.addEventListener("mouseup", listener);
return () => {
ownerDocument.removeEventListener("mouseup", listener);
};
function listener() {
mouseEventStarted.current = false;
}
}, []);
return {
data: {
disabled,
},
props: {
id: useItemId(index),
tabIndex: -1,
...props,
ref,
"data-disabled": disabled ? "" : undefined,
"data-selected": isSelected ? "" : undefined,
"data-valuetext": valueText,
onClick: composeEventHandlers(onClick, handleClick),
onDragStart: composeEventHandlers(onDragStart, handleDragStart),
onMouseDown: composeEventHandlers(onMouseDown, handleMouseDown),
onMouseEnter: composeEventHandlers(onMouseEnter, handleMouseEnter),
onMouseLeave: composeEventHandlers(onMouseLeave, handleMouseLeave),
onMouseMove: composeEventHandlers(onMouseMove, handleMouseMove),
onFocus: composeEventHandlers(onFocus, handleFocus),
onMouseUp: composeEventHandlers(onMouseUp, handleMouseUp),
},
};
}
/**
* DropdownItem
*/
const DropdownItem = React.forwardRef(
({ as: Comp = "div", ...rest }, forwardedRef) => {
let { props } = useDropdownItem({ ...rest, ref: forwardedRef });
return <Comp data-reach-dropdown-item="" {...props} />;
}
) as Polymorphic.ForwardRefComponent<"div", DropdownItemProps>;
interface DropdownItemProps {
children: React.ReactNode;
onSelect(): void;
index?: number;
isLink?: boolean;
valueText?: string;
disabled?: boolean;
}
if (__DEV__) {
DropdownItem.displayName = "DropdownItem";
}
////////////////////////////////////////////////////////////////////////////////
function useDropdownItems({
id,
onKeyDown,
ref: forwardedRef,
...props
}: DropdownItemsProps &
React.ComponentPropsWithoutRef<"div"> & {
ref: React.ForwardedRef<HTMLDivElement>;
}) {
let {
dispatch,
triggerRef,
dropdownRef,
selectCallbacks,
dropdownId,
state: { isExpanded, triggerId, selectionIndex, typeaheadQuery },
} = useDropdownContext();
let items = useDropdownDescendants();
let ref = useComposedRefs(dropdownRef, forwardedRef);
React.useEffect(() => {
// Respond to user char key input with typeahead
let match = findItemFromTypeahead(items, typeaheadQuery);
if (typeaheadQuery && match != null) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index: match,
dropdownRef,
},
});
}
let timeout = window.setTimeout(
() => typeaheadQuery && dispatch({ type: SEARCH_FOR_ITEM, payload: "" }),
1000
);
return () => window.clearTimeout(timeout);
}, [dispatch, items, typeaheadQuery, dropdownRef]);
let prevItemsLength = usePrevious(items.length);
let prevSelected = usePrevious(items[selectionIndex]);
let prevSelectionIndex = usePrevious(selectionIndex);
React.useEffect(() => {
if (selectionIndex > items.length - 1) {
// If for some reason our selection index is larger than our possible
// index range (let's say the last item is selected and the list
// dynamically updates), we need to select the last item in the list.
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index: items.length - 1,
dropdownRef,
},
});
} else if (
// Checks if
// - item length has changed
// - selection index has not changed BUT selected item has changed
//
// This prevents any dynamic adding/removing of items from actually
// changing a user's expected selection.
prevItemsLength !== items.length &&
selectionIndex > -1 &&
prevSelected &&
prevSelectionIndex === selectionIndex &&
items[selectionIndex] !== prevSelected
) {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index: items.findIndex((i) => i.key === prevSelected?.key),
dropdownRef,
},
});
}
}, [
dropdownRef,
dispatch,
items,
prevItemsLength,
prevSelected,
prevSelectionIndex,
selectionIndex,
]);
let handleKeyDown = composeEventHandlers(
function handleKeyDown(event: React.KeyboardEvent) {
let { key } = event;
if (!isExpanded) {
return;
}
switch (key) {
case "Enter":
case " ":
let selected = items.find((item) => item.index === selectionIndex);
// For links, the Enter key will trigger a click by default, but for
// consistent behavior across items we'll trigger a click when the
// spacebar is pressed.
if (selected && !selected.disabled) {
event.preventDefault();
if (selected.isLink && selected.element) {
selected.element.click();
} else {
// Focus the button first by default when an item is selected.
// We fire the onSelect callback next so the app can manage
// focus if needed.
focus(triggerRef.current);
selectCallbacks.current[selected.index] &&
selectCallbacks.current[selected.index]();
dispatch({ type: CLICK_MENU_ITEM });
}
}
break;
case "Escape":
focus(triggerRef.current);
dispatch({ type: CLOSE_MENU });
break;
case "Tab":
// prevent leaving
event.preventDefault();
break;
default:
// Check if a user is typing some char keys and respond by setting
// the query state.
if (isString(key) && key.length === 1) {
let query = typeaheadQuery + key.toLowerCase();
dispatch({
type: SEARCH_FOR_ITEM,
payload: query,
});
}
break;
}
},
useDescendantKeyDown(DropdownDescendantContext, {
currentIndex: selectionIndex,
orientation: "vertical",
rotate: false,
filter: (item) => !item.disabled,
callback: (index: number) => {
dispatch({
type: SELECT_ITEM_AT_INDEX,
payload: {
index,
dropdownRef,
},
});
},
key: "index",
})
);
return {
data: {
activeDescendant: useItemId(selectionIndex) || undefined,
triggerId,
},
props: {
tabIndex: -1,
...props,
ref,
id: dropdownId,
onKeyDown: composeEventHandlers(onKeyDown, handleKeyDown),
},
};
}
/**
* DropdownItem
*/
const DropdownItems = React.forwardRef(
({ as: Comp = "div", ...rest }, forwardedRef) => {
let { props } = useDropdownItems({ ...rest, ref: forwardedRef });
return <Comp data-reach-dropdown-items="" {...props} />;
}
) as Polymorphic.ForwardRefComponent<"div", DropdownItemsProps>;
interface DropdownItemsProps {
children: React.ReactNode;
}
if (__DEV__) {
DropdownItems.displayName = "DropdownItems";
}
////////////////////////////////////////////////////////////////////////////////
function useDropdownPopover({
onBlur,
portal = true,
position,
ref: forwardedRef,
...props
}: DropdownPopoverProps &
React.ComponentPropsWithoutRef<"div"> & {
ref: React.ForwardedRef<HTMLDivElement>;
}) {
let {
triggerRef,
triggerClickedRef,
dispatch,
dropdownRef,
popoverRef,
state: { isExpanded },
} = useDropdownContext();
let ref = useComposedRefs(popoverRef, forwardedRef);
React.useEffect(() => {
if (!isExpanded) {
return;
}
let ownerDocument = getOwnerDocument(popoverRef.current)!;
function listener(event: MouseEvent | TouchEvent) {
if (triggerClickedRef.current) {
triggerClickedRef.current = false;
} else if (
!popoverContainsEventTarget(popoverRef.current, event.target)
) {
// We on want to close only if focus rests outside the dropdown
dispatch({ type: CLOSE_MENU });
}
}
ownerDocument.addEventListener("mousedown", listener);
// see https://github.com/reach/reach-ui/pull/700#discussion_r530369265
// ownerDocument.addEventListener("touchstart", listener);
return () => {
ownerDocument.removeEventListener("mousedown", listener);
// ownerDocument.removeEventListener("touchstart", listener);
};
}, [
triggerClickedRef,
triggerRef,
dispatch,
dropdownRef,
popoverRef,
isExpanded,
]);
return {
data: {
portal,
position,
targetRef: triggerRef,
isExpanded,
},
props: {
ref,
hidden: !isExpanded,
onBlur: composeEventHandlers(onBlur, (event) => {
if (event.currentTarget.contains(event.relatedTarget as Node)) {
return;
}
dispatch({ type: CLOSE_MENU });
}),
...props,
},
};
}
const DropdownPopover = React.forwardRef(
({ as: Comp = "div", ...rest }, forwardedRef) => {
let {
data: { portal, targetRef, position },
props,
} = useDropdownPopover({ ...rest, ref: forwardedRef });
let sharedProps = {
"data-reach-dropdown-popover": "",
};
return portal ? (
<Popover
{...props}
{...sharedProps}
as={Comp}
targetRef={targetRef as any}
position={position}
/>
) : (
<Comp {...props} {...sharedProps} />
);
}
) as Polymorphic.ForwardRefComponent<"div", DropdownPopoverProps>;
interface DropdownPopoverProps {
children: React.ReactNode;
portal?: boolean;
position?: Position;
}
if (__DEV__) {
DropdownPopover.displayName = "DropdownPopover";
}
////////////////////////////////////////////////////////////////////////////////
/**
* When a user's typed input matches the string displayed in an item, it is
* expected that the matching item is selected. This is our matching function.
*/
function findItemFromTypeahead(
items: DropdownDescendant[],
string: string = ""
) {
if (!string) {
return null;
}
let found = items.find((item) => {
return item.disabled
? false
: item.element?.dataset?.valuetext?.toLowerCase().startsWith(string);
});
return found ? items.indexOf(found) : null;
}
function useItemId(index: number | null) {
let { dropdownId } = React.useContext(DropdownContext);
return index != null && index > -1
? makeId(`option-${index}`, dropdownId)
: undefined;
}
interface DropdownState {
isExpanded: boolean;
selectionIndex: number;
triggerId: null | string;
typeaheadQuery: string;
}
type DropdownAction =
| { type: "CLICK_MENU_ITEM" }
| { type: "CLOSE_MENU" }
| { type: "OPEN_MENU_AT_FIRST_ITEM" }
| { type: "OPEN_MENU_AT_INDEX"; payload: { index: number } }
| { type: "OPEN_MENU_CLEARED" }
| {
type: "SELECT_ITEM_AT_INDEX";
payload: {
dropdownRef?: React.RefObject<HTMLElement | null>;
index: number;
max?: number;
min?: number;
};
}
| { type: "CLEAR_SELECTION_INDEX" }
| { type: "SET_BUTTON_ID"; payload: string }
| { type: "SEARCH_FOR_ITEM"; payload: string };
function focus<T extends HTMLElement = HTMLElement>(
element: T | undefined | null
) {
element && element.focus();
}
function popoverContainsEventTarget(
popover: HTMLElement | null,
target: HTMLElement | EventTarget | null
) {
return !!(popover && popover.contains(target as HTMLElement));
}
function reducer(
state: DropdownState,
action: DropdownAction = {} as DropdownAction
): DropdownState {
switch (action.type) {
case CLICK_MENU_ITEM:
return {
...state,
isExpanded: false,
selectionIndex: -1,
};
case CLOSE_MENU:
return {
...state,
isExpanded: false,
selectionIndex: -1,
};
case OPEN_MENU_AT_FIRST_ITEM:
return {
...state,
isExpanded: true,
selectionIndex: 0,
};
case OPEN_MENU_AT_INDEX:
return {
...state,
isExpanded: true,
selectionIndex: action.payload.index,
};
case OPEN_MENU_CLEARED:
return {
...state,
isExpanded: true,
selectionIndex: -1,
};
case SELECT_ITEM_AT_INDEX: {
let { dropdownRef = { current: null } } = action.payload;
if (
action.payload.index >= 0 &&
action.payload.index !== state.selectionIndex
) {
if (dropdownRef.current) {
let doc = getOwnerDocument(dropdownRef.current);
if (dropdownRef.current !== doc?.activeElement) {
dropdownRef.current.focus();
}
}
return {
...state,
selectionIndex:
action.payload.max != null
? Math.min(Math.max(action.payload.index, 0), action.payload.max)
: Math.max(action.payload.index, 0),
};
}
return state;
}
case CLEAR_SELECTION_INDEX:
return {
...state,
selectionIndex: -1,
};
case SET_BUTTON_ID:
return {
...state,
triggerId: action.payload,
};
case SEARCH_FOR_ITEM:
if (typeof action.payload !== "undefined") {
return {
...state,
typeaheadQuery: action.payload,
};
}
return state;
default:
return state;
}
}
function useDropdownContext() {
return React.useContext(DropdownContext);
}
function useDropdownDescendants() {
return useDescendants(DropdownDescendantContext);
}
////////////////////////////////////////////////////////////////////////////////
// Types
type DropdownDescendant = Descendant<HTMLElement> & {
key: string;
isLink: boolean;
disabled?: boolean;
};
type TriggerRef = React.RefObject<null | HTMLElement>;
type DropdownRef = React.RefObject<null | HTMLElement>;
type PopoverRef = React.RefObject<null | HTMLElement>;
interface InternalDropdownContextValue {
dispatch: React.Dispatch<DropdownAction>;
dropdownId: string | undefined;
dropdownRef: DropdownRef;
mouseDownStartPosRef: React.MutableRefObject<{ x: number; y: number }>;
popoverRef: PopoverRef;
readyToSelect: React.MutableRefObject<boolean>;
selectCallbacks: React.MutableRefObject<(() => void)[]>;
state: DropdownState;
triggerClickedRef: React.MutableRefObject<boolean>;
triggerRef: TriggerRef;
}
interface DropdownContextValue {
isExpanded: boolean;
}
////////////////////////////////////////////////////////////////////////////////
// Exports
export type {
DropdownTriggerProps,
DropdownItemProps,
DropdownItemsProps,
DropdownPopoverProps,
DropdownProviderProps,
};
export {
DropdownProvider,
DropdownTrigger,
DropdownItem,
DropdownItems,
DropdownPopover,
useDropdownTrigger,
useDropdownItem,
useDropdownItems,
useDropdownPopover,
useDropdownContext,
useDropdownDescendants,
}; | the_stack |
import { LitElement, html, customElement, property, CSSResult, TemplateResult, css, PropertyValues } from 'lit-element';
import {
HomeAssistant,
hasConfigOrEntityChanged,
applyThemesOnElement,
computeStateDisplay,
relativeTime,
hasAction,
ActionHandlerEvent,
handleAction,
LovelaceCardEditor,
getLovelace,
LovelaceCard,
} from 'custom-card-helpers';
import './editor';
import { RPiMonitorCardConfig } from './types';
import { actionHandler } from './action-handler-directive';
import * as Constants from './const';
import { localize } from './localize/localize';
/* eslint no-console: 0 */
console.info(
`%c RPI-MONITOR-CARD \n%c ${localize('common.version')} ${Constants.CARD_VERSION} `,
'color: orange; font-weight: bold; background: black',
'color: white; font-weight: bold; background: dimgray',
);
(window as any).customCards = (window as any).customCards || [];
(window as any).customCards.push({
type: 'rpi-monitor-card',
name: 'RPi Monitor Card',
description: 'A template custom card for you to create something awesome',
});
// Name our custom element
@customElement('rpi-monitor-card')
export class RPiMonitorCard extends LitElement {
public static async getConfigElement(): Promise<LovelaceCardEditor> {
return document.createElement('rpi-monitor-card-editor') as LovelaceCardEditor;
}
public static getStubConfig(): object {
return {};
}
// Properities that should cause your element to re-render here
@property() public hass!: HomeAssistant;
@property() private _config!: RPiMonitorCardConfig;
// and those that don't cause a re-render
private _firstTime: boolean = true;
private _sensorAvailable: boolean = false;
private _updateTimerID: NodeJS.Timeout | undefined;
private _hostname: string = '';
private kREPLACE_WITH_TEMP_UNITS: string = 'replace-with-temp-units';
// WARNING set following to false before commit!
private _show_debug: boolean = false;
//private _show_debug: boolean = true;
//
// FULL-SIZE CARD tables
//
private _cardFullElements = {
// top to bottom
Storage: Constants.RPI_FS_TOTAL_GB_KEY,
'Storage Use': Constants.RPI_FS_USED_PERCENT_KEY,
Updated: Constants.RPI_LAST_UPDATE_KEY,
Temperature: Constants.RPI_TEMPERATURE_IN_C_KEY,
'Up-time': Constants.RPI_UP_TIME_KEY,
OS: Constants.SHOW_OS_PARTS_VALUE,
Model: Constants.RPI_MODEL_KEY,
Interfaces: Constants.RPI_INTERFACES_KEY,
};
private _cardFullIconNames = {
// top to bottom
Storage: 'sd',
'Storage Use': 'file-percent',
Updated: 'update',
Temperature: 'thermometer',
'Up-time': 'clock-check-outline',
OS: 'linux',
Model: 'raspberry-pi',
Interfaces: '',
};
// attribute ICON IDs
private kClassIdIconFSAvail = 'ico-fs-percent';
private kClassIdIconFSTotal = 'ico-fs-total';
private kClassIdIconSysTemp = 'ico-sys-temp';
private kClassIdIconUptime = 'ico-up-time';
private kClassIdIconUpdated = 'ico-last-update';
private kClassIdIconOS = 'ico-*nix';
private kClassIdIconRPiModel = 'ico-rpi-model';
private kClassIdIconInterfaces = 'ico-rpi-ifaces';
// attribute value label IDs
private kClassIdFSAvail = 'fs-percent';
private kClassIdFSTotal = 'fs-total';
private kClassIdSysTemp = 'sys-temp';
private kClassIdUptime = 'up-time';
private kClassIdUpdated = 'last-update';
private kClassIdOS = '*nix';
private kClassIdRPiModel = 'rpi-model';
private kClassIdInterfaces = 'rpi-ifaces';
// ond one special for unit
private kClassIdTempScale = 'sys-temp-scale';
private _cardFullCssIDs = {
// top to bottom
Storage: this.kClassIdFSTotal,
'Storage Use': this.kClassIdFSAvail,
Updated: this.kClassIdUpdated,
Temperature: this.kClassIdSysTemp,
'Up-time': this.kClassIdUptime,
OS: this.kClassIdOS,
Model: this.kClassIdRPiModel,
Interfaces: this.kClassIdInterfaces,
};
private _cardFullIconCssIDs = {
// top to bottom
Storage: this.kClassIdIconFSTotal,
'Storage Use': this.kClassIdIconFSAvail,
Updated: this.kClassIdIconUpdated,
Temperature: this.kClassIdIconSysTemp,
'Up-time': this.kClassIdIconUptime,
OS: this.kClassIdIconOS,
Model: this.kClassIdIconRPiModel,
Interfaces: this.kClassIdIconInterfaces,
};
//
// GLANCE CARD tables
//
private _cardGlanceElements = {
// left to right
'%': Constants.RPI_FS_USED_PERCENT_KEY,
GB: Constants.RPI_FS_TOTAL_GB_KEY,
'replace-with-temp-units': Constants.RPI_TEMPERATURE_IN_C_KEY,
UpTime: Constants.RPI_UP_TIME_KEY,
Upd: Constants.RPI_LAST_UPDATE_KEY,
};
private _cardGlanceIconNames = {
// left to right
'%': 'file-percent',
GB: 'sd',
'replace-with-temp-units': 'thermometer',
UpTime: 'clock-check-outline',
Upd: 'update',
};
private _cardGlanceCssIDs = {
// left to right
'%': this.kClassIdFSAvail,
GB: this.kClassIdFSTotal,
'replace-with-temp-units': this.kClassIdSysTemp,
UpTime: this.kClassIdUptime,
Upd: this.kClassIdUpdated,
};
private _cardGlanceIconCssIDs = {
// left to right
'%': this.kClassIdIconFSAvail,
GB: this.kClassIdIconFSTotal,
'replace-with-temp-units': this.kClassIdIconSysTemp,
UpTime: this.kClassIdIconUptime,
Upd: this.kClassIdIconUpdated,
};
// space used icon set
private _circleIconsValueByName = {
'circle-outline': 0,
'circle-slice-1': 13,
'circle-slice-2': 25,
'circle-slice-3': 38,
'circle-slice-4': 50,
'circle-slice-5': 63,
'circle-slice-6': 75,
'circle-slice-7': 88,
'circle-slice-8': 100,
};
/*
* COLORING Goals (default)
*
* 1) color time since reported: yellow if longer than 1 reporting interval, red if two or more
* 2) color space-used: nothing to 60%, 61-85% yellow, 86%+ red
* 3) color temp: nothing to 59C, 60-79C yellow, 80C+ red
*/
// DEFAULT coloring for used space
// user sets 'fs_severity' to override
private _colorUsedSpaceDefault = [
{
color: 'undefined',
from: 0,
to: 59,
},
{
color: 'yellow',
from: 60,
to: 84,
},
{
color: 'red',
from: 85,
to: 100,
},
];
// coloring for temp-in-C
// user sets 'temp_severity' to override
private _colorTemperatureDefault = [
{
color: 'undefined',
from: 0,
to: 59,
},
{
color: 'yellow',
from: 60,
to: 79,
},
{
color: 'red',
from: 85,
to: 100,
},
];
// coloring for temp-in-C
// no user override for now
private _colorReportPeriodsAgoDefault = [
{
color: 'undefined',
from: 0,
to: 0,
},
{
color: 'yellow',
from: 1,
to: 1,
},
{
color: 'red',
from: 2,
to: 100,
},
];
public setConfig(config: RPiMonitorCardConfig): void {
if (this._showDebug()) {
console.log('- setConfig()');
}
// Optional: Check for required fields and that they are of the proper format
if (!config || config.show_error) {
throw new Error(localize('common.invalid_configuration'));
}
if (config.card_style != undefined) {
const styleValue: string = config.card_style.toLocaleLowerCase();
if (styleValue != 'full' && styleValue != 'glance') {
console.log('Invalid configuration. INVALID card_style = [' + config.card_style + ']');
throw new Error('Illegal card_style: value (card_style: ' + config.card_style + ') must be [full or glance]');
}
}
if (config.temp_scale != undefined) {
const scaleValue: string = config.temp_scale.toLocaleLowerCase();
if (scaleValue != 'c' && scaleValue != 'f') {
console.log('Invalid configuration. INVALID temp_scale = [' + config.temp_scale + ']');
throw new Error('Illegal temp_scale: value (temp_scale: ' + config.temp_scale + ') must be [F or C]');
}
}
if (!config.entity) {
console.log("Invalid configuration. If no entity provided, you'll need to provide a remote entity");
throw new Error('You need to associate an entity');
}
if (config.test_gui) {
getLovelace().setEditMode(true);
}
this._config = {
...config,
};
//console.log('- config:');
//console.log(this._config);
this._updateSensorAvailability();
}
/*
public getCardSize(): number {
// adjust this based on glance or full card type
return this._useFullCard() == true ? 3 : 1;
}
*/
protected shouldUpdate(changedProps: PropertyValues): boolean {
//return hasConfigOrEntityChanged(this, changedProps, false);
this._updateSensorAvailability();
if (changedProps.has('_config')) {
return true;
}
if (this.hass && this._config) {
const oldHass = changedProps.get('hass') as HomeAssistant | undefined;
if (oldHass) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return oldHass.states[this._config.entity!] !== this.hass.states[this._config.entity!];
}
}
return true;
}
protected render(): TemplateResult | void {
// Check for stateObj or other necessary things and render a warning if missing
if (this._showDebug()) {
console.log('- render()');
}
if (this._config.show_warning) {
return this.showWarning(localize('common.show_warning'));
}
const entityId = this._config.entity ? this._config.entity : undefined;
if (entityId && !this._sensorAvailable) {
const warningMessage = 'Entity Unavailable: ' + entityId;
return this.showWarning(warningMessage);
}
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
if (!entityId && !stateObj) {
return this.showWarning('Entity Unavailable');
}
if (this._firstTime) {
if (this._showDebug()) {
console.log('- stateObj:');
console.log(stateObj);
}
// set timer so our card updates timestamp every 5 seconds : 5000 (1 second: 1000)
// FIXME: UNDONE remember to clear this interval when entity NOT avail. and restore when comes avail again...
this._startCardRefreshTimer();
if (this._showDebug()) {
console.log('- 1st-time _config:');
console.log(this._config);
}
this._firstTime = false;
}
const rpi_fqdn = this._getAttributeValueForKey(Constants.RPI_FQDN_KEY);
let cardName = 'RPi monitor ' + rpi_fqdn;
cardName = this._config.name_prefix != undefined ? this._config.name_prefix + ' ' + rpi_fqdn : cardName;
cardName = this._config.name != undefined ? this._config.name : cardName;
const showCardName = this._config.show_title != undefined ? this._config.show_title : true;
if (showCardName == false) {
cardName = '';
}
const last_heard_full_class = showCardName == false ? 'last-heard-full-notitle' : 'last-heard-full';
const last_heard_class = showCardName == false ? 'last-heard-notitle' : 'last-heard';
const card_timestamp_value = this._getRelativeTimeSinceUpdate();
if (this._useFullCard()) {
// our FULL card
const fullRows = this._generateFullsizeCardRows();
return html`
<ha-card
.header=${cardName}
@action=${this._handleAction}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config.hold_action),
hasDoubleClick: hasAction(this._config.double_tap_action),
})}
tabindex="0"
aria-label=${cardName}
>
<div id="states" class="card-content">
${fullRows}
<div id="card-timestamp" class=${last_heard_full_class}>${card_timestamp_value}</div>
</div>
</ha-card>
`;
} else {
// our GLANCE card
const glanceRows = this._generateGlanceCardRows();
return html`
<ha-card
.header=${cardName}
@action=${this._handleAction}
.actionHandler=${actionHandler({
hasHold: hasAction(this._config.hold_action),
hasDoubleClick: hasAction(this._config.double_tap_action),
})}
tabindex="0"
aria-label=${cardName}
>
<div class="content">
${glanceRows}
<div id="card-timestamp" class=${last_heard_class}>${card_timestamp_value}</div>
</div>
</ha-card>
`;
}
}
private _getRelativeTimeSinceUpdate(): string {
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const stateStrInterp = computeStateDisplay(this.hass?.localize, stateObj!, this.hass?.language);
const relativeInterp =
stateStrInterp === undefined ? '{unknown}' : relativeTime(new Date(stateStrInterp), this.hass?.localize);
const desiredValue = this._sensorAvailable ? relativeInterp : '{unknown}';
return desiredValue;
}
private _getMinutesSinceUpdate(): number {
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const stateStrInterp = computeStateDisplay(this.hass?.localize, stateObj!, this.hass?.language);
const then = new Date(stateStrInterp);
const now = new Date();
let diff = (now.getTime() - then.getTime()) / 1000;
diff /= 60;
return Math.abs(Math.round(diff));
}
// Here we need to refresh the rings and titles after it has been initially rendered
protected updated(changedProps): void {
if (this._showDebug()) {
console.log('- updated()');
}
if (!this._config) {
return;
}
// update cards' theme if changed
if (this.hass) {
const oldHass = changedProps.get('hass');
if (!oldHass || oldHass.themes !== this.hass.themes) {
applyThemesOnElement(this, this.hass.themes, this._config.theme);
}
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const stateObj = this.hass!.states[this._config.entity!];
if (!stateObj) {
this._stopCardRefreshTimer();
}
//console.log('- changed Props: ');
//console.log(changedProps);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const root: any = this.shadowRoot;
if (this._sensorAvailable) {
if (this._useFullCard()) {
// update our FULL card
for (const currName in this._cardFullCssIDs) {
const currLabelID = this._cardFullCssIDs[currName];
const currAttrKey = this._cardFullElements[currName];
const rawValue = this._getAttributeValueForKey(currAttrKey);
const latestValue = this._getFullCardValueForAttributeKey(currAttrKey);
const labelElement = root.getElementById(currLabelID);
labelElement.textContent = latestValue;
const currIconCssID = this._cardFullIconCssIDs[currName];
const iconElement = root.getElementById(currIconCssID);
if (currAttrKey == Constants.RPI_FS_USED_PERCENT_KEY) {
const color = this._computeFileSystemUsageColor(rawValue);
if (color != '') {
labelElement.style.setProperty('color', color);
iconElement.style.setProperty('color', color);
}
}
if (currAttrKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
const color = this._computeTemperatureColor(rawValue);
if (color != '') {
labelElement.style.setProperty('color', color);
iconElement.style.setProperty('color', color);
}
}
}
} else {
// update our GLANCE card
for (const currName in this._cardGlanceCssIDs) {
const currLabelID = this._cardGlanceCssIDs[currName];
const currAttrKey = this._cardGlanceElements[currName];
const rawValue = this._getAttributeValueForKey(currAttrKey);
const latestValue = this._getGlanceCardValueForAttributeKey(currAttrKey);
const labelElement = root.getElementById(currLabelID);
labelElement.textContent = latestValue;
const currIconCssID = this._cardGlanceIconCssIDs[currName];
const iconElement = root.getElementById(currIconCssID);
if (currAttrKey == Constants.RPI_FS_USED_PERCENT_KEY) {
const color = this._computeFileSystemUsageColor(rawValue);
if (color != '') {
labelElement.style.setProperty('color', color);
iconElement.style.setProperty('color', color);
}
}
if (currAttrKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
// don't place temp scale (C or F) when 'n/a'
if (latestValue != 'n/a') {
const color = this._computeTemperatureColor(rawValue);
if (color != '') {
labelElement.style.setProperty('color', color);
iconElement.style.setProperty('color', color);
}
const scaleLabelElement = root.getElementById(this.kClassIdTempScale);
scaleLabelElement.textContent = this._getTemperatureScale();
}
}
}
}
}
}
private _handleAction(ev: ActionHandlerEvent): void {
if (this.hass && this._config && ev.detail.action) {
handleAction(this, this.hass, this._config, ev.detail.action);
}
}
private showWarning(warning: string): TemplateResult {
// generate a warning message for use in card
return html`
<hui-warning>${warning}</hui-warning>
`;
}
private showError(error: string): TemplateResult {
// display an error card
const errorCard = document.createElement('hui-error-card') as LovelaceCard;
errorCard.setConfig({
type: 'error',
error,
origConfig: this._config,
});
return html`
${errorCard}
`;
}
// ===========================================================================
// PRIVATE (utility) functions
// ---------------------------------------------------------------------------
private _startCardRefreshTimer(): void {
this._updateTimerID = setInterval(() => this._handleCardUpdateTimerExpiration(), 1000);
}
private _stopCardRefreshTimer(): void {
if (this._updateTimerID != undefined) {
clearInterval(this._updateTimerID);
this._updateTimerID = undefined;
}
}
private _handleCardUpdateTimerExpiration(): void {
//
// timestamp portion of card
//
const root: any = this.shadowRoot;
let needCardFlush = false;
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
if (stateObj != undefined) {
const labelElement = root.getElementById('card-timestamp');
if (labelElement) {
let card_timestamp_value = this._getRelativeTimeSinceUpdate();
if (card_timestamp_value) {
// BUGFIX let's NOT show 'in NaN weeks' message on reload...
if (card_timestamp_value.includes('NaN')) {
card_timestamp_value = 'waiting for report...';
needCardFlush = true;
}
labelElement.textContent = card_timestamp_value;
// now apply color if our entry is OLD
/*
const sinceInMinutes = this._getMinutesSinceUpdate();
const periodMinutes = this._getAttributeValueForKey(Constants.RPI_SCRIPT_INTERVAL_KEY);
const mumber_periods: number = sinceInMinutes / parseInt(periodMinutes);
const intervalColor = this._computeReporterAgeColor(mumber_periods.toString());
if (intervalColor != '') {
labelElement.style.setProperty('color', intervalColor);
}
*/
}
if (needCardFlush) {
this._emptyCardValuesWhileWaitingForSensor();
}
}
}
}
private _useFullCard(): boolean {
let useFullCardStatus = true;
if (this._config) {
if (this._config.card_style != undefined) {
// NOTE this depends upon full validation of the two legal values [full|glance] above
useFullCardStatus = this._config.card_style.toLocaleLowerCase() == 'full' ? true : false;
}
}
return useFullCardStatus;
}
private _useTempsInC(): boolean {
let useTempsInCStatus = true;
if (this._config) {
if (this._config.temp_scale != undefined) {
// NOTE this depends upon full validation of the two legal values [full|glance] above
useTempsInCStatus = this._config.temp_scale.toLocaleLowerCase() == 'c' ? true : false;
}
}
return useTempsInCStatus;
}
private _logChangeMessage(message: string): void {
if (this._hostname == '') {
this._hostname = this._getAttributeValueForKey(Constants.RPI_HOST_NAME_KEY);
}
const logMessage = '(' + this._hostname + '): ' + message;
if (this._showDebug()) {
console.log(logMessage);
}
}
private _updateSensorAvailability(): void {
let availChanged: boolean = false;
if (this.hass && this._config) {
const entityId = this._config.entity ? this._config.entity : undefined;
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
if (!entityId && !stateObj) {
this._sensorAvailable = false;
availChanged = true; // force output in this case
} else {
try {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const tmpAvail = this.hass.states[this._config.entity!].state != 'unavailable';
availChanged = this._sensorAvailable != tmpAvail ? true : false;
this._sensorAvailable = tmpAvail;
} catch (error) {
this._sensorAvailable = false;
availChanged = true; // force output in this case
}
}
} else {
this._sensorAvailable = false;
availChanged = true; // force output in this case
}
if (availChanged) {
this._logChangeMessage('* SENSOR available: ' + this._sensorAvailable);
}
}
private _getIconNameForPercent(percent: string): string {
// return name of icon we should show for given %
let desiredIconName = '';
for (const currIconName in this._circleIconsValueByName) {
const currMaxValue = this._circleIconsValueByName[currIconName];
if (percent <= currMaxValue) {
desiredIconName = currIconName;
break;
}
}
return desiredIconName;
}
private _computeReporterAgeColor(value: string): unknown {
const numberValue = Number(value);
const sections = this._colorReportPeriodsAgoDefault;
//console.log('color-table: sections=');
//console.log(sections);
//return '';
let color: undefined | string;
sections.forEach(section => {
if (numberValue >= section.from && numberValue <= section.to) {
color = section.color;
}
});
if (color == undefined) color = '';
return color;
}
private _computeTemperatureColor(value: string): unknown {
const config = this._config;
const numberValue = Number(value);
const sections = config.temp_severity ? config.temp_severity : this._colorTemperatureDefault;
//console.log('color-table: sections=');
//console.log(sections);
//return '';
let color: undefined | string;
if (isNaN(numberValue)) {
sections.forEach(section => {
if (value == section.text) {
color = section.color;
}
});
} else {
sections.forEach(section => {
if (numberValue >= section.from && numberValue <= section.to) {
color = section.color;
const logMessage =
'_computeTemperatureColor() - value=[' +
value +
'] matched(from=' +
section.from +
', to=' +
section.to +
', color=' +
color +
')';
if (this._showDebug()) {
console.log(logMessage);
}
}
});
}
const logMessage = '_computeTemperatureColor() - value=[' + value + '] returns(color=' + color + ')';
if (this._showDebug()) {
console.log(logMessage);
}
if (color == undefined) color = '';
return color;
}
private _computeFileSystemUsageColor(value: string): string {
const config = this._config;
const numberValue = Number(value);
const sections = config.fs_severity ? config.fs_severity : this._colorUsedSpaceDefault;
//console.log('color-table: sections=');
//console.log(sections);
//return '';
let color: undefined | string;
if (isNaN(numberValue)) {
sections.forEach(section => {
if (value == section.text) {
color = section.color;
}
});
} else {
sections.forEach(section => {
if (numberValue >= section.from && numberValue <= section.to) {
color = section.color;
const logMessage =
'_computeFileSystemUsageColor() - value=[' +
value +
'] matched(from=' +
section.from +
', to=' +
section.to +
', color=' +
color +
')';
if (this._showDebug()) {
console.log(logMessage);
}
}
});
}
const logMessage = '_computeFileSystemUsageColor() - value=[' + value + '] returns(color=' + color + ')';
if (this._showDebug()) {
console.log(logMessage);
}
if (color == undefined) color = '';
return color;
}
private _filterUptime(uptimeRaw: string): string {
const lineParts: string[] = uptimeRaw.split(' ');
let interpValue = uptimeRaw;
if (interpValue.includes(':')) {
for (let index = 0; index < lineParts.length; index++) {
const currPart = lineParts[index];
if (currPart.includes(':')) {
const timeParts = currPart.split(':');
const newPart = timeParts[0] + 'h:' + timeParts[1] + 'm';
lineParts[index] = newPart;
}
}
interpValue = lineParts.join(' ');
}
return interpValue;
}
private _getAttributeValueForKey(key: string): string {
// HELPER UTILITY: get requested named value from config
if (!this.hass || !this._config) {
return '';
}
const entityId = this._config.entity ? this._config.entity : undefined;
const stateObj = this._config.entity ? this.hass.states[this._config.entity] : undefined;
if (!entityId && !stateObj) {
return '';
}
if (stateObj?.attributes == undefined) {
return '';
}
let desired_value: string = ''; // empty string
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (key in stateObj?.attributes!) {
desired_value = stateObj?.attributes[key];
}
return desired_value;
}
private _emptyCardValuesWhileWaitingForSensor(): void {
const root: any = this.shadowRoot;
if (this._sensorAvailable) {
if (this._useFullCard()) {
// clear values for our FULL card
for (const currName in this._cardFullCssIDs) {
const currLabelID = this._cardFullCssIDs[currName];
const labelElement = root.getElementById(currLabelID);
labelElement.textContent = '';
}
} else {
// clear values for our GLANCE card
for (const currName in this._cardGlanceCssIDs) {
const currLabelID = this._cardGlanceCssIDs[currName];
const currAttrKey = this._cardGlanceElements[currName];
const labelElement = root.getElementById(currLabelID);
labelElement.textContent = '';
if (currAttrKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
const scaleLabelElement = root.getElementById(this.kClassIdTempScale);
scaleLabelElement.textContent = this._getTemperatureScale();
}
}
}
}
}
private _generateFullsizeCardRows(): TemplateResult[] {
// create the rows for the GLANCE card
const rowsArray: TemplateResult[] = [];
for (const currName in this._cardFullElements) {
const currAttributeKey = this._cardFullElements[currName];
// Use `key` and `value`
const interpValue = this._getFullCardValueForAttributeKey(currAttributeKey);
// determine icon we should display
let currIconName = this._cardFullIconNames[currName];
if (currAttributeKey == Constants.RPI_FS_USED_PERCENT_KEY) {
const latestRawValue = this._getAttributeValueForKey(currAttributeKey);
currIconName = this._getIconNameForPercent(latestRawValue);
}
const currIconCssID = this._cardFullIconCssIDs[currName];
// get ID for values that need updating
const currLabelCssID = this._cardFullCssIDs[currName];
// adjust our row size for bottom rows (group them visually)
let rowHightAttribute = 'attribute-row';
if (currName == 'Model') {
rowHightAttribute = 'first-short';
} else if (currName == 'Interfaces') {
rowHightAttribute = 'last-short';
}
// now generate row....
rowsArray.push(html`
<div class="${rowHightAttribute}">
<rpi-attribute-row>
<div class="icon-holder">
<ha-icon id="${currIconCssID}" class="attr-icon-full pointer" icon="mdi:${currIconName}"></ha-icon>
</div>
<div class="info pointer text-content attr-value">${currName}</div>
<div id="${currLabelCssID}" class="text-content right uom">${interpValue}</div>
</rpi-attribute-row>
</div>
`);
}
return rowsArray;
}
private _generateGlanceCardRows(): TemplateResult[] {
// create the columns for the GLANCE card
const columnsArray: TemplateResult[] = [];
for (const currName in this._cardGlanceElements) {
const currAttributeKey = this._cardGlanceElements[currName];
// Use `key` and `value`
const interpValue = this._getGlanceCardValueForAttributeKey(currAttributeKey);
let currUnits = currName;
if (currUnits == this.kREPLACE_WITH_TEMP_UNITS) {
if (interpValue != 'n/a') {
currUnits = this._getTemperatureScale();
} else {
// when 'n/a' don't show units!
currUnits = '';
}
}
let currIconName = this._cardGlanceIconNames[currName];
if (currAttributeKey == Constants.RPI_FS_USED_PERCENT_KEY) {
currIconName = this._getIconNameForPercent(interpValue);
}
const currLabelCssID = this._cardGlanceCssIDs[currName];
const currIconCssID = this._cardGlanceIconCssIDs[currName];
let scaleCssID = 'units';
if (currAttributeKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
scaleCssID = this.kClassIdTempScale;
}
columnsArray.push(html`
<div class="attributes" tabindex="0">
<div>
<ha-icon id="${currIconCssID}" class="attr-icon" icon="mdi:${currIconName}"></ha-icon>
</div>
<div id="${currLabelCssID}" class="attr-value">${interpValue}</div>
<div id="${scaleCssID}" class="uom">${currUnits}</div>
</div>
`);
}
return columnsArray;
}
private _getTemperatureScale(): string {
const scaleInterp = this._useTempsInC() == true ? 'ºC' : 'ºF';
const logMessage = '_getTemperatureScale() scaleInterp=(' + scaleInterp + ')';
if (this._showDebug()) {
console.log(logMessage);
}
return scaleInterp;
}
private _getScaledTemperatureValue(temperature_raw: string): string {
let interpValue = temperature_raw;
if (interpValue != 'n/a') {
if (this._useTempsInC() == false) {
// if not inC convert to F
interpValue = ((parseFloat(temperature_raw) * 9) / 5 + 32.0).toFixed(1);
}
}
const logMessage = '_getScaledTemperatureValue(' + temperature_raw + ') scaleInterp=(' + interpValue + ')';
if (this._showDebug()) {
console.log(logMessage);
}
return interpValue;
}
private _getFullCardValueForAttributeKey(attrKey: string): string {
const latestValue = this._getAttributeValueForKey(attrKey);
let interpValue = latestValue;
if (attrKey == Constants.RPI_LAST_UPDATE_KEY) {
// regenerate the date value
interpValue = this._getUIDateForTimestamp(latestValue);
} else if (attrKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
// let's format our temperature value
interpValue = this._getScaledTemperatureValue(latestValue);
if (interpValue != 'n/a') {
const currUnits = this._getTemperatureScale();
interpValue = interpValue + ' ' + currUnits;
}
} else if (attrKey == Constants.RPI_FS_TOTAL_GB_KEY) {
// append our units
interpValue = latestValue + ' GB';
} else if (attrKey == Constants.RPI_FS_USED_PERCENT_KEY) {
// append our % sign
interpValue = latestValue + ' %';
} else if (attrKey == Constants.RPI_UP_TIME_KEY) {
interpValue = this._filterUptime(interpValue);
} else if (attrKey == Constants.SHOW_OS_PARTS_VALUE) {
// replace value with os release and version
const osRelease = this._getAttributeValueForKey(Constants.RPI_NIX_RELEASE_KEY);
const osVersion = this._getAttributeValueForKey(Constants.RPI_NIX_VERSION_KEY);
interpValue = osRelease + ' v' + osVersion;
} else if (attrKey == Constants.RPI_INTERFACES_KEY) {
const namesArray: string[] = [];
// expand our single letters into interface names
if (latestValue.includes('e')) {
namesArray.push('Ether');
}
if (latestValue.includes('w')) {
namesArray.push('WiFi');
}
if (latestValue.includes('b')) {
namesArray.push('Bluetooth');
}
interpValue = namesArray.join(', ');
}
return interpValue;
}
private _getGlanceCardValueForAttributeKey(attrKey: string): string {
const latestValue = this._getAttributeValueForKey(attrKey);
let interpValue = latestValue;
if (attrKey == Constants.RPI_LAST_UPDATE_KEY) {
// regenerate the date value
interpValue = this._getUIDateForTimestamp(latestValue);
} else if (attrKey == Constants.RPI_TEMPERATURE_IN_C_KEY) {
// let's scale our temperature value
interpValue = this._getScaledTemperatureValue(latestValue);
} else if (attrKey == Constants.RPI_UP_TIME_KEY) {
interpValue = this._filterUptime(interpValue);
}
return interpValue;
}
private _getUIDateForTimestamp(dateISO: string): string {
const uiDateOptions = {
year: 'numeric',
month: 'short',
day: 'numeric',
};
const timestamp = new Date(dateISO);
const desiredInterp = timestamp.toLocaleDateString('en-us', uiDateOptions);
return desiredInterp;
}
private _showDebug(): boolean {
// we show debug if enabled in code or if found enabled in config for this card!
let showDebugStatus = this._show_debug;
if (this._config) {
if (this._config.show_debug != undefined) {
showDebugStatus = showDebugStatus == true || this._config.show_debug == true;
}
}
return showDebugStatus;
}
static get styles(): CSSResult {
// style our GLANCE card
return css`
ha-card {
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
overflow: hidden;
}
rpi-attribute-row {
display: grid;
flex-direction: row;
align-items: center;
height: 40px;
grid-template-columns: 40px 2fr 3fr;
}
#states > * {
margin: 8px 0px;
}
#states > div > * {
overflow: hidden;
}
#states {
flex: 1 1 0%;
}
.right {
text-align: right;
}
.first-short {
margin: 8px 0px 0px 0px;
height: 20px;
}
.mid-short {
margin: 0px;
height: 20px;
}
.last-short {
margin: 0px 0px 8px 0px;
height: 20px;
}
.pointer {
cursor: pointer;
}
.icon-holder {
align-items: center;
margin-left: 8px;
}
.attr-icon-full {
color: var(--paper-item-icon-color);
}
.attribute-row {
height: 40px;
}
.text-content {
display: inline;
line-height: 20px;
}
.info {
white-space: nowrap;
text-overflow: ellipses;
overflow: hidden;
margin-left: 16px;
flex: 1 0 60px;
}
.content {
display: flex;
justify-content: space-between;
padding: 16px 32px 24px 32px;
}
.attributes {
cursor: pointer;
}
.attributes div {
text-align: center;
}
.uom {
color: var(--secondary-text-color);
}
.attr-value {
color: var(--primary-text-color);
}
.attr-icon {
color: var(--paper-item-icon-color);
margin-bottom: 8px;
}
.last-heard-full {
position: absolute;
top: 45px;
right: 30px;
font-size: 12px;
color: var(--primary-text-color);
}
.last-heard {
position: absolute;
top: 55px;
right: 30px;
font-size: 12px;
color: var(--primary-text-color);
}
.last-heard-full-notitle {
position: absolute;
top: 3px;
right: 30px;
font-size: 12px;
color: var(--primary-text-color);
}
.last-heard-notitle {
position: absolute;
bottom: 5px;
right: 90px;
font-size: 12px;
color: var(--primary-text-color);
}
`;
}
} | the_stack |
import { Component, ViewChild, ComponentRef } from '@angular/core';
import {
async,
TestBed,
ComponentFixture,
fakeAsync,
flush,
} from '@angular/core/testing';
import { ConfirmationPopoverModule } from '../public-api';
import { ConfirmationPopoverDirective } from '../lib/confirmation-popover.directive';
import { ConfirmationPopoverWindowComponent } from '../lib/confirmation-popover-window.component';
import { expect } from 'chai';
import * as sinon from 'sinon';
describe('bootstrap confirm', () => {
describe('ConfirmationPopover directive', () => {
@Component({
template: `
<button
class="btn btn-outline-secondary"
mwlConfirmationPopover
[popoverTitle]="popoverTitle"
[popoverMessage]="popoverMessage"
[confirmText]="confirmText"
[cancelText]="cancelText"
[placement]="placement"
(confirm)="confirmClicked($event)"
(cancel)="cancelClicked($event)"
confirmButtonType="danger"
cancelButtonType="outline-secondary"
[popoverClass]="popoverClass"
[focusButton]="focusButton"
[hideConfirmButton]="hideConfirmButton"
[hideCancelButton]="hideCancelButton"
[isDisabled]="isDisabled"
[(isOpen)]="isOpen"
[appendToBody]="appendToBody"
[reverseButtonOrder]="reverseButtonOrder"
>
Show popover
</button>
`,
})
class TestComponent {
@ViewChild(ConfirmationPopoverDirective, { static: true })
confirm: ConfirmationPopoverDirective;
placement: string = 'left';
popoverTitle: string = 'Are you sure?';
popoverMessage: string =
'Are you really <b>sure</b> you want to do this?';
confirmText: string = 'Yes <i class="glyphicon glyphicon-ok"></i>';
cancelText: string = 'No <i class="glyphicon glyphicon-remove"></i>';
focusButton: string;
hideConfirmButton: boolean = false;
hideCancelButton: boolean = false;
isDisabled: boolean = false;
isOpen: boolean;
popoverClass: string = 'my-class';
appendToBody: boolean = false;
confirmClicked: sinon.SinonSpy = sinon.spy();
cancelClicked: sinon.SinonSpy = sinon.spy();
reverseButtonOrder = false;
}
let createPopover: () => ComponentRef<ConfirmationPopoverWindowComponent>;
function clickFixture(fixture: ComponentFixture<TestComponent>) {
fixture.nativeElement.querySelector('button').click();
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ConfirmationPopoverModule.forRoot()],
declarations: [TestComponent],
});
createPopover = (): ComponentRef<ConfirmationPopoverWindowComponent> => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
return popover;
};
});
it('should show a popover when the element is clicked', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
const showPopover = sinon.spy(confirm, 'showPopover');
expect(confirm.popover).not.to.be.ok;
clickFixture(fixture);
expect(showPopover).to.have.been.calledOnce;
expect(confirm.popover).to.be.ok;
});
it('should hide the popover when the element is clicked if the popover is open', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
clickFixture(fixture);
const hidePopover = sinon.spy(confirm, 'hidePopover');
clickFixture(fixture);
expect(hidePopover).to.have.been.calledOnce;
});
it('should hide the popover when the parent component is destroyed', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
const hidePopover = sinon.spy(confirm, 'hidePopover');
fixture.destroy();
expect(hidePopover).to.have.been.calledOnce;
});
it('should hide the popover when the confirm button is clicked', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
clickFixture(fixture);
const hidePopover = sinon.spy(confirm, 'hidePopover');
confirm.popover.changeDetectorRef.detectChanges();
confirm.popover.location.nativeElement
.querySelectorAll('button')[0]
.click();
expect(hidePopover).to.have.been.calledOnce;
});
it('should hide the popover when the cancel button is clicked', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
clickFixture(fixture);
const hidePopover = sinon.spy(confirm, 'hidePopover');
confirm.popover.changeDetectorRef.detectChanges();
confirm.popover.location.nativeElement
.querySelectorAll('button')[1]
.click();
expect(hidePopover).to.have.been.calledOnce;
});
it('should hide the popover when an element not inside the popover is clicked', fakeAsync(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
clickFixture(fixture);
const hidePopover = sinon.spy(confirm, 'hidePopover');
confirm.popover.changeDetectorRef.detectChanges();
flush();
const btn: HTMLElement = document.createElement('button');
document.body.appendChild(btn);
btn.click();
flush();
expect(hidePopover).to.have.been.calledOnce;
btn.parentNode!.removeChild(btn);
}));
it('should allow the popover title to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelector('.popover-title')
).to.have.html('Are you sure?');
});
it('should allow the popover description to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelector('.popover-content > p')
).to.have.html('Are you really <b>sure</b> you want to do this?');
});
it('should allow the confirm button text to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelectorAll('button')[1]
).to.have.html('Yes <i class="glyphicon glyphicon-ok"></i>');
});
it('should allow the cancel button text to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelectorAll('button')[0]
).to.have.html('No <i class="glyphicon glyphicon-remove"></i>');
});
it('should allow the confirm button type to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelectorAll('button')[1]
).to.have.class('btn-danger');
});
it('should allow the cancel button type to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(
popover.location.nativeElement.querySelectorAll('button')[0]
).to.have.class('btn-outline-secondary');
});
it('should allow the placement to be customised', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(popover.location.nativeElement.children[0]).to.have.class(
'popover-left'
);
});
it('should a custom class to be set on the popover', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(popover.location.nativeElement.children[0]).to.have.class(
'my-class'
);
});
it('should re-position the popover when the window resizes', fakeAsync(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.componentInstance.focusButton = 'confirm';
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
flush();
const positionPopover: sinon.SinonSpy = sinon.spy(
fixture.componentInstance.confirm as any,
'positionPopover'
);
window.dispatchEvent(new Event('resize'));
expect(positionPopover).to.have.been.calledOnce;
}));
it('should not focus either button by default', () => {
const popover: ComponentRef<ConfirmationPopoverWindowComponent> = createPopover();
expect(popover.location.nativeElement.contains(document.activeElement))
.not.to.be.ok;
});
it('should focus the confirm button', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.componentInstance.focusButton = 'confirm';
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelectorAll('button')[1]
).to.equal(document.activeElement);
});
it('should focus the cancel button', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentInstance.focusButton = 'cancel';
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelectorAll('button')[0]
).to.equal(document.activeElement);
});
it('should hide the confirm button', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentInstance.hideConfirmButton = true;
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelectorAll('button')
).to.have.length(1);
expect(
popover.location.nativeElement.querySelectorAll('button')[0]
).to.have.class('btn-outline-secondary');
});
it('should hide the cancel button', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentInstance.hideCancelButton = true;
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelectorAll('button')
).to.have.length(1);
expect(
popover.location.nativeElement.querySelectorAll('button')[0]
).to.have.class('btn-danger');
});
it('should disable the popover from opening', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentInstance.isDisabled = true;
fixture.detectChanges();
const confirm: ConfirmationPopoverDirective =
fixture.componentInstance.confirm;
clickFixture(fixture);
expect(confirm.popover).not.to.be.ok;
});
it('should open the popover when isOpen is set to true', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentInstance.isOpen = true;
fixture.detectChanges();
expect(fixture.componentInstance.confirm).to.be.ok;
});
it('should close the popover when isOpen is set to false', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
clickFixture(fixture);
const hidePopover: sinon.SinonSpy = sinon.spy(
fixture.componentInstance.confirm as any,
'hidePopover'
);
fixture.componentInstance.isOpen = false;
fixture.detectChanges();
expect(hidePopover).to.have.been.calledOnce;
});
it('should call the confirm callback when the confirm button is clicked', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(fixture.componentInstance.confirmClicked).not.to.have.been.called;
popover.location.nativeElement.querySelectorAll('button')[1].click();
expect(fixture.componentInstance.confirmClicked).to.have.been.calledOnce;
expect(
fixture.componentInstance.confirmClicked.getCall(0).args[0]
.clickEvent instanceof MouseEvent
).to.be.true;
});
it('should call the cancel callback when the cancel button is clicked', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(fixture.componentInstance.cancelClicked).not.to.have.been.called;
popover.location.nativeElement.querySelectorAll('button')[0].click();
expect(fixture.componentInstance.cancelClicked).to.have.been.calledOnce;
expect(
fixture.componentInstance.cancelClicked.getCall(0).args[0]
.clickEvent instanceof MouseEvent
).to.be.true;
});
it('should initialise isOpen to false', async(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.whenStable().then(() => {
// let isOpenChange be called with false
expect(fixture.componentInstance.isOpen).to.be.false;
});
}));
it('should set isOpen to true when the popover is opened', async(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture
.whenStable()
.then(() => {
// let isOpenChange be called with false
clickFixture(fixture);
return fixture.whenStable();
})
.then(() => {
expect(fixture.componentInstance.isOpen).to.be.true;
});
}));
it('should set isOpen to false when the popover is closed', async(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture
.whenStable()
.then(() => {
// let isOpenChange be called with false
clickFixture(fixture);
return fixture.whenStable();
})
.then(() => {
clickFixture(fixture);
return fixture.whenStable();
})
.then(() => {
expect(fixture.componentInstance.isOpen).to.be.false;
});
}));
it('should not append the popover to the document body', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentRef.instance.appendToBody = false;
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
document.body.children[document.body.children.length - 1].children[0]
).not.to.have.class('popover');
expect(
fixture.componentRef.location.nativeElement.querySelector('.popover')
).to.be.ok;
});
it('should append the popover to the document body', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentRef.instance.appendToBody = true;
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
document.body.children[document.body.children.length - 1].children[0]
).to.have.class('popover');
expect(
fixture.componentRef.location.nativeElement.querySelector('.popover')
).not.to.be.ok;
});
it('should allow a custom template to be set', () => {
const html: string = `
<ng-template #customTemplate let-options="options">
<div [class]="'popover ' + options.placement" style="display: block">
<div class="arrow"></div>
<h3 class="popover-title">{{ options.popoverTitle }}</h3>
<div class="popover-content">
<p [innerHTML]="options.popoverMessage"></p>
<div id="customTemplate">Custom template</div>
<button [mwlFocus]="options.focusButton === 'confirm'">Confirm</button>
</div>
</div>
</ng-template>
<button
mwlConfirmationPopover
popoverTitle="My Title"
popoverMessage="My Message"
placement="right"
focusButton="confirm"
[customTemplate]="customTemplate">
Show popover
</button>
`;
TestBed.overrideComponent(TestComponent, { set: { template: html } });
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
const popoverElm: HTMLElement =
popover.location.nativeElement.children[0];
expect(popoverElm.querySelector('.popover-title')).to.have.html(
'My Title'
);
expect(popoverElm.querySelector('.popover-content > p')).to.have.html(
'My Message'
);
expect(popoverElm).to.have.class('right');
expect(popoverElm.querySelector('#customTemplate')).to.have.html(
'Custom template'
);
expect(popoverElm.querySelectorAll('button')[0]).to.equal(
document.activeElement
);
});
it('should reverse the button order', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.componentRef.instance.reverseButtonOrder = true;
fixture.detectChanges();
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelector('.confirm-btns')
).to.have.class('confirm-btns-reversed');
});
it('should add a selector to the popover window component', () => {
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
clickFixture(fixture);
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
expect(popover.location.nativeElement.tagName.toLowerCase()).to.equal(
'mwl-confirmation-popover-window'
);
});
it('should allow configuring clicking outside of popover to close it', fakeAsync(() => {
const fixture: ComponentFixture<TestComponent> = TestBed.overrideTemplate(
TestComponent,
`
<button type="button"
class="btn btn-outline-secondary"
mwlConfirmationPopover
[closeOnOutsideClick]="false"
>Show Popover</button>
`
).createComponent(TestComponent);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
clickFixture(fixture);
// We will be tracking the hidePopover
const hidePopover = sinon.spy(confirm, 'hidePopover');
confirm.popover.changeDetectorRef.detectChanges();
flush();
// Simulating clicking outside of the popup
const btn: HTMLElement = document.createElement('button');
document.body.appendChild(btn);
btn.click();
flush();
// Popover should still be open
expect(hidePopover).to.not.have.been.called;
btn.parentNode!.removeChild(btn);
}));
it('should allow configuring clicking outside of popover globally', fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
ConfirmationPopoverModule.forRoot({
closeOnOutsideClick: false,
}),
],
});
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
const confirm: any = fixture.componentInstance.confirm;
fixture.nativeElement.querySelector('button').click();
// We will be tracking the hidePopover
const hidePopover = sinon.spy(confirm, 'hidePopover');
confirm.popover.changeDetectorRef.detectChanges();
flush();
// Simulating clicking outside of the popup
const btn: HTMLElement = document.createElement('button');
document.body.appendChild(btn);
btn.click();
flush();
// Popover should still be open
expect(hidePopover).to.not.have.been.called;
}));
});
describe('ConfirmOptions', () => {
@Component({
template: `
<button class="btn btn-outline-secondary" mwlConfirmationPopover>
Show popover
</button>
`,
})
class TestComponent {
@ViewChild(ConfirmationPopoverDirective, { static: true })
confirm: ConfirmationPopoverDirective;
}
it('should allow default options to be configured globally', () => {
TestBed.configureTestingModule({
imports: [
ConfirmationPopoverModule.forRoot({
confirmText: 'Derp',
}),
],
declarations: [TestComponent],
});
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelectorAll('button')[1]
).to.have.html('Derp');
});
it('should allow the appendToBody option to be configured globally', () => {
TestBed.configureTestingModule({
imports: [
ConfirmationPopoverModule.forRoot({
appendToBody: true,
}),
],
declarations: [TestComponent],
});
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
document.body.children[document.body.children.length - 1].children[0]
).to.have.class('popover');
expect(
fixture.componentRef.location.nativeElement.querySelector('.popover')
).not.to.be.ok;
});
it('should allow the appendToBody option to be overridden locally when set to true globally', () => {
TestBed.overrideComponent(TestComponent, {
set: {
template: `
<button
class="btn btn-outline-secondary"
mwlConfirmationPopover
[appendToBody]="false">
Show popover
</button>
`,
},
});
TestBed.configureTestingModule({
imports: [
ConfirmationPopoverModule.forRoot({
appendToBody: true,
}),
],
declarations: [TestComponent],
});
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
document.body.children[document.body.children.length - 1].children[0]
).not.to.have.class('popover');
expect(
fixture.componentRef.location.nativeElement.querySelector('.popover')
).to.be.ok;
});
it('should allow the defauult title and message to be configured globally', () => {
TestBed.configureTestingModule({
imports: [
ConfirmationPopoverModule.forRoot({
popoverTitle: 'Default title',
popoverMessage: 'Default message',
}),
],
declarations: [TestComponent],
});
const fixture: ComponentFixture<TestComponent> = TestBed.createComponent(
TestComponent
);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
const popover: ComponentRef<ConfirmationPopoverWindowComponent> =
fixture.componentInstance.confirm.popover;
popover.changeDetectorRef.detectChanges();
expect(
popover.location.nativeElement.querySelector('.popover-title')
).to.have.html('Default title');
expect(
popover.location.nativeElement.querySelector('.popover-content p')
).to.have.html('Default message');
});
});
}); | the_stack |
export class Array {
/**
* Create an instance of Array
* @param {number[]} data a javascript array of doubles/floats
*/
constructor(data: number[]);
/**
* Get the underlying javascript array
* @returns number[] the data
*/
getData(): number[];
/**
* The lenght of the underlying data
*/
readonly length:number;
}
/**
* Represents the ImageGray object
* @export
* @interface ImageGray
*/
export interface ImageGray {
/**
* Get the number of columns
* @type {number}
* @memberof ImageGray
*/
readonly cols: number;
/**
* Get the number of rows
* @type {number}
* @memberof ImageGray
*/
readonly rows: number;
}
/**
* Represents the ImageRGB object
* @export
* @interface ImageRGB
*/
export interface ImageRGB {
/**
* Get the number of columns
* @type {number}
* @memberof ImageRGB
*/
readonly cols: number;
/**
* Get the number of rows
* @type {number}
* @memberof ImageRGB
*/
readonly rows: number;
/**
* Convert the image to ImageGray
* @returns {ImageGray} the new ImageGray
* @memberof ImageRGB
*/
toGray(): ImageGray;
}
/**
* Represents the CvImageWrap object
* @export
* @interface CvImage
*/
export class CvImage {
/**
* Get the number of columns
* @type {number}
* @memberof ImageRGB
*/
readonly cols: number;
/**
* Get the number of rows
* @type {number}
* @memberof ImageRGB
*/
readonly rows: number;
constructor(cvMat: any);
}
/**
* Represents the region in the image using a rectangle
* @export
* @class Rect
*/
export class Rect {
/**
* Creates an instance of Rect.
* @param {number} left
* @param {number} top
* @param {number} right
* @param {number} bottom
* @memberof Rect
*/
constructor(left: number, top: number, right: number, bottom: number);
/**
* Get the left coordinate of the rectangle
* @type {number}
* @memberof Rect
*/
readonly left: number;
/**
* Get the top coordinate of the rectangle
* @type {number}
* @memberof Rect
*/
readonly top: number;
/**
* Get the right coordinate of the rectangle
* @type {number}
* @memberof Rect
*/
readonly right: number;
/**
* Get the bottom coordinate of the rectangle
* @type {number}
* @memberof Rect
*/
readonly bottom: number;
/**
* Get the area of the rectangle
* @type {number}
* @memberof Rect
*/
readonly area: number;
}
/**
* Represents a point in the image
* @export
* @interface Point
*/
export interface Point {
/**
* Get the z coordinate of the Point
* @type {number}
* @memberof Point
*/
readonly z: number;
/**
* Get the y coordinate of the Point
* @type {number}
* @memberof Point
*/
readonly y: number;
/**
* Get the x coordinate of the Point
* @type {number}
* @memberof Point
*/
readonly x: number;
}
/**
* Represents a rectangle with the confidence score
* @export
* @interface MmodRect
*/
export interface MmodRect {
/**
* Get the confidence score
* @type {number}
* @memberof MmodRect
*/
readonly confidence: number;
/**
* Get the rectangle
* @type {Rect}
* @memberof MmodRect
*/
readonly rect: Rect;
}
/**
* Represents the FaceDescriptorState object
* @export
* @interface FaceDescriptorState
*/
export interface FaceDescriptorState {
/**
* Get the className/label for the faces
* @type {string}
* @memberof FaceDescriptorState
*/
className: string;
/**
* Get the number of faces
* @type {number}
* @memberof FaceDescriptorState
*/
numFaces: number;
}
/**
* Represents the FaceDescriptor object
* @export
* @interface FaceDescriptor
*/
export interface FaceDescriptor {
/**
* Get the className/label for the descriptors
* @type {string}
* @memberof FaceDescriptor
*/
className: string;
/**
* Get the array of FaceDescriptors
* @type {number[][]}
* @memberof FaceDescriptor
*/
faceDescriptors: number[][];
}
/**
* Represents the FacePrediction for a className
* @export
* @interface FacePrediction
*/
export interface FacePrediction {
/**
* Get the className/label for which the prediction is provided
* @type {string}
* @memberof FacePrediction
*/
className: string;
/**
* Get the prediction in terms of distance
* @type {number}
* @memberof FacePrediction
*/
distance: number;
}
/**
* This object describes where an image chip is to be extracted from within
* another image. In particular, it specifies that the image chip is
* contained within the rectangle rect and that prior to extraction the
* image should be rotated counter-clockwise by angle radians. Finally,
* the extracted chip should have rows and columns in it
* regardless of the shape of rect. This means that the extracted chip
* will be stretched to fit via bilinear interpolation when necessary.
* @export
* @interface ChipDetails
*/
export interface ChipDetails {
readonly rect: Rect;
readonly size: number;
readonly angle: number;
readonly cols: number;
readonly rows: number;
}
/**
* Provide methods to detect and locate the faces in the image
* @export
* @interface FaceDetector
*/
export interface FaceDetector {
/**
* Detect the faces in the image and return them as a set of images
* @param {ImageRGB} img the image in which to look for the faces
* @param {number} [faceSize] the optional size of the face
* @returns {ImageRGB[]} an array of images that contain the faces
* @memberof FaceDetector
*/
detectFaces(img: ImageRGB, faceSize?: number): ImageRGB[];
/**
* Get the region/rectangles for the faces in the provided image
* @param {ImageRGB} img the image in which to look for the faces
* @returns {MmodRect[]} the region/rectangle with confidence score
* @memberof FaceDetector
*/
locateFaces(img: ImageRGB): MmodRect[];
/**
* Get the faces from the image and supplied regions
* @param {ImageRGB} img the image in which to look for the faces
* @param {Rect[]} rects the regions where the faces are
* @param {number} [faceSize] an optional minimum size for the facec
* @returns {ImageRGB[]} an array of images contains the faces
* @memberof FaceDetector
*/
getFacesFromLocations(img: ImageRGB, rects: Rect[], faceSize?: number): ImageRGB[];
}
/**
* Provide methods to asynchronously detect and locate the faces in the image
* @export
* @interface AsyncFaceDetector
*/
export interface AsyncFaceDetector {
/**
* Detect the faces in the image and return them as a set of images
* @param {ImageRGB} img the image in which to look for the faces
* @param {number} [faceSize] the optional size of the face
* @returns {Promise<ImageRGB[]>} an array of images that contain the faces
* @memberof AsyncFaceDetector
*/
detectFaces(img: ImageRGB, faceSize?: number): Promise<ImageRGB[]>;
/**
* Get the region/rectangles for the faces in the provided image
* @param {ImageRGB} img the image in which to look for the faces
* @returns {Promise<MmodRect[]>} the region/rectangle with confidence score
* @memberof AsyncFaceDetector
*/
locateFaces(img: ImageRGB): Promise<MmodRect[]>;
/**
* Get the faces from the image and supplied regions
* @param {ImageRGB} img the image in which to look for the faces
* @param {Rect[]} rects the regions where the faces are
* @param {number} [faceSize] an optional minimum size for the facec
* @returns {Promise<ImageRGB[]>} an array of images contains the faces
* @memberof AsyncFaceDetector
*/
getFacesFromLocations(img: ImageRGB, rects: Rect[], faceSize?: number): Promise<ImageRGB[]>;
}
/**
* Provide methods to perform Face Recognition
* @export
* @interface FaceRecognizer
*/
export interface FaceRecognizer {
/**
* Given an image provide the FacePrediction
* @param {ImageRGB} image the image to be analyzed
* @returns {FacePrediction[]} the face predictions
* @memberof FaceRecognizer
*/
predict(image: ImageRGB): FacePrediction[];
/**
* Given an image provide the best FacePrediction
* @param {ImageRGB} image the image to be analyzed
* @param {number} [unknownThreshold] the threshold for the unknown
* @returns {FacePrediction} the best FacePrediction
* @memberof FaceRecognizer
*/
predictBest(image: ImageRGB, unknownThreshold?: number): FacePrediction;
/**
* Load the provided descriptors
* @param {FaceDescriptor[]} descriptors the descriptors to be loaded
* @memberof FaceRecognizer
*/
load(descriptors: FaceDescriptor[]): void;
/**
* Get the descriptor states
* @returns {FaceDescriptorState[]} the face descriptor states
* @memberof FaceRecognizer
*/
getDescriptorState(): FaceDescriptorState[];
/**
* Serializes the FaceDescription
* @returns {FaceDescriptor[]} an array of FaceDescriptor objects
* @memberof FaceRecognizer
*/
serialize(): FaceDescriptor[];
/**
* Add the faces for a give class with optional jittering
* @param {ImageRGB[]} faces the faces to be added to the test data
* @param {string} className the label/class of for the faces
* @param {number} [numJitters] the number of jitters to be applied to each face
* @memberof FaceRecognizer
*/
addFaces(faces: ImageRGB[], className: string, numJitters?: number): void;
/**
* Clears the descriptors
* @memberof FaceRecognizer
*/
clear(): void;
/**
* Get the 128 representative descriptors for a supplied face
* @param {ImageRGB | CvImage} face image of the face to evaluate
* @returns {Number[]} an array of 128 representative descriptors
*/
getFaceDescriptors(face: ImageRGB | CvImage): Number[];
}
/**
* Provide methods to asynchrnously perform Face Recognition
* @export
* @interface AsyncFaceRecognizer
*/
export interface AsyncFaceRecognizer {
/**
* Given an image provide the FacePrediction
* @param {ImageRGB} image the image to be analyzed
* @returns {Promise<FacePrediction[]>} the promise containing the FacePredictions
* @memberof AsyncFaceRecognizer
*/
predict(image: ImageRGB): Promise<FacePrediction[]>;
/**
* Given an image provide the best FacePrediction
* @param {ImageRGB} image the image to be analyzed
* @param {number} [unknownThreshold] the threshold for the unknown
* @returns {Promise<FacePrediction>} the promise containig the best FacePrediction
* @memberof AsyncFaceRecognizer
*/
predictBest(image: ImageRGB, unknownThreshold?: number): Promise<FacePrediction>;
/**
* Load the raw FaceDescriptors
* @param {*} rawDescriptors
* @memberof AsyncFaceRecognizer
*/
load(rawDescriptors: any): void;
/**
* Get the descriptor states
* @returns {FaceDescriptorState[]} the face descriptor states
* @memberof AsyncFaceRecognizer
*/
getDescriptorState(): FaceDescriptorState[];
/**
* Serializes the FaceDescription
* @returns {FaceDescriptor[]} an array of FaceDescriptor objects
* @memberof AsyncFaceRecognizer
*/
serialize(): FaceDescriptor[];
/**
* Add the faces for a give class with optional jittering
* @param {ImageRGB[]} faces the faces to be added to the test data
* @param {string} className the label/class of for the faces
* @param {number} [numJitters] the number of jitters to be applied to each face
* @returns {Promise<void>}
* @memberof AsyncFaceRecognizer
*/
addFaces(faces: ImageRGB[], className: string, numJitters?: number): Promise<void>;
/**
* Clears the descriptors
* @memberof AsyncFaceRecognizer
*/
clear(): void;
}
/**
* Represents the point locations obtained after predicting using the FaceLandmarkPredictor
* @export
* @interface FullObjectDetection
*/
export interface FullObjectDetection {
/**
*
* @type {number}
* @memberof FullObjectDetection
*/
readonly numParts: number;
/**
*
* @type {Rect}
* @memberof FullObjectDetection
*/
readonly rect: Rect;
/**
*
* @returns {Point[]}
* @memberof FullObjectDetection
*/
getParts(): Point[];
}
/**
* Provides methods to get set of point locations that define the pose of the object (face).
* @export
* @interface FaceLandmarkPredictor
*/
export interface FaceLandmarkPredictor {
/**
* Get the location of important facial landmarks
* such as the corners of the mouth and eyes, tip of the nose, and so forth.
* @param {ImageRGB} img the image
* @param {Rect} rect the region of the image from which to get the landmarks
* @returns {FullObjectDetection}
* @memberof FaceLandmarkPredictor
*/
predict(img: ImageRGB, rect: Rect): FullObjectDetection;
/**
* Asynchronously get the location of important facial landmarks
* such as the corners of the mouth and eyes, tip of the nose, and so forth.
* @param {ImageRGB} img the image
* @param {Rect} rect the region of the image from which to get the landmarks
* @returns {Promise<FullObjectDetection>}
* @memberof FaceLandmarkPredictor
*/
predictAsync(img: ImageRGB, rect: Rect): Promise<FullObjectDetection>;
}
/**
* Provides methods to find human faces that are more or less looking towards the camera.
*
* @export
* @class FrontalFaceDetector
*/
export class FrontalFaceDetector {
/**
* Creates an instance of FrontalFaceDetector.
* @memberof FrontalFaceDetector
*/
constructor();
/**
* Detect the faces in the supplied image
*
* See more example related to adjustThreshold parameter here
* http://dlib.net/face_detector.py.html
*
* @param {ImageRGB} img the image in which to detect the faces
* @param {number} adjustThreshold this optional argument provides the flexibility of detecting more faces by upscaling if value is > 0
* @returns {Rect[]} the regions for the faces
* @memberof FrontalFaceDetector
*/
detect(img: ImageRGB, adjustThreshold?: number): Rect[];
}
/**
* Helper utility to help exit the process
* cleanly when it was terminated by Ctrl-C etc
* @export
*/
export function winKillProcessOnExit(): void;
/**
* Listen for a keyboard event
* @export
*/
export function hitEnterToContinue(): void;
/**
* Load the image from the provide path
* @export
* @param {string} path the path to the image file
* @returns {ImageRGB} the image object
*/
export function loadImage(path: string): ImageRGB;
/**
* Save the image to the provided path
* @export
* @param {string} path the path of the image file
* @param {(ImageRGB | ImageGray)} image the image to be saved
* @param {boolean} [isJpeg] true if the image is JPEG
*/
export function saveImage(path: string, image: ImageRGB | ImageGray, isJpeg?: boolean): void;
/**
* Generate an image that has the input images tiled
* @export
* @param {ImageRGB[]} images the images to be put in the tiles
* @returns {ImageRGB} the tiled image
*/
export function tileImages(images: ImageRGB[]): ImageRGB;
/**
* Get the upscaled version of the supplied image
* @export
* @param {ImageRGB} image the image to be upscaled
* @returns {ImageRGB} the upscaled image
*/
export function pyramidUp(image: ImageRGB): ImageRGB;
/**
* Resize the image using the provide scale
* @export
* @param {ImageRGB} image the image to be resized
* @param {number} scale the scale to reize
* @returns {ImageRGB} the resized image
*/
export function resizeImage(image: ImageRGB, scale: number): ImageRGB;
/**
* Converts an CvImage wrap to an ImageRGB
* @export
* @param {CvImage} image the image to be converted
* @returns {ImageRGB} the converted image
*/
export function cvImageToImageRGB(image: CvImage): ImageRGB;
/**
* Jitter the images. This may help create more training data for your images
* @export
* @param {ImageRGB} image the image on which jittering is applied
* @param {number} numJitters the number of jitters
* @returns {ImageRGB[]} the array of images returned after applying the jitters
*/
export function jitterImage(image: ImageRGB, numJitters: number): ImageRGB[];
/**
* This function assumes detections contains a human face detection with face parts
* annotated using the annotation scheme from the iBUG 300-W face landmark
* dataset or a 5 point face annotation. Given these assumptions, it creates a
* ChipDetails object that will extract a copy of the face that has been
* rotated upright, centered, and scaled to a standard size when given to
* extractImageChips()
* @export
* @param {FullObjectDetection[]} detections an array of FullObjectDetection
* @returns {ChipDetails[]} an array of ChipDetails
*/
export function getFaceChipDetails(detections: FullObjectDetection[], faceSize?: number, padding?: number): ChipDetails[];
/**
* This function extracts "chips" from an image. That is, it takes a list of
* rectangular sub-windows (i.e. chips) within an image and extracts those
* sub-windows, storing each into its own image. It also scales and rotates the
* image chips according to the instructions inside each chip_details object.
* @export
* @param {ImageRGB} image the image from which to extract the chips
* @param {ChipDetails[]} chipDetails the details of the chip
* @returns {ImageRGB[]} an array of images
*/
export function extractImageChips(image: ImageRGB, chipDetails: ChipDetails[]): ImageRGB[];
/**
* Compute the mean of the provide array of Array
* @export
* @param {Array[]} input the array of Array on which to compute the mean
* @returns {Array} the mean
*/
export function mean(input:Array[]): Array;
/**
* Compute the distance between two Array
* @export
* @param {Array} input1 the first input
* @param {Array} input2 the second input
* @returns {number} the distance between input1 and input2
*/
export function distance(input1:Array, input2:Array): number;
/**
* Get the FaceDetector object
* @export
* @returns {FaceDetector}
*/
export function FaceDetector(useFaceLandmarks68Model?: boolean): FaceDetector;
/**
* Get the FaceRecognizer object
* @export
* @returns {FaceRecognizer}
*/
export function FaceRecognizer(): FaceRecognizer;
/**
* Get the FaceLandmark5Predictor object
* @export
* @returns {FaceLandmarkPredictor}
*/
export function FaceLandmark5Predictor(): FaceLandmarkPredictor;
/**
* Get the FaceLandmark68Predictor object
* @export
* @returns {FaceLandmarkPredictor}
*/
export function FaceLandmark68Predictor(): FaceLandmarkPredictor;
/**
* Get the Asynchronous FaceDetector object
* @export
* @returns {AsyncFaceDetector}
*/
export function AsyncFaceDetector(useFaceLandmarks68Model?: boolean): AsyncFaceDetector;
/**
* Get the Asynchronous FaceRecoginzer object
* @export
* @returns {AsyncFaceRecognizer}
*/
export function AsyncFaceRecognizer(): AsyncFaceRecognizer;
/**
* Creates a window that can display an image
* @export
* @class ImageWindow
*/
export class ImageWindow {
/**
* Creates an instance of ImageWindow.
* @memberof ImageWindow
*/
constructor();
/**
* Close the window
* @memberof ImageWindow
*/
close(): void;
/**
* Sets the image to be displayed in the window
* @param {(ImageRGB | ImageGray)} image the image to be displayed
* @memberof ImageWindow
*/
setImage(image: ImageRGB | ImageGray): void;
/**
* Adds an overlay on the top of the image
*
* @param {Rect} rect specify the dimensions of the overlay
* @param {string} [label] specify the (optional) label to be displayed
* @memberof ImageWindow
*/
addOverlay(rect: Rect, label?: string): void;
/**
* Remove/Clear the overlay
* @memberof ImageWindow
*/
clearOverlay(): void;
/**
* Set the size of the window
* @param {number} width width of the window
* @param {number} height height of the window
* @memberof ImageWindow
*/
setSize(width: number, height: number): void;
/**
* Display all the detected faces
* @param {FullObjectDetection[]} shapes
* @memberof ImageWindow
*/
renderFaceDetections(shapes: FullObjectDetection[]): void;
}
export class ShapePredictor {
constructor(faceLandmarksModelFilePath: string);
predict(image: ImageRGB, rect: Rect): FullObjectDetection
predictAsync(image: ImageRGB, rect: Rect): Promise<FullObjectDetection>
}
export class FaceDetectorNet {
constructor(faceDetectionModelFilePath: string);
detect(image: ImageRGB): MmodRect
detectAsync(image: ImageRGB): Promise<MmodRect>
}
export class FaceRecognizerNet {
constructor(faceRecognitionModelFilePath: string);
computeFaceDescriptor(faceImage: ImageRGB): Array
computeFaceDescriptorAsync(faceImage: ImageRGB): Promise<Array>
}
export const models: {
faceLandmarks5Model: string;
faceLandmarks68Model: string;
faceDetectionModel: string;
faceRecognitionModel: string;
}
export function withCv(cv: any): void;
export function toCvRect(dlibRect: Rect): any;
export function fromCvRect(cvRect: any): Rect; | the_stack |
import {
DataStore as DataStoreType,
PersistentModelConstructor,
initSchema as initSchemaType,
} from '../src/';
import {
pause,
expectMutation,
Model,
User,
Profile,
Post,
Comment,
testSchema,
} from './helpers';
export { pause };
/**
* Adds common query test cases that all adapters should support.
*
* @param ctx A context object that provides a DataStore property, which returns
* a DataStore instance loaded with the storage adapter to test.
*/
export function addCommonQueryTests({
initSchema,
DataStore,
storageAdapter,
getMutations,
clearOutbox,
}) {
describe('Common `query()` cases', () => {
let Model: PersistentModelConstructor<Model>;
let Comment: PersistentModelConstructor<Comment>;
let Post: PersistentModelConstructor<Post>;
/**
* Creates the given number of models, with `field1` populated to
* `field1 value ${i}`.
*
* @param qty number of models to create. (default 3)
*/
async function addModels(qty = 3) {
// NOTE: sort() test on these models can be flaky unless we
// strictly control the datestring of each! In a non-negligible percentage
// of test runs on a reasonably fast machine, DataStore.save() seemed to return
// quickly enough that dates were colliding. (or so it seemed!)
const baseDate = new Date();
for (let i = 0; i < qty; i++) {
await DataStore.save(
new Model({
field1: `field1 value ${i}`,
dateCreated: new Date(baseDate.getTime() + i).toISOString(),
emails: [`field${i}@example.com`],
})
);
}
}
beforeEach(async () => {
DataStore.configure({ storageAdapter });
// establishing a fake appsync endpoint tricks DataStore into attempting
// sync operations, which we'll leverage to monitor how DataStore manages
// the outbox.
(DataStore as any).amplifyConfig.aws_appsync_graphqlEndpoint =
'https://0.0.0.0/does/not/exist/graphql';
const classes = initSchema(testSchema());
({ Comment, Model, Post } = classes as {
Comment: PersistentModelConstructor<Comment>;
Model: PersistentModelConstructor<Model>;
Post: PersistentModelConstructor<Post>;
});
await DataStore.clear();
// start() ensures storageAdapter is set
await DataStore.start();
const adapter = (DataStore as any).storageAdapter;
const db = (adapter as any).db;
const syncEngine = (DataStore as any).sync;
// my jest spy-fu wasn't up to snuff here. but, this succesfully
// prevents the mutation process from clearing the mutation queue, which
// allows us to observe the state of mutations.
(syncEngine as any).mutationsProcessor.isReady = () => false;
await addModels(3);
});
afterAll(async () => {
await DataStore.clear();
// prevent cross-contamination with other test suites that are not ~literally~
// expecting sync call counts to be ZERO.
(DataStore as any).amplifyConfig.aws_appsync_graphqlEndpoint = '';
});
it('should match fields of any non-empty value for `("ne", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('ne', undefined)
);
expect(results.length).toEqual(3);
});
it('should match fields of any non-empty value for `("ne", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('ne', null));
expect(results.length).toEqual(3);
});
it('should NOT match fields of any non-empty value for `("eq", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('eq', undefined)
);
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("eq", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('eq', null));
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("gt", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('gt', null));
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("ge", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('ge', null));
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("lt", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('lt', null));
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("le", null)`', async () => {
const results = await DataStore.query(Model, m => m.field1('le', null));
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("gt", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('gt', undefined)
);
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("ge", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('ge', undefined)
);
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("lt", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('lt', undefined)
);
expect(results.length).toEqual(0);
});
it('should NOT match fields of any non-empty value for `("le", undefined)`', async () => {
const results = await DataStore.query(Model, m =>
m.field1('le', undefined)
);
expect(results.length).toEqual(0);
});
it('should match gt', async () => {
const results = await DataStore.query(Model, m =>
m.field1('gt', 'field1 value 0')
);
expect(results.length).toEqual(2);
});
it('should match ge', async () => {
const results = await DataStore.query(Model, m =>
m.field1('ge', 'field1 value 1')
);
expect(results.length).toEqual(2);
});
it('should match lt', async () => {
const results = await DataStore.query(Model, m =>
m.field1('lt', 'field1 value 2')
);
expect(results.length).toEqual(2);
});
it('should match le', async () => {
const results = await DataStore.query(Model, m =>
m.field1('le', 'field1 value 1')
);
expect(results.length).toEqual(2);
});
it('should match eq', async () => {
const results = await DataStore.query(Model, m =>
m.field1('eq', 'field1 value 1')
);
expect(results.length).toEqual(1);
});
it('should match ne', async () => {
const results = await DataStore.query(Model, m =>
m.field1('ne', 'field1 value 1')
);
expect(results.length).toEqual(2);
});
});
describe('Common `save()` cases', () => {
let Comment: PersistentModelConstructor<Comment>;
let Post: PersistentModelConstructor<Post>;
let Profile: PersistentModelConstructor<Profile>;
let User: PersistentModelConstructor<User>;
let adapter: any;
beforeEach(async () => {
DataStore.configure({ storageAdapter });
// establishing a fake appsync endpoint tricks DataStore into attempting
// sync operations, which we'll leverage to monitor how DataStore manages
// the outbox.
(DataStore as any).amplifyConfig.aws_appsync_graphqlEndpoint =
'https://0.0.0.0/does/not/exist/graphql';
const classes = initSchema(testSchema());
({ User, Profile, Comment, Post } = classes as {
Comment: PersistentModelConstructor<Comment>;
Model: PersistentModelConstructor<Model>;
Post: PersistentModelConstructor<Post>;
Profile: PersistentModelConstructor<Profile>;
User: PersistentModelConstructor<User>;
});
await DataStore.clear();
// start() ensures storageAdapter is set
await DataStore.start();
adapter = (DataStore as any).storageAdapter;
const db = (adapter as any).db;
const syncEngine = (DataStore as any).sync;
// my jest spy-fu wasn't up to snuff here. but, this succesfully
// prevents the mutation process from clearing the mutation queue, which
// allows us to observe the state of mutations.
(syncEngine as any).mutationsProcessor.isReady = () => false;
});
afterAll(async () => {
await DataStore.clear();
(DataStore as any).amplifyConfig.aws_appsync_graphqlEndpoint = '';
});
it('should allow linking model via model field', async () => {
const profile = await DataStore.save(
new Profile({ firstName: 'Rick', lastName: 'Bob' })
);
const savedUser = await DataStore.save(
new User({ name: 'test', profile })
);
const user1Id = savedUser.id;
const user = await DataStore.query(User, user1Id);
expect(user.profileID).toEqual(profile.id);
expect(user.profile).toEqual(profile);
});
it('should allow linking model via FK', async () => {
const profile = await DataStore.save(
new Profile({ firstName: 'Rick', lastName: 'Bob' })
);
const savedUser = await DataStore.save(
new User({ name: 'test', profileID: profile.id })
);
const user1Id = savedUser.id;
const user = await DataStore.query(User, user1Id);
expect(user.profileID).toEqual(profile.id);
expect(user.profile).toEqual(profile);
});
it('should produce a single mutation for an updated model with a BelongTo (regression test)', async () => {
// SQLite adapter, for example, was producing an extra mutation
// in this scenario.
const post = await DataStore.save(
new Post({
title: 'some post',
})
);
const comment = await DataStore.save(
new Comment({
content: 'some comment',
post,
})
);
const updatedComment = await DataStore.save(
Comment.copyOf(comment, draft => {
draft.content = 'updated content';
})
);
const mutations = await getMutations(adapter);
// comment update should be smashed to together with post
expect(mutations.length).toBe(2);
expectMutation(mutations[0], { title: 'some post' });
expectMutation(mutations[1], {
content: 'updated content',
postId: mutations[0].modelId,
});
});
it('should produce a mutation for a nested BELONGS_TO insert', async () => {
const comment = await DataStore.save(
new Comment({
content: 'newly created comment',
post: new Post({
title: 'newly created post',
}),
})
);
const mutations = await getMutations(adapter);
// one for the new comment, one for the new post
expect(mutations.length).toBe(2);
expectMutation(mutations[0], { title: 'newly created post' });
expectMutation(mutations[1], {
content: 'newly created comment',
postId: mutations[0].modelId,
});
});
it('only includes changed fields in mutations', async () => {
const profile = await DataStore.save(
new Profile({ firstName: 'original first', lastName: 'original last' })
);
await clearOutbox(adapter);
await DataStore.save(
Profile.copyOf(profile, draft => {
draft.firstName = 'new first';
})
);
const mutations = await getMutations(adapter);
expect(mutations.length).toBe(1);
expectMutation(mutations[0], {
firstName: 'new first',
_version: v => v === undefined || v === null,
_lastChangedAt: v => v === undefined || v === null,
_deleted: v => v === undefined || v === null,
});
});
});
} | the_stack |
import {
createConnection,
TextDocuments,
ProposedFeatures,
InitializeParams,
DidChangeConfigurationNotification,
CompletionItem,
CompletionItemKind,
TextDocumentPositionParams,
TextDocumentSyncKind,
InitializeResult,
WorkspaceFolder
} from 'vscode-languageserver/node';
import {sendTelemetryEvent} from './telemetry/ServerTelemetry';
import * as nearley from 'nearley';
import { getEditedLineContent } from './lib/LineReader';
import { getMatchedManifestRecords, IManifestElement } from './lib/PortalManifestReader';
import {
TextDocument
} from 'vscode-languageserver-textdocument';
import { IAutoCompleteTelemetryData } from '../common/TelemetryData';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const grammar = require('./Parser/liquidTagGrammar.js');
interface ILiquidAutoComplete {
LiquidExpression: string;
AutoCompleteAtIndex: number;
}
// Create a connection for the server, using Node's IPC as a transport.
// Also include all preview / proposed LSP features.
const connection = createConnection(ProposedFeatures.all);
// Create a simple text document manager.
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
let hasConfigurationCapability = false;
let hasWorkspaceFolderCapability = false;
let hasDiagnosticRelatedInformationCapability = false;
let workspaceRootFolders: WorkspaceFolder[] | null = null;
let editedTextDocument: TextDocument;
const startTagOfLiquidExpression = '{%';
const endTagOfLiquidExpression = '%}';
connection.onInitialize((params: InitializeParams) => {
const capabilities = params.capabilities;
workspaceRootFolders = params.workspaceFolders;
// Does the client support the `workspace/configuration` request?
// If not, we fall back using global settings.
hasConfigurationCapability = !!(
capabilities.workspace && !!capabilities.workspace.configuration
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && !!capabilities.workspace.workspaceFolders
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
hasDiagnosticRelatedInformationCapability = !!(
capabilities.textDocument &&
capabilities.textDocument.publishDiagnostics &&
capabilities.textDocument.publishDiagnostics.relatedInformation
);
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Incremental,
// Tell the client that this server supports code completion.
completionProvider: {
resolveProvider: true
}
}
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true
}
};
}
return result;
});
connection.onInitialized(() => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
connection.client.register(DidChangeConfigurationNotification.type, undefined);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders(() => {
// connection.console.log('Workspace folder change event received.');
});
}
});
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
editedTextDocument = (change.document);
});
// This handler provides the initial list of the completion items.
connection.onCompletion(
async (_textDocumentPosition: TextDocumentPositionParams): Promise<CompletionItem[]> => {
const pathOfFileBeingEdited = _textDocumentPosition.textDocument.uri;
const rowIndex = _textDocumentPosition.position.line;
const colIndex = _textDocumentPosition.position.character;
return await getSuggestions(rowIndex, colIndex, pathOfFileBeingEdited);
}
);
function getSuggestions(rowIndex: number, colIndex: number, pathOfFileBeingEdited: string) {
const telemetryData: IAutoCompleteTelemetryData = {
eventName: "AutoComplete",
properties: {
server: 'html',
},
measurements: {},
};
const completionItems: CompletionItem[] = [];
const editedLine = getEditedLineContent(rowIndex, editedTextDocument);
const liquidForAutocomplete = getEditedLiquidExpression(colIndex, editedLine);
const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar));
let liquidTagForCompletion = null;
let liquidKeyForCompletion = '';
if (!!liquidForAutocomplete.LiquidExpression && !!liquidForAutocomplete.AutoCompleteAtIndex) {
const timeStampBeforeLiquidParsing = new Date().getTime();
try {
parser.feed(liquidForAutocomplete.LiquidExpression);
liquidTagForCompletion = parser.results[0]?.tag;
liquidKeyForCompletion = parser.results[0]?.map[liquidForAutocomplete.AutoCompleteAtIndex];
} catch (e) {
// Add telemetry log. Failed to parse liquid expression. (This may bloat up the logs so double check about this)
}
telemetryData.measurements.liquidParseTimeMs = new Date().getTime() - timeStampBeforeLiquidParsing;
if (liquidTagForCompletion && liquidKeyForCompletion) {
telemetryData.properties.tagForCompletion = liquidTagForCompletion;
telemetryData.properties.keyForCompletion = liquidKeyForCompletion;
const keyForCompletion = getKeyForCompletion(liquidTagForCompletion);
const timeStampBeforeParsingManifestFile = new Date().getTime();
const matchedManifestRecords: IManifestElement[] = getMatchedManifestRecords(workspaceRootFolders, keyForCompletion, pathOfFileBeingEdited);
telemetryData.measurements.manifestParseTimeMs = new Date().getTime() - timeStampBeforeParsingManifestFile;
if (matchedManifestRecords) {
matchedManifestRecords.forEach((element: IManifestElement) => {
const item: CompletionItem = {
label: '',
insertText: '',
kind: CompletionItemKind.Value
}
switch (liquidKeyForCompletion) {
case 'id': {
item.label = element.DisplayName + " (" + element.RecordId + ")";
item.insertText = element.RecordId;
break;
}
case 'name': {
item.label = element.DisplayName + " (" + element.RecordId + ")";
item.insertText = element.DisplayName;
break;
}
case 'key': {
item.label = element.DisplayName + " (" + element.RecordId + ")";
item.insertText = element.DisplayName;
break;
}
case 'editable_tag_value': {
item.label = element.DisplayName + " (" + element.RecordId + ")";
item.insertText = element.DisplayName;
break;
}
default: {
break;
}
}
completionItems.push(item);
});
}
}
}
// we send telemetry data only in case of success, otherwise the logs will be bloated with unnecessary data
if(completionItems.length > 0) {
telemetryData.properties.success = 'true';
telemetryData.measurements.countOfAutoCompleteResults = completionItems.length;
sendTelemetryEvent(connection, telemetryData);
}
return completionItems;
}
function getEditedLiquidExpression(colIndex: number, editedLine: string) {
const liquidForAutocomplete: ILiquidAutoComplete = {
LiquidExpression: '',
AutoCompleteAtIndex: -1,
}
try {
const contentOnLeftOfCursor = editedLine.substring(0, colIndex);
const startIndexOfEditedLiquidExpression = contentOnLeftOfCursor.lastIndexOf(startTagOfLiquidExpression);
const editedLiquidExpressionOnLeftOfCursor = contentOnLeftOfCursor.substring(startIndexOfEditedLiquidExpression, contentOnLeftOfCursor.length);
const contentOnRightOfCursor = editedLine.substring(colIndex, editedLine.length);
const endIndexOfEditedLiquidExpression = contentOnRightOfCursor.indexOf(endTagOfLiquidExpression);
const editedLiquidExpressionOnRightOfCursor = contentOnRightOfCursor.substring(0, endIndexOfEditedLiquidExpression + endTagOfLiquidExpression.length);
if (editedLiquidExpressionOnLeftOfCursor && editedLiquidExpressionOnRightOfCursor) {
liquidForAutocomplete.LiquidExpression = editedLiquidExpressionOnLeftOfCursor + editedLiquidExpressionOnRightOfCursor;
liquidForAutocomplete.AutoCompleteAtIndex = colIndex - startIndexOfEditedLiquidExpression;
}
} catch (e) {
// Add Telemetry for index out of bounds...not a proper liquid expression. This may again bloat up the logs (since the autocomplete events can be fired even for non-portal html files)
}
return liquidForAutocomplete;
}
function getKeyForCompletion(liquidTag: string): string {
switch (liquidTag) {
case 'entity_list': {
return 'adx_entitylist';
}
case 'entityform': {
return 'adx_entityform';
}
case 'webform': {
return 'adx_webform';
}
case 'snippets': {
return 'adx_contentsnippet';
}
default: {
return '';
}
}
}
// This handler resolves additional information for the item selected in
// the completion list.
connection.onCompletionResolve(
(item: CompletionItem): CompletionItem => {
return item;
}
);
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Listen on the connection
connection.listen(); | the_stack |
import { DriveItem } from '@microsoft/microsoft-graph-types';
import { customElement, html, property, TemplateResult } from 'lit-element';
import { styles } from './mgt-file-css';
import { MgtTemplatedComponent, Providers, ProviderState } from '@microsoft/mgt-element';
import {
getDriveItemById,
getDriveItemByPath,
getDriveItemByQuery,
getGroupDriveItemById,
getGroupDriveItemByPath,
getListDriveItemById,
getMyDriveItemById,
getMyDriveItemByPath,
getMyInsightsDriveItemById,
getSiteDriveItemById,
getSiteDriveItemByPath,
getUserDriveItemById,
getUserDriveItemByPath,
getUserInsightsDriveItemById
} from '../../graph/graph.files';
import { getRelativeDisplayDate } from '../../utils/Utils';
import { OfficeGraphInsightString, ViewType } from '../../graph/types';
import { getFileTypeIconUriByExtension } from '../../styles/fluent-icons';
import { getSvg, SvgIcon } from '../../utils/SvgHelper';
import { strings } from './strings';
/**
* The File component is used to represent an individual file/folder from OneDrive or SharePoint by displaying information such as the file/folder name, an icon indicating the file type, and other properties such as the author, last modified date, or other details selected by the developer.
*
* @export
* @class MgtFile
* @extends {MgtTemplatedComponent}
*
* @cssprop --file-type-icon-size - {Length} file type icon size
* @cssprop --file-border - {String} file item border style
* @cssprop --file-box-shadow - {String} file item box shadow style
* @cssprop --file-background-color - {Color} file background color
* @cssprop --font-family - {String} Font family
* @cssprop --font-size - {Length} Font size
* @cssprop --font-weight - {Length} Font weight
* @cssprop --text-transform - {String} text transform
* @cssprop --color -{Color} text color
* @cssprop --line2-font-size - {Length} Line 2 font size
* @cssprop --line2-font-weight - {Length} Line 2 font weight
* @cssprop --line2-color - {Color} Line 2 color
* @cssprop --line2-text-transform - {String} Line 2 text transform
* @cssprop --line3-font-size - {Length} Line 2 font size
* @cssprop --line3-font-weight - {Length} Line 2 font weight
* @cssprop --line3-color - {Color} Line 2 color
* @cssprop --line3-text-transform - {String} Line 2 text transform
*/
@customElement('mgt-file')
export class MgtFile extends MgtTemplatedComponent {
/**
* Array of styles to apply to the element. The styles should be defined
* using the `css` tag function.
*/
static get styles() {
return styles;
}
protected get strings() {
return strings;
}
/**
* allows developer to provide query for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'file-query'
})
public get fileQuery(): string {
return this._fileQuery;
}
public set fileQuery(value: string) {
if (value === this._fileQuery) {
return;
}
this._fileQuery = value;
this.requestStateUpdate();
}
/**
* allows developer to provide site id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'site-id'
})
public get siteId(): string {
return this._siteId;
}
public set siteId(value: string) {
if (value === this._siteId) {
return;
}
this._siteId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide drive id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'drive-id'
})
public get driveId(): string {
return this._driveId;
}
public set driveId(value: string) {
if (value === this._driveId) {
return;
}
this._driveId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide group id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'group-id'
})
public get groupId(): string {
return this._groupId;
}
public set groupId(value: string) {
if (value === this._groupId) {
return;
}
this._groupId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide list id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'list-id'
})
public get listId(): string {
return this._listId;
}
public set listId(value: string) {
if (value === this._listId) {
return;
}
this._listId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide user id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'user-id'
})
public get userId(): string {
return this._userId;
}
public set userId(value: string) {
if (value === this._userId) {
return;
}
this._userId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide item id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'item-id'
})
public get itemId(): string {
return this._itemId;
}
public set itemId(value: string) {
if (value === this._itemId) {
return;
}
this._itemId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide item path for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'item-path'
})
public get itemPath(): string {
return this._itemPath;
}
public set itemPath(value: string) {
if (value === this._itemPath) {
return;
}
this._itemPath = value;
this.requestStateUpdate();
}
/**
* allows developer to provide insight type for a file
* can be trending, used, or shared
*
* @type {OfficeGraphInsightString}
* @memberof MgtFile
*/
@property({
attribute: 'insight-type'
})
public get insightType(): OfficeGraphInsightString {
return this._insightType;
}
public set insightType(value: OfficeGraphInsightString) {
if (value === this._insightType) {
return;
}
this._insightType = value;
this.requestStateUpdate();
}
/**
* allows developer to provide insight id for a file
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'insight-id'
})
public get insightId(): string {
return this._insightId;
}
public set insightId(value: string) {
if (value === this._insightId) {
return;
}
this._insightId = value;
this.requestStateUpdate();
}
/**
* allows developer to provide DriveItem object
*
* @type {MicrosoftGraph.DriveItem}
* @memberof MgtFile
*/
@property({
type: Object
})
public get fileDetails(): DriveItem {
return this._fileDetails;
}
public set fileDetails(value: DriveItem) {
if (value === this._fileDetails) {
return;
}
this._fileDetails = value;
this.requestStateUpdate();
}
/**
* allows developer to provide file type icon url
*
* @type {string}
* @memberof MgtFile
*/
@property({
attribute: 'file-icon'
})
public get fileIcon(): string {
return this._fileIcon;
}
public set fileIcon(value: string) {
if (value === this._fileIcon) {
return;
}
this._fileIcon = value;
this.requestStateUpdate();
}
/**
* object containing Graph details on item
*
* @type {MicrosoftGraph.DriveItem}
* @memberof MgtFile
*/
@property({ type: Object })
public driveItem: DriveItem;
/**
* Sets the property of the file to use for the first line of text.
* Default is file name
*
* @type {string}
* @memberof MgtFile
*/
@property({ attribute: 'line1-property' }) public line1Property: string;
/**
* Sets the property of the file to use for the second line of text.
* Default is last modified date time
*
* @type {string}
* @memberof MgtFile
*/
@property({ attribute: 'line2-property' }) public line2Property: string;
/**
* Sets the property of the file to use for the second line of text.
* Default is file size
*
* @type {string}
* @memberof MgtFile
*/
@property({ attribute: 'line3-property' }) public line3Property: string;
/**
* Sets what data to be rendered (file icon only, oneLine, twoLines threeLines).
* Default is 'threeLines'.
*
* @type {ViewType}
* @memberof MgtFile
*/
@property({
attribute: 'view',
converter: value => {
if (!value || value.length === 0) {
return ViewType.threelines;
}
value = value.toLowerCase();
if (typeof ViewType[value] === 'undefined') {
return ViewType.threelines;
} else {
return ViewType[value];
}
}
})
public view: ViewType;
/**
* Get the scopes required for file
*
* @static
* @return {*} {string[]}
* @memberof MgtFile
*/
public static get requiredScopes(): string[] {
return [...new Set(['files.read', 'files.read.all', 'sites.read.all'])];
}
private _fileQuery: string;
private _siteId: string;
private _itemId: string;
private _driveId: string;
private _itemPath: string;
private _listId: string;
private _groupId: string;
private _userId: string;
private _insightType: OfficeGraphInsightString;
private _insightId: string;
private _fileDetails: DriveItem;
private _fileIcon: string;
constructor() {
super();
this.line1Property = 'name';
this.line2Property = 'lastModifiedDateTime';
this.line3Property = 'size';
this.view = ViewType.threelines;
}
public render() {
if (!this.driveItem && this.isLoadingState) {
return this.renderLoading();
}
if (!this.driveItem) {
return this.renderNoData();
}
const file = this.driveItem;
let fileTemplate;
fileTemplate = this.renderTemplate('default', { file });
if (!fileTemplate) {
const fileDetailsTemplate: TemplateResult = this.renderDetails(file);
const fileTypeIconTemplate: TemplateResult = this.renderFileTypeIcon();
fileTemplate = html`
<div class="item">
${fileTypeIconTemplate} ${fileDetailsTemplate}
</div>
`;
}
return html`
<span dir=${this.direction}>
${fileTemplate}
</span>
`;
}
/**
* Render the loading state
*
* @protected
* @returns {TemplateResult}
* @memberof MgtFile
*/
protected renderLoading(): TemplateResult {
return this.renderTemplate('loading', null) || html``;
}
/**
* Render the state when no data is available
*
* @protected
* @returns {TemplateResult}
* @memberof MgtFile
*/
protected renderNoData(): TemplateResult {
return this.renderTemplate('no-data', null) || html``;
}
/**
* Render the file type icon
*
* @protected
* @param {string} [iconSrc]
* @memberof MgtFile
*/
protected renderFileTypeIcon(): TemplateResult {
if (!this.fileIcon && !this.driveItem.name) {
return html``;
}
let fileIconSrc;
if (this.fileIcon) {
fileIconSrc = this.fileIcon;
} else {
// get file type extension from file name
const re = /(?:\.([^.]+))?$/;
const fileType =
this.driveItem.package === undefined && this.driveItem.folder === undefined
? re.exec(this.driveItem.name)[1]
? re.exec(this.driveItem.name)[1].toLowerCase()
: 'null'
: this.driveItem.package !== undefined
? this.driveItem.package.type === 'oneNote'
? 'onetoc'
: 'folder'
: 'folder';
fileIconSrc = getFileTypeIconUriByExtension(fileType, 48, 'svg');
}
return html`
<div class="item__file-type-icon">
${
fileIconSrc
? html`
<img src=${fileIconSrc} alt="File icon" />
`
: html`
${getSvg(SvgIcon.File)}
`
}
</div>
`;
}
/**
* Render the file details
*
* @protected
* @param {MicrosoftGraph.DriveItem} [driveItem]
* @memberof MgtFile
*/
protected renderDetails(driveItem: DriveItem): TemplateResult {
if (!driveItem || this.view === ViewType.image) {
return html``;
}
const details: TemplateResult[] = [];
if (this.view > ViewType.image) {
const text = this.getTextFromProperty(driveItem, this.line1Property);
if (text) {
details.push(html`
<div class="line1" aria-label="${text}">${text}</div>
`);
}
}
if (this.view > ViewType.oneline) {
const text = this.getTextFromProperty(driveItem, this.line2Property);
if (text) {
details.push(html`
<div class="line2" aria-label="${text}">${text}</div>
`);
}
}
if (this.view > ViewType.twolines) {
const text = this.getTextFromProperty(driveItem, this.line3Property);
if (text) {
details.push(html`
<div class="line3" aria-label="${text}">${text}</div>
`);
}
}
return html`
<div class="item__details">
${details}
</div>
`;
}
/**
* load state into the component.
*
* @protected
* @returns
* @memberof MgtFile
*/
protected async loadState() {
if (this.fileDetails) {
this.driveItem = this.fileDetails;
return;
}
const provider = Providers.globalProvider;
if (!provider || provider.state === ProviderState.Loading) {
return;
}
if (provider.state === ProviderState.SignedOut) {
this.driveItem = null;
return;
}
const graph = provider.graph.forComponent(this);
let driveItem;
// evaluate to true when only item-id or item-path is provided
const getFromMyDrive = !this.driveId && !this.siteId && !this.groupId && !this.listId && !this.userId;
if (
// return null when a combination of provided properties are required
(this.driveId && !this.itemId && !this.itemPath) ||
(this.siteId && !this.itemId && !this.itemPath) ||
(this.groupId && !this.itemId && !this.itemPath) ||
(this.listId && !this.siteId && !this.itemId) ||
(this.insightType && !this.insightId) ||
(this.userId && !this.itemId && !this.itemPath && !this.insightType && !this.insightId)
) {
driveItem = null;
} else if (this.fileQuery) {
driveItem = await getDriveItemByQuery(graph, this.fileQuery);
} else if (this.itemId && getFromMyDrive) {
driveItem = await getMyDriveItemById(graph, this.itemId);
} else if (this.itemPath && getFromMyDrive) {
driveItem = await getMyDriveItemByPath(graph, this.itemPath);
} else if (this.userId) {
if (this.itemId) {
driveItem = await getUserDriveItemById(graph, this.userId, this.itemId);
} else if (this.itemPath) {
driveItem = await getUserDriveItemByPath(graph, this.userId, this.itemPath);
} else if (this.insightType && this.insightId) {
driveItem = await getUserInsightsDriveItemById(graph, this.userId, this.insightType, this.insightId);
}
} else if (this.driveId) {
if (this.itemId) {
driveItem = await getDriveItemById(graph, this.driveId, this.itemId);
} else if (this.itemPath) {
driveItem = await getDriveItemByPath(graph, this.driveId, this.itemPath);
}
} else if (this.siteId && !this.listId) {
if (this.itemId) {
driveItem = await getSiteDriveItemById(graph, this.siteId, this.itemId);
} else if (this.itemPath) {
driveItem = await getSiteDriveItemByPath(graph, this.siteId, this.itemPath);
}
} else if (this.listId) {
driveItem = await getListDriveItemById(graph, this.siteId, this.listId, this.itemId);
} else if (this.groupId) {
if (this.itemId) {
driveItem = await getGroupDriveItemById(graph, this.groupId, this.itemId);
} else if (this.itemPath) {
driveItem = await getGroupDriveItemByPath(graph, this.groupId, this.itemPath);
}
} else if (this.insightType && !this.userId) {
driveItem = await getMyInsightsDriveItemById(graph, this.insightType, this.insightId);
}
this.driveItem = driveItem;
}
private getTextFromProperty(driveItem: DriveItem, properties: string) {
if (!properties || properties.length === 0) {
return null;
}
const propertyList = properties.trim().split(',');
let text;
let i = 0;
while (!text && i < propertyList.length) {
const current = propertyList[i].trim();
switch (current) {
case 'size':
// convert size to kb, mb, gb
let size;
if (driveItem.size) {
size = this.formatBytes(driveItem.size);
} else {
size = '0';
}
text = `${this.strings.sizeSubtitle}: ${size}`;
break;
case 'lastModifiedDateTime':
// convert date time
let relativeDateString;
let lastModifiedString;
if (driveItem.lastModifiedDateTime) {
const lastModifiedDateTime = new Date(driveItem.lastModifiedDateTime);
relativeDateString = getRelativeDisplayDate(lastModifiedDateTime);
lastModifiedString = `${this.strings.modifiedSubtitle} ${relativeDateString}`;
} else {
lastModifiedString = '';
}
text = lastModifiedString;
break;
default:
text = driveItem[current];
}
i++;
}
return text;
}
private formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
} | the_stack |
export {};
type numeric = number | bigint;
export interface TypedArrayLike<T extends numeric = numeric> extends Readonly<ArrayBufferView> {
/** The length of the array. */
readonly length: number;
[index: number]: T;
}
export interface TypedArrayConstructor {
readonly prototype: TypedArrayPrototype;
new (...args: unknown[]): TypedArrayPrototype;
/**
* Returns a new typed array from a set of elements.
* @param items A set of elements to include in the new typed array object.
*/
of(this: new (length: number) => Int8Array, ...items: number[]): Int8Array;
of(this: new (length: number) => Uint8Array, ...items: number[]): Uint8Array;
of(this: new (length: number) => Uint8ClampedArray, ...items: number[]): Uint8ClampedArray;
of(this: new (length: number) => Int16Array, ...items: number[]): Int16Array;
of(this: new (length: number) => Uint16Array, ...items: number[]): Uint16Array;
of(this: new (length: number) => Int32Array, ...items: number[]): Int32Array;
of(this: new (length: number) => Uint32Array, ...items: number[]): Uint32Array;
// For whatever reason, `array-type` considers `bigint` a non-simple type:
// tslint:disable: array-type
of(this: new (length: number) => BigInt64Array, ...items: bigint[]): BigInt64Array;
of(this: new (length: number) => BigUint64Array, ...items: bigint[]): BigUint64Array;
// tslint:enable: array-type
of(this: new (length: number) => Float32Array, ...items: number[]): Float32Array;
of(this: new (length: number) => Float64Array, ...items: number[]): Float64Array;
/**
* Creates a new typed array from an array-like or iterable object.
* @param source An array-like or iterable object to convert to a typed array.
* @param mapfn A mapping function to call on every element of the source object.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(this: new (length: number) => Int8Array, source: Iterable<number> | ArrayLike<number>): Int8Array;
from<U>(
this: new (length: number) => Int8Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int8Array;
from(this: new (length: number) => Uint8Array, source: Iterable<number> | ArrayLike<number>): Uint8Array;
from<U>(
this: new (length: number) => Uint8Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint8Array;
from(
this: new (length: number) => Uint8ClampedArray,
source: Iterable<number> | ArrayLike<number>,
): Uint8ClampedArray;
from<U>(
this: new (length: number) => Uint8ClampedArray,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint8ClampedArray;
from(this: new (length: number) => Int16Array, source: Iterable<number> | ArrayLike<number>): Int16Array;
from<U>(
this: new (length: number) => Int16Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int16Array;
from(this: new (length: number) => Uint16Array, source: Iterable<number> | ArrayLike<number>): Uint16Array;
from<U>(
this: new (length: number) => Uint16Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint16Array;
from(this: new (length: number) => Int32Array, source: Iterable<number> | ArrayLike<number>): Int32Array;
from<U>(
this: new (length: number) => Int32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int32Array;
from(this: new (length: number) => Uint32Array, source: Iterable<number> | ArrayLike<number>): Uint32Array;
from<U>(
this: new (length: number) => Uint32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint32Array;
from(this: new (length: number) => BigInt64Array, source: Iterable<bigint> | ArrayLike<bigint>): BigInt64Array;
from<U>(
this: new (length: number) => BigInt64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => bigint,
thisArg?: unknown,
): BigInt64Array;
from(this: new (length: number) => BigUint64Array, source: Iterable<bigint> | ArrayLike<bigint>): BigUint64Array;
from<U>(
this: new (length: number) => BigUint64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => bigint,
thisArg?: unknown,
): BigUint64Array;
from(this: new (length: number) => Float32Array, source: Iterable<number> | ArrayLike<number>): Float32Array;
from<U>(
this: new (length: number) => Float32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Float32Array;
from(this: new (length: number) => Float64Array, source: Iterable<number> | ArrayLike<number>): Float64Array;
from<U>(
this: new (length: number) => Float64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Float64Array;
}
export interface TypedArrayPrototype {
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: ArrayBufferLike;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin<THIS extends TypedArrayLike>(this: THIS, target: number, start: number, end?: number): THIS;
/** Yields index, value pairs for every entry in the array. */
entries<T extends numeric>(this: TypedArrayLike<T>): IterableIterator<[number, T]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns false,
* or until the end of 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.
*/
every<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill<T extends numeric, THIS extends TypedArrayLike<T>>(this: THIS, value: T, start?: number, end?: number): THIS;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter 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.
*/
filter<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): THIS;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach 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.
*/
forEach<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
callbackfn: (value: T, index: number, array: THIS) => void,
thisArg?: unknown,
): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes<T extends numeric>(this: TypedArrayLike<T>, searchElement: T, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @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.
*/
indexOf<T extends numeric>(this: TypedArrayLike<T>, searchElement: T, fromIndex?: number): boolean;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(this: TypedArrayLike, separator?: string): string;
/** Yields each index in the array. */
keys(this: TypedArrayLike): IterableIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @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.
*/
lastIndexOf<T extends numeric>(this: TypedArrayLike<T>, searchElement: T, fromIndex?: number): boolean;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @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.
*/
map<T extends numeric, THIS extends TypedArrayLike>(
this: THIS,
mapper: (value: T, index: number, array: THIS) => T,
thisArg?: unknown,
): THIS;
/**
* 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.
* @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.
*/
reduce<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
reducer: (previousValue: T, currentValue: T, currentIndex: number, array: THIS) => T,
): T;
reduce<T extends numeric, U, THIS extends TypedArrayLike<T>>(
this: THIS,
reducer: (previousValue: U, currentValue: T, currentIndex: number, array: THIS) => U,
initialValue: U,
): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* 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.
* @param callbackfn A function that accepts up to four arguments. The reduceRight 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.
*/
reduceRight<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
reducer: (previousValue: T, currentValue: T, currentIndex: number, array: THIS) => T,
): T;
reduceRight<T extends numeric, U, THIS extends TypedArrayLike<T>>(
this: THIS,
reducer: (previousValue: U, currentValue: T, currentIndex: number, array: THIS) => U,
initialValue: U,
): U;
/** Reverses the elements in the array. */
reverse<THIS extends TypedArrayLike>(this: THIS): THIS;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set<T extends numeric>(this: TypedArrayLike<T>, array: ArrayLike<T>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice<THIS extends TypedArrayLike>(this: THIS, start?: number, end?: number): THIS;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the
* callbackfn function for each element in the array until the callbackfn returns true, or until
* the end of 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.
*/
some<T extends numeric, THIS extends TypedArrayLike<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): boolean;
/**
* Sorts the array.
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
*/
sort<T extends numeric, THIS extends TypedArrayLike<T>>(this: THIS, comparator?: (a: T, b: T) => number): THIS;
/**
* Gets a new subview of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray<THIS extends TypedArrayLike>(this: THIS, begin?: number, end?: number): THIS;
/** Converts the array to a string by using the current locale. */
toLocaleString(this: TypedArrayLike, locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/** Returns a string representation of the array. */
toString(): string;
/** Yields each value in the array. */
values<T extends numeric>(this: TypedArrayLike<T>): IterableIterator<T>;
/** Yields each value in the array. */
[Symbol.iterator]<T extends numeric>(this: TypedArrayLike<T>): IterableIterator<T>;
readonly [Symbol.toStringTag]: string | undefined;
} | the_stack |
import { Observable } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import {
BlockInfoDTO,
BlockRoutesApi,
TransactionInfoDTO,
TransactionPage,
TransactionRoutesApi,
} from 'symbol-openapi-typescript-fetch-client';
import { DtoMapping } from '../core/utils';
import {
CosignatureSignedTransaction,
SignedTransaction,
Transaction,
TransactionAnnounceResponse,
TransactionInfo,
TransactionType,
} from '../model/transaction';
import { Http } from './Http';
import { Page } from './Page';
import { TransactionPaginationStreamer } from './paginationStreamer';
import { TransactionSearchCriteria } from './searchCriteria';
import { CreateTransactionFromDTO } from './transaction';
import { TransactionGroup } from './TransactionGroup';
import { TransactionRepository } from './TransactionRepository';
/**
* Transaction http repository.
*
* @since 1.0
*/
export class TransactionHttp extends Http implements TransactionRepository {
/**
* @internal
* Symbol openapi typescript-node client transaction routes api
*/
private transactionRoutesApi: TransactionRoutesApi;
/**
* @internal
* Symbol openapi typescript-node client blockchain routes api
*/
private blockRoutesApi: BlockRoutesApi;
/**
* Constructor
* @param url Base catapult-rest url
* @param fetchApi fetch function to be used when performing rest requests.
*/
constructor(url: string, fetchApi?: any) {
super(url, fetchApi);
this.transactionRoutesApi = new TransactionRoutesApi(this.config());
this.blockRoutesApi = new BlockRoutesApi(this.config());
}
/**
* Gets a transaction for a transactionId
* @param transactionId - Transaction id or hash.
* @param transactionGroup - Transaction group.
* @returns Observable<Transaction>
*/
public getTransaction(transactionId: string, transactionGroup: TransactionGroup): Observable<Transaction> {
return this.call(this.getTransactionByGroup(transactionId, transactionGroup), (body) => CreateTransactionFromDTO(body));
}
/**
* Gets an array of transactions for different transaction ids
* @param transactionIds - Array of transactions id and/or hash.
* @param transactionGroup - Transaction group.
* @returns Observable<Transaction[]>
*/
public getTransactionsById(transactionIds: string[], transactionGroup: TransactionGroup): Observable<Transaction[]> {
const transactionIdsBody = {
transactionIds,
};
switch (transactionGroup) {
case TransactionGroup.Confirmed:
return this.call(this.transactionRoutesApi.getConfirmedTransactions(transactionIdsBody), (body) =>
body.map((transactionDTO) => {
return CreateTransactionFromDTO(transactionDTO);
}),
);
case TransactionGroup.Unconfirmed:
return this.call(this.transactionRoutesApi.getUnconfirmedTransactions(transactionIdsBody), (body) =>
body.map((transactionDTO) => {
return CreateTransactionFromDTO(transactionDTO);
}),
);
case TransactionGroup.Partial:
return this.call(this.transactionRoutesApi.getPartialTransactions(transactionIdsBody), (body) =>
body.map((transactionDTO) => {
return CreateTransactionFromDTO(transactionDTO);
}),
);
}
}
/**
* Send a signed transaction
* @param signedTransaction - Signed transaction
* @returns Observable<TransactionAnnounceResponse>
*/
public announce(signedTransaction: SignedTransaction): Observable<TransactionAnnounceResponse> {
if (signedTransaction.type === TransactionType.AGGREGATE_BONDED) {
throw new Error("Announcing aggregate bonded transaction should use 'announceAggregateBonded'");
}
return this.call(
this.transactionRoutesApi.announceTransaction(signedTransaction),
(body) => new TransactionAnnounceResponse(body.message),
);
}
/**
* Send a signed transaction with missing signatures
* @param signedTransaction - Signed transaction
* @returns Observable<TransactionAnnounceResponse>
*/
public announceAggregateBonded(signedTransaction: SignedTransaction): Observable<TransactionAnnounceResponse> {
if (signedTransaction.type !== TransactionType.AGGREGATE_BONDED) {
throw new Error('Only Transaction Type 0x4241 is allowed for announce aggregate bonded');
}
return this.call(
this.transactionRoutesApi.announcePartialTransaction(signedTransaction),
(body) => new TransactionAnnounceResponse(body.message),
);
}
/**
* Send a cosignature signed transaction of an already announced transaction
* @param cosignatureSignedTransaction - Cosignature signed transaction
* @returns Observable<TransactionAnnounceResponse>
*/
public announceAggregateBondedCosignature(
cosignatureSignedTransaction: CosignatureSignedTransaction,
): Observable<TransactionAnnounceResponse> {
const cosignature = {
parentHash: cosignatureSignedTransaction.parentHash,
signerPublicKey: cosignatureSignedTransaction.signerPublicKey,
signature: cosignatureSignedTransaction.signature,
version: cosignatureSignedTransaction.version.toString(),
};
return this.call(
this.transactionRoutesApi.announceCosignatureTransaction(cosignature),
(body) => new TransactionAnnounceResponse(body.message),
);
}
/**
* Gets a transaction's effective paid fee
* @param transactionId - Transaction id or hash.
* @returns Observable<number>
*/
public getTransactionEffectiveFee(transactionId: string): Observable<number> {
return this.call(this.getTransactionByGroup(transactionId, TransactionGroup.Confirmed), CreateTransactionFromDTO).pipe(
mergeMap((transaction) => {
// now read block details
return this.call(
this.blockRoutesApi.getBlockByHeight((transaction.transactionInfo as TransactionInfo).height.toString()),
(blockDTO: BlockInfoDTO) => {
// @see https://nemtech.github.io/concepts/transaction.html#fees
// effective_fee = feeMultiplier x transaction::size
return blockDTO.block.feeMultiplier * transaction.size;
},
);
}),
);
}
/**
* Returns an array of transactions.
* @summary Get transactions
* @param criteria Transaction search criteria
* @returns {Observable<Page<Transaction>>}
*/
public search(criteria: TransactionSearchCriteria): Observable<Page<Transaction>> {
return this.call(this.searchTransactionByGroup(criteria), (body) =>
super.toPage(body.pagination, body.data, CreateTransactionFromDTO),
);
}
public streamer(): TransactionPaginationStreamer {
return new TransactionPaginationStreamer(this);
}
/**
* @internal
* Gets a transaction info
* @param transactionId - Transaction id or hash.
* @param transactionGroup - Transaction group.
* @returns Promise<{response: http.ClientResponse; body: TransactionInfoDTO;}>
*/
private getTransactionByGroup(transactionId: string, transactionGroup: TransactionGroup): Promise<TransactionInfoDTO> {
switch (transactionGroup) {
case TransactionGroup.Confirmed:
return this.transactionRoutesApi.getConfirmedTransaction(transactionId);
case TransactionGroup.Unconfirmed:
return this.transactionRoutesApi.getUnconfirmedTransaction(transactionId);
case TransactionGroup.Partial:
return this.transactionRoutesApi.getPartialTransaction(transactionId);
}
}
/**
* @internal
* Gets a transaction search result
* @param criteria - the criteria.
* @returns Promise<{response: http.ClientResponse; body: TransactionInfoDTO;}>
*/
private searchTransactionByGroup(criteria: TransactionSearchCriteria): Promise<TransactionPage> {
switch (criteria.group) {
case TransactionGroup.Confirmed:
return this.transactionRoutesApi.searchConfirmedTransactions(
criteria.address?.plain(),
criteria.recipientAddress?.plain(),
criteria.signerPublicKey,
criteria.height?.toString(),
criteria.fromHeight?.toString(),
criteria.toHeight?.toString(),
criteria.fromTransferAmount?.toString(),
criteria.toTransferAmount?.toString(),
criteria.type?.map((type) => type.valueOf()),
criteria.embedded,
criteria.transferMosaicId?.toHex(),
criteria.pageSize,
criteria.pageNumber,
criteria.offset,
DtoMapping.mapEnum(criteria.order),
);
case TransactionGroup.Unconfirmed:
return this.transactionRoutesApi.searchUnconfirmedTransactions(
criteria.address?.plain(),
criteria.recipientAddress?.plain(),
criteria.signerPublicKey,
criteria.height?.toString(),
criteria.fromHeight?.toString(),
criteria.toHeight?.toString(),
criteria.fromTransferAmount?.toString(),
criteria.toTransferAmount?.toString(),
criteria.type?.map((type) => type.valueOf()),
criteria.embedded,
criteria.transferMosaicId?.toHex(),
criteria.pageSize,
criteria.pageNumber,
criteria.offset,
DtoMapping.mapEnum(criteria.order),
);
case TransactionGroup.Partial:
return this.transactionRoutesApi.searchPartialTransactions(
criteria.address?.plain(),
criteria.recipientAddress?.plain(),
criteria.signerPublicKey,
criteria.height?.toString(),
criteria.fromHeight?.toString(),
criteria.toHeight?.toString(),
criteria.fromTransferAmount?.toString(),
criteria.toTransferAmount?.toString(),
criteria.type?.map((type) => type.valueOf()),
criteria.embedded,
criteria.transferMosaicId?.toHex(),
criteria.pageSize,
criteria.pageNumber,
criteria.offset,
DtoMapping.mapEnum(criteria.order),
);
}
}
} | the_stack |
import {
expect
} from 'chai';
import {
AttachedProperty
} from '@phosphor/properties';
class Model {
dummyValue = 42;
}
describe('@phosphor/properties', () => {
describe('AttachedProperty', () => {
describe('#constructor()', () => {
it('should accept a single options argument', () => {
let p = new AttachedProperty<Model, number>({
name: 'p',
create: (owner) => 42,
coerce: (owner, value) => Math.max(0, value),
compare: (oldValue, newValue) => oldValue === newValue,
changed: (owner, oldValue, newValue) => { }
});
expect(p).to.be.an.instanceof(AttachedProperty);
});
});
describe('#name', () => {
it('should be the name provided to the constructor', () => {
let create = () => 0;
let p = new AttachedProperty<Model, number>({ name: 'p', create });
expect(p.name).to.equal('p');
});
});
describe('#get()', () => {
it('should return the current value of the property', () => {
let tick = 42;
let create = () => tick++;
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
expect(p1.get(m1)).to.equal(42);
expect(p2.get(m1)).to.equal(43);
expect(p3.get(m1)).to.equal(44);
expect(p1.get(m2)).to.equal(45);
expect(p2.get(m2)).to.equal(46);
expect(p3.get(m2)).to.equal(47);
expect(p1.get(m3)).to.equal(48);
expect(p2.get(m3)).to.equal(49);
expect(p3.get(m3)).to.equal(50);
});
it('should not invoke the coerce function', () => {
let called = false;
let create = () => 0;
let coerce = (m: Model, v: number) => (called = true, v);
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create, coerce });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create, coerce });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create, coerce });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.get(m1);
p2.get(m1);
p3.get(m1);
p1.get(m2);
p2.get(m2);
p3.get(m2);
p1.get(m3);
p2.get(m3);
p3.get(m3);
expect(called).to.equal(false);
});
it('should not invoke the compare function', () => {
let called = false;
let create = () => 0;
let compare = (v1: number, v2: number) => (called = true, v1 === v2);
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create, compare });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create, compare });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create, compare });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.get(m1);
p2.get(m1);
p3.get(m1);
p1.get(m2);
p2.get(m2);
p3.get(m2);
p1.get(m3);
p2.get(m3);
p3.get(m3);
expect(called).to.equal(false);
});
it('should not invoke the changed function', () => {
let called = false;
let create = () => 0;
let changed = () => { called = true; };
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create, changed });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create, changed });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create, changed });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.get(m1);
p2.get(m1);
p3.get(m1);
p1.get(m2);
p2.get(m2);
p3.get(m2);
p1.get(m3);
p2.get(m3);
p3.get(m3);
expect(called).to.equal(false);
});
});
describe('#set()', () => {
it('should set the current value of the property', () => {
let create = () => 0;
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.set(m1, 1);
p1.set(m2, 2);
p1.set(m3, 3);
p2.set(m1, 4);
p2.set(m2, 5);
p2.set(m3, 6);
p3.set(m1, 7);
p3.set(m2, 8);
p3.set(m3, 9);
expect(p1.get(m1)).to.equal(1);
expect(p1.get(m2)).to.equal(2);
expect(p1.get(m3)).to.equal(3);
expect(p2.get(m1)).to.equal(4);
expect(p2.get(m2)).to.equal(5);
expect(p2.get(m3)).to.equal(6);
expect(p3.get(m1)).to.equal(7);
expect(p3.get(m2)).to.equal(8);
expect(p3.get(m3)).to.equal(9);
});
it('should invoke the changed function if the value changes', () => {
let oldvals: number[] = [];
let newvals: number[] = [];
let changed = (m: Model, o: number, n: number) => {
oldvals.push(o);
newvals.push(n);
};
let create = () => 0;
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create, changed });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create, changed });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create, changed });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.set(m1, 1);
p1.set(m2, 2);
p1.set(m3, 3);
p2.set(m1, 4);
p2.set(m2, 5);
p2.set(m3, 6);
p3.set(m1, 7);
p3.set(m2, 8);
p3.set(m3, 9);
expect(oldvals).to.deep.equal([0, 0, 0, 0, 0, 0, 0, 0, 0]);
expect(newvals).to.deep.equal([1, 2, 3, 4, 5, 6, 7, 8, 9]);
});
it('should invoke the coerce function on the new value', () => {
let create = () => 0;
let coerce = (o: Model, v: number) => Math.max(0, v);
let p = new AttachedProperty<Model, number>({ name: 'p', create, coerce });
let m = new Model();
p.set(m, -10);
expect(p.get(m)).to.equal(0);
p.set(m, 10);
expect(p.get(m)).to.equal(10);
p.set(m, -42);
expect(p.get(m)).to.equal(0);
p.set(m, 42);
expect(p.get(m)).to.equal(42);
p.set(m, 0);
expect(p.get(m)).to.equal(0);
});
it('should not invoke the compare function if there is no changed function', () => {
let called = false;
let create = () => 0;
let compare = (v1: number, v2: number) => (called = true, v1 === v2);
let p = new AttachedProperty<Model, number>({ name: 'p', create, compare });
let m = new Model();
p.set(m, 42);
expect(called).to.equal(false);
});
it('should invoke the compare function if there is a changed function', () => {
let called = false;
let create = () => 0;
let changed = () => { };
let compare = (v1: number, v2: number) => (called = true, v1 === v2);
let p = new AttachedProperty<Model, number>({ name: 'p', create, compare, changed });
let m = new Model();
p.set(m, 42);
expect(called).to.equal(true);
});
it('should not invoke the changed function if the value does not change', () => {
let called = false;
let create = () => 1;
let changed = () => { called = true; };
let compare = (v1: number, v2: number) => true;
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create, changed });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create, compare, changed });
let m = new Model();
p1.set(m, 1);
p1.set(m, 1);
p2.set(m, 1);
p2.set(m, 2);
p2.set(m, 3);
p2.set(m, 4);
expect(called).to.equal(false);
});
});
describe('#coerce()', () => {
it('should coerce the current value of the property', () => {
let min = 20;
let max = 50;
let create = () => 0;
let coerce = (m: Model, v: number) => Math.max(min, Math.min(v, max));
let p = new AttachedProperty<Model, number>({ name: 'p', create, coerce });
let m = new Model();
p.set(m, 10);
expect(p.get(m)).to.equal(20);
min = 30;
p.coerce(m);
expect(p.get(m)).to.equal(30);
min = 10;
max = 20;
p.coerce(m);
expect(p.get(m)).to.equal(20);
});
it('should invoke the changed function if the value changes', () => {
let called = false;
let create = () => 0;
let coerce = (m: Model, v: number) => Math.max(20, v);
let changed = () => { called = true };
let p = new AttachedProperty<Model, number>({ name: 'p', create, coerce, changed });
let m = new Model();
p.coerce(m);
expect(called).to.equal(true);
});
it('should use the default value as old value if value is not yet set', () => {
let oldval = -1;
let newval = -1;
let create = () => 0;
let coerce = (m: Model, v: number) => Math.max(20, v);
let changed = (m: Model, o: number, n: number) => { oldval = o; newval = n; };
let p = new AttachedProperty<Model, number>({ name: 'p', create, coerce, changed });
let m = new Model();
p.coerce(m);
expect(oldval).to.equal(0);
expect(newval).to.equal(20);
});
it('should not invoke the compare function if there is no changed function', () => {
let called = false;
let create = () => 0;
let compare = (v1: number, v2: number) => (called = true, v1 === v2);
let p = new AttachedProperty<Model, number>({ name: 'p', create, compare });
let m = new Model();
p.coerce(m);
expect(called).to.equal(false);
});
it('should invoke the compare function if there is a changed function', () => {
let called = false;
let create = () => 0;
let changed = () => { };
let compare = (v1: number, v2: number) => (called = true, v1 === v2);
let p = new AttachedProperty<Model, number>({ name: 'p', create, compare, changed });
let m = new Model();
p.coerce(m);
expect(called).to.equal(true);
});
it('should not invoke the changed function if the value does not change', () => {
let called = false;
let create = () => 0;
let changed = () => { called = true; };
let p = new AttachedProperty<Model, number>({ name: 'p', create, changed });
let m = new Model();
p.coerce(m);
expect(called).to.equal(false);
});
});
describe('.clearData()', () => {
it('should clear all property data for a property owner', () => {
let create = () => 42;
let p1 = new AttachedProperty<Model, number>({ name: 'p1', create });
let p2 = new AttachedProperty<Model, number>({ name: 'p2', create });
let p3 = new AttachedProperty<Model, number>({ name: 'p3', create });
let m1 = new Model();
let m2 = new Model();
let m3 = new Model();
p1.set(m1, 1);
p1.set(m2, 2);
p1.set(m3, 3);
p2.set(m1, 4);
p2.set(m2, 5);
p2.set(m3, 6);
p3.set(m1, 7);
p3.set(m2, 8);
p3.set(m3, 9);
expect(p1.get(m1)).to.equal(1);
expect(p1.get(m2)).to.equal(2);
expect(p1.get(m3)).to.equal(3);
expect(p2.get(m1)).to.equal(4);
expect(p2.get(m2)).to.equal(5);
expect(p2.get(m3)).to.equal(6);
expect(p3.get(m1)).to.equal(7);
expect(p3.get(m2)).to.equal(8);
expect(p3.get(m3)).to.equal(9);
AttachedProperty.clearData(m1);
expect(p1.get(m1)).to.equal(42);
expect(p1.get(m2)).to.equal(2);
expect(p1.get(m3)).to.equal(3);
expect(p2.get(m1)).to.equal(42);
expect(p2.get(m2)).to.equal(5);
expect(p2.get(m3)).to.equal(6);
expect(p3.get(m1)).to.equal(42);
expect(p3.get(m2)).to.equal(8);
expect(p3.get(m3)).to.equal(9);
AttachedProperty.clearData(m2);
expect(p1.get(m1)).to.equal(42);
expect(p1.get(m2)).to.equal(42);
expect(p1.get(m3)).to.equal(3);
expect(p2.get(m1)).to.equal(42);
expect(p2.get(m2)).to.equal(42);
expect(p2.get(m3)).to.equal(6);
expect(p3.get(m1)).to.equal(42);
expect(p3.get(m2)).to.equal(42);
expect(p3.get(m3)).to.equal(9);
AttachedProperty.clearData(m3);
expect(p1.get(m1)).to.equal(42);
expect(p1.get(m2)).to.equal(42);
expect(p1.get(m3)).to.equal(42);
expect(p2.get(m1)).to.equal(42);
expect(p2.get(m2)).to.equal(42);
expect(p2.get(m3)).to.equal(42);
expect(p3.get(m1)).to.equal(42);
expect(p3.get(m2)).to.equal(42);
expect(p3.get(m3)).to.equal(42);
});
});
});
}); | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import "mocha";
import * as chai from "chai";
import * as util from "../common/testUtils";
const completionCasesDir = path.join(process.cwd(), "tests", "language-service", "completion_cases");
const snippetCasesDir = path.join(process.cwd(), "tests", "language-service", "snippet_cases");
const testPackage = path.relative(process.cwd(), path.join("tests", "language-service", "test-package"));
function initGlobals() {
let g = global as any
g.pxt = pxt;
g.ts = ts;
g.pxtc = pxtc;
g.btoa = (str: string) => Buffer.from(str, "binary").toString("base64");
g.atob = (str: string) => Buffer.from(str, "base64").toString("binary");
}
initGlobals();
pxt.setAppTarget(util.testAppTarget);
enum FileCheck {
Keep,
Only,
Skip
}
function checkTestFile(file: string): FileCheck {
// ignore hidden files
if (file[0] == ".") {
return FileCheck.Skip
}
// ignore files that start with TODO_; these represent future work
if (file.indexOf("TODO") >= 0) {
console.log("Skipping test file marked as 'TODO': " + file);
return FileCheck.Skip
}
const ext = file.substr(-3)
if (ext !== ".ts" && ext !== ".py") {
console.error("Skipping unknown/unsupported file in test folder: " + file);
return FileCheck.Skip
}
// if a file is named "ONLY", only run that one file
// (this is useful for working on a specific test case when
// the test suite gets large)
if (file.indexOf("ONLY") >= 0) {
return FileCheck.Only
}
return FileCheck.Keep
}
function getTestCaseFilenames(dir: string) {
let files = fs.readdirSync(dir)
.map(f => [checkTestFile(f), path.join(dir, f)] as [FileCheck, string])
.filter(([c, _]) => c !== FileCheck.Skip)
if (files.some(([c, _]) => c === FileCheck.Only))
files = files.filter(([c, _]) => c === FileCheck.Only)
return files.map(([_, f]) => f)
}
interface LangServTestCase {
fileName: string;
isPython: boolean;
}
interface SnippetTestCase extends LangServTestCase {
qName: string;
expectedSnippet: string;
}
interface CompletionTestCase extends LangServTestCase {
fileText: string;
lineText: string;
position: number;
wordStartPos: number;
wordEndPos: number;
expectedSymbols: string[];
unwantedSymbols: string[];
}
function getSnippetTestCases(): SnippetTestCase[] {
const filenames = getTestCaseFilenames(snippetCasesDir)
const cases = filenames
.map(getSnippetTestCasesInFile)
.reduce((p, n) => [...p, ...n], [])
return cases;
}
function getSnippetTestCasesInFile(fileName: string): SnippetTestCase[] {
const testCases: SnippetTestCase[] = [];
const fileText = fs.readFileSync(fileName, { encoding: "utf8" });
const isPython = fileName.substr(-3) !== ".ts";
const commentString = isPython ? "#" : "//";
/* Snippet case spec:
example:
// testNamespace.someFunction
testNamespace.someFunction("")
Each line that starts in a comment begins a new test case.
The case ends when the next line with a comment starts or the end of file is reached.
The content on the comment line is read as the qualified symbol name (qName) of the symbol we want to create a snippet for.
The non-comment content is the expected snippet result.
*/
const lines = fileText.split("\n");
const startsWithComment = (l: string) => l.substr(0, commentString.length) === commentString;
const linesAndTypes = lines.map(l => [l, startsWithComment(l)] as [string, boolean])
let currentCommentLine = ""
let currentCaseLines: string[] = []
for (let [line, startsWithComment] of linesAndTypes) {
if (startsWithComment) {
// finish current test case
if (currentCommentLine) {
const testCase = makeTestCase(currentCommentLine, currentCaseLines.join("\n"));
testCases.push(testCase);
}
// start new test case
currentCommentLine = line
currentCaseLines = []
} else {
// add to current test case
currentCaseLines.push(line)
}
}
// finish last current test case
if (currentCommentLine) {
const testCase = makeTestCase(currentCommentLine, currentCaseLines.join("\n"));
testCases.push(testCase);
}
return testCases;
function makeTestCase(comment: string, content: string): SnippetTestCase {
const qName = comment
.substr(commentString.length)
.trim()
const expectedSnippet = content.trim()
return {
fileName,
isPython,
qName,
expectedSnippet
}
}
}
function getCompletionTestCases(): CompletionTestCase[] {
const filenames = getTestCaseFilenames(completionCasesDir)
const testCases: CompletionTestCase[] = [];
for (const fileName of filenames) {
const fileText = fs.readFileSync(fileName, { encoding: "utf8" });
const isPython = fileName.substr(-3) !== ".ts";
const commentString = isPython ? "#" : "//";
const lines = fileText.split("\n");
let position = 0;
/* Completion case spec:
example:
foo.ba // foo.bar; foo.baz
Each line that ends in a comment is a test cases.
The comment is a ";" seperated list of expected symbols.
Symbols that start with "!" must not be present in the completion list.
The completions are triggered as if the user's cursor was at the end of
the line right after the last non-whitespace character.
*/
for (const line of lines) {
const commentIndex = line.indexOf(commentString);
if (commentIndex !== -1) {
const comment = line.substr(commentIndex + commentString.length).trim();
const symbols = comment.split(";")
.map(s => s.trim())
const expectedSymbols = symbols
.filter(s => s.indexOf("!") === -1)
const unwantedSymbols = symbols
.filter(s => s.indexOf("!") !== -1)
.map(s => s.replace("!", ""))
const lineWithoutCommment = line.substring(0, commentIndex);
// find last non-whitespace character
let lastNonWhitespace: number;
let endsInDot = false;
for (let i = lineWithoutCommment.length - 1; i >= 0; i--) {
lastNonWhitespace = i
if (lineWithoutCommment[i] !== " ") {
endsInDot = lineWithoutCommment[i] === "."
break
}
}
let relativeCompletionPosition = lastNonWhitespace + 1
const completionPosition = position + relativeCompletionPosition;
const lineText = line.substr(0, commentIndex);
// Find word start and end
let wordStartPos = fileText.slice(0, completionPosition).search(/[a-zA-Z\d]+\s*$/)
let wordEndPos = wordStartPos + fileText.slice(wordStartPos).search(/[^a-zA-Z\d]/)
if (wordStartPos < 0 || wordEndPos < 0) {
wordStartPos = completionPosition
wordEndPos = completionPosition
}
testCases.push({
fileName,
fileText,
lineText,
isPython,
expectedSymbols,
unwantedSymbols,
position: completionPosition,
wordStartPos,
wordEndPos,
})
}
position += line.length + 1/*new line char*/;
}
}
return testCases;
}
const fileName = (isPython: boolean) => isPython ? pxt.MAIN_PY : pxt.MAIN_TS
function runCompletionTestCaseAsync(testCase: CompletionTestCase): Promise<void> {
return getOptionsAsync(testCase.fileText, testCase.isPython)
.then(opts => {
setOptionsOp(opts);
ensureAPIInfoOp();
const result = completionsOp(
fileName(testCase.isPython),
testCase.position,
testCase.wordStartPos,
testCase.wordEndPos,
testCase.fileText
);
if (pxtc.service.IsOpErr(result)) {
chai.assert(false, `Lang service crashed with:\n${result.errorMessage}`)
return;
}
const symbolIndex = (sym: string) => result.entries.reduce((prevIdx, s, idx) => {
if (prevIdx >= 0)
return prevIdx
if ((testCase.isPython ? s.pyQName : s.qName) === sym)
return idx;
return -1
}, -1)
const hasSymbol = (sym: string) => symbolIndex(sym) >= 0;
let lastFoundIdx = -1;
for (const sym of testCase.expectedSymbols) {
let idx = symbolIndex(sym)
const foundSymbol = idx >= 0
chai.assert(foundSymbol, `Did not receive symbol '${sym}' for '${testCase.lineText}'; instead we got ${result.entries.length} other symbols${result.entries.length < 5 ? ": " + result.entries.map(e => e.qName).join(", ") : "."}`);
chai.assert(!foundSymbol || idx > lastFoundIdx, `Found symbol '${sym}', but in the wrong order at index: ${idx}. Expected it after: ${lastFoundIdx >= 0 ? result.entries[lastFoundIdx].qName : ""}`)
lastFoundIdx = idx;
}
for (const sym of testCase.unwantedSymbols) {
chai.assert(!hasSymbol(sym), `Receive explicitly unwanted symbol '${sym}' for '${testCase.lineText}'`);
}
})
}
function runSnippetTestCaseAsync(testCase: SnippetTestCase): Promise<void> {
return getOptionsAsync("", testCase.isPython)
.then(opts => {
setOptionsOp(opts);
ensureAPIInfoOp();
const { qName, isPython, expectedSnippet } = testCase;
const result = snippetOp(qName, isPython);
if (pxtc.service.IsOpErr(result)) {
chai.assert(false, `Lang service crashed with:\n${result.errorMessage}`)
return;
}
chai.assert(typeof result === "string", `Lang service returned non-string result: ${JSON.stringify(result)}`)
const match = util.compareBaselines(result, expectedSnippet, {
whitespaceSensitive: false
})
chai.assert(match, `Snippet for ${qName} "${result}" did not match expected "${expectedSnippet}"`);
})
}
function getOptionsAsync(fileContent: string, isPython: boolean) {
const packageFiles: pxt.Map<string> = {};
packageFiles[fileName(isPython)] = fileContent;
return util.getTestCompileOptsAsync(packageFiles, [testPackage], true)
.then(opts => {
if (isPython)
opts.target.preferredEditor = pxt.PYTHON_PROJECT_NAME
return opts
})
}
function ensureAPIInfoOp() {
pxtc.service.performOperation("apiInfo", {});
}
function setOptionsOp(opts: pxtc.CompileOptions) {
return pxtc.service.performOperation("setOptions", {
options: opts
});
}
function completionsOp(fileName: string, position: number, wordStartPos: number, wordEndPos: number, fileContent?: string): pxtc.service.OpError | pxtc.CompletionInfo {
return pxtc.service.performOperation("getCompletions", {
fileName,
fileContent,
position,
wordStartPos,
wordEndPos,
runtime: pxt.appTarget.runtime
}) as pxtc.service.OpError | pxtc.CompletionInfo;
}
function snippetOp(qName: string, python: boolean): pxtc.service.OpError | string {
return pxtc.service.performOperation("snippet", {
snippet: {
qName,
python
},
runtime: pxt.appTarget.runtime
}) as pxtc.service.OpError | string;
}
describe("language service", () => {
const completionCases = getCompletionTestCases();
for (const testCase of completionCases) {
it("get completions " + testCase.fileName + testCase.position, () => {
return runCompletionTestCaseAsync(testCase);
});
}
const snippetCases = getSnippetTestCases();
for (const testCase of snippetCases) {
it(`snippet for ${testCase.qName} in ${testCase.fileName}`, () => {
return runSnippetTestCaseAsync(testCase);
});
}
}) | the_stack |
import {
ConditionalTransferCreatedEventData,
ConditionalTransferTypes,
EventNames,
HashLockTransferStatus,
IConnextClient,
NodeResponses,
PublicParams,
} from "@connext/types";
import {
delay,
getChainId,
getRandomBytes32,
stringify,
} from "@connext/utils";
import { BigNumber, providers, constants, utils } from "ethers";
import {
AssetOptions,
createClient,
ETH_AMOUNT_SM,
ethProviderUrl,
expect,
fundChannel,
getTestLoggers,
requestCollateral,
TOKEN_AMOUNT,
} from "../util";
const { AddressZero, HashZero } = constants;
const { soliditySha256 } = utils;
const TIMEOUT_BUFFER = 100; // This currently isn't exported by the node so must be hardcoded
const name = "HashLock Transfers";
const { timeElapsed } = getTestLoggers(name);
describe(name, () => {
let clientA: IConnextClient;
let clientB: IConnextClient;
let provider: providers.JsonRpcProvider;
let start: number;
let tokenAddress: string;
before(async () => {
start = Date.now();
provider = new providers.JsonRpcProvider(ethProviderUrl, await getChainId(ethProviderUrl));
const currBlock = await provider.getBlockNumber();
if (currBlock > TIMEOUT_BUFFER) {
// no adjustment needed, return
return;
}
for (let index = currBlock; index <= TIMEOUT_BUFFER + 1; index++) {
await provider.send("evm_mine", []);
}
timeElapsed("beforeEach complete", start);
});
// Define helper functions
const sendHashlockTransfer = async (
sender: IConnextClient,
receiver: IConnextClient,
transfer: AssetOptions & { preImage: string; timelock: string },
): Promise<ConditionalTransferCreatedEventData<"HashLockTransferApp">> => {
// Fund sender channel
await fundChannel(sender, transfer.amount, transfer.assetId);
// Create transfer parameters
const expiry = BigNumber.from(transfer.timelock).add(await provider.getBlockNumber());
const lockHash = soliditySha256(["bytes32"], [transfer.preImage]);
// return promise with [sender ret, receiver event data]
const [senderResult, receiverEvent] = await Promise.all([
// sender result
clientA.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock: transfer.timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientA.publicIdentifier },
recipient: clientB.publicIdentifier,
}),
// receiver created event
new Promise((resolve) => {
receiver.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, (eventPayload) =>
resolve(eventPayload),
);
}),
]);
const paymentId = soliditySha256(["address", "bytes32"], [transfer.assetId, lockHash]);
const expectedVals = {
amount: transfer.amount,
assetId: transfer.assetId,
paymentId,
recipient: receiver.publicIdentifier,
sender: sender.publicIdentifier,
transferMeta: {
timelock: transfer.timelock,
lockHash,
expiry: expiry.sub(TIMEOUT_BUFFER),
},
};
// verify the receiver event
expect(receiverEvent).to.containSubset({
...expectedVals,
type: ConditionalTransferTypes.HashLockTransfer,
});
// verify sender return value
expect(senderResult).to.containSubset({
...expectedVals,
transferMeta: {
...expectedVals.transferMeta,
expiry,
},
});
return receiverEvent as any;
};
// returns [resolveResult, undefined, undefined]
const waitForResolve = (
sender: IConnextClient,
receiver: IConnextClient,
transfer: AssetOptions & { preImage: string; timelock: string },
waitForSender: boolean = true,
) => {
const lockHash = soliditySha256(["bytes32"], [transfer.preImage]);
const paymentId = soliditySha256(["address", "bytes32"], [transfer.assetId, lockHash]);
return Promise.all([
// receiver result
receiver.resolveCondition({
conditionType: ConditionalTransferTypes.HashLockTransfer,
preImage: transfer.preImage,
assetId: transfer.assetId,
paymentId,
}),
// receiver event
new Promise((resolve, reject) => {
receiver.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve);
receiver.once(EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT, reject);
}),
// sender event
new Promise((resolve, reject) => {
if (waitForSender) {
sender.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve);
sender.once(EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT, reject);
} else {
resolve();
}
}),
]);
};
const assertSenderDecrement = async (
sender: IConnextClient,
transfer: AssetOptions & { preImage: string; timelock: string },
) => {
const { [sender.signerAddress]: senderBal } = await sender.getFreeBalance(transfer.assetId);
expect(senderBal).to.eq(0);
};
const assertPostTransferBalances = async (
sender: IConnextClient,
receiver: IConnextClient,
transfer: AssetOptions & { preImage: string; timelock: string },
) => {
const { [sender.signerAddress]: senderBal } = await sender.getFreeBalance(transfer.assetId);
expect(senderBal).to.eq(0);
const { [receiver.signerAddress]: receiverBal } = await receiver.getFreeBalance(
transfer.assetId,
);
expect(receiverBal).to.eq(transfer.amount);
};
const assertRetrievedTransfer = async (
client: IConnextClient,
transfer: AssetOptions & {
timelock: string;
preImage: string;
senderIdentifier: string;
receiverIdentifier: string;
},
expected: Partial<NodeResponses.GetHashLockTransfer> = {},
) => {
const lockHash = soliditySha256(["bytes32"], [transfer.preImage]);
const retrieved = await client.getHashLockTransfer(lockHash, transfer.assetId);
const paymentId = soliditySha256(["address", "bytes32"], [transfer.assetId, lockHash]);
expect(retrieved).to.containSubset({
amount: transfer.amount.toString(),
assetId: transfer.assetId,
lockHash,
senderIdentifier: transfer.senderIdentifier,
receiverIdentifier: transfer.receiverIdentifier,
meta: {
sender: transfer.senderIdentifier,
timelock: transfer.timelock,
paymentId,
},
...expected,
});
};
beforeEach(async () => {
clientA = await createClient({ id: "A" });
clientB = await createClient({ id: "B" });
tokenAddress = clientA.config.contractAddresses[clientA.chainId].Token!;
});
afterEach(async () => {
await clientA.off();
await clientB.off();
});
it("client A hashlock transfers eth to client B through node", async () => {
const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
await sendHashlockTransfer(clientA, clientB, opts);
await assertSenderDecrement(clientA, opts);
await waitForResolve(clientA, clientB, opts);
await assertPostTransferBalances(clientA, clientB, opts);
});
it("client A hashlock transfers tokens to client B through node", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
await sendHashlockTransfer(clientA, clientB, opts);
await assertSenderDecrement(clientA, opts);
await waitForResolve(clientA, clientB, opts);
await assertPostTransferBalances(clientA, clientB, opts);
});
it("transfer is cancelled if receiver is offline", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
await fundChannel(clientA, transfer.amount, transfer.assetId);
// Create transfer parameters
const expiry = BigNumber.from(timelock).add(await provider.getBlockNumber());
const lockHash = soliditySha256(["bytes32"], [preImage]);
// return promise with [sender ret, receiver event data]
// sender result
await clientB.off();
await expect(
clientA.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock: expiry,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientA.publicIdentifier },
recipient: clientB.publicIdentifier,
}),
).to.be.rejected;
const fb = await clientA.getFreeBalance(transfer.assetId);
expect(fb[clientA.signerAddress]).to.eq(transfer.amount);
});
it("gets a pending hashlock transfer by lock hash", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
await sendHashlockTransfer(clientA, clientB, opts);
await assertRetrievedTransfer(
clientB,
{
...opts,
senderIdentifier: clientA.publicIdentifier,
receiverIdentifier: clientB.publicIdentifier,
},
{
status: HashLockTransferStatus.PENDING,
preImage: HashZero,
},
);
});
it("gets a completed hashlock transfer by lock hash", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
await sendHashlockTransfer(clientA, clientB, opts);
// wait for transfer to be picked up by receiver, but not reclaim
// by node for sender
await waitForResolve(clientA, clientB, opts, false);
await assertRetrievedTransfer(
clientB,
{
...opts,
senderIdentifier: clientA.publicIdentifier,
receiverIdentifier: clientB.publicIdentifier,
},
{
status: HashLockTransferStatus.COMPLETED,
preImage,
},
);
});
it("can send two hashlock transfers with different assetIds and the same lock hash", async () => {
const transferToken = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const transferEth = { amount: ETH_AMOUNT_SM, assetId: AddressZero };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const ethOpts = { ...transferEth, preImage, timelock };
const tokenOpts = { ...transferToken, preImage, timelock };
await sendHashlockTransfer(clientA, clientB, ethOpts);
await sendHashlockTransfer(clientA, clientB, tokenOpts);
await waitForResolve(clientA, clientB, ethOpts);
await waitForResolve(clientA, clientB, tokenOpts);
await assertPostTransferBalances(clientA, clientB, ethOpts);
await assertPostTransferBalances(clientA, clientB, tokenOpts);
});
it("cannot resolve a hashlock transfer if pre image is wrong", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
const { paymentId } = await sendHashlockTransfer(clientA, clientB, opts);
const badPreImage = getRandomBytes32();
await expect(
clientB.resolveCondition({
conditionType: ConditionalTransferTypes.HashLockTransfer,
preImage: badPreImage,
paymentId: paymentId!,
assetId: transfer.assetId,
} as PublicParams.ResolveHashLockTransfer),
).to.be.rejectedWith(/Hash generated from preimage does not match hash in state/);
// verfy payment did not go through
const { [clientB.signerAddress]: receiverBal } = await clientB.getFreeBalance(transfer.assetId);
expect(receiverBal).to.eq(0);
});
// NOTE: if the node tries to collateralize or send a transaction during
// this test, it will likely pass due to the 1 block margin of error in the
// timelock variable
it("cannot resolve a hashlock if timelock is expired", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (101).toString();
const opts = { ...transfer, preImage, timelock };
const { paymentId } = await sendHashlockTransfer(clientA, clientB, opts);
await new Promise((resolve) => provider.once("block", resolve));
await expect(
clientB.resolveCondition({
conditionType: ConditionalTransferTypes.HashLockTransfer,
preImage,
paymentId: paymentId!,
assetId: transfer.assetId,
} as PublicParams.ResolveHashLockTransfer),
).to.be.rejectedWith(/Cannot take action if expiry is expired/);
});
it("cannot install receiver app without sender app installed", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const lockHash = soliditySha256(["bytes32"], [preImage]);
clientA.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientA.publicIdentifier },
recipient: clientB.publicIdentifier,
} as PublicParams.HashLockTransfer);
await expect(
new Promise((res, rej) => {
// should not see this event, wait 10 seconds to make sure it doesnt happen
// TODO: change to rej
clientB.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, () => {
rej("Should not get this event!");
});
setTimeout(res, 10_000);
}),
).to.be.fulfilled;
});
it("receiver should be able to cancel an active payment", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (5000).toString();
const opts = { ...transfer, preImage, timelock };
const { paymentId } = await sendHashlockTransfer(clientA, clientB, opts);
await assertSenderDecrement(clientA, opts);
const { [clientB.signerAddress]: initialBal } = await clientB.getFreeBalance(transfer.assetId);
expect(initialBal).to.eq(0);
await new Promise((resolve, reject) => {
clientA.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve);
clientB
.resolveCondition({
paymentId: paymentId!,
preImage: HashZero,
conditionType: ConditionalTransferTypes.HashLockTransfer,
assetId: transfer.assetId,
})
.catch((e) => reject(e));
});
const { [clientA.signerAddress]: senderBal } = await clientA.getFreeBalance(transfer.assetId);
const { [clientB.signerAddress]: receiverBal } = await clientB.getFreeBalance(transfer.assetId);
expect(senderBal).to.eq(transfer.amount);
expect(receiverBal).to.eq(0);
});
it("receiver should be able to cancel an expired payment", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (101).toString();
const opts = { ...transfer, preImage, timelock };
const { paymentId } = await sendHashlockTransfer(clientA, clientB, opts);
await assertSenderDecrement(clientA, opts);
await new Promise((resolve) => provider.on("block", resolve));
await new Promise((resolve, reject) => {
clientA.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve);
clientB
.resolveCondition({
paymentId: paymentId!,
preImage: HashZero,
conditionType: ConditionalTransferTypes.HashLockTransfer,
assetId: transfer.assetId,
})
.catch((e) => reject(e));
});
const { [clientA.signerAddress]: senderBal } = await clientA.getFreeBalance(transfer.assetId);
const { [clientB.signerAddress]: receiverBal } = await clientB.getFreeBalance(transfer.assetId);
expect(senderBal).to.eq(transfer.amount);
expect(receiverBal).to.eq(0);
});
it.skip("sender should be able to refund an expired payment", async () => {
const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress };
const preImage = getRandomBytes32();
const timelock = (1).toString();
const opts = { ...transfer, preImage, timelock };
const { paymentId } = await sendHashlockTransfer(clientA, clientB, opts);
await assertSenderDecrement(clientA, opts);
// FIXME: how to move blocks successfully?
// for (const i of Array(parseInt(timelock) + 5)) {
// await new Promise((resolve) => provider.once("block", resolve));
// }
await assertRetrievedTransfer(
clientB,
{
...opts,
senderIdentifier: clientA.publicIdentifier,
receiverIdentifier: clientB.publicIdentifier,
},
{
status: HashLockTransferStatus.EXPIRED,
preImage: HashZero,
},
);
await clientA.resolveCondition({
paymentId: paymentId!,
preImage: HashZero,
conditionType: ConditionalTransferTypes.HashLockTransfer,
assetId: transfer.assetId,
});
// make sure payment was reverted in balances
const { [clientA.signerAddress]: senderBal } = await clientA.getFreeBalance(transfer.assetId);
const { [clientB.signerAddress]: receiverBal } = await clientB.getFreeBalance(transfer.assetId);
expect(senderBal).to.eq(transfer.amount);
expect(receiverBal).to.eq(0);
// make sure payment says failed on node
await assertRetrievedTransfer(
clientB,
{
...opts,
senderIdentifier: clientA.publicIdentifier,
receiverIdentifier: clientB.publicIdentifier,
},
{
status: HashLockTransferStatus.FAILED,
preImage: HashZero,
},
);
});
// FIXME: may not work depending on collateral, will expect some payment
// errors even with a small number of payments until this is handled better
it.skip("can send concurrent hashlock transfers", async () => {
const transfer = { amount: TOKEN_AMOUNT.div(5), assetId: tokenAddress };
await fundChannel(clientA, transfer.amount.mul(5), transfer.assetId);
await fundChannel(clientB, transfer.amount.mul(5), transfer.assetId);
await requestCollateral(clientA, transfer.assetId, true);
await requestCollateral(clientB, transfer.assetId, true);
// add in assertions that will cause the test to fail once these
// events are thrown
const registerAssertions = (client: IConnextClient): Promise<void> => {
return new Promise((resolve, reject) => {
let reclaimed = 0;
client.once(EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT, (data) => {
return reject(`${EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT}: ${stringify(data)}`);
});
// client.once(EventNames.PROPOSE_INSTALL_FAILED_EVENT, (data) => {
// return reject(`${EventNames.PROPOSE_INSTALL_FAILED_EVENT}: ${stringify(data)}`);
// });
// client.once(EventNames.INSTALL_FAILED_EVENT, (data) => {
// return reject(`${EventNames.INSTALL_FAILED_EVENT}: ${stringify(data)}`);
// });
// client.once(EventNames.UNINSTALL_FAILED_EVENT, (data) => {
// return reject(`${EventNames.UNINSTALL_FAILED_EVENT}: ${stringify(data)}`);
// });
client.once(EventNames.SYNC_FAILED_EVENT, (data) => {
return reject(`${EventNames.SYNC_FAILED_EVENT}: ${stringify(data)}`);
});
client.on(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, (data) => {
if (data.sender !== client.publicIdentifier) {
return;
}
reclaimed += 1;
if (reclaimed === 2) {
return resolve();
}
});
});
};
const a = registerAssertions(clientA);
const b = registerAssertions(clientB);
const timelock = (5000).toString();
let preImage = getRandomBytes32();
let lockHash = soliditySha256(["bytes32"], [preImage]);
const t1 = clientA.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientA.publicIdentifier },
recipient: clientB.publicIdentifier,
} as PublicParams.HashLockTransfer);
preImage = getRandomBytes32();
lockHash = soliditySha256(["bytes32"], [preImage]);
const t2 = clientA.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientA.publicIdentifier },
recipient: clientB.publicIdentifier,
} as PublicParams.HashLockTransfer);
await delay(100);
preImage = getRandomBytes32();
lockHash = soliditySha256(["bytes32"], [preImage]);
const t3 = clientB.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientB.publicIdentifier },
recipient: clientA.publicIdentifier,
} as PublicParams.HashLockTransfer);
preImage = getRandomBytes32();
lockHash = soliditySha256(["bytes32"], [preImage]);
const t4 = clientB.conditionalTransfer({
amount: transfer.amount.toString(),
conditionType: ConditionalTransferTypes.HashLockTransfer,
lockHash,
timelock,
assetId: transfer.assetId,
meta: { foo: "bar", sender: clientB.publicIdentifier },
recipient: clientA.publicIdentifier,
} as PublicParams.HashLockTransfer);
const [aRes, bRes] = await Promise.all([a, b, t1, t2, t3, t4]);
expect(aRes).to.be.undefined;
expect(bRes).to.be.undefined;
// await delay(20000);
});
}); | the_stack |
import React, { ChangeEvent } from 'react';
import './App.css';
import 'typeface-roboto';
import { createStyles, withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import IconButton from '@material-ui/core/IconButton';
import Slider from '@material-ui/core/Slider';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import RefreshIcon from '@material-ui/icons/Refresh';
import SettingsIcon from '@material-ui/icons/Settings';
import CloseIcon from '@material-ui/icons/Close';
import ShuffleIcon from '@material-ui/icons/Shuffle';
import Snackbar from '@material-ui/core/Snackbar';
import FormControl from '@material-ui/core/FormControl';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormGroup from '@material-ui/core/FormGroup';
import Checkbox from '@material-ui/core/Checkbox';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import MuiExpansionPanel from '@material-ui/core/ExpansionPanel';
import MuiExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import MuiExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import Backdrop from '@material-ui/core/Backdrop';
import Chart from './Chart';
import { Graph } from './graphUtils';
const styles = createStyles({
bottomAppBar: {
top: 'auto',
bottom: 0,
zIndex: 'auto',
},
title: {
flexGrow: 1,
textAlign: 'left'
},
panel: {
position: 'absolute',
top: 76,
right: 16,
width: 400,
},
listItem: {
paddingLeft: 0,
paddingRight: 0,
paddingTop: 2,
paddingBottom: 2,
fontSize: '0.8em',
wordBreak: 'break-all',
},
listSubtitle: {
fontWeight: 600,
paddingLeft: 0,
paddingRight: 0,
fontSize: '0.9em',
},
listTitle: {
lineHeight: 1.1,
wordBreak: 'break-all'
},
backdrop: {
color: '#fff',
zIndex: 100,
},
snackbar: {
bottom: 76
}
});
const ExpansionPanel = withStyles({
root: {
'&$expanded': {
margin: 'auto',
},
},
expanded: {},
})(MuiExpansionPanel);
const ExpansionPanelSummary = withStyles({
root: {},
content: {
'&$expanded': {
margin: '12px 0',
},
},
expanded: {},
})(MuiExpansionPanelSummary);
const ExpansionPanelDetails = withStyles(theme => ({
root: {
paddingTop: 0,
paddingBottom: theme.spacing(1),
},
}))(MuiExpansionPanelDetails);
type AppState = {
graph: Graph | undefined,
graphData: any,
logData: any[],
sliderValue: number,
maxSliderValue: number,
sliderStep: number,
settingsOpen: boolean,
hideSidechainNodes: boolean,
hidePrimitiveNodes: boolean,
snackbarOpen: boolean,
selectedNode: string,
loading: boolean,
layout: boolean,
}
type AppProps = {
classes: any
}
class App extends React.Component<AppProps, AppState> {
constructor(props: any) {
super(props);
this.state = {
graph: undefined,
graphData: undefined,
logData: [],
sliderValue: 0,
maxSliderValue: 0,
sliderStep: 1,
settingsOpen: false,
hideSidechainNodes: true,
hidePrimitiveNodes: true,
selectedNode: '',
loading: false,
snackbarOpen: false,
layout: false,
};
this.refresh = this.refresh.bind(this);
}
componentDidMount() {
this.refresh();
}
refresh() {
this.setState({ loading: true });
fetch('/refresh')
.then((response) => { return response.json() })
.then((data) => {
const graph = new Graph(data.graph, this.state.hideSidechainNodes);
this.setState({
graphData: data.graph,
graph: graph,
logData: data.log,
maxSliderValue: data.log.length - 1,
sliderStep: Math.max(1, Math.floor(data.log.length / 20)),
sliderValue: Math.min(data.log.length, this.state.sliderValue),
loading: false,
snackbarOpen: graph.nodes.length > 100
});
});
}
private renderExpansionPanel() {
const { classes } = this.props;
const { selectedNode, graph } = this.state;
if (graph === undefined)
return null;
const info = graph.nodeSummary(selectedNode);
if (info === undefined)
return null;
const subtitle = info.op ?
(info.op === 'IO Node' ? info.op : `Operation: ${info.op}`) :
`Subgraph: ${info.nodeCount} nodes, ${info.edgeCount} edges`;
return (
<ExpansionPanel className={classes.panel}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
>
<Typography variant='subtitle1' className={classes.listTitle}><b>{info.name}</b><br />{subtitle}</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<List dense={true} style={{
maxHeight: window.innerHeight * .5,
overflowY: 'auto',
paddingTop: 0,
width: '100%'
}}>
{
info.attributes &&
<React.Fragment>
<ListItem className={classes.listSubtitle}>Attributes</ListItem>
<ListItem className={classes.listItem}>{info.attributes}</ListItem>
</React.Fragment>
}
{
info.inputs.length > 0 &&
<React.Fragment>
<ListItem className={classes.listSubtitle}>Inputs ({info.inputs.length})</ListItem>
{
info.inputs.map((item, i) => <ListItem className={classes.listItem} key={`input${i}`}>{item}</ListItem>)
}
</React.Fragment>
}
{
info.outputs.length > 0 &&
<React.Fragment>
<ListItem className={classes.listSubtitle}>Outputs ({info.outputs.length})</ListItem>
{
info.outputs.map((item, i) => <ListItem className={classes.listItem} key={`output${i}`}>{item}</ListItem>)
}
</React.Fragment>
}
</List>
</ExpansionPanelDetails>
</ExpansionPanel>
);
}
render() {
const { classes } = this.props;
const { sliderValue, maxSliderValue, sliderStep, settingsOpen, loading, snackbarOpen } = this.state;
const handleSliderChange = (event: ChangeEvent<{}>, value: number | number[]) => {
this.setState({ sliderValue: value as number });
};
const handleSettingsDialogToggle = (value: boolean) => () => {
this.setState({ settingsOpen: value });
};
const handleSettingsChange = (name: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
this.setState({
...this.state,
[name]: event.target.checked
}, () => {
this.setState({
graph: new Graph(this.state.graphData, this.state.hideSidechainNodes),
})
});
};
const handleSelectionChange = (node: string) => {
this.setState({
selectedNode: node
});
};
const handleLoadingState = (state: boolean) => () => {
this.setState({ loading: state });
};
const handleSnackbarClose = () => {
this.setState({ snackbarOpen: false });
};
const handleLayoutStateChanged = (state: boolean) => () => {
this.setState({ layout: state });
};
return (
<div className='App'>
<Chart
width={window.innerWidth}
height={window.innerHeight}
graph={this.state.graph}
activation={sliderValue < this.state.logData.length ? this.state.logData[sliderValue] : undefined}
handleSelectionChange={handleSelectionChange}
onRefresh={handleLoadingState(true)}
onRefreshComplete={handleLoadingState(false)}
layout={this.state.layout}
onLayoutComplete={handleLayoutStateChanged(false)}
/>
<AppBar position='fixed' color='primary'>
<Toolbar>
<Typography variant='h6' className={classes.title}>
NNI NAS Board
</Typography>
<IconButton color='inherit' onClick={handleLayoutStateChanged(true)}>
<ShuffleIcon />
</IconButton>
<IconButton color='inherit' onClick={this.refresh}>
<RefreshIcon />
</IconButton>
<IconButton color='inherit' onClick={handleSettingsDialogToggle(true)}>
<SettingsIcon />
</IconButton>
</Toolbar>
</AppBar>
<AppBar position='fixed' color='default' className={classes.bottomAppBar}>
<Toolbar variant='dense'>
<Grid container spacing={2} alignItems='center'>
<Grid item xs>
<Slider
value={sliderValue}
max={maxSliderValue}
min={0}
step={sliderStep}
onChange={handleSliderChange}
/>
</Grid>
<Grid item>
<Typography variant='body1'>
{sliderValue}/{maxSliderValue}
</Typography>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<Dialog onClose={handleSettingsDialogToggle(false)} open={settingsOpen}>
<DialogTitle>Settings</DialogTitle>
<DialogContent>
<FormControl component='fieldset'>
<FormGroup>
<FormControlLabel
control={<Checkbox checked={this.state.hideSidechainNodes}
onChange={handleSettingsChange('hideSidechainNodes')}
value='hideSidechainNodes' />}
label='Hide sidechain nodes'
/>
{ // TODO: hide primitive nodes
/* <FormControlLabel
control={<Checkbox checked={this.state.hidePrimitiveNodes}
onChange={handleSettingsChange('hidePrimitiveNodes')}
value='hidePrimitiveNodes' />}
label='Hide primitive nodes'
/> */}
</FormGroup>
</FormControl>
</DialogContent>
<DialogActions>
<Button onClick={handleSettingsDialogToggle(false)} color='primary'>
Close
</Button>
</DialogActions>
</Dialog>
{this.renderExpansionPanel()}
<Snackbar
className={classes.snackbar}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
open={snackbarOpen}
message='Graph is too large. Might induce performance issue.'
onClose={handleSnackbarClose}
action={
<IconButton size='small' color='inherit' onClick={handleSnackbarClose}>
<CloseIcon fontSize='small' />
</IconButton>
}
/>
{
loading && <Backdrop className={classes.backdrop} open={true}>
<Typography>Loading...</Typography>
</Backdrop>
}
</div>
);
}
}
export default withStyles(styles)(App); | the_stack |
import * as Hoek from '@hapi/hoek';
// Internal helpers
type Class<T = any> = new (...args: any[]) => T;
type UnpackArray<T> = T extends (infer U)[] ? U : T;
type RecursivePartial<T> = {
[P in keyof T]?:
T[P] extends (infer U)[] ? RecursivePartial<U>[] :
T[P] extends object ? RecursivePartial<T[P]> :
T[P];
};
type Loosely<T> = T extends object ? RecursivePartial<T> & { [key: string]: any } : T;
/**
* Configure code behavior
*/
export const settings: Settings;
export interface Settings {
/**
* Truncate long assertion error messages for readability.
*
* @default false
*/
truncateMessages?: boolean;
/**
* Ignore object prototypes when doing a deep comparison.
*
* @defaults false
*/
comparePrototypes?: boolean;
}
/**
* Makes the test fail.
*
* @param message - the error message generated.
*/
export function fail(message?: string): void;
/**
* Returns the total number of assertions created using the `expect()` method.
*
* @returns total number of assertions.
*/
export function count(): number;
/**
* Returns an array of the locations where incomplete assertions were declared or `null` if no incomplete assertions found.
*
* @returns array of incomplete assertion locations.
*/
export function incomplete(): string[] | null;
/**
* Returns the filename, line number, and column number of where the `error` was created. If no error is provided, the current location returned.
*
* @param error - an error object.
*
* @returns the location where the error was thrown.
*/
export function thrownAt(error?: Error): thrownAt.Location;
export namespace thrownAt {
interface Location {
filename: string;
line: string;
column: string;
}
}
/**
* Declares an assertion chain.
*
* @param value - the value being asserted.
* @param prefix - a string prefix added to error messages.
*
* @returns Assertion object.
*/
export function expect<T, TTest extends T = T>(value: T, prefix?: string):
TTest extends string ? expect.StringAssertion<T> :
TTest extends number | bigint ? expect.NumberAssertion<T> :
TTest extends Promise<any> ? expect.PromiseAssertion<T> :
expect.Assertion<T>;
declare namespace expect {
interface Assertion<T> {
// Grammar
a: this;
an: this;
and: this;
at: this;
be: this;
have: this;
in: this;
to: this;
// Flags
/**
* Inverses the expected result of the assertion chain.
*/
not: this;
/**
* Requires that inclusion matches appear only once in the provided value.
*/
once: this;
/**
* Requires that only the provided elements appear in the provided value.
*/
only: this;
/**
* Allows a partial match when asserting inclusion instead of a full comparison.
*/
part: this;
/**
* Performs a comparison using strict equality (===) instead of a deep comparison.
*/
shallow: this;
// Types
/**
* Asserts that the reference value is an arguments object.
*
* @returns assertion chain object.
*/
arguments(): this;
/**
* Asserts that the reference value is an Array.
*
* @returns assertion chain object.
*/
array(): this;
/**
* Asserts that the reference value is a boolean.
*
* @returns assertion chain object.
*/
boolean(): this;
/**
* Asserts that the reference value is a Buffer.
*
* @returns assertion chain object.
*/
buffer(): this;
/**
* Asserts that the reference value is a Date
*
* @returns assertion chain object.
*/
date(): this;
/**
* Asserts that the reference value is an error.
*
* @param type - constructor function the error must be an instance of.
* @param message - string or regular expression the error message must match.
*
* @returns assertion chain object.
*/
error(type: Class, message?: string | RegExp): this;
error(message?: string | RegExp): this;
/**
* Asserts that the reference value is a function.
*
* @returns assertion chain object.
*/
function(): this;
/**
* Asserts that the reference value is a number.
*
* @returns assertion chain object.
*/
number(): this;
/**
* Asserts that the reference value is a RegExp.
*
* @returns assertion chain object.
*/
regexp(): this;
/**
* Asserts that the reference value is a string.
*
* @returns assertion chain object.
*/
string(): this;
/**
* Asserts that the reference value is an object (excluding array, buffer, or other native objects).
*
* @returns assertion chain object.
*/
object(): this;
// Values
/**
* Asserts that the reference value is true.
*
* @returns assertion chain object.
*/
true(): this;
/**
* Asserts that the reference value is false.
*
* @returns assertion chain object.
*/
false(): this;
/**
* Asserts that the reference value is null.
*
* @returns assertion chain object.
*/
null(): this;
/**
* Asserts that the reference value is undefined.
*
* @returns assertion chain object.
*/
undefined(): this;
/**
* Asserts that the reference value is `NaN`.
*
* @returns assertion chain object.
*/
NaN(): this;
// Tests
/**
* Asserts that the reference value (a string, array, or object) includes the provided values.
*
* @param values - the values to include.
*
* @returns assertion chain object.
*/
include(values: UnpackArray<Loosely<T> | Loosely<T>[]>): this;
include(values: string | string[]): this;
/**
* Asserts that the reference value (a string, array, or object) includes the provided values.
*
* @param values - the values to include.
*
* @returns assertion chain object.
*/
includes(values: UnpackArray<Loosely<T> | Loosely<T>[]>): this;
includes(values: string | string[]): this;
/**
* Asserts that the reference value (a string, array, or object) includes the provided values.
*
* @param values - the values to include.
*
* @returns assertion chain object.
*/
contain(values: UnpackArray<Loosely<T> | Loosely<T>[]>): this;
contain(values: string | string[]): this;
/**
* Asserts that the reference value (a string, array, or object) includes the provided values.
*
* @param values - the values to include.
*
* @returns assertion chain object.
*/
contains(values: UnpackArray<Loosely<T> | Loosely<T>[]>): this;
contains(values: string | string[]): this;
/**
* Asserts that the reference value exists (not null or undefined).
*
* @returns assertion chain object.
*/
exist(): this;
/**
* Asserts that the reference value exists (not null or undefined).
*
* @returns assertion chain object.
*/
exists(): this;
/**
* Asserts that the reference value has a length property equal to zero or is an object with no keys.
*
* @returns assertion chain object.
*/
empty(): this;
/**
* Asserts that the reference value has a length property matching the provided size or an object with the specified number of keys.
*
* @param size - the required length.
*
* @returns assertion chain object.
*/
length(size: T extends string | Buffer | object | any[] ? number : never): this;
/**
* Asserts that the reference value equals the provided value.
*
* @param value - the value to match.
* @param options - comparison options.
*
* @returns assertion chain object.
*/
equal(value: T, options?: Hoek.deepEqual.Options): this;
/**
* Asserts that the reference value equals the provided value.
*
* @param value - the value to match.
* @param options - comparison options.
*
* @returns assertion chain object.
*/
equals(value: T, options?: Hoek.deepEqual.Options): this;
/**
* Asserts that the reference value has the provided instanceof value.
*
* @param type - the constructor function to be an instance of.
*/
instanceof(type: Class): this;
/**
* Asserts that the reference value has the provided instanceof value.
*
* @param type - the constructor function to be an instance of.
*/
instanceOf(type: Class): this;
/**
* Asserts that the reference value's toString() representation matches the provided regular expression.
*
* @param regex - the pattern to match.
*
* @returns assertion chain object.
*/
match(regex: RegExp): this;
/**
* Asserts that the reference value's toString() representation matches the provided regular expression.
*
* @param regex - the pattern to match.
*
* @returns assertion chain object.
*/
matches(regex: RegExp): this;
/**
* Asserts that the reference value satisfies the provided validator function.
*
* @param validator
*
* @returns assertion chain object.
*/
satisfy(validator: (value: T) => boolean): this;
/**
* Asserts that the reference value satisfies the provided validator function.
*
* @param validator
*
* @returns assertion chain object.
*/
satisfies(validator: (value: T) => boolean): this;
/**
* Asserts that the function reference value throws an exception when called.
*
* @param type - constructor function the error must be an instance of.
* @param message - string or regular expression the error message must match.
*
* @returns assertion chain object.
*/
throw(type: Class, message?: string | RegExp): this;
throw(message?: string | RegExp): this;
/**
* Asserts that the function reference value throws an exception when called.
*
* @param type - constructor function the error must be an instance of.
* @param message - string or regular expression the error message must match.
*
* @returns assertion chain object.
*/
throws(type: Class, message?: string | RegExp): this;
throws(message?: string | RegExp): this;
}
interface StringAssertion<T> extends Assertion<T> {
/**
* Asserts that the reference value (a string) starts with the provided value.
*
* @param value - the value to start with.
*
* @returns assertion chain object.
*/
startWith(value: string): this;
/**
* Asserts that the reference value (a string) starts with the provided value.
*
* @param value - the value to start with.
*
* @returns assertion chain object.
*/
startsWith(value: string): this;
/**
* Asserts that the reference value (a string) ends with the provided value.
*
* @param value - the value to end with.
*
* @returns assertion chain object.
*/
endWith(value: string): this;
/**
* Asserts that the reference value (a string) ends with the provided value.
*
* @param value - the value to end with.
*
* @returns assertion chain object.
*/
endsWith(value: string): this;
}
interface NumberAssertion<T> extends Assertion<T> {
/**
* Asserts that the reference value is greater than (>) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
above(value: T): this;
/**
* Asserts that the reference value is greater than (>) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
greaterThan(value: T): this;
/**
* Asserts that the reference value is at least (>=) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
least(value: T): this;
/**
* Asserts that the reference value is at least (>=) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
min(value: T): this;
/**
* Asserts that the reference value is less than (<) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
below(value: T): this;
/**
* Asserts that the reference value is less than (<) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
lessThan(value: T): this;
/**
* Asserts that the reference value is at most (<=) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
most(value: T): this;
/**
* Asserts that the reference value is at most (<=) the provided value.
*
* @param value - the value to compare to.
*
* @returns assertion chain object.
*/
max(value: T): this;
/**
* Asserts that the reference value is within (from <= value <= to) the provided values.
*
* @param from - the value to be equal to or above.
* @param to - the value to be equal to or below.
*
* @returns assertion chain object.
*/
within(from: T, to: T): this;
/**
* Asserts that the reference value is within (from <= value <= to) the provided values.
*
* @param from - the value to be equal to or above.
* @param to - the value to be equal to or below.
*
* @returns assertion chain object.
*/
range(from: T, to: T): this;
/**
* Asserts that the reference value is between but not equal (from < value < to) the provided values.
*
* @param from - the value to be above.
* @param to - the value to be below.
*
* @returns assertion chain object.
*/
between(from: T, to: T): this;
/**
* Asserts that the reference value is about the provided value within a delta margin of difference.
*
* @param value - the value to be near.
* @param delta - the max distance to be from the value.
*
* @returns assertion chain object.
*/
about(value: T extends number ? T : never, delta: T extends number ? T : never): this;
}
interface PromiseAssertion<T> extends Assertion<T> {
/**
* Asserts that the Promise reference value rejects with an exception when called.
*
* @param type - constructor function the error must be an instance of.
* @param message - string or regular expression the error message must match.
*
* @returns assertion chain object.
*/
reject<E extends {}>(type: Class<E>, message?: string | RegExp): Promise<E>;
reject<E = unknown>(message: string | RegExp): Promise<E>;
reject(): Promise<null>;
/**
* Asserts that the Promise reference value rejects with an exception when called.
*
* @param type - constructor function the error must be an instance of.
* @param message - string or regular expression the error message must match.
*
* @returns assertion chain object.
*/
rejects<E extends {}>(type: Class<E>, message?: string | RegExp): Promise<E>;
rejects<E = unknown>(message: string | RegExp): Promise<E>;
rejects(): Promise<null>;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreRatingInfo } from '@features/rating/services/rating';
import { CoreTagItem } from '@features/tag/services/tag';
import { CoreUser } from '@features/user/services/user';
import { CoreApp } from '@services/app';
import { CoreFileEntry } from '@services/file-helper';
import { CoreGroups } from '@services/groups';
import { CoreSitesCommonWSOptions, CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreUrlUtils } from '@services/utils/url';
import { CoreUtils } from '@services/utils/utils';
import { CoreStatusWithWarningsWSResponse, CoreWSExternalFile, CoreWSExternalWarning, CoreWSStoredFile } from '@services/ws';
import { makeSingleton, Translate } from '@singletons';
import { AddonModForumOffline, AddonModForumOfflineDiscussion, AddonModForumReplyOptions } from './forum-offline';
const ROOT_CACHE_KEY = 'mmaModForum:';
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModForumProvider.NEW_DISCUSSION_EVENT]: AddonModForumNewDiscussionData;
[AddonModForumProvider.REPLY_DISCUSSION_EVENT]: AddonModForumReplyDiscussionData;
[AddonModForumProvider.CHANGE_DISCUSSION_EVENT]: AddonModForumChangeDiscussionData;
[AddonModForumProvider.MARK_READ_EVENT]: AddonModForumMarkReadData;
}
}
/**
* Service that provides some features for forums.
*/
@Injectable({ providedIn: 'root' })
export class AddonModForumProvider {
static readonly COMPONENT = 'mmaModForum';
static readonly DISCUSSIONS_PER_PAGE = 10; // Max of discussions per page.
static readonly NEW_DISCUSSION_EVENT = 'addon_mod_forum_new_discussion';
static readonly REPLY_DISCUSSION_EVENT = 'addon_mod_forum_reply_discussion';
static readonly CHANGE_DISCUSSION_EVENT = 'addon_mod_forum_change_discussion_status';
static readonly MARK_READ_EVENT = 'addon_mod_forum_mark_read';
static readonly LEAVING_POSTS_PAGE = 'addon_mod_forum_leaving_posts_page';
static readonly PREFERENCE_SORTORDER = 'forum_discussionlistsortorder';
static readonly SORTORDER_LASTPOST_DESC = 1;
static readonly SORTORDER_LASTPOST_ASC = 2;
static readonly SORTORDER_CREATED_DESC = 3;
static readonly SORTORDER_CREATED_ASC = 4;
static readonly SORTORDER_REPLIES_DESC = 5;
static readonly SORTORDER_REPLIES_ASC = 6;
static readonly ALL_PARTICIPANTS = -1;
static readonly ALL_GROUPS = -2;
/**
* Get cache key for can add discussion WS calls.
*
* @param forumId Forum ID.
* @param groupId Group ID.
* @return Cache key.
*/
protected getCanAddDiscussionCacheKey(forumId: number, groupId: number): string {
return this.getCommonCanAddDiscussionCacheKey(forumId) + groupId;
}
/**
* Get common part of cache key for can add discussion WS calls.
* TODO: Use getForumDataCacheKey as a prefix.
*
* @param forumId Forum ID.
* @return Cache key.
*/
protected getCommonCanAddDiscussionCacheKey(forumId: number): string {
return ROOT_CACHE_KEY + 'canadddiscussion:' + forumId + ':';
}
/**
* Get prefix cache key for all forum activity data WS calls.
*
* @param forumId Forum ID.
* @return Cache key.
*/
protected getForumDataPrefixCacheKey(forumId: number): string {
return ROOT_CACHE_KEY + forumId;
}
/**
* Get cache key for discussion post data WS calls.
*
* @param forumId Forum ID.
* @param discussionId Discussion ID.
* @param postId Course ID.
* @return Cache key.
*/
protected getDiscussionPostDataCacheKey(forumId: number, discussionId: number, postId: number): string {
return this.getForumDiscussionDataCacheKey(forumId, discussionId) + ':post:' + postId;
}
/**
* Get cache key for forum data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getForumDiscussionDataCacheKey(forumId: number, discussionId: number): string {
return this.getForumDataPrefixCacheKey(forumId) + ':discussion:' + discussionId;
}
/**
* Get cache key for forum data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getForumDataCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'forum:' + courseId;
}
/**
* Get cache key for forum access information WS calls.
* TODO: Use getForumDataCacheKey as a prefix.
*
* @param forumId Forum ID.
* @return Cache key.
*/
protected getAccessInformationCacheKey(forumId: number): string {
return ROOT_CACHE_KEY + 'accessInformation:' + forumId;
}
/**
* Get cache key for forum discussion posts WS calls.
* TODO: Use getForumDiscussionDataCacheKey instead.
*
* @param discussionId Discussion ID.
* @return Cache key.
*/
protected getDiscussionPostsCacheKey(discussionId: number): string {
return ROOT_CACHE_KEY + 'discussion:' + discussionId;
}
/**
* Get cache key for forum discussions list WS calls.
*
* @param forumId Forum ID.
* @param sortOrder Sort order.
* @return Cache key.
*/
protected getDiscussionsListCacheKey(forumId: number, sortOrder: number): string {
let key = ROOT_CACHE_KEY + 'discussions:' + forumId;
if (sortOrder != AddonModForumProvider.SORTORDER_LASTPOST_DESC) {
key += ':' + sortOrder;
}
return key;
}
/**
* Add a new discussion. It will fail if offline or cannot connect.
*
* @param forumId Forum ID.
* @param subject New discussion's subject.
* @param message New discussion's message.
* @param options Options (subscribe, pin, ...).
* @param groupId Group this discussion belongs to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the discussion is created.
*/
async addNewDiscussionOnline(
forumId: number,
subject: string,
message: string,
options?: AddonModForumAddDiscussionWSOptionsObject,
groupId?: number,
siteId?: string,
): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumAddDiscussionWSParams = {
forumid: forumId,
subject: subject,
message: message,
// eslint-disable-next-line max-len
options: CoreUtils.objectToArrayOfObjects<AddonModForumAddDiscussionWSOptionsArray[0], AddonModForumAddDiscussionWSOptionsObject>(
options || {},
'name',
'value',
),
};
if (groupId) {
params.groupid = groupId;
}
const response = await site.write<AddonModForumAddDiscussionWSResponse>('mod_forum_add_discussion', params);
// Other errors ocurring.
return response.discussionid;
}
/**
* Check if a user can post to a certain group.
*
* @param forumId Forum ID.
* @param groupId Group ID.
* @param options Other options.
* @return Promise resolved with an object with the following properties:
* - status (boolean)
* - canpindiscussions (boolean)
* - cancreateattachment (boolean)
*/
async canAddDiscussion(
forumId: number,
groupId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModForumCanAddDiscussion> {
const params: AddonModForumCanAddDiscussionWSParams = {
forumid: forumId,
groupid: groupId,
};
const preSets = {
cacheKey: this.getCanAddDiscussionCacheKey(forumId, groupId),
component: AddonModForumProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const site = await CoreSites.getSite(options.siteId);
const result = await site.read<AddonModForumCanAddDiscussionWSResponse>('mod_forum_can_add_discussion', params, preSets);
if (!result) {
throw new Error('Invalid response calling mod_forum_can_add_discussion');
}
if (typeof result.canpindiscussions == 'undefined') {
// WS doesn't support it yet, default it to false to prevent students from seeing the option.
result.canpindiscussions = false;
}
if (typeof result.cancreateattachment == 'undefined') {
// WS doesn't support it yet, default it to true since usually the users will be able to create them.
result.cancreateattachment = true;
}
return result;
}
/**
* Check if a user can post to all groups.
*
* @param forumId Forum ID.
* @param options Other options.
* @return Promise resolved with an object with the following properties:
* - status (boolean)
* - canpindiscussions (boolean)
* - cancreateattachment (boolean)
*/
canAddDiscussionToAll(forumId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModForumCanAddDiscussion> {
return this.canAddDiscussion(forumId, AddonModForumProvider.ALL_PARTICIPANTS, options);
}
/**
* Delete a post.
*
* @param postId Post id.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
* @since 3.8
*/
async deletePost(postId: number, siteId?: string): Promise<AddonModForumDeletePostWSResponse> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumDeletePostWSParams = {
postid: postId,
};
return site.write<AddonModForumDeletePostWSResponse>('mod_forum_delete_post', params);
}
/**
* Extract the starting post of a discussion from a list of posts. The post is removed from the array passed as a parameter.
*
* @param posts Posts to search.
* @return Starting post or undefined if not found.
*/
extractStartingPost(posts: AddonModForumPost[]): AddonModForumPost | undefined {
const index = posts.findIndex((post) => !post.parentid);
return index >= 0 ? posts.splice(index, 1).pop() : undefined;
}
/**
* There was a bug adding new discussions to All Participants (see MDL-57962). Check if it's fixed.
*
* @return True if fixed, false otherwise.
*/
isAllParticipantsFixed(): boolean {
return !!CoreSites.getCurrentSite()?.isVersionGreaterEqualThan(['3.1.5', '3.2.2']);
}
/**
* Returns whether or not getDiscussionPost WS available or not.
*
* @return If WS is available.
* @since 3.8
*/
isGetDiscussionPostAvailable(): boolean {
return CoreSites.wsAvailableInCurrentSite('mod_forum_get_discussion_post');
}
/**
* Returns whether or not getDiscussionPost WS available or not.
*
* @param site Site. If not defined, current site.
* @return If WS is available.
* @since 3.7
*/
isGetDiscussionPostsAvailable(site?: CoreSite): boolean {
return site
? site.wsAvailable('mod_forum_get_discussion_posts')
: CoreSites.wsAvailableInCurrentSite('mod_forum_get_discussion_posts');
}
/**
* Returns whether or not deletePost WS available or not.
*
* @return If WS is available.
* @since 3.8
*/
isDeletePostAvailable(): boolean {
return CoreSites.wsAvailableInCurrentSite('mod_forum_delete_post');
}
/**
* Returns whether or not updatePost WS available or not.
*
* @return If WS is available.
* @since 3.8
*/
isUpdatePostAvailable(): boolean {
return CoreSites.wsAvailableInCurrentSite('mod_forum_update_discussion_post');
}
/**
* Format discussions, setting groupname if the discussion group is valid.
*
* @param cmId Forum cmid.
* @param discussions List of discussions to format.
* @return Promise resolved with the formatted discussions.
*/
formatDiscussionsGroups(cmId: number, discussions: AddonModForumDiscussion[]): Promise<AddonModForumDiscussion[]>;
formatDiscussionsGroups(cmId: number, discussions: AddonModForumOfflineDiscussion[]): Promise<AddonModForumOfflineDiscussion[]>;
formatDiscussionsGroups(
cmId: number,
discussions: AddonModForumDiscussion[] | AddonModForumOfflineDiscussion[],
): Promise<AddonModForumDiscussion[] | AddonModForumOfflineDiscussion[]> {
discussions = CoreUtils.clone(discussions);
return CoreGroups.getActivityAllowedGroups(cmId).then((result) => {
const strAllParts = Translate.instant('core.allparticipants');
const strAllGroups = Translate.instant('core.allgroups');
// Turn groups into an object where each group is identified by id.
const groups = {};
result.groups.forEach((fg) => {
groups[fg.id] = fg;
});
// Format discussions.
discussions.forEach((disc) => {
if (disc.groupid == AddonModForumProvider.ALL_PARTICIPANTS) {
disc.groupname = strAllParts;
} else if (disc.groupid == AddonModForumProvider.ALL_GROUPS) {
// Offline discussions only.
disc.groupname = strAllGroups;
} else {
const group = groups[disc.groupid];
if (group) {
disc.groupname = group.name;
}
}
});
return discussions;
}).catch(() => discussions);
}
/**
* Get all course forums.
*
* @param courseId Course ID.
* @param options Other options.
* @return Promise resolved when the forums are retrieved.
*/
async getCourseForums(courseId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModForumData[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModForumGetForumsByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getForumDataCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModForumProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy),
};
return site.read('mod_forum_get_forums_by_courses', params, preSets);
}
/**
* Get a particular discussion post.
*
* @param forumId Forum ID.
* @param discussionId Discussion ID.
* @param postId Post ID.
* @param options Other options.
* @return Promise resolved when the post is retrieved.
*/
async getDiscussionPost(
forumId: number,
discussionId: number,
postId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModForumPost> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModForumGetDiscussionPostWSParams = {
postid: postId,
};
const preSets = {
cacheKey: this.getDiscussionPostDataCacheKey(forumId, discussionId, postId),
updateFrequency: CoreSite.FREQUENCY_USUALLY,
component: AddonModForumProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModForumGetDiscussionPostWSResponse>(
'mod_forum_get_discussion_post',
params,
preSets,
);
if (!response.post) {
throw new Error('Post not found');
}
return this.translateWSPost(response.post);
}
/**
* Get a forum by course module ID.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved when the forum is retrieved.
*/
async getForum(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModForumData> {
const forums = await this.getCourseForums(courseId, options);
const forum = forums.find(forum => forum.cmid == cmId);
if (!forum) {
throw new Error('Forum not found');
}
return forum;
}
/**
* Get a forum by forum ID.
*
* @param courseId Course ID.
* @param forumId Forum ID.
* @param options Other options.
* @return Promise resolved when the forum is retrieved.
*/
async getForumById(courseId: number, forumId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModForumData> {
const forums = await this.getCourseForums(courseId, options);
const forum = forums.find(forum => forum.id === forumId);
if (!forum) {
throw new Error(`Forum with id ${forumId} not found`);
}
return forum;
}
/**
* Get access information for a given forum.
*
* @param forumId Forum ID.
* @param options Other options.
* @return Object with access information.
* @since 3.7
*/
async getAccessInformation(
forumId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModForumAccessInformation> {
const site = await CoreSites.getSite(options.siteId);
if (!site.wsAvailable('mod_forum_get_forum_access_information')) {
// Access information not available for 3.6 or older sites.
return {};
}
const params: AddonModForumGetForumAccessInformationWSParams = {
forumid: forumId,
};
const preSets = {
cacheKey: this.getAccessInformationCacheKey(forumId),
component: AddonModForumProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read<AddonModForumGetForumAccessInformationWSResponse>(
'mod_forum_get_forum_access_information',
params,
preSets,
);
}
/**
* Get forum discussion posts.
*
* @param discussionId Discussion ID.
* @param options Other options.
* @return Promise resolved with forum posts and rating info.
*/
async getDiscussionPosts(discussionId: number, options: CoreCourseCommonModWSOptions = {}): Promise<{
posts: AddonModForumPost[];
courseid?: number;
forumid?: number;
ratinginfo?: CoreRatingInfo;
}> {
// Convenience function to translate legacy data to new format.
const translateLegacyPostsFormat = (posts: AddonModForumLegacyPost[]): AddonModForumPost[] => posts.map((post) => {
const newPost: AddonModForumPost = {
id: post.id,
discussionid: post.discussion,
parentid: post.parent,
hasparent: !!post.parent,
author: {
id: post.userid,
fullname: post.userfullname,
urls: { profileimage: post.userpictureurl },
},
timecreated: post.created,
subject: post.subject,
message: post.message,
attachments: post.attachments,
capabilities: {
reply: !!post.canreply,
},
unread: !post.postread,
isprivatereply: !!post.isprivatereply,
tags: post.tags,
};
if ('groupname' in post && typeof post['groupname'] === 'string') {
newPost.author['groups'] = [{ name: post['groupname'] }];
}
return newPost;
});
// For some reason, the new WS doesn't use the tags exporter so it returns a different format than other WebServices.
// Convert the new format to the exporter one so it's the same as in other WebServices.
const translateTagsFormatToLegacy = (posts: AddonModForumWSPost[]): AddonModForumPost[] => {
posts.forEach(post => this.translateWSPost(post));
return posts as unknown as AddonModForumPost[];
};
const params: AddonModForumGetDiscussionPostsWSParams | AddonModForumGetForumDiscussionPostsWSParams = {
discussionid: discussionId,
};
const preSets = {
cacheKey: this.getDiscussionPostsCacheKey(discussionId),
component: AddonModForumProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const site = await CoreSites.getSite(options.siteId);
const isGetDiscussionPostsAvailable = this.isGetDiscussionPostsAvailable(site);
const response = isGetDiscussionPostsAvailable
? await site.read<AddonModForumGetDiscussionPostsWSResponse>('mod_forum_get_discussion_posts', params, preSets)
: await site.read<AddonModForumGetForumDiscussionPostsWSResponse>(
'mod_forum_get_forum_discussion_posts',
params,
preSets,
);
if (!response) {
throw new Error('Could not get forum posts');
}
const posts = isGetDiscussionPostsAvailable
? translateTagsFormatToLegacy((response as AddonModForumGetDiscussionPostsWSResponse).posts)
: translateLegacyPostsFormat((response as AddonModForumGetForumDiscussionPostsWSResponse).posts);
this.storeUserData(posts);
return {
...response,
posts,
};
}
/**
* Sort forum discussion posts by an specified field.
*
* @param posts Discussion posts to be sorted in place.
* @param direction Direction of the sorting (ASC / DESC).
*/
sortDiscussionPosts(posts: AddonModForumPost[], direction: string): void {
// @todo: Check children when sorting.
posts.sort((a, b) => {
const timeCreatedA = Number(a.timecreated) || 0;
const timeCreatedB = Number(b.timecreated) || 0;
if (timeCreatedA == 0 || timeCreatedB == 0) {
// Leave 0 at the end.
return timeCreatedB - timeCreatedA;
}
if (direction == 'ASC') {
return timeCreatedA - timeCreatedB;
} else {
return timeCreatedB - timeCreatedA;
}
});
}
/**
* Return whether discussion lists can be sorted.
*
* @param site Site. If not defined, current site.
* @return True if discussion lists can be sorted.
*/
isDiscussionListSortingAvailable(site?: CoreSite): boolean {
site = site || CoreSites.getCurrentSite();
return !!site?.isVersionGreaterEqualThan('3.7');
}
/**
* Return the list of available sort orders.
*
* @return List of sort orders.
*/
getAvailableSortOrders(): AddonModForumSortOrder[] {
const sortOrders = [
{
label: 'addon.mod_forum.discussionlistsortbylastpostdesc',
value: AddonModForumProvider.SORTORDER_LASTPOST_DESC,
},
];
if (this.isDiscussionListSortingAvailable()) {
sortOrders.push(
{
label: 'addon.mod_forum.discussionlistsortbylastpostasc',
value: AddonModForumProvider.SORTORDER_LASTPOST_ASC,
},
{
label: 'addon.mod_forum.discussionlistsortbycreateddesc',
value: AddonModForumProvider.SORTORDER_CREATED_DESC,
},
{
label: 'addon.mod_forum.discussionlistsortbycreatedasc',
value: AddonModForumProvider.SORTORDER_CREATED_ASC,
},
{
label: 'addon.mod_forum.discussionlistsortbyrepliesdesc',
value: AddonModForumProvider.SORTORDER_REPLIES_DESC,
},
{
label: 'addon.mod_forum.discussionlistsortbyrepliesasc',
value: AddonModForumProvider.SORTORDER_REPLIES_ASC,
},
);
}
return sortOrders;
}
/**
* Get forum discussions.
*
* @param forumId Forum ID.
* @param options Other options.
* @return Promise resolved with an object with:
* - discussions: List of discussions. Note that for every discussion in the list discussion.id is the main post ID but
* discussion ID is discussion.discussion.
* - canLoadMore: True if there may be more discussions to load.
*/
async getDiscussions(
forumId: number,
options: AddonModForumGetDiscussionsOptions = {},
): Promise<{ discussions: AddonModForumDiscussion[]; canLoadMore: boolean }> {
options.sortOrder = options.sortOrder || AddonModForumProvider.SORTORDER_LASTPOST_DESC;
options.page = options.page || 0;
const site = await CoreSites.getSite(options.siteId);
let method = 'mod_forum_get_forum_discussions_paginated';
const params: AddonModForumGetForumDiscussionsPaginatedWSParams | AddonModForumGetForumDiscussionsWSParams = {
forumid: forumId,
page: options.page,
perpage: AddonModForumProvider.DISCUSSIONS_PER_PAGE,
};
if (site.wsAvailable('mod_forum_get_forum_discussions')) {
// Since Moodle 3.7.
method = 'mod_forum_get_forum_discussions';
(params as AddonModForumGetForumDiscussionsWSParams).sortorder = options.sortOrder;
} else {
if (options.sortOrder !== AddonModForumProvider.SORTORDER_LASTPOST_DESC) {
throw new Error('Sorting not supported with the old WS method.');
}
(params as AddonModForumGetForumDiscussionsPaginatedWSParams).sortby = 'timemodified';
(params as AddonModForumGetForumDiscussionsPaginatedWSParams).sortdirection = 'DESC';
}
const preSets = {
cacheKey: this.getDiscussionsListCacheKey(forumId, options.sortOrder),
component: AddonModForumProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
let response: AddonModForumGetForumDiscussionsPaginatedWSResponse | AddonModForumGetForumDiscussionsWSResponse;
try {
// eslint-disable-next-line max-len
response = await site.read<AddonModForumGetForumDiscussionsPaginatedWSResponse | AddonModForumGetForumDiscussionsWSResponse>(
method,
params,
preSets,
);
} catch (error) {
// Try to get the data from cache stored with the old WS method.
if (
CoreApp.isOnline() ||
method !== 'mod_forum_get_forum_discussions' ||
options.sortOrder !== AddonModForumProvider.SORTORDER_LASTPOST_DESC
) {
throw error;
}
const params: AddonModForumGetForumDiscussionsPaginatedWSParams = {
forumid: forumId,
page: options.page,
perpage: AddonModForumProvider.DISCUSSIONS_PER_PAGE,
sortby: 'timemodified',
sortdirection: 'DESC',
};
Object.assign(preSets, CoreSites.getReadingStrategyPreSets(CoreSitesReadingStrategy.PREFER_CACHE));
response = await site.read<AddonModForumGetForumDiscussionsPaginatedWSResponse>(
'mod_forum_get_forum_discussions_paginated',
params,
preSets,
);
}
if (!response) {
throw new Error('Could not get discussions');
}
this.storeUserData(response.discussions);
return {
discussions: response.discussions,
canLoadMore: response.discussions.length >= AddonModForumProvider.DISCUSSIONS_PER_PAGE,
};
}
/**
* Get forum discussions in several pages.
* If a page fails, the discussions until that page will be returned along with a flag indicating an error occurred.
*
* @param forumId Forum ID.
* @param cmId Forum cmid.
* @param sortOrder Sort order.
* @param forceCache True to always get the value from cache, false otherwise.
* @param numPages Number of pages to get. If not defined, all pages.
* @param startPage Page to start. If not defined, first page.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with an object with:
* - discussions: List of discussions.
* - error: True if an error occurred, false otherwise.
*/
async getDiscussionsInPages(
forumId: number,
options: AddonModForumGetDiscussionsInPagesOptions = {},
): Promise<{ discussions: AddonModForumDiscussion[]; error: boolean }> {
options.page = options.page || 0;
const result = {
discussions: [] as AddonModForumDiscussion[],
error: false,
};
let numPages = typeof options.numPages == 'undefined' ? -1 : options.numPages;
if (!numPages) {
return result;
}
const getPage = (page: number): Promise<{ discussions: AddonModForumDiscussion[]; error: boolean }> =>
// Get page discussions.
this.getDiscussions(forumId, options).then((response) => {
result.discussions = result.discussions.concat(response.discussions);
numPages--;
if (response.canLoadMore && numPages !== 0) {
return getPage(page + 1); // Get next page.
} else {
return result;
}
}).catch(() => {
// Error getting a page.
result.error = true;
return result;
})
;
return getPage(options.page);
}
/**
* Invalidates can add discussion WS calls.
*
* @param forumId Forum ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateCanAddDiscussion(forumId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getCommonCanAddDiscussionCacheKey(forumId));
}
/**
* Invalidate the prefetched content except files.
*
* @param moduleId The module ID.
* @param courseId Course ID.
* @return Promise resolved when data is invalidated.
*/
async invalidateContent(moduleId: number, courseId: number): Promise<void> {
// Get the forum first, we need the forum ID.
const forum = await this.getForum(courseId, moduleId);
const promises: Promise<void>[] = [];
promises.push(this.invalidateForumData(courseId));
promises.push(this.invalidateDiscussionsList(forum.id));
promises.push(this.invalidateCanAddDiscussion(forum.id));
promises.push(this.invalidateAccessInformation(forum.id));
this.getAvailableSortOrders().forEach((sortOrder) => {
// We need to get the list of discussions to be able to invalidate their posts.
promises.push(
this
.getDiscussionsInPages(forum.id, {
cmId: forum.cmid,
sortOrder: sortOrder.value,
readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE,
})
.then((response) => {
// Now invalidate the WS calls.
const promises: Promise<void>[] = [];
response.discussions.forEach((discussion) => {
promises.push(this.invalidateDiscussionPosts(discussion.discussion, forum.id));
});
return CoreUtils.allPromises(promises);
}),
);
});
if (this.isDiscussionListSortingAvailable()) {
promises.push(CoreUser.invalidateUserPreference(AddonModForumProvider.PREFERENCE_SORTORDER));
}
return CoreUtils.allPromises(promises);
}
/**
* Invalidates access information.
*
* @param forumId Forum ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAccessInformation(forumId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(forumId));
}
/**
* Invalidates forum discussion posts.
*
* @param discussionId Discussion ID.
* @param forumId Forum ID. If not set, we can't invalidate individual post information.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateDiscussionPosts(discussionId: number, forumId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const promises = [site.invalidateWsCacheForKey(this.getDiscussionPostsCacheKey(discussionId))];
if (forumId) {
promises.push(site.invalidateWsCacheForKeyStartingWith(this.getForumDiscussionDataCacheKey(forumId, discussionId)));
}
await CoreUtils.allPromises(promises);
}
/**
* Invalidates discussion list.
*
* @param forumId Forum ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateDiscussionsList(forumId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await CoreUtils.allPromises(
this.getAvailableSortOrders()
.map(sortOrder => site.invalidateWsCacheForKey(this.getDiscussionsListCacheKey(forumId, sortOrder.value))),
);
}
/**
* Invalidates forum data.
*
* @param courseId Course ID.
* @return Promise resolved when the data is invalidated.
*/
async invalidateForumData(courseId: number): Promise<void> {
const site = CoreSites.getCurrentSite();
await site?.invalidateWsCacheForKey(this.getForumDataCacheKey(courseId));
}
/**
* Report a forum as being viewed.
*
* @param id Module ID.
* @param name Name of the forum.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
logView(id: number, name?: string, siteId?: string): Promise<void> {
const params = {
forumid: id,
};
return CoreCourseLogHelper.logSingle(
'mod_forum_view_forum',
params,
AddonModForumProvider.COMPONENT,
id,
name,
'forum',
{},
siteId,
);
}
/**
* Report a forum discussion as being viewed.
*
* @param id Discussion ID.
* @param forumId Forum ID.
* @param name Name of the forum.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
logDiscussionView(id: number, forumId: number, name?: string, siteId?: string): Promise<void> {
const params = {
discussionid: id,
};
return CoreCourseLogHelper.logSingle(
'mod_forum_view_forum_discussion',
params,
AddonModForumProvider.COMPONENT,
forumId,
name,
'forum',
params,
siteId,
);
}
/**
* Reply to a certain post.
*
* @param postId ID of the post being replied.
* @param discussionId ID of the discussion the user is replying to.
* @param forumId ID of the forum the user is replying to.
* @param name Forum name.
* @param courseId Course ID the forum belongs to.
* @param subject New post's subject.
* @param message New post's message.
* @param options Options (subscribe, attachments, ...).
* @param siteId Site ID. If not defined, current site.
* @param allowOffline True if it can be stored in offline, false otherwise.
* @return Promise resolved with a boolean indicating if the test was sent online or not.
*/
async replyPost(
postId: number,
discussionId: number,
forumId: number,
name: string,
courseId: number,
subject: string,
message: string,
options?: AddonModForumReplyOptions,
siteId?: string,
allowOffline?: boolean,
): Promise<boolean> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = async (): Promise<boolean> => {
if (!forumId) {
// Not enough data to store in offline, reject.
throw new Error(Translate.instant('core.networkerrormsg'));
}
await AddonModForumOffline.replyPost(
postId,
discussionId,
forumId,
name,
courseId,
subject,
message,
options,
siteId,
);
return false;
};
if (!CoreApp.isOnline() && allowOffline) {
// App is offline, store the action.
return storeOffline();
}
// If there's already a reply to be sent to the server, discard it first.
try {
await AddonModForumOffline.deleteReply(postId, siteId);
await this.replyPostOnline(
postId,
subject,
message,
options as unknown as AddonModForumAddDiscussionPostWSOptionsObject,
siteId,
);
return true;
} catch (error) {
if (allowOffline && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
} else {
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
}
/**
* Reply to a certain post. It will fail if offline or cannot connect.
*
* @param postId ID of the post being replied.
* @param subject New post's subject.
* @param message New post's message.
* @param options Options (subscribe, attachments, ...).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the created post id.
*/
async replyPostOnline(
postId: number,
subject: string,
message: string,
options?: AddonModForumAddDiscussionPostWSOptionsObject,
siteId?: string,
): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumAddDiscussionPostWSParams = {
postid: postId,
subject: subject,
message: message,
options: CoreUtils.objectToArrayOfObjects<
AddonModForumAddDiscussionPostWSOptionsArray[0],
AddonModForumAddDiscussionPostWSOptionsObject
>(
options || {},
'name',
'value',
),
};
const response = await site.write<AddonModForumAddDiscussionPostWSResponse>('mod_forum_add_discussion_post', params);
if (!response || !response.postid) {
throw new Error('Post id missing from response');
}
return response.postid;
}
/**
* Lock or unlock a discussion.
*
* @param forumId Forum id.
* @param discussionId DIscussion id.
* @param locked True to lock, false to unlock.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
* @since 3.7
*/
async setLockState(
forumId: number,
discussionId: number,
locked: boolean,
siteId?: string,
): Promise<AddonModForumSetLockStateWSResponse> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumSetLockStateWSParams = {
forumid: forumId,
discussionid: discussionId,
targetstate: locked ? 0 : 1,
};
return site.write<AddonModForumSetLockStateWSResponse>('mod_forum_set_lock_state', params);
}
/**
* Returns whether the set pin state WS is available.
*
* @param site Site. If not defined, current site.
* @return Whether it's available.
* @since 3.7
*/
isSetPinStateAvailableForSite(): boolean {
return CoreSites.wsAvailableInCurrentSite('mod_forum_set_pin_state');
}
/**
* Pin or unpin a discussion.
*
* @param discussionId Discussion id.
* @param locked True to pin, false to unpin.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
* @since 3.7
*/
async setPinState(discussionId: number, pinned: boolean, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumSetPinStateWSParams = {
discussionid: discussionId,
targetstate: pinned ? 1 : 0,
};
await site.write<AddonModForumSetPinStateWSResponse>('mod_forum_set_pin_state', params);
}
/**
* Star or unstar a discussion.
*
* @param discussionId Discussion id.
* @param starred True to star, false to unstar.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
* @since 3.7
*/
async toggleFavouriteState(discussionId: number, starred: boolean, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumToggleFavouriteStateWSParams = {
discussionid: discussionId,
targetstate: starred,
};
await site.write<AddonModForumToggleFavouriteStateWSResponse>('mod_forum_toggle_favourite_state', params);
}
/**
* Store the users data from a discussions/posts list.
*
* @param list Array of posts or discussions.
*/
protected storeUserData(list: AddonModForumPost[] | AddonModForumDiscussion[]): void {
const users = {};
list.forEach((entry: AddonModForumPost | AddonModForumDiscussion) => {
if ('author' in entry) {
const authorId = Number(entry.author.id);
if (!isNaN(authorId) && !users[authorId]) {
users[authorId] = {
id: entry.author.id,
fullname: entry.author.fullname,
profileimageurl: entry.author.urls?.profileimage,
};
}
}
const userId = parseInt(entry['userid']);
if ('userid' in entry && !isNaN(userId) && !users[userId]) {
users[userId] = {
id: userId,
fullname: entry.userfullname,
profileimageurl: entry.userpictureurl,
};
}
const userModified = parseInt(entry['usermodified']);
if ('usermodified' in entry && !isNaN(userModified) && !users[userModified]) {
users[userModified] = {
id: userModified,
fullname: entry.usermodifiedfullname,
profileimageurl: entry.usermodifiedpictureurl,
};
}
});
CoreUser.storeUsers(CoreUtils.objectToArray(users));
}
/**
* Update a certain post.
*
* @param postId ID of the post being edited.
* @param subject New post's subject.
* @param message New post's message.
* @param options Options (subscribe, attachments, ...).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with success boolean when done.
*/
async updatePost(
postId: number,
subject: string,
message: string,
options?: AddonModForumUpdateDiscussionPostWSOptionsObject,
siteId?: string,
): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
const params: AddonModForumUpdateDiscussionPostWSParams = {
postid: postId,
subject: subject,
message: message,
options: CoreUtils.objectToArrayOfObjects<
AddonModForumUpdateDiscussionPostWSOptionsArray[0],
AddonModForumUpdateDiscussionPostWSOptionsObject
>(
options || {},
'name',
'value',
),
};
const response = await site.write<AddonModForumUpdateDiscussionPostWSResponse>('mod_forum_update_discussion_post', params);
return response && response.status;
}
/**
* For some reason, the new WS doesn't use the tags exporter so it returns a different format than other WebServices.
* Convert the new format to the exporter one so it's the same as in other WebServices.
*
* @param post Post returned by the new WS.
* @return Post using the same format as other WebServices.
*/
protected translateWSPost(post: AddonModForumWSPost): AddonModForumPost {
(post as unknown as AddonModForumPost).tags = (post.tags || []).map((tag) => {
const viewUrl = (tag.urls && tag.urls.view) || '';
const params = CoreUrlUtils.extractUrlParams(viewUrl);
return {
id: tag.tagid,
taginstanceid: tag.id,
flag: tag.flag ? 1 : 0,
isstandard: tag.isstandard,
rawname: tag.displayname,
name: tag.displayname,
tagcollid: params.tc ? Number(params.tc) : undefined,
taginstancecontextid: params.from ? Number(params.from) : undefined,
};
});
return post as unknown as AddonModForumPost;
}
}
export const AddonModForum = makeSingleton(AddonModForumProvider);
/**
* Params of mod_forum_get_forums_by_courses WS.
*/
type AddonModForumGetForumsByCoursesWSParams = {
courseids?: number[]; // Array of Course IDs.
};
/**
* General forum activity data.
*/
export type AddonModForumData = {
id: number; // Forum id.
course: number; // Course id.
type: string; // The forum type.
name: string; // Forum name.
intro: string; // The forum intro.
introformat: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
introfiles?: CoreWSExternalFile[];
duedate?: number; // Duedate for the user.
cutoffdate?: number; // Cutoffdate for the user.
assessed: number; // Aggregate type.
assesstimestart: number; // Assess start time.
assesstimefinish: number; // Assess finish time.
scale: number; // Scale.
// eslint-disable-next-line @typescript-eslint/naming-convention
grade_forum: number; // Whole forum grade.
// eslint-disable-next-line @typescript-eslint/naming-convention
grade_forum_notify: number; // Whether to send notifications to students upon grading by default.
maxbytes: number; // Maximum attachment size.
maxattachments: number; // Maximum number of attachments.
forcesubscribe: number; // Force users to subscribe.
trackingtype: number; // Subscription mode.
rsstype: number; // RSS feed for this activity.
rssarticles: number; // Number of RSS recent articles.
timemodified: number; // Time modified.
warnafter: number; // Post threshold for warning.
blockafter: number; // Post threshold for blocking.
blockperiod: number; // Time period for blocking.
completiondiscussions: number; // Student must create discussions.
completionreplies: number; // Student must post replies.
completionposts: number; // Student must post discussions or replies.
cmid: number; // Course module id.
numdiscussions?: number; // Number of discussions in the forum.
cancreatediscussions?: boolean; // If the user can create discussions.
lockdiscussionafter?: number; // After what period a discussion is locked.
istracked?: boolean; // If the user is tracking the forum.
unreadpostscount?: number; // The number of unread posts for tracked forums.
};
/**
* Forum discussion.
*/
export type AddonModForumDiscussion = {
id: number; // Post id.
name: string; // Discussion name.
groupid: number; // Group id.
groupname?: string; // Group name (not returned by WS).
timemodified: number; // Time modified.
usermodified: number; // The id of the user who last modified.
timestart: number; // Time discussion can start.
timeend: number; // Time discussion ends.
discussion: number; // Discussion id.
parent: number; // Parent id.
userid: number; // User who started the discussion id.
created: number; // Creation time.
modified: number; // Time modified.
mailed: number; // Mailed?.
subject: string; // The post subject.
message: string; // The post message.
messageformat: number; // Message format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
messagetrust: number; // Can we trust?.
messageinlinefiles?: CoreWSExternalFile[];
attachment: string; // Has attachments?.
attachments?: CoreWSExternalFile[];
totalscore: number; // The post message total score.
mailnow: number; // Mail now?.
userfullname: string | boolean; // Post author full name.
usermodifiedfullname: string; // Post modifier full name.
userpictureurl?: string; // Post author picture.
usermodifiedpictureurl: string; // Post modifier picture.
numreplies: number; // The number of replies in the discussion.
numunread: number; // The number of unread discussions.
pinned: boolean; // Is the discussion pinned.
locked: boolean; // Is the discussion locked.
starred?: boolean; // Is the discussion starred.
canreply: boolean; // Can the user reply to the discussion.
canlock: boolean; // Can the user lock the discussion.
canfavourite?: boolean; // Can the user star the discussion.
};
/**
* Forum post data returned by web services.
*/
export type AddonModForumPost = {
id: number; // Id.
subject: string; // Subject.
replysubject?: string; // Replysubject.
message: string; // Message.
author: {
id?: number; // Id.
fullname?: string; // Fullname.
urls?: {
profileimage?: string; // The URL for the use profile image.
};
groups?: { // Groups.
name: string; // Name.
}[];
};
discussionid: number; // Discussionid.
hasparent: boolean; // Hasparent.
parentid?: number; // Parentid.
timecreated: number | false; // Timecreated.
unread?: boolean; // Unread.
isprivatereply: boolean; // Isprivatereply.
capabilities: {
reply: boolean; // Whether the user can reply to the post.
view?: boolean; // Whether the user can view the post.
edit?: boolean; // Whether the user can edit the post.
delete?: boolean; // Whether the user can delete the post.
split?: boolean; // Whether the user can split the post.
selfenrol?: boolean; // Whether the user can self enrol into the course.
export?: boolean; // Whether the user can export the post.
controlreadstatus?: boolean; // Whether the user can control the read status of the post.
canreplyprivately?: boolean; // Whether the user can post a private reply.
};
attachment?: 0 | 1;
attachments?: CoreFileEntry[];
messageinlinefiles?: CoreWSExternalFile[];
haswordcount?: boolean; // Haswordcount.
wordcount?: number; // Wordcount.
tags?: { // Tags.
id: number; // Tag id.
name: string; // Tag name.
rawname: string; // The raw, unnormalised name for the tag as entered by users.
// isstandard: boolean; // Whether this tag is standard.
tagcollid?: number; // Tag collection id.
taginstanceid: number; // Tag instance id.
taginstancecontextid?: number; // Context the tag instance belongs to.
// itemid: number; // Id of the record tagged.
// ordering: number; // Tag ordering.
flag: number; // Whether the tag is flagged as inappropriate.
}[];
};
/**
* Legacy forum post data.
*/
export type AddonModForumLegacyPost = {
id: number; // Post id.
discussion: number; // Discussion id.
parent: number; // Parent id.
userid: number; // User id.
created: number; // Creation time.
modified: number; // Time modified.
mailed: number; // Mailed?.
subject: string; // The post subject.
message: string; // The post message.
messageformat: number; // Message format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
messagetrust: number; // Can we trust?.
messageinlinefiles?: CoreWSExternalFile[];
attachment: string; // Has attachments?.
attachments?: CoreWSExternalFile[];
totalscore: number; // The post message total score.
mailnow: number; // Mail now?.
children: number[];
canreply: boolean; // The user can reply to posts?.
postread: boolean; // The post was read.
userfullname: string; // Post author full name.
userpictureurl?: string; // Post author picture.
deleted: boolean; // This post has been removed.
isprivatereply: boolean; // The post is a private reply.
tags?: CoreTagItem[]; // Tags.
};
/**
* Options to pass to get discussions.
*/
export type AddonModForumGetDiscussionsOptions = CoreCourseCommonModWSOptions & {
sortOrder?: number; // Sort order.
page?: number; // Page. Defaults to 0.
};
/**
* Options to pass to get discussions in pages.
*/
export type AddonModForumGetDiscussionsInPagesOptions = AddonModForumGetDiscussionsOptions & {
numPages?: number; // Number of pages to get. If not defined, all pages.
};
/**
* Forum access information.
*/
export type AddonModForumAccessInformation = {
canaddinstance?: boolean; // Whether the user has the capability mod/forum:addinstance allowed.
canviewdiscussion?: boolean; // Whether the user has the capability mod/forum:viewdiscussion allowed.
canviewhiddentimedposts?: boolean; // Whether the user has the capability mod/forum:viewhiddentimedposts allowed.
canstartdiscussion?: boolean; // Whether the user has the capability mod/forum:startdiscussion allowed.
canreplypost?: boolean; // Whether the user has the capability mod/forum:replypost allowed.
canaddnews?: boolean; // Whether the user has the capability mod/forum:addnews allowed.
canreplynews?: boolean; // Whether the user has the capability mod/forum:replynews allowed.
canviewrating?: boolean; // Whether the user has the capability mod/forum:viewrating allowed.
canviewanyrating?: boolean; // Whether the user has the capability mod/forum:viewanyrating allowed.
canviewallratings?: boolean; // Whether the user has the capability mod/forum:viewallratings allowed.
canrate?: boolean; // Whether the user has the capability mod/forum:rate allowed.
canpostprivatereply?: boolean; // Whether the user has the capability mod/forum:postprivatereply allowed.
canreadprivatereplies?: boolean; // Whether the user has the capability mod/forum:readprivatereplies allowed.
cancreateattachment?: boolean; // Whether the user has the capability mod/forum:createattachment allowed.
candeleteownpost?: boolean; // Whether the user has the capability mod/forum:deleteownpost allowed.
candeleteanypost?: boolean; // Whether the user has the capability mod/forum:deleteanypost allowed.
cansplitdiscussions?: boolean; // Whether the user has the capability mod/forum:splitdiscussions allowed.
canmovediscussions?: boolean; // Whether the user has the capability mod/forum:movediscussions allowed.
canpindiscussions?: boolean; // Whether the user has the capability mod/forum:pindiscussions allowed.
caneditanypost?: boolean; // Whether the user has the capability mod/forum:editanypost allowed.
canviewqandawithoutposting?: boolean; // Whether the user has the capability mod/forum:viewqandawithoutposting allowed.
canviewsubscribers?: boolean; // Whether the user has the capability mod/forum:viewsubscribers allowed.
canmanagesubscriptions?: boolean; // Whether the user has the capability mod/forum:managesubscriptions allowed.
canpostwithoutthrottling?: boolean; // Whether the user has the capability mod/forum:postwithoutthrottling allowed.
canexportdiscussion?: boolean; // Whether the user has the capability mod/forum:exportdiscussion allowed.
canexportforum?: boolean; // Whether the user has the capability mod/forum:exportforum allowed.
canexportpost?: boolean; // Whether the user has the capability mod/forum:exportpost allowed.
canexportownpost?: boolean; // Whether the user has the capability mod/forum:exportownpost allowed.
canaddquestion?: boolean; // Whether the user has the capability mod/forum:addquestion allowed.
canallowforcesubscribe?: boolean; // Whether the user has the capability mod/forum:allowforcesubscribe allowed.
cancanposttomygroups?: boolean; // Whether the user has the capability mod/forum:canposttomygroups allowed.
cancanoverridediscussionlock?: boolean; // Whether the user has the capability mod/forum:canoverridediscussionlock allowed.
cancanoverridecutoff?: boolean; // Whether the user has the capability mod/forum:canoverridecutoff allowed.
cancantogglefavourite?: boolean; // Whether the user has the capability mod/forum:cantogglefavourite allowed.
cangrade?: boolean; // Whether the user has the capability mod/forum:grade allowed.
};
/**
* Reply info.
*/
export type AddonModForumReply = {
id: number;
subject: string | null; // Null means original data is not set.
message: string | null; // Null means empty or just white space.
files: CoreFileEntry[];
replyingTo?: number;
isEditing?: boolean;
isprivatereply?: boolean;
};
/**
* Can add discussion info.
*/
export type AddonModForumCanAddDiscussion = {
status: boolean; // True if the user can add discussions, false otherwise.
canpindiscussions?: boolean; // True if the user can pin discussions, false otherwise.
cancreateattachment?: boolean; // True if the user can add attachments, false otherwise.
};
/**
* Sorting order.
*/
export type AddonModForumSortOrder = {
label: string;
value: number;
};
/**
* Forum post data returned by web services.
*/
export type AddonModForumWSPost = {
id: number; // Id.
subject: string; // Subject.
replysubject: string; // Replysubject.
message: string; // Message.
messageformat: number; // Message format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
author: {
id?: number; // Id.
fullname?: string; // Fullname.
isdeleted?: boolean; // Isdeleted.
groups?: { // Groups.
id: number; // Id.
name: string; // Name.
urls: {
image?: string; // Image.
};
}[];
urls: {
profile?: string; // The URL for the use profile page.
profileimage?: string; // The URL for the use profile image.
};
};
discussionid: number; // Discussionid.
hasparent: boolean; // Hasparent.
parentid?: number; // Parentid.
timecreated: number; // Timecreated.
unread?: boolean; // Unread.
isdeleted: boolean; // Isdeleted.
isprivatereply: boolean; // Isprivatereply.
haswordcount: boolean; // Haswordcount.
wordcount?: number; // Wordcount.
charcount?: number; // Charcount.
capabilities: {
view: boolean; // Whether the user can view the post.
edit: boolean; // Whether the user can edit the post.
delete: boolean; // Whether the user can delete the post.
split: boolean; // Whether the user can split the post.
reply: boolean; // Whether the user can reply to the post.
selfenrol: boolean; // Whether the user can self enrol into the course.
export: boolean; // Whether the user can export the post.
controlreadstatus: boolean; // Whether the user can control the read status of the post.
canreplyprivately: boolean; // Whether the user can post a private reply.
};
urls?: {
view?: string; // The URL used to view the post.
viewisolated?: string; // The URL used to view the post in isolation.
viewparent?: string; // The URL used to view the parent of the post.
edit?: string; // The URL used to edit the post.
delete?: string; // The URL used to delete the post.
// The URL used to split the discussion with the selected post being the first post in the new discussion.
split?: string;
reply?: string; // The URL used to reply to the post.
export?: string; // The URL used to export the post.
markasread?: string; // The URL used to mark the post as read.
markasunread?: string; // The URL used to mark the post as unread.
discuss?: string; // Discuss.
};
attachments: CoreWSStoredFile[]; // Attachments.
tags?: { // Tags.
id: number; // The ID of the Tag.
tagid: number; // The tagid.
isstandard: boolean; // Whether this is a standard tag.
displayname: string; // The display name of the tag.
flag: boolean; // Wehther this tag is flagged.
urls: {
view: string; // The URL to view the tag.
};
}[];
html?: {
rating?: string; // The HTML source to rate the post.
taglist?: string; // The HTML source to view the list of tags.
authorsubheading?: string; // The HTML source to view the author details.
};
};
/**
* Params of mod_forum_get_forum_discussions WS.
*/
export type AddonModForumGetForumDiscussionsWSParams = {
forumid: number; // Forum instance id.
sortorder?: number; // Sort by this element: numreplies, , created or timemodified.
page?: number; // Current page.
perpage?: number; // Items per page.
groupid?: number; // Group id.
};
/**
* Data returned by mod_forum_get_forum_discussions WS.
*/
export type AddonModForumGetForumDiscussionsWSResponse = {
discussions: AddonModForumDiscussion[];
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_forum_get_forum_discussions_paginated WS.
*/
export type AddonModForumGetForumDiscussionsPaginatedWSParams = {
forumid: number; // Forum instance id.
sortby?: string; // Sort by this element: id, timemodified, timestart or timeend.
sortdirection?: string; // Sort direction: ASC or DESC.
page?: number; // Current page.
perpage?: number; // Items per page.
};
/**
* Data returned by mod_forum_get_forum_discussions_paginated WS.
*/
export type AddonModForumGetForumDiscussionsPaginatedWSResponse = {
discussions: AddonModForumDiscussion[];
warnings?: CoreWSExternalWarning[];
};
/**
* Data returned by mod_forum_get_forums_by_courses WS.
*/
export type AddonModForumGetForumsByCoursesWSResponse = AddonModForumData[];
/**
* Array options of mod_forum_add_discussion WS.
*/
export type AddonModForumAddDiscussionWSOptionsArray = {
// Option name.
name: 'discussionsubscribe' | 'discussionpinned' | 'inlineattachmentsid' | 'attachmentsid';
// Option value.
// This param is validated in the external function, expected values are:
// discussionsubscribe (bool) - subscribe to the discussion?, default to true
// discussionpinned (bool) - is the discussion pinned, default to false
// inlineattachmentsid (int) - the draft file area id for inline attachments
// attachmentsid (int) - the draft file area id for attachments.
value: string;
}[];
/**
* Object options of mod_forum_add_discussion WS.
*/
export type AddonModForumAddDiscussionWSOptionsObject = {
discussionsubscribe?: string;
discussionpinned?: string;
inlineattachmentsid?: string;
attachmentsid?: string;
};
/**
* Array options of mod_forum_add_discussion_post WS.
*/
export type AddonModForumAddDiscussionPostWSOptionsArray = {
// Option name.
name: 'discussionsubscribe' | 'private' | 'inlineattachmentsid' | 'attachmentsid' | 'topreferredformat';
// Option value.
// This param is validated in the external function, expected values are:
// discussionsubscribe (bool) - subscribe to the discussion?, default to true
// private (bool) - make this reply private to the author of the parent post, default to false.
// inlineattachmentsid (int) - the draft file area id for inline attachments
// attachmentsid (int) - the draft file area id for attachments
// topreferredformat (bool) - convert the message & messageformat to FORMAT_HTML, defaults to false.
value: string;
}[];
/**
* Object options of mod_forum_add_discussion_post WS.
*/
export type AddonModForumAddDiscussionPostWSOptionsObject = {
discussionsubscribe?: boolean;
private?: boolean;
inlineattachmentsid?: number;
attachmentsid?: number;
topreferredformat?: boolean;
};
/**
* Array options of mod_forum_update_discussion_post WS.
*/
export type AddonModForumUpdateDiscussionPostWSOptionsArray = {
// Option name.
name: 'pinned' | 'discussionsubscribe' | 'inlineattachmentsid' | 'attachmentsid';
// Option value.
// This param is validated in the external function, expected values are:
// pinned (bool) - (only for discussions) whether to pin this discussion or not
// discussionsubscribe (bool) - whether to subscribe to the post or not
// inlineattachmentsid (int) - the draft file area id for inline attachments in the text
// attachmentsid (int) - the draft file area id for attachments.
value: string; // The value of the option.
}[];
/**
* Object options of mod_forum_update_discussion_post WS.
*/
export type AddonModForumUpdateDiscussionPostWSOptionsObject = {
pinned?: boolean;
discussionsubscribe?: boolean;
inlineattachmentsid?: number;
attachmentsid?: number;
};
/**
* Params of mod_forum_add_discussion WS.
*/
export type AddonModForumAddDiscussionWSParams = {
forumid: number; // Forum instance ID.
subject: string; // New Discussion subject.
message: string; // New Discussion message (only html format allowed).
groupid?: number; // The group, default to 0.
options?: AddonModForumAddDiscussionWSOptionsArray;
};
/**
* Data returned by mod_forum_add_discussion WS.
*/
export type AddonModForumAddDiscussionWSResponse = {
discussionid: number; // New Discussion ID.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_forum_add_discussion_post WS.
*/
export type AddonModForumAddDiscussionPostWSParams = {
postid: number; // The post id we are going to reply to (can be the initial discussion post).
subject: string; // New post subject.
message: string; // New post message (html assumed if messageformat is not provided).
options?: AddonModForumAddDiscussionPostWSOptionsArray;
messageformat?: number; // Message format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
};
/**
* Data returned by mod_forum_add_discussion_post WS.
*/
export type AddonModForumAddDiscussionPostWSResponse = {
postid: number; // New post id.
warnings?: CoreWSExternalWarning[];
post: AddonModForumWSPost;
messages?: { // List of warnings.
type: string; // The classification to be used in the client side.
message: string; // Untranslated english message to explain the warning.
}[];
};
/**
* Params of mod_forum_get_forum_access_information WS.
*/
export type AddonModForumGetForumAccessInformationWSParams = {
forumid: number; // Forum instance id.
};
/**
* Data returned by mod_forum_get_forum_access_information WS.
*/
export type AddonModForumGetForumAccessInformationWSResponse = {
warnings?: CoreWSExternalWarning[];
} & AddonModForumAccessInformation;
/**
* Params of mod_forum_can_add_discussion WS.
*/
export type AddonModForumCanAddDiscussionWSParams = {
forumid: number; // Forum instance ID.
groupid?: number; // The group to check, default to active group (Use -1 to check if the user can post in all the groups).
};
/**
* Data returned by mod_forum_can_add_discussion WS.
*/
export type AddonModForumCanAddDiscussionWSResponse = {
warnings?: CoreWSExternalWarning[];
} & AddonModForumCanAddDiscussion;
/**
* Params of mod_forum_delete_post WS.
*/
export type AddonModForumDeletePostWSParams = {
postid: number; // Post to be deleted. It can be a discussion topic post.
};
/**
* Data returned by mod_forum_delete_post WS.
*/
export type AddonModForumDeletePostWSResponse = CoreStatusWithWarningsWSResponse;
/**
* Params of mod_forum_get_discussion_post WS.
*/
export type AddonModForumGetDiscussionPostWSParams = {
postid: number; // Post to fetch.
};
/**
* Data returned by mod_forum_get_discussion_post WS.
*/
export type AddonModForumGetDiscussionPostWSResponse = {
post: AddonModForumWSPost;
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_forum_get_discussion_posts WS.
*/
export type AddonModForumGetDiscussionPostsWSParams = {
discussionid: number; // The ID of the discussion from which to fetch posts.
sortby?: string; // Sort by this element: id, created or modified.
sortdirection?: string; // Sort direction: ASC or DESC.
};
/**
* Data returned by mod_forum_get_discussion_posts WS.
*/
export type AddonModForumGetDiscussionPostsWSResponse = {
posts: AddonModForumWSPost[];
forumid: number; // The forum id.
courseid: number; // The forum course id.
ratinginfo?: CoreRatingInfo; // Rating information.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_forum_get_forum_discussion_posts WS.
*/
export type AddonModForumGetForumDiscussionPostsWSParams = {
discussionid: number; // Discussion ID.
sortby?: string; // Sort by this element: id, created or modified.
sortdirection?: string; // Sort direction: ASC or DESC.
};
/**
* Data returned by mod_forum_get_forum_discussion_posts WS.
*/
export type AddonModForumGetForumDiscussionPostsWSResponse = {
posts: AddonModForumLegacyPost[];
ratinginfo?: CoreRatingInfo; // Rating information.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_forum_set_lock_state WS.
*/
export type AddonModForumSetLockStateWSParams = {
forumid: number; // Forum that the discussion is in.
discussionid: number; // The discussion to lock / unlock.
targetstate: number; // The timestamp for the lock state.
};
/**
* Data returned by mod_forum_set_lock_state WS.
*/
export type AddonModForumSetLockStateWSResponse = {
id: number; // The discussion we are locking.
locked: boolean; // The locked state of the discussion.
times: {
locked: number; // The locked time of the discussion.
};
};
/**
* Params of mod_forum_set_pin_state WS.
*/
export type AddonModForumSetPinStateWSParams = {
discussionid: number; // The discussion to pin or unpin.
targetstate: number; // The target state.
};
/**
* Data returned by mod_forum_set_pin_state WS.
*/
export type AddonModForumSetPinStateWSResponse = {
id: number; // Id.
forumid: number; // Forumid.
pinned: boolean; // Pinned.
locked: boolean; // Locked.
istimelocked: boolean; // Istimelocked.
name: string; // Name.
firstpostid: number; // Firstpostid.
group?: {
name: string; // Name.
urls: {
picture?: string; // Picture.
userlist?: string; // Userlist.
};
};
times: {
modified: number; // Modified.
start: number; // Start.
end: number; // End.
locked: number; // Locked.
};
userstate: {
subscribed: boolean; // Subscribed.
favourited: boolean; // Favourited.
};
capabilities: {
subscribe: boolean; // Subscribe.
move: boolean; // Move.
pin: boolean; // Pin.
post: boolean; // Post.
manage: boolean; // Manage.
favourite: boolean; // Favourite.
};
urls: {
view: string; // View.
viewlatest?: string; // Viewlatest.
viewfirstunread?: string; // Viewfirstunread.
markasread: string; // Markasread.
subscribe: string; // Subscribe.
pin?: string; // Pin.
};
timed: {
istimed?: boolean; // Istimed.
visible?: boolean; // Visible.
};
};
/**
* Params of mod_forum_toggle_favourite_state WS.
*/
export type AddonModForumToggleFavouriteStateWSParams = {
discussionid: number; // The discussion to subscribe or unsubscribe.
targetstate: boolean; // The target state.
};
/**
* Data returned by mod_forum_toggle_favourite_state WS.
*/
export type AddonModForumToggleFavouriteStateWSResponse = {
id: number; // Id.
forumid: number; // Forumid.
pinned: boolean; // Pinned.
locked: boolean; // Locked.
istimelocked: boolean; // Istimelocked.
name: string; // Name.
firstpostid: number; // Firstpostid.
group?: {
name: string; // Name.
urls: {
picture?: string; // Picture.
userlist?: string; // Userlist.
};
};
times: {
modified: number; // Modified.
start: number; // Start.
end: number; // End.
locked: number; // Locked.
};
userstate: {
subscribed: boolean; // Subscribed.
favourited: boolean; // Favourited.
};
capabilities: {
subscribe: boolean; // Subscribe.
move: boolean; // Move.
pin: boolean; // Pin.
post: boolean; // Post.
manage: boolean; // Manage.
favourite: boolean; // Favourite.
};
urls: {
view: string; // View.
viewlatest?: string; // Viewlatest.
viewfirstunread?: string; // Viewfirstunread.
markasread: string; // Markasread.
subscribe: string; // Subscribe.
pin?: string; // Pin.
};
timed: {
istimed?: boolean; // Istimed.
visible?: boolean; // Visible.
};
};
/**
* Params of mod_forum_update_discussion_post WS.
*/
export type AddonModForumUpdateDiscussionPostWSParams = {
postid: number; // Post to be updated. It can be a discussion topic post.
subject?: string; // Updated post subject.
message?: string; // Updated post message (HTML assumed if messageformat is not provided).
messageformat?: number; // Message format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
options?: AddonModForumUpdateDiscussionPostWSOptionsArray; // Configuration options for the post.
};
/**
* Data returned by mod_forum_update_discussion_post WS.
*/
export type AddonModForumUpdateDiscussionPostWSResponse = CoreStatusWithWarningsWSResponse;
/**
* Data passed to NEW_DISCUSSION_EVENT event.
*/
export type AddonModForumNewDiscussionData = {
forumId: number;
cmId: number;
discussionIds?: number[] | null;
discTimecreated?: number;
};
/**
* Data passed to REPLY_DISCUSSION_EVENT event.
*/
export type AddonModForumReplyDiscussionData = {
forumId: number;
discussionId: number;
cmId: number;
};
/**
* Data passed to CHANGE_DISCUSSION_EVENT event.
*/
export type AddonModForumChangeDiscussionData = {
forumId: number;
discussionId: number;
cmId: number;
deleted?: boolean;
post?: AddonModForumPost;
locked?: boolean;
pinned?: boolean;
starred?: boolean;
};
/**
* Data passed to MARK_READ_EVENT event.
*/
export type AddonModForumMarkReadData = {
courseId: number;
moduleId: number;
}; | the_stack |
import * as React from 'react';
import { styled } from 'linaria/react';
import type { Metadata, Separator, Page, Group, GroupItem } from '../types';
import Link from './Link';
const SidebarContent = styled.aside`
background-color: #f8f9fa;
background-color: var(--theme-secondary-bg);
@media (min-width: 640px) {
height: 100%;
min-width: 240px;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
`;
const Navigation = styled.nav`
padding: 12px 24px;
@media (min-width: 640px) {
padding: 20px 32px;
}
`;
const Searchbar = styled.input`
appearance: none;
width: calc(100% - 48px);
padding: 8px 12px;
margin: 32px 24px 0;
font-size: 1em;
background-color: rgba(0, 0, 55, 0.08);
transition: background-color 0.3s;
border-radius: 3px;
border: 0;
outline: 0;
color: #000;
color: var(--theme-text-color);
&:focus {
background-color: rgba(0, 0, 55, 0.12);
}
.dark-theme & {
background-color: rgba(255, 255, 200, 0.08);
}
.dark-theme &:focus {
background-color: rgba(255, 255, 200, 0.08);
}
@media (min-width: 640px) {
width: calc(100% - 64px);
margin: 32px 32px 0;
}
`;
const MenuContent = styled.div`
position: fixed;
opacity: 0;
pointer-events: none;
@media (min-width: 640px) {
position: relative;
opacity: 1;
pointer-events: auto;
}
@media (max-width: 639px) {
${Searchbar}:first-child {
margin-top: 72px;
}
}
`;
const MenuIcon = styled.label`
font-size: 20px;
line-height: 1;
cursor: pointer;
position: fixed;
bottom: 0;
right: 0;
padding: 16px;
margin: 16px;
background-color: #f8f9fa;
background-color: var(--theme-secondary-bg);
border-radius: 3px;
z-index: 10;
-webkit-tap-highlight-color: transparent;
@media (min-width: 640px) {
display: none;
}
`;
const MenuButton = styled.input`
display: none;
&:checked ~ ${MenuContent} {
position: relative;
opacity: 1;
pointer-events: auto;
}
&:checked ~ label {
color: #111;
user-select: none;
}
`;
const SeparatorItem = styled.hr`
border: 0;
background-color: rgba(0, 0, 0, 0.04);
height: 1px;
margin: 20px 0;
`;
// @ts-ignore: FIXME
const LinkItem = styled(Link)`
display: block;
padding: 12px 0;
text-decoration: none;
color: #888;
line-height: 1;
&:hover {
color: #111;
color: var(--theme-primary-color);
text-decoration: none;
}
&[data-selected='true'] {
color: #333;
color: var(--theme-primary-color);
&:hover {
color: #333;
color: var(--theme-primary-color);
}
}
`;
const Row = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
${LinkItem} {
flex: 1;
}
`;
const GroupItems = styled.div`
position: relative;
padding-left: 12px;
transition: 0.3s;
&:before {
content: '';
display: block;
position: absolute;
background-color: rgba(0, 0, 0, 0.04);
width: 1px;
top: 0;
bottom: 0;
left: 0;
margin: 12px 0;
}
&[data-visible='true'] {
opacity: 1;
}
&[data-visible='false'] {
opacity: 0;
pointer-events: none;
}
`;
const ButtonIcon = styled.button`
background-color: transparent;
border: none;
color: #aaa;
cursor: pointer;
margin: 0;
padding: 10px 12px;
transition: 0.3s;
opacity: 0.8;
&:hover {
color: #555;
}
&:focus {
outline: none;
}
&[data-expanded='true'] {
transform: rotate(0deg);
}
&[data-expanded='false'] {
transform: rotate(-180deg);
}
`;
type Props = {
path: string;
data: Array<Metadata | Separator>;
};
type Expanded = Record<
string,
{ height: number | undefined; expanded: boolean }
>;
type State = {
query: string;
open: boolean;
expanded: Expanded;
};
export default class Sidebar extends React.Component<Props, State> {
state = {
query: '',
open: false,
expanded: this.props.data.reduce<Expanded>((acc, item) => {
if (item.type === 'separator') {
return acc;
}
if (item.group) {
const group = acc[item.group];
if (!group) {
acc[item.group] = {
height: undefined,
expanded: true,
};
}
}
return acc;
}, {}),
mode: 'light',
};
componentDidMount() {
setTimeout(() => this.measureHeights(), 1000);
}
componentDidUpdate(prevProps: Props) {
if (prevProps.data !== this.props.data) {
this.measureHeights();
}
}
private measureHeights = () => {
this.setState({
expanded: this.props.data.reduce<Expanded>((acc, item) => {
if (item.type === 'separator') {
return acc;
}
if (item.group) {
const group = acc[item.group];
const height = this.items[item.group]
? this.items[item.group]?.clientHeight
: undefined;
if (!group) {
acc[item.group] = {
height,
expanded: true,
};
}
}
return acc;
}, {}),
});
};
private items: Record<string, HTMLDivElement | null> = {};
render() {
const { path, data } = this.props;
const mapper = (item: Separator | Group | GroupItem, i: number) => {
if (item.type === 'separator') {
return <SeparatorItem key={`separator-${i + 1}`} />;
}
if (item.type === 'group') {
const groupItem = this.state.expanded[item.title] || {
height: null,
expanded: true,
};
return (
<div key={item.link || item.title + i}>
<Row>
<LinkItem
data-selected={path === item.link}
to={item.link}
onClick={() =>
this.setState((state) => {
const group = state.expanded[item.title];
return {
expanded: {
...state.expanded,
[item.title]: {
...group,
expanded:
path === item.link || !item.link
? !group.expanded
: group.expanded,
},
},
open: path === item.link ? state.open : false,
query: '',
};
})
}
>
{item.title}
</LinkItem>
<ButtonIcon
data-expanded={groupItem.expanded}
style={{
opacity: typeof groupItem.height === 'number' ? 1 : 0,
}}
onClick={() =>
this.setState((state) => {
const group = state.expanded[item.title];
return {
expanded: {
...state.expanded,
[item.title]: {
...group,
expanded: !group.expanded,
},
},
};
})
}
>
<svg width="16px" height="16px" viewBox="0 0 16 16">
<polygon
stroke="none"
strokeWidth="1"
fillRule="evenodd"
fill="currentColor"
points="8 4 2 10 3.4 11.4 8 6.8 12.6 11.4 14 10"
/>
</svg>
</ButtonIcon>
</Row>
<GroupItems
ref={(container) => {
this.items[item.title] = container;
}}
data-visible={!!groupItem.expanded}
style={
typeof groupItem.height === 'number'
? {
height: `${groupItem.expanded ? groupItem.height : 0}px`,
}
: {}
}
>
{item.items.map(mapper)}
</GroupItems>
</div>
);
}
return (
<LinkItem
data-selected={path === item.link}
key={item.link}
to={item.link}
onClick={() => this.setState({ open: false, query: '' })}
>
{item.title}
</LinkItem>
);
};
let items;
if (this.state.query) {
items = data.filter((item) => {
if (item.type === 'separator') {
return false;
}
return item.title
.toLowerCase()
.includes(this.state.query.toLowerCase());
});
} else {
// Find all groups names in our data and create a list of groups
const groups = ((data.filter((item) =>
// @ts-ignore
Boolean(item.group)
) as any) as (Page & { group: string })[])
.map((item): string => item.group)
.filter((item, i, self) => self.lastIndexOf(item) === i)
.reduce<
Record<
string,
{
type: 'group';
items: GroupItem[];
title: string;
}
>
>(
(acc, title: string) =>
Object.assign(acc, {
[title]: {
type: 'group',
items: [],
title,
},
}),
{}
);
// Find items belonging to groups and add them to the groups
items = data.reduce<(Separator | Group | GroupItem)[]>((acc, item) => {
if (item.type === 'separator') {
acc.push(item);
} else if (item.title in groups) {
// If the title of the item matches a group, replace the item with the group
const group = groups[item.title];
acc.push({ ...group, link: item.link });
} else if (item.group) {
// If the item belongs to a group, find an item matching the group first
const index = acc.findIndex(
(it) => it.type !== 'separator' && it.title === item.group
);
let group = acc[index];
if (group) {
if (group.type !== 'group') {
// If the item exists, but is not a group, turn it a to a group first
group = { ...groups[item.group], link: item.link };
acc[index] = group;
} else {
// If the group exists, add our item
group.items.push(item);
}
} else {
// If the item doesn't exist at all, add a new group to the list
group = groups[item.group];
group.items.push(item);
acc.push(group);
}
} else {
acc.push(item);
}
return acc;
}, []);
}
const links = items.map(mapper);
return (
<SidebarContent>
<MenuButton
id="slide-sidebar"
type="checkbox"
role="button"
checked={this.state.open}
onChange={(e) => this.setState({ open: e.target.checked })}
/>
<MenuIcon htmlFor="slide-sidebar">☰</MenuIcon>
<MenuContent>
<Searchbar
type="search"
value={this.state.query}
onChange={(e) => this.setState({ query: e.target.value })}
placeholder="Filter…"
/>
<Navigation>{links}</Navigation>
</MenuContent>
</SidebarContent>
);
}
} | the_stack |
import * as React from "react";
import * as Hammer from "hammerjs";
import { Graphics, Prototypes, Geometry } from "../../../../core";
import { classNames } from "../../../utils";
import { renderSVGPath } from "../../../renderer";
import { HandlesDragContext, HandleViewProps } from "./common";
export interface RelativeLineRatioHandleViewProps extends HandleViewProps {
handle: Prototypes.Handles.GapRatio;
}
export interface RelativeLineRatioHandleViewState {
dragging: boolean;
newValue: number;
}
export class GapRatioHandleView extends React.Component<
RelativeLineRatioHandleViewProps,
RelativeLineRatioHandleViewState
> {
public refs: {
cOrigin: SVGCircleElement;
line: SVGLineElement;
};
public hammer: HammerManager;
constructor(props: RelativeLineRatioHandleViewProps) {
super(props);
this.state = {
dragging: false,
newValue: this.props.handle.value,
};
}
// eslint-disable-next-line
public componentDidMount() {
this.hammer = new Hammer(this.refs.line);
this.hammer.add(new Hammer.Pan({ threshold: 1 }));
let context: HandlesDragContext = null;
let oldValue: number;
let xStart: number = 0;
let yStart: number = 0;
let dXIntegrate: number = 0;
let dXLast: number = 0;
let dYIntegrate: number = 0;
let dYLast: number = 0;
let scale = 1 / this.props.handle.scale;
const getNewValue = () => {
const cs = this.props.handle.coordinateSystem;
if (cs == null || cs instanceof Graphics.CartesianCoordinates) {
if (this.props.handle.axis == "x") {
return oldValue + scale * dXIntegrate;
}
if (this.props.handle.axis == "y") {
return oldValue + scale * dYIntegrate;
}
}
if (cs instanceof Graphics.PolarCoordinates) {
if (this.props.handle.axis == "x") {
const getAngle = (x: number, y: number) => {
return 90 - (Math.atan2(y, x) / Math.PI) * 180;
};
const angle0 = getAngle(xStart, yStart);
let angle1 = getAngle(xStart + dXIntegrate, yStart + dYIntegrate);
if (angle1 > angle0 + 180) {
angle1 -= 360;
}
if (angle1 < angle0 - 180) {
angle1 += 360;
}
return oldValue + scale * (angle1 - angle0);
}
if (this.props.handle.axis == "y") {
const nX = xStart + dXIntegrate;
const nY = yStart + dYIntegrate;
const radius0 = Math.sqrt(xStart * xStart + yStart * yStart);
const radius1 = Math.sqrt(nX * nX + nY * nY);
return oldValue + scale * (radius1 - radius0);
}
}
return oldValue;
};
this.hammer.on("panstart", (e) => {
context = new HandlesDragContext();
oldValue = this.props.handle.value;
if (this.refs.cOrigin) {
const bbox = this.refs.cOrigin.getBoundingClientRect();
xStart = (e.center.x - e.deltaX - bbox.left) / this.props.zoom.scale;
yStart = -(e.center.y - e.deltaY - bbox.top) / this.props.zoom.scale;
} else {
xStart = (e.center.x - e.deltaX) / this.props.zoom.scale;
yStart = -(e.center.y - e.deltaY) / this.props.zoom.scale;
}
dXLast = e.deltaX;
dYLast = e.deltaY;
dXIntegrate = e.deltaX / this.props.zoom.scale;
dYIntegrate = -e.deltaY / this.props.zoom.scale;
scale = 1 / this.props.handle.scale;
this.setState({
dragging: true,
newValue: oldValue,
});
if (this.props.onDragStart) {
this.props.onDragStart(this.props.handle, context);
}
});
this.hammer.on("pan", (e) => {
if (context) {
dXIntegrate += (e.deltaX - dXLast) / this.props.zoom.scale;
dYIntegrate += -(e.deltaY - dYLast) / this.props.zoom.scale;
dXLast = e.deltaX;
dYLast = e.deltaY;
let newValue = getNewValue();
if (this.props.handle.range) {
newValue = Math.min(
this.props.handle.range[1],
Math.max(newValue, this.props.handle.range[0])
);
} else {
newValue = Math.min(1, Math.max(newValue, 0));
}
this.setState({
newValue,
});
context.emit("drag", { value: newValue });
}
});
this.hammer.on("panend", (e) => {
if (context) {
dXIntegrate += (e.deltaX - dXLast) / this.props.zoom.scale;
dYIntegrate += -(e.deltaY - dYLast) / this.props.zoom.scale;
dXLast = e.deltaX;
dYLast = e.deltaY;
let newValue = getNewValue();
if (this.props.handle.range) {
newValue = Math.min(
this.props.handle.range[1],
Math.max(newValue, this.props.handle.range[0])
);
} else {
newValue = Math.min(1, Math.max(newValue, 0));
}
context.emit("end", { value: newValue });
this.setState({
dragging: false,
});
context = null;
}
});
}
public componentWillUnmount() {
this.hammer.destroy();
}
public render() {
const handle = this.props.handle;
if (
handle.coordinateSystem == null ||
handle.coordinateSystem instanceof Graphics.CartesianCoordinates
) {
return this.renderCartesian();
}
if (handle.coordinateSystem instanceof Graphics.PolarCoordinates) {
return this.renderPolar();
}
return null;
}
// eslint-disable-next-line
public renderPolar() {
const { handle } = this.props;
const polar = handle.coordinateSystem as Graphics.PolarCoordinates;
const center = Geometry.applyZoom(this.props.zoom, {
x: polar.origin.x,
y: -polar.origin.y,
});
switch (handle.axis) {
case "x": {
// angular axis
const pathValue = Graphics.makePath();
const pathRegion = Graphics.makePath();
const angle = handle.reference + handle.scale * handle.value;
const angleRef = handle.reference;
const r1 = handle.span[0] * this.props.zoom.scale,
r2 = handle.span[1] * this.props.zoom.scale;
pathValue.polarLineTo(
center.x,
-center.y,
-angle + 90,
r1,
-angle + 90,
r2,
true
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle + 90,
r1,
-angle + 90,
r2,
true
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle + 90,
r2,
-angleRef + 90,
r2,
false
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angleRef + 90,
r2,
-angleRef + 90,
r1,
false
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angleRef + 90,
r1,
-angle + 90,
r1,
false
);
pathRegion.closePath();
const pathNew = Graphics.makePath();
if (this.state.dragging) {
const angleNew =
handle.reference + handle.scale * this.state.newValue;
pathNew.polarLineTo(
center.x,
-center.y,
-angleNew + 90,
r1,
-angleNew + 90,
r2,
true
);
}
return (
<g
className={classNames(
"handle",
"handle-line-angular",
["active", this.state.dragging],
["visible", handle.visible || this.props.visible]
)}
>
<circle ref="cOrigin" cx={center.x} cy={center.y} r={0} />
<g ref="line">
<path
d={renderSVGPath(pathRegion.path.cmds)}
className="element-region handle-ghost"
/>
<path
d={renderSVGPath(pathValue.path.cmds)}
className="element-line handle-ghost"
/>
<path
d={renderSVGPath(pathRegion.path.cmds)}
className="element-region handle-highlight"
/>
<path
d={renderSVGPath(pathValue.path.cmds)}
className="element-line handle-highlight"
/>
</g>
{this.state.dragging ? (
<path
d={renderSVGPath(pathNew.path.cmds)}
className="element-line handle-hint"
/>
) : null}
</g>
);
}
case "y": {
const pathValue = Graphics.makePath();
const pathRegion = Graphics.makePath();
const radius =
(handle.reference + handle.scale * handle.value) *
this.props.zoom.scale;
const radiusRef = handle.reference * this.props.zoom.scale;
const angle1 = handle.span[0],
angle2 = handle.span[1];
pathValue.polarLineTo(
center.x,
-center.y,
-angle1 + 90,
radius,
-angle2 + 90,
radius,
true
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle1 + 90,
radius,
-angle2 + 90,
radius,
true
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle2 + 90,
radius,
-angle2 + 90,
radiusRef,
false
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle2 + 90,
radiusRef,
-angle1 + 90,
radiusRef,
false
);
pathRegion.polarLineTo(
center.x,
-center.y,
-angle1 + 90,
radiusRef,
-angle1 + 90,
radius,
false
);
pathRegion.closePath();
const pathNew = Graphics.makePath();
if (this.state.dragging) {
const radiusNew =
(handle.reference + handle.scale * this.state.newValue) *
this.props.zoom.scale;
pathNew.polarLineTo(
center.x,
-center.y,
-angle1 + 90,
radiusNew,
-angle2 + 90,
radiusNew,
true
);
}
return (
<g
className={classNames(
"handle",
"handle-line-radial",
["active", this.state.dragging],
["visible", handle.visible || this.props.visible]
)}
>
<circle ref="cOrigin" cx={center.x} cy={center.y} r={0} />
<g ref="line">
<path
d={renderSVGPath(pathRegion.path.cmds)}
className="element-region handle-ghost"
/>
<path
d={renderSVGPath(pathValue.path.cmds)}
className="element-line handle-ghost"
/>
<path
d={renderSVGPath(pathRegion.path.cmds)}
className="element-region handle-highlight"
/>
<path
d={renderSVGPath(pathValue.path.cmds)}
className="element-line handle-highlight"
/>
</g>
{this.state.dragging ? (
<path
d={renderSVGPath(pathNew.path.cmds)}
className="element-line handle-hint"
/>
) : null}
</g>
);
}
}
}
// eslint-disable-next-line
public renderCartesian() {
const { handle } = this.props;
const fX = (x: number) =>
x * this.props.zoom.scale + this.props.zoom.centerX;
const fY = (y: number) =>
-y * this.props.zoom.scale + this.props.zoom.centerY;
switch (handle.axis) {
case "x": {
const fxRef = fX(handle.reference);
const fxVal = fX(handle.reference + handle.scale * handle.value);
const fy1 = fY(handle.span[0]);
const fy2 = fY(handle.span[1]);
return (
<g
className={classNames(
"handle",
"handle-line-x",
["active", this.state.dragging],
["visible", handle.visible || this.props.visible]
)}
>
<g ref="line">
<line
className="element-line handle-ghost"
x1={fxVal}
x2={fxVal}
y1={fy1}
y2={fy2}
/>
<rect
className="element-region handle-ghost"
x={Math.min(fxRef, fxVal)}
width={Math.abs(fxRef - fxVal)}
y={Math.min(fy1, fy2)}
height={Math.abs(fy2 - fy1)}
/>
<line
className="element-line handle-highlight"
x1={fxVal}
x2={fxVal}
y1={fy1}
y2={fy2}
/>
<rect
className="element-region handle-highlight"
x={Math.min(fxRef, fxVal)}
width={Math.abs(fxRef - fxVal)}
y={Math.min(fy1, fy2)}
height={Math.abs(fy2 - fy1)}
/>
</g>
{this.state.dragging ? (
<g>
<line
className={`element-line handle-hint`}
x1={fX(handle.reference + handle.scale * this.state.newValue)}
x2={fX(handle.reference + handle.scale * this.state.newValue)}
y1={fY(handle.span[0])}
y2={fY(handle.span[1])}
/>
</g>
) : null}
</g>
);
}
case "y": {
const fyRef = fY(handle.reference);
const fyVal = fY(handle.reference + handle.scale * handle.value);
const fx1 = fX(handle.span[0]);
const fx2 = fX(handle.span[1]);
return (
<g
className={classNames(
"handle",
"handle-line-y",
["active", this.state.dragging],
["visible", handle.visible || this.props.visible]
)}
>
<g ref="line">
<line
className="element-line handle-ghost"
y1={fyVal}
y2={fyVal}
x1={fx1}
x2={fx2}
/>
<rect
className="element-region handle-ghost"
y={Math.min(fyRef, fyVal)}
height={Math.abs(fyRef - fyVal)}
x={Math.min(fx1, fx2)}
width={Math.abs(fx2 - fx1)}
/>
<line
className="element-line handle-highlight"
y1={fyVal}
y2={fyVal}
x1={fx1}
x2={fx2}
/>
<rect
className="element-region handle-highlight"
y={Math.min(fyRef, fyVal)}
height={Math.abs(fyRef - fyVal)}
x={Math.min(fx1, fx2)}
width={Math.abs(fx2 - fx1)}
/>
</g>
{this.state.dragging ? (
<g>
<line
className={`element-line handle-hint`}
y1={fY(handle.reference + handle.scale * this.state.newValue)}
y2={fY(handle.reference + handle.scale * this.state.newValue)}
x1={fx1}
x2={fx2}
/>
</g>
) : null}
</g>
);
}
}
}
} | the_stack |
import { FixedContentTypeMapper } from '../../../../src/storage/mapping/FixedContentTypeMapper';
import { BadRequestHttpError } from '../../../../src/util/errors/BadRequestHttpError';
import { NotFoundHttpError } from '../../../../src/util/errors/NotFoundHttpError';
import { trimTrailingSlashes } from '../../../../src/util/PathUtil';
jest.mock('fs');
describe('An FixedContentTypeMapper', (): void => {
const base = 'http://test.com/';
const rootFilepath = 'uploads/';
describe('without suffixes', (): void => {
const mapper = new FixedContentTypeMapper(base, rootFilepath, 'text/turtle');
describe('mapUrlToFilePath', (): void => {
it('throws 404 if the input path does not contain the base.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: 'invalid' }, false)).rejects.toThrow(NotFoundHttpError);
});
it('throws 404 if the relative path does not start with a slash.', async(): Promise<void> => {
const result = mapper.mapUrlToFilePath({ path: `${trimTrailingSlashes(base)}test` }, false);
await expect(result).rejects.toThrow(BadRequestHttpError);
await expect(result).rejects.toThrow('URL needs a / after the base');
});
it('throws 400 if the input path contains relative parts.', async(): Promise<void> => {
const result = mapper.mapUrlToFilePath({ path: `${base}test/../test2` }, false);
await expect(result).rejects.toThrow(BadRequestHttpError);
await expect(result).rejects.toThrow('Disallowed /.. segment in URL');
});
it('returns the corresponding file path for container identifiers.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}container/` }, false)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('always returns the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test` }, false)).resolves.toEqual({
identifier: { path: `${base}test` },
filePath: `${rootFilepath}test`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapUrlToFilePath({ path: `${base}test.txt` }, false)).resolves.toEqual({
identifier: { path: `${base}test.txt` },
filePath: `${rootFilepath}test.txt`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('generates a file path if supported content-type was provided.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'text/turtle')).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 400 if the given content-type is not supported.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'application/n-quads')).rejects
.toThrow(
new BadRequestHttpError(`Unsupported content type application/n-quads, only text/turtle is allowed`),
);
});
});
describe('mapFilePathToUrl', (): void => {
it('throws an error if the input path does not contain the root file path.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl('invalid', true)).rejects.toThrow(Error);
});
it('returns a generated identifier for directories.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}container/`, true)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('returns files with the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test`, false)).resolves.toEqual({
identifier: { path: `${base}test` },
filePath: `${rootFilepath}test`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.ttl`, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.txt`, false)).resolves.toEqual({
identifier: { path: `${base}test.txt` },
filePath: `${rootFilepath}test.txt`,
contentType: 'text/turtle',
isMetadata: false,
});
});
});
});
describe('with path suffix', (): void => {
// Internally, everything uses the .ttl extension, but it's exposed without.
const mapper = new FixedContentTypeMapper(base, rootFilepath, 'text/turtle', '.ttl');
describe('mapUrlToFilePath', (): void => {
it('returns the corresponding file path for container identifiers.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}container/` }, false)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('always returns the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test` }, false)).resolves.toEqual({
identifier: { path: `${base}test` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.ttl.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapUrlToFilePath({ path: `${base}test.txt` }, false)).resolves.toEqual({
identifier: { path: `${base}test.txt` },
filePath: `${rootFilepath}test.txt.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('generates a file path if supported content-type was provided.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'text/turtle')).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.ttl.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 400 if the given content-type is not supported.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'application/n-quads')).rejects
.toThrow(
new BadRequestHttpError(`Unsupported content type application/n-quads, only text/turtle is allowed`),
);
});
});
describe('mapFilePathToUrl', (): void => {
it('returns a generated identifier for directories.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}container/`, true)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('returns files with the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.ttl`, false)).resolves.toEqual({
identifier: { path: `${base}test` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 404 if the input path does not end with the suffix.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test`, false)).rejects.toThrow(NotFoundHttpError);
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.txt`, false)).rejects.toThrow(NotFoundHttpError);
});
});
});
describe('with url suffix', (): void => {
// Internally, no extensions are used, but everything is exposed with the .ttl extension
const mapper = new FixedContentTypeMapper(base, rootFilepath, 'text/turtle', undefined, '.ttl');
describe('mapUrlToFilePath', (): void => {
it('returns the corresponding file path for container identifiers.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}container/` }, false)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('always returns the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapUrlToFilePath({ path: `${base}test.txt.ttl` }, false)).resolves.toEqual({
identifier: { path: `${base}test.txt.ttl` },
filePath: `${rootFilepath}test.txt`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('generates a file path if supported content-type was provided.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'text/turtle')).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 404 if the url does not end with the suffix.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.nq` }, false, 'text/turtle')).rejects
.toThrow(NotFoundHttpError);
await expect(mapper.mapUrlToFilePath({ path: `${base}test` }, false, 'text/turtle')).rejects
.toThrow(NotFoundHttpError);
});
it('throws 400 if the given content-type is not supported.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false, 'application/n-quads')).rejects
.toThrow(
new BadRequestHttpError(`Unsupported content type application/n-quads, only text/turtle is allowed`),
);
});
});
describe('mapFilePathToUrl', (): void => {
it('returns a generated identifier for directories.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}container/`, true)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('returns files with the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test`, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.ttl`, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl.ttl` },
filePath: `${rootFilepath}test.ttl`,
contentType: 'text/turtle',
isMetadata: false,
});
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.txt`, false)).resolves.toEqual({
identifier: { path: `${base}test.txt.ttl` },
filePath: `${rootFilepath}test.txt`,
contentType: 'text/turtle',
isMetadata: false,
});
});
});
});
describe('with path and url suffix', (): void => {
// Internally, everything uses the .nq extension, but it's exposed with the .ttl extension.
const mapper = new FixedContentTypeMapper(base, rootFilepath, 'text/turtle', '.nq', '.ttl');
describe('mapUrlToFilePath', (): void => {
it('returns the corresponding file path for container identifiers.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}container/` }, false)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('always returns the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.ttl` }, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.nq`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 404 if the url does not end with the suffix.', async(): Promise<void> => {
await expect(mapper.mapUrlToFilePath({ path: `${base}test.nq` }, false, 'text/turtle')).rejects
.toThrow(NotFoundHttpError);
await expect(mapper.mapUrlToFilePath({ path: `${base}test` }, false, 'text/turtle')).rejects
.toThrow(NotFoundHttpError);
});
});
describe('mapFilePathToUrl', (): void => {
it('returns a generated identifier for directories.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}container/`, true)).resolves.toEqual({
identifier: { path: `${base}container/` },
filePath: `${rootFilepath}container/`,
isMetadata: false,
});
});
it('returns files with the configured content-type.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.nq`, false)).resolves.toEqual({
identifier: { path: `${base}test.ttl` },
filePath: `${rootFilepath}test.nq`,
contentType: 'text/turtle',
isMetadata: false,
});
});
it('throws 404 if the input path does not end with the suffix.', async(): Promise<void> => {
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test`, false)).rejects.toThrow(NotFoundHttpError);
await expect(mapper.mapFilePathToUrl(`${rootFilepath}test.ttl`, false)).rejects.toThrow(NotFoundHttpError);
});
});
});
}); | the_stack |
import { HttpResponse, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';import { HttpOptions } from './types';
import * as models from './models';
export interface APIClientInterface {
/**
* Arguments object for method `getItems`.
*/
getItemsParams?: {
pageSize: number,
/** page number */
page: number,
};
/**
* Get items list
* Response generated for [ 200 ] HTTP response code.
*/
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ItemList>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ItemList>>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ItemList>>;
/**
* Arguments object for method `getItemModels`.
*/
getItemModelsParams?: {
pageSize: number,
/** page number */
page: number,
};
/**
* Get item models list
* Response generated for [ 200 ] HTTP response code.
*/
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Arguments object for method `getPetsId`.
*/
getPetsIdParams?: {
id: string,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet[]>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet[]>>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet[]>>;
/**
* Arguments object for method `deletePetsId`.
*/
deletePetsIdParams?: {
id: string,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Arguments object for method `getPetsWithDefaultIdParamId`.
*/
getPetsWithDefaultIdParamIdParams?: {
/** An ID or a slug identifying this Pet. */
id: string,
};
/**
* Get details of the game.
* Default id param should be overridden to string
* Response generated for [ 200 ] HTTP response code.
*/
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Pet>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Pet>>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Pet>>;
/**
* Arguments object for method `patchPetsWithDefaultIdParamId`.
*/
patchPetsWithDefaultIdParamIdParams?: {
/** A unique integer value identifying this Pet. */
id: number,
body?: any,
};
/**
* Default id param should be number and not string
* Response generated for [ 200 ] HTTP response code.
*/
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<(models.Customer[]) | null>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<(models.Customer[]) | null>>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<(models.Customer[]) | null>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Dictionary>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Dictionary>>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Dictionary>>;
/**
* Arguments object for method `getFileId`.
*/
getFileIdParams?: {
id: string,
};
/**
* Response generated for [ 200 ] HTTP response code.
*/
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<string>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<string>>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<string>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<{ [key: string]: number }>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<{ [key: string]: number }>>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<{ [key: string]: number }>>;
/**
* Response generated for [ 200 ] HTTP response code.
*/
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<{ [key: string]: number }[]>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<{ [key: string]: number }[]>>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<{ [key: string]: number }[]>>;
/**
* Arguments object for method `firestoreProjectsDatabasesDocumentsCommit`.
*/
firestoreProjectsDatabasesDocumentsCommitParams?: {
/**
* - error format
* - 1 V1
* - 2 V2
*
*/
wololo?: models.NumberEnumParam,
/**
* Data format for response.
* If not set, server will use the default value: json
*/
alt?: models.StringEnumParam,
/** OAuth access token. */
accessToken?: string,
/**
* Pretty-print response.
* If not set, server will use the default value: true
*/
pp?: boolean,
/**
* should pretty print
* If not set, server will use the default value: true
*/
prettyPrint?: boolean,
/**
* this params is deprecated
* @deprecated this parameter has been deprecated and may be removed in future.
*/
simpleQueryParam?: string,
/** @deprecated this parameter has been deprecated and may be removed in future. */
simpleArrayQueryParam?: number[],
body?: models.Data,
/** The database name. In the format `database:{{name}}` */
database: string,
};
/**
* Commits a transaction, while optionally updating documents.
* Response generated for [ 200 ] HTTP response code.
*/
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Dictionary>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Dictionary>>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Dictionary>>;
/**
* Arguments object for method `postReposOwnerRepoGitBlobs`.
*/
postReposOwnerRepoGitBlobsParams?: {
/** Name of repository owner. */
owner: string,
/** Name of repository. */
repo: string,
/** Is used to set specified media type. */
accept?: string,
/** Custom blob (should be imported from models) */
body: models.Blob,
};
/**
* Create a custom Blob.
* Response generated for [ 201 ] HTTP response code.
*/
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Blob[]>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Blob[]>>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Blob[]>>;
/**
* Arguments object for method `getReposOwnerRepoGitBlobsShaCode`.
*/
getReposOwnerRepoGitBlobsShaCodeParams?: {
/** Name of repository owner. */
owner: string,
/** Name of repository. */
repo: string,
/** SHA-1 code. */
shaCode: string,
/** Is used to set specified media type. */
accept?: string,
};
/**
* Get standard File
* Response generated for [ 200 ] HTTP response code.
*/
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
} | the_stack |
import * as parser from "jsonc-parser";
import * as vscode from "vscode";
import { Constants } from "../common/constants";
import { DigitalTwinConstants } from "./digitalTwinConstants";
import { ClassNode, PropertyNode, ValueSchema } from "./digitalTwinGraph";
import { IntelliSenseUtility, JsonNodeType, PropertyPair, ModelContent } from "./intelliSenseUtility";
import { LANGUAGE_CODE } from "./languageCode";
/**
* Diagnostic problem
*/
interface Suggestion {
isProperty: boolean;
label: string;
insertText: string;
}
/**
* Completion item provider for DigitalTwin IntelliSense
*/
export class DigitalTwinCompletionItemProvider implements vscode.CompletionItemProvider {
/**
* complete text to be valid json content
* @param document text document
* @param position position
*/
private static completeTextForParse(document: vscode.TextDocument, position: vscode.Position): string {
const text: string = document.getText();
const offset: number = document.offsetAt(position);
if (text[offset] === Constants.COMPLETION_TRIGGER) {
const edit: parser.Edit = {
offset,
length: 1,
content: Constants.COMPLETION_TRIGGER + Constants.DEFAULT_SEPARATOR
};
return parser.applyEdits(text, [edit]);
}
return text;
}
/**
* create completion item
* @param suggestion suggestion
* @param position position
* @param range overwrite range
* @param separator separator
*/
private static createCompletionItem(
suggestion: Suggestion,
position: vscode.Position,
range: vscode.Range,
separator: string
): vscode.CompletionItem {
const completionItem: vscode.CompletionItem = {
label: suggestion.label,
kind: suggestion.isProperty ? vscode.CompletionItemKind.Property : vscode.CompletionItemKind.Value,
insertText: new vscode.SnippetString(suggestion.insertText + separator),
// the start of range should be after position, otherwise completion item will not be shown
range: new vscode.Range(position, range.end)
};
if (position.isAfter(range.start)) {
completionItem.additionalTextEdits = [vscode.TextEdit.delete(new vscode.Range(range.start, position))];
}
return completionItem;
}
/**
* evaluate the overwrite range for completion text
* @param document text document
* @param position position
* @param node json node
*/
private static evaluateOverwriteRange(
document: vscode.TextDocument,
position: vscode.Position,
node: parser.Node
): vscode.Range {
let range: vscode.Range;
if (node.type === JsonNodeType.String || node.type === JsonNodeType.Number || node.type === JsonNodeType.Boolean) {
range = IntelliSenseUtility.getNodeRange(document, node);
} else {
const word: string = DigitalTwinCompletionItemProvider.getCurrentWord(document, position);
const start: number = document.offsetAt(position) - word.length;
range = new vscode.Range(document.positionAt(start), position);
}
return range;
}
/**
* get the current word before position
* @param document text document
* @param position position
*/
private static getCurrentWord(document: vscode.TextDocument, position: vscode.Position): string {
let i: number = position.character - 1;
const text: string = document.lineAt(position.line).text;
while (i >= 0 && DigitalTwinConstants.WORD_STOP.indexOf(text.charAt(i)) === -1) {
i--;
}
return text.substring(i + 1, position.character);
}
/**
* evaluate if need to add separator after offset
* @param text text
* @param offset offset
*/
private static evaluateSeparatorAfter(text: string, offset: number): string {
const scanner: parser.JSONScanner = parser.createScanner(text, true);
scanner.setPosition(offset);
const token: parser.SyntaxKind = scanner.scan();
switch (token) {
case parser.SyntaxKind.CommaToken:
case parser.SyntaxKind.CloseBraceToken:
case parser.SyntaxKind.CloseBracketToken:
case parser.SyntaxKind.EOF:
return Constants.EMPTY_STRING;
default:
return Constants.DEFAULT_SEPARATOR;
}
}
/**
* suggest completion item for property
* @param version target version
* @param node json node
* @param includeValue identifiy if includes property value
* @param suggestions suggestion collection
*/
private static suggestProperty(
version: number,
node: parser.Node,
includeValue: boolean,
suggestions: Suggestion[]
): void {
const exist = new Set<string>();
let classNode: ClassNode | undefined = DigitalTwinCompletionItemProvider.getObjectType(version, node, exist);
// class is not avaiable in target version
if (classNode && !IntelliSenseUtility.isAvailableByVersion(version, classNode.version)) {
classNode = undefined;
}
let dummyNode: PropertyNode;
if (!classNode) {
// there are 3 cases when classNode is not defined
// 1. there are multiple choice. In this case, ask user to specifiy @type
// 2. invalid @type value. In this case, diagnostic shows error and user need to correct value
// 3. type is not avaiable in target version. In this case, same behavior as case 2
if (!exist.has(DigitalTwinConstants.TYPE)) {
// suggest @type property
dummyNode = { id: DigitalTwinConstants.TYPE };
suggestions.push({
isProperty: true,
label: `${dummyNode.id} ${DigitalTwinConstants.REQUIRED_PROPERTY_LABEL}`,
insertText: DigitalTwinCompletionItemProvider.getInsertTextForProperty(dummyNode, includeValue)
});
}
} else if (IntelliSenseUtility.isLanguageNode(classNode)) {
// suggest language code
const stringValueSchema: ClassNode = { id: ValueSchema.String };
dummyNode = { id: Constants.EMPTY_STRING, range: [stringValueSchema] };
for (const code of LANGUAGE_CODE) {
if (exist.has(code)) {
continue;
}
dummyNode.id = code;
suggestions.push({
isProperty: true,
label: code,
insertText: DigitalTwinCompletionItemProvider.getInsertTextForProperty(dummyNode, includeValue)
});
}
} else {
const required =
classNode.constraint && classNode.constraint.required
? new Set<string>(classNode.constraint.required)
: new Set<string>();
for (const property of IntelliSenseUtility.getPropertiesOfClassByVersion(classNode, version)) {
if (!property.label || exist.has(property.label)) {
continue;
}
suggestions.push({
isProperty: true,
label: DigitalTwinCompletionItemProvider.formatLabel(property.label, required),
insertText: DigitalTwinCompletionItemProvider.getInsertTextForProperty(property, includeValue)
});
}
// suggest reversed property
DigitalTwinCompletionItemProvider.suggestReservedProperty(includeValue, exist, required, suggestions);
required.clear();
}
exist.clear();
}
/**
* get object type of json node and record existing properties
* @param version target version
* @param node json node
* @param exist existing properties
*/
private static getObjectType(version: number, node: parser.Node, exist: Set<string>): ClassNode | undefined {
// get json node of Object
const parent: parser.Node | undefined = node.parent;
if (!parent || parent.type !== JsonNodeType.Object || !parent.children) {
return undefined;
}
let propertyName: string;
let objectType: ClassNode | undefined;
let propertyPair: PropertyPair | undefined;
for (const child of parent.children) {
// skip current node since it has no name yet
if (child === node) {
continue;
}
propertyPair = IntelliSenseUtility.parseProperty(child);
if (!propertyPair) {
continue;
}
propertyName = propertyPair.name.value as string;
exist.add(propertyName);
// get from @type property
if (propertyName === DigitalTwinConstants.TYPE) {
const propertyValue: parser.Node = propertyPair.value;
if (propertyValue.type === JsonNodeType.String) {
// not return here since it need record all existing properties
objectType = IntelliSenseUtility.getClasNode(propertyValue.value as string);
} else if (propertyValue.type === JsonNodeType.Array && propertyValue.children) {
// support semantic types
for (const child of propertyValue.children) {
if (child.type !== JsonNodeType.String) {
continue;
}
const type: string = child.value as string;
if (type && DigitalTwinConstants.SUPPORT_SEMANTIC_TYPES.has(type)) {
objectType = IntelliSenseUtility.getClasNode(type);
}
}
}
}
}
// infer from outer property
if (!objectType) {
const propertyNode: PropertyNode | undefined = DigitalTwinCompletionItemProvider.getOuterPropertyNode(parent);
if (propertyNode) {
const classes: ClassNode[] = IntelliSenseUtility.getObjectClasses(propertyNode, version);
// object type should be definite
if (classes.length === 1) {
objectType = classes[0];
}
}
}
return objectType;
}
/**
* get outer DigitalTwin property node
* @param node json node
*/
private static getOuterPropertyNode(node: parser.Node): PropertyNode | undefined {
const propertyPair: PropertyPair | undefined = IntelliSenseUtility.getOuterPropertyPair(node);
if (!propertyPair) {
return undefined;
}
const propertyName: string = IntelliSenseUtility.resolvePropertyName(propertyPair);
return IntelliSenseUtility.getPropertyNode(propertyName);
}
/**
* format property label with required information
* @param label label
* @param required required properties
*/
private static formatLabel(label: string, required: Set<string>): string {
return required.has(label) ? `${label} ${DigitalTwinConstants.REQUIRED_PROPERTY_LABEL}` : label;
}
/**
* suggest completion item for reserved property
* @param includeValue identifiy if includes property value
* @param exist existing properties
* @param required required properties
* @param suggestions suggestion collection
*/
private static suggestReservedProperty(
includeValue: boolean,
exist: Set<string>,
required: Set<string>,
suggestions: Suggestion[]
): void {
const properties: PropertyNode[] = [];
const propertyNode: PropertyNode | undefined = IntelliSenseUtility.getPropertyNode(DigitalTwinConstants.ID);
if (propertyNode) {
properties.push(propertyNode);
}
// suggest @type property for inline Interface
if (required.has(DigitalTwinConstants.TYPE)) {
properties.push({ id: DigitalTwinConstants.TYPE });
}
for (const property of properties) {
if (exist.has(property.id)) {
continue;
}
suggestions.push({
isProperty: true,
label: DigitalTwinCompletionItemProvider.formatLabel(property.id, required),
insertText: DigitalTwinCompletionItemProvider.getInsertTextForProperty(property, includeValue)
});
}
properties.length = 0;
}
/**
* get insert text for property
* @param propertyNode DigitalTwin property node
* @param includeValue identify if insert text includes property value
*/
private static getInsertTextForProperty(propertyNode: PropertyNode, includeValue: boolean): string {
const name: string = propertyNode.label || propertyNode.id;
if (!includeValue) {
return name;
}
// provide value snippet according to property type
let value = "$1";
if (propertyNode.isArray) {
value = "[$1]";
} else if (propertyNode.range && propertyNode.range.length === 1) {
// property type should be definite
const classNode: ClassNode = propertyNode.range[0];
if (IntelliSenseUtility.isObjectClass(classNode)) {
value = "{$1}";
} else if (!classNode.label) {
// class is value schema
switch (classNode.id) {
case ValueSchema.String:
value = '"$1"';
break;
case ValueSchema.Int:
value = "${1:0}";
break;
case ValueSchema.Boolean:
value = "${1:false}";
break;
default:
}
}
}
return `"${name}": ${value}`;
}
/**
* suggest completion item for property value
* @param version target version
* @param node json node
* @param suggestions suggestion collection
*/
private static suggestValue(version: number, node: parser.Node, suggestions: Suggestion[]): void {
const propertyPair: PropertyPair | undefined = IntelliSenseUtility.parseProperty(node);
if (!propertyPair) {
return;
}
let propertyNode: PropertyNode | undefined;
let propertyName: string = propertyPair.name.value as string;
if (propertyName === DigitalTwinConstants.TYPE) {
// suggest value of @type property
if (!node.parent) {
return;
}
// assign to entry node if json object node is the top node
propertyNode =
DigitalTwinCompletionItemProvider.getOuterPropertyNode(node.parent) || IntelliSenseUtility.getEntryNode();
if (propertyNode) {
let value: string;
const classes: ClassNode[] = IntelliSenseUtility.getObjectClasses(propertyNode, version);
for (const classNode of classes) {
value = IntelliSenseUtility.getClassType(classNode);
suggestions.push({
isProperty: false,
label: value,
insertText: `"${value}"`
});
}
}
} else {
// suggest enum value
propertyName = IntelliSenseUtility.resolvePropertyName(propertyPair);
propertyNode = IntelliSenseUtility.getPropertyNode(propertyName);
if (propertyNode) {
const enums = IntelliSenseUtility.getEnums(propertyNode, version);
for (const value of enums) {
suggestions.push({
isProperty: false,
label: value,
insertText: `"${value}"`
});
}
}
}
}
/**
* provide completion items
* @param document text document
* @param position position
*/
provideCompletionItems(
document: vscode.TextDocument,
position: vscode.Position
): vscode.ProviderResult<vscode.CompletionItem[] | vscode.CompletionList> {
if (!IntelliSenseUtility.enabled()) {
return undefined;
}
const text: string = DigitalTwinCompletionItemProvider.completeTextForParse(document, position);
const modelContent: ModelContent | undefined = IntelliSenseUtility.parseDigitalTwinModel(text);
if (!modelContent) {
return undefined;
}
const node: parser.Node | undefined = parser.findNodeAtOffset(modelContent.jsonNode, document.offsetAt(position));
if (!node || node.type !== JsonNodeType.String) {
return undefined;
}
// get json node of Property
const parent: parser.Node | undefined = node.parent;
if (!parent || parent.type !== JsonNodeType.Property || !parent.children) {
return undefined;
}
let completionItems: vscode.CompletionItem[] = [];
const suggestions: Suggestion[] = [];
// find out the current node is property name or property value
if (node === parent.children[0]) {
const includeValue: boolean = parent.children.length < 2;
DigitalTwinCompletionItemProvider.suggestProperty(modelContent.version, parent, includeValue, suggestions);
} else {
DigitalTwinCompletionItemProvider.suggestValue(modelContent.version, parent, suggestions);
}
const range: vscode.Range = DigitalTwinCompletionItemProvider.evaluateOverwriteRange(document, position, node);
const separator: string = DigitalTwinCompletionItemProvider.evaluateSeparatorAfter(
document.getText(),
document.offsetAt(range.end)
);
completionItems = suggestions.map(s =>
DigitalTwinCompletionItemProvider.createCompletionItem(s, position, range, separator)
);
suggestions.length = 0;
return completionItems;
}
} | the_stack |
import {LastSnapshot} from '@/services/data/account/last-snapshot-types';
import {Favorite} from '@/services/data/console/favorite-types';
import {AvailableSpaceInConsole, ConsoleSettings} from '@/services/data/console/settings-types';
import {ConnectedSpace, ConnectedSpaceGraphics, ConnectedSpaceId} from '@/services/data/tuples/connected-space-types';
import {Dashboard, DashboardId} from '@/services/data/tuples/dashboard-types';
import {Enum, EnumId} from '@/services/data/tuples/enum-types';
import {Topic} from '@/services/data/tuples/topic-types';
export enum FavoriteState {
HIDDEN = 'hidden',
SHOWN = 'shown',
PIN = 'pin'
}
export enum ConsoleEventTypes {
SETTINGS_LOADED = 'settings-loaded',
ASK_SETTINGS_LOADED = 'ask-settings-loaded',
SHOW_FAVORITE = 'show-favorite',
PIN_FAVORITE = 'pin-favorite',
UNPIN_FAVORITE = 'unpin-favorite',
HIDE_FAVORITE = 'hide-favorite',
ASK_FAVORITE_STATE = 'ask-favorite-state',
// data changing
DASHBOARD_ADDED_INTO_FAVORITE = 'dashboard-added-into-favorite',
DASHBOARD_REMOVED_FROM_FAVORITE = 'dashboard-removed-from-favorite',
CONNECTED_SPACE_ADDED_INTO_FAVORITE = 'connected-space-added-into-favorite',
CONNECTED_SPACE_REMOVED_FROM_FAVORITE = 'connected-space-removed-from-favorite',
DASHBOARD_CREATED = 'dashboard-created',
DASHBOARD_RENAMED = 'dashboard-renamed',
DASHBOARD_REMOVED = 'dashboard-removed',
CONNECTED_SPACE_CREATED = 'connected-space-created',
CONNECTED_SPACE_RENAMED = 'connected-space-renamed',
CONNECTED_SPACE_REMOVED = 'connected-space-removed',
CONNECTED_SPACE_GRAPHICS_CHANGED = 'connected-space-graphics-changed',
// ask data
ASK_LAST_SNAPSHOT = 'ask-last-snapshot',
ASK_FAVORITE = 'ask-favorite',
ASK_CONNECTED_SPACES = 'ask-connected-spaces',
ASK_CONNECTED_SPACE_GRAPHICS = 'ask-connected-space-graphics',
ASK_DASHBOARDS = 'ask-dashboards',
ASK_AVAILABLE_SPACES = 'ask-available-spaces',
ASK_AVAILABLE_TOPICS = 'ask-available-topics',
ASK_ENUM = 'ask-enum',
}
export interface ConsoleEventBus {
// settings load
fire(type: ConsoleEventTypes.SETTINGS_LOADED, settings: ConsoleSettings): this;
on(type: ConsoleEventTypes.SETTINGS_LOADED, listener: (settings: ConsoleSettings) => void): this;
off(type: ConsoleEventTypes.SETTINGS_LOADED, listener: (settings: ConsoleSettings) => void): this;
fire(type: ConsoleEventTypes.ASK_SETTINGS_LOADED, onSettingsLoadedGet: (initialized: boolean) => void): this;
on(type: ConsoleEventTypes.ASK_SETTINGS_LOADED, listener: (onSettingsLoadedGet: (initialized: boolean) => void) => void): this;
off(type: ConsoleEventTypes.ASK_SETTINGS_LOADED, listener: (onSettingsLoadedGet: (initialized: boolean) => void) => void): this;
// favorite
fire(type: ConsoleEventTypes.SHOW_FAVORITE, position: { top: number, left: number }): this;
on(type: ConsoleEventTypes.SHOW_FAVORITE, listener: (position: { top: number, left: number }) => void): this;
off(type: ConsoleEventTypes.SHOW_FAVORITE, listener: (position: { top: number, left: number }) => void): this;
fire(type: ConsoleEventTypes.PIN_FAVORITE): this;
on(type: ConsoleEventTypes.PIN_FAVORITE, listener: () => void): this;
off(type: ConsoleEventTypes.PIN_FAVORITE, listener: () => void): this;
fire(type: ConsoleEventTypes.UNPIN_FAVORITE): this;
on(type: ConsoleEventTypes.UNPIN_FAVORITE, listener: () => void): this;
off(type: ConsoleEventTypes.UNPIN_FAVORITE, listener: () => void): this;
fire(type: ConsoleEventTypes.HIDE_FAVORITE): this;
on(type: ConsoleEventTypes.HIDE_FAVORITE, listener: () => void): this;
off(type: ConsoleEventTypes.HIDE_FAVORITE, listener: () => void): this;
fire(type: ConsoleEventTypes.ASK_FAVORITE_STATE, onStateGet: (state: FavoriteState) => void): this;
on(type: ConsoleEventTypes.ASK_FAVORITE_STATE, listener: (onStateGet: (state: FavoriteState) => void) => void): this;
off(type: ConsoleEventTypes.ASK_FAVORITE_STATE, listener: (onStateGet: (state: FavoriteState) => void) => void): this;
fire(type: ConsoleEventTypes.DASHBOARD_ADDED_INTO_FAVORITE, dashboardId: DashboardId): this;
on(type: ConsoleEventTypes.DASHBOARD_ADDED_INTO_FAVORITE, listener: (dashboardId: DashboardId) => void): this;
off(type: ConsoleEventTypes.DASHBOARD_ADDED_INTO_FAVORITE, listener: (dashboardId: DashboardId) => void): this;
fire(type: ConsoleEventTypes.DASHBOARD_REMOVED_FROM_FAVORITE, dashboardId: DashboardId): this;
on(type: ConsoleEventTypes.DASHBOARD_REMOVED_FROM_FAVORITE, listener: (dashboardId: DashboardId) => void): this;
off(type: ConsoleEventTypes.DASHBOARD_REMOVED_FROM_FAVORITE, listener: (dashboardId: DashboardId) => void): this;
fire(type: ConsoleEventTypes.CONNECTED_SPACE_ADDED_INTO_FAVORITE, connectedSpaceId: ConnectedSpaceId): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_ADDED_INTO_FAVORITE, listener: (connectedSpaceId: ConnectedSpaceId) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_ADDED_INTO_FAVORITE, listener: (connectedSpaceId: ConnectedSpaceId) => void): this;
fire(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED_FROM_FAVORITE, connectedSpaceId: ConnectedSpaceId): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED_FROM_FAVORITE, listener: (connectedSpaceId: ConnectedSpaceId) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED_FROM_FAVORITE, listener: (connectedSpaceId: ConnectedSpaceId) => void): this;
// dashboard
fire(type: ConsoleEventTypes.DASHBOARD_CREATED, dashboard: Dashboard): this;
on(type: ConsoleEventTypes.DASHBOARD_CREATED, listener: (dashboard: Dashboard) => void): this;
off(type: ConsoleEventTypes.DASHBOARD_CREATED, listener: (dashboard: Dashboard) => void): this;
fire(type: ConsoleEventTypes.DASHBOARD_RENAMED, dashboard: Dashboard): this;
on(type: ConsoleEventTypes.DASHBOARD_RENAMED, listener: (dashboard: Dashboard) => void): this;
off(type: ConsoleEventTypes.DASHBOARD_RENAMED, listener: (dashboard: Dashboard) => void): this;
fire(type: ConsoleEventTypes.DASHBOARD_REMOVED, dashboard: Dashboard): this;
on(type: ConsoleEventTypes.DASHBOARD_REMOVED, listener: (dashboard: Dashboard) => void): this;
off(type: ConsoleEventTypes.DASHBOARD_REMOVED, listener: (dashboard: Dashboard) => void): this;
// connected space
fire(type: ConsoleEventTypes.CONNECTED_SPACE_CREATED, connectedSpace: ConnectedSpace): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_CREATED, listener: (connectedSpace: ConnectedSpace) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_CREATED, listener: (connectedSpace: ConnectedSpace) => void): this;
fire(type: ConsoleEventTypes.CONNECTED_SPACE_RENAMED, connectedSpace: ConnectedSpace): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_RENAMED, listener: (connectedSpace: ConnectedSpace) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_RENAMED, listener: (connectedSpace: ConnectedSpace) => void): this;
fire(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED, connectedSpace: ConnectedSpace): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED, listener: (connectedSpace: ConnectedSpace) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_REMOVED, listener: (connectedSpace: ConnectedSpace) => void): this;
fire(type: ConsoleEventTypes.CONNECTED_SPACE_GRAPHICS_CHANGED, graphics: ConnectedSpaceGraphics): this;
on(type: ConsoleEventTypes.CONNECTED_SPACE_GRAPHICS_CHANGED, listener: (graphics: ConnectedSpaceGraphics) => void): this;
off(type: ConsoleEventTypes.CONNECTED_SPACE_GRAPHICS_CHANGED, listener: (graphics: ConnectedSpaceGraphics) => void): this;
// ask state or data
fire(type: ConsoleEventTypes.ASK_LAST_SNAPSHOT, onData: (lastSnapshot: LastSnapshot) => void): this;
on(type: ConsoleEventTypes.ASK_LAST_SNAPSHOT, listener: (onData: (lastSnapshot: LastSnapshot) => void) => void): this;
off(type: ConsoleEventTypes.ASK_LAST_SNAPSHOT, listener: (onData: (lastSnapshot: LastSnapshot) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_FAVORITE, onData: (favorite: Favorite) => void): this;
on(type: ConsoleEventTypes.ASK_FAVORITE, listener: (onData: (favorite: Favorite) => void) => void): this;
off(type: ConsoleEventTypes.ASK_FAVORITE, listener: (onData: (favorite: Favorite) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_CONNECTED_SPACES, onData: (connectedSpaces: Array<ConnectedSpace>) => void): this;
on(type: ConsoleEventTypes.ASK_CONNECTED_SPACES, listener: (onData: (connectedSpaces: Array<ConnectedSpace>) => void) => void): this;
off(type: ConsoleEventTypes.ASK_CONNECTED_SPACES, listener: (onData: (connectedSpaces: Array<ConnectedSpace>) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_CONNECTED_SPACE_GRAPHICS, onData: (connectedSpaceGraphics: Array<ConnectedSpaceGraphics>) => void): this;
on(type: ConsoleEventTypes.ASK_CONNECTED_SPACE_GRAPHICS, listener: (onData: (connectedSpaceGraphics: Array<ConnectedSpaceGraphics>) => void) => void): this;
off(type: ConsoleEventTypes.ASK_CONNECTED_SPACE_GRAPHICS, listener: (onData: (connectedSpaceGraphics: Array<ConnectedSpaceGraphics>) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_DASHBOARDS, onData: (dashboards: Array<Dashboard>) => void): this;
on(type: ConsoleEventTypes.ASK_DASHBOARDS, listener: (onData: (dashboards: Array<Dashboard>) => void) => void): this;
off(type: ConsoleEventTypes.ASK_DASHBOARDS, listener: (onData: (dashboards: Array<Dashboard>) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_AVAILABLE_SPACES, onData: (availableSpaces: Array<AvailableSpaceInConsole>) => void): this;
on(type: ConsoleEventTypes.ASK_AVAILABLE_SPACES, listener: (onData: (availableSpaces: Array<AvailableSpaceInConsole>) => void) => void): this;
off(type: ConsoleEventTypes.ASK_AVAILABLE_SPACES, listener: (onData: (availableSpaces: Array<AvailableSpaceInConsole>) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_AVAILABLE_TOPICS, onData: (availableTopics: Array<Topic>) => void): this;
on(type: ConsoleEventTypes.ASK_AVAILABLE_TOPICS, listener: (onData: (availableTopics: Array<Topic>) => void) => void): this;
off(type: ConsoleEventTypes.ASK_AVAILABLE_TOPICS, listener: (onData: (availableTopics: Array<Topic>) => void) => void): this;
fire(type: ConsoleEventTypes.ASK_ENUM, enumId: EnumId, onData: (enumeration?: Enum) => void): this;
on(type: ConsoleEventTypes.ASK_ENUM, listener: (enumId: EnumId, onData: (enumeration?: Enum) => void) => void): this;
off(type: ConsoleEventTypes.ASK_ENUM, listener: (enumId: EnumId, onData: (enumeration?: Enum) => void) => void): this;
} | the_stack |
import React, {createContext} from 'react';
import AnimationProvider from './AnimationProvider';
import { clamp } from './common/utils';
import AnimationKeyframePresets from './Animations';
export default class AnimationLayerData {
private _progress: number = 0;
private _play: boolean = true;
private _isPlaying: boolean = false;
private _currentScreen: AnimationProvider | null = null;
private _nextScreen: AnimationProvider | null = null;
private _onExit: Function | undefined;
private _progressUpdateID: number = 0;
private _duration: number = 0;
private _inAnimation: Animation | null = null;
private _outAnimation: Animation | null = null;
private _playbackRate: number = 1;
private _gestureNavigating: boolean = false;
private _backNavigating: boolean = false;
private _onEnd: Function | null = null;
private _onProgress: ((progress: number) => void) | null = null;
private _shouldAnimate: boolean = true;
private updateProgress() {
if (this._gestureNavigating && !this._play) {
// update in set progress() instead
window.cancelAnimationFrame(this._progressUpdateID);
return;
}
const update = () => {
if (!this._outAnimation && !this._inAnimation) return;
const currentTime = this._gestureNavigating ? this._outAnimation?.currentTime || 0 : this._inAnimation?.currentTime || 0;
const progress = clamp((currentTime / this._duration) * 100, 0, 100);
this._progress = progress;
if (this._onProgress) {
this._onProgress(this._progress);
}
}
update();
this._progressUpdateID = window.requestAnimationFrame(this.updateProgress.bind(this));
Promise.all([this._inAnimation?.finished, this._outAnimation?.finished])
.then(() => {
window.cancelAnimationFrame(this._progressUpdateID);
if (this._progress !== 100) {
update();
}
});
}
reset() {
this._onEnd = null;
this._playbackRate = 1;
this._play = true;
this._progress = 0;
this._gestureNavigating = false;
}
finish() {
if (this._inAnimation && this._outAnimation) {
this._inAnimation.finish();
this._outAnimation.finish();
}
}
cancel() {
if (this._inAnimation && this._outAnimation) {
this._inAnimation.cancel();
this._outAnimation.cancel();
}
}
async animate() {
if (this._isPlaying) {
// cancel playing animation
this.finish();
if (this._onEnd) this._onEnd();
if (this._nextScreen) await this._nextScreen.mounted(true);
return;
}
if (this._currentScreen && this._nextScreen && this._shouldAnimate) {
if (this._gestureNavigating) {
await this._currentScreen.mounted(true);
}
if (this._backNavigating) {
this._currentScreen.zIndex = 1;
this._nextScreen.zIndex = 0;
} else {
this._currentScreen.zIndex = 0;
this._nextScreen.zIndex = 1;
}
if (this._gestureNavigating) {
this._progress = 100;
} else {
this._progress = 0;
}
if (this._onProgress) this._onProgress(this._progress);
// failing to call _onExit to disable SETs
if (this._onExit && this._shouldAnimate) this._onExit();
await this._nextScreen.mounted(true);
let easingFunction = this._gestureNavigating ? 'linear' : 'ease-out';
if (Array.isArray(this._currentScreen.outAnimation)) { // predefined animation
const [animation, duration, userDefinedEasingFunction] = this._currentScreen.outAnimation;
this._outAnimation = this._currentScreen.animate(AnimationKeyframePresets[animation], {
fill: 'both',
duration: duration,
easing: userDefinedEasingFunction || easingFunction
});
if (this._gestureNavigating || this._backNavigating) this._duration = duration;
} else { // user provided animation
let {keyframes, options} = this._currentScreen.outAnimation;
if (typeof options === "number") {
options = {
duration: options,
easing: easingFunction,
fill: 'both'
};
} else {
options = {
...options,
easing: options?.easing || easingFunction,
duration: options?.duration || this.duration,
fill: options?.fill || 'both'
};
}
this._outAnimation = this._currentScreen.animate(keyframes, options);
if (this._gestureNavigating || this._backNavigating) {
let duration = this._outAnimation?.effect?.getTiming().duration;
if (typeof duration === "string") duration = parseFloat(duration);
this._duration = duration || this._duration;
}
}
if (Array.isArray(this._nextScreen.inAnimation)) { // predefined animation
const [animation, duration, userDefinedEasingFunction] = this._nextScreen.inAnimation;
this._inAnimation = this._nextScreen.animate(AnimationKeyframePresets[animation], {
fill: 'both',
duration: duration,
easing: userDefinedEasingFunction || easingFunction
});
if (!this.gestureNavigating && !this._backNavigating) this._duration = duration;
} else { // user provided animation
let {keyframes, options} = this._nextScreen.inAnimation;
if (typeof options === "number") {
options = {
duration: options,
easing: easingFunction,
fill: 'both'
};
} else {
options = {
...options,
fill: options?.fill || 'both',
duration: options?.duration || this.duration,
easing: options?.easing || easingFunction
};
}
this._inAnimation = this._nextScreen.animate(keyframes, options);
if (!this._gestureNavigating && !this._backNavigating) {
let duration = this._inAnimation?.effect?.getTiming().duration;
if (typeof duration === "string") duration = parseFloat(duration);
this._duration = duration || this._duration;
}
}
this._isPlaying = true;
const startAnimationEvent = new CustomEvent('page-animation-start');
window.dispatchEvent(startAnimationEvent);
if (this._inAnimation && this._outAnimation) {
if (!this._shouldAnimate) {
this.finish();
this._isPlaying = false;
this._shouldAnimate = true;
return;
}
this._inAnimation.playbackRate = this._playbackRate;
this._outAnimation.playbackRate = this._playbackRate;
if (this._gestureNavigating) {
let inDuration = this._inAnimation.effect?.getTiming().duration || this._duration;
if (typeof inDuration === "string") inDuration = parseFloat(inDuration);
let outDuration = this._outAnimation.effect?.getTiming().duration || this._duration;
if (typeof outDuration === "string") outDuration = parseFloat(outDuration);
this._inAnimation.currentTime = inDuration;
this._outAnimation.currentTime = outDuration;
}
if (!this._play) {
this._inAnimation.pause();
this._outAnimation.pause();
this._isPlaying = false;
}
await Promise.all([this._inAnimation.ready, this._outAnimation.ready])
this.updateProgress();
await Promise.all([this._outAnimation.finished, this._inAnimation.finished])
if (this._inAnimation) {
this._inAnimation.commitStyles();
this._inAnimation.cancel();
this._inAnimation = null;
}
if (this._outAnimation) {
this._outAnimation.commitStyles();
this._outAnimation.cancel();
this._outAnimation = null;
}
// if playback rate is 2 then gesture navigation was aborted
if (!this._gestureNavigating || this._playbackRate === 0.5) {
this._currentScreen.zIndex = 0;
this._nextScreen.zIndex = 1;
if (this._currentScreen)
this._currentScreen.mounted(false);
} else {
this._nextScreen.zIndex = 0;
this._currentScreen.zIndex = 1;
if (this._nextScreen)
await this._nextScreen.mounted(false);
}
if (this._onEnd) {
this._onEnd();
}
this._isPlaying = false;
const endAnimationEvent = new CustomEvent('page-animation-end');
window.dispatchEvent(endAnimationEvent);
}
} else {
this._shouldAnimate = true;
}
}
set onProgress(_onProgress: ((progress: number) => void) | null) {
this._onProgress = _onProgress;
}
set onEnd(_onEnd: Function | null) {
this._onEnd = _onEnd;
}
set shouldAnimate(_shouldAnimate: boolean) {
this._shouldAnimate = _shouldAnimate;
}
set playbackRate(_playbackRate: number) {
this._playbackRate = _playbackRate;
if (this._inAnimation && this._outAnimation) {
this._inAnimation.playbackRate = this._playbackRate;
this._outAnimation.playbackRate = this._playbackRate;
}
}
set gestureNavigating(_gestureNavigating: boolean) {
this._gestureNavigating = _gestureNavigating;
}
set backNavigating(_backNavigating: boolean) {
this._backNavigating = _backNavigating;
}
set play(_play: boolean) {
if (this._play !== _play) {
this._play = _play;
if (this._play && this._gestureNavigating) {
this.updateProgress();
}
if (this._inAnimation && this._outAnimation) {
if (_play) {
this._inAnimation.play();
this._outAnimation.play();
} else {
this._inAnimation.pause();
this._outAnimation.pause();
}
}
}
}
set progress(_progress: number) {
this._progress = _progress;
if (this._onProgress) {
this._onProgress(this._progress);
}
let inDuration = this._inAnimation?.effect?.getTiming().duration || this._duration;
if (typeof inDuration === "string") inDuration = parseFloat(inDuration);
const inCurrentTime = (this._progress / 100) * inDuration;
let outDuration = this._outAnimation?.effect?.getTiming().duration || this._duration;
if (typeof outDuration === "string") outDuration = parseFloat(outDuration);
const outCurrentTime = (this._progress / 100) * outDuration;
if (this._inAnimation && this._outAnimation) {
this._inAnimation.currentTime = inCurrentTime;
this._outAnimation.currentTime = outCurrentTime;
}
}
set currentScreen(_screen: AnimationProvider) {
this._currentScreen = _screen;
}
set nextScreen(_screen: AnimationProvider) {
this._nextScreen = _screen;
if (!this._currentScreen) {
_screen.mounted(true, false);
this._nextScreen = null;
}
}
set onExit(_onExit: Function | undefined) {
this._onExit = _onExit;
}
get duration() {
return this._duration;
}
get progress() {
return this._progress;
}
get gestureNavigating() {
return this._gestureNavigating;
}
get backNavigating() {
return this._backNavigating;
}
get isPlying() {
return this._isPlaying;
}
}
export const AnimationLayerDataContext = createContext<AnimationLayerData>(new AnimationLayerData()); | the_stack |
import { debug } from "../../debug"
import * as node_fetch from "node-fetch"
import { Agent } from "http"
import HttpsProxyAgent from "https-proxy-agent"
import { URLSearchParams } from "url"
import { Env } from "../../ci_source/ci_source"
import { dangerIDToString } from "../../runner/templates/bitbucketCloudTemplate"
import { api as fetch } from "../../api/fetch"
import {
BitBucketCloudPagedResponse,
BitBucketCloudPRDSL,
BitBucketCloudCommit,
BitBucketCloudPRActivity,
BitBucketCloudPRComment,
} from "../../dsl/BitBucketCloudDSL"
import { Comment } from "../platform"
import { RepoMetaData } from "../../dsl/BitBucketServerDSL"
export type BitBucketCloudCredentials = {
/** Unique ID for this user, must be wrapped with brackets */
uuid?: string
} & (BitBucketCloudCredentialsOAuth | BitBucketCloudCredentialsPassword)
interface BitBucketCloudCredentialsOAuth {
type: "OAUTH"
oauthKey: string
oauthSecret: string
}
interface BitBucketCloudCredentialsPassword {
type: "PASSWORD"
username: string
password: string
}
export function bitbucketCloudCredentialsFromEnv(env: Env): BitBucketCloudCredentials {
const uuid: string | undefined = env["DANGER_BITBUCKETCLOUD_UUID"]
if (uuid != null && uuid.length > 0) {
if (!uuid.startsWith("{") || !uuid.endsWith("}")) {
throw new Error(`DANGER_BITBUCKETCLOUD_UUID must be wraped with brackets`)
}
}
if (env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"]) {
if (!env["DANGER_BITBUCKETCLOUD_OAUTH_SECRET"]) {
throw new Error(`DANGER_BITBUCKETCLOUD_OAUTH_SECRET is not set`)
}
return {
type: "OAUTH",
uuid,
oauthKey: env["DANGER_BITBUCKETCLOUD_OAUTH_KEY"],
oauthSecret: env["DANGER_BITBUCKETCLOUD_OAUTH_SECRET"],
}
} else if (env["DANGER_BITBUCKETCLOUD_USERNAME"]) {
if (!env["DANGER_BITBUCKETCLOUD_PASSWORD"]) {
throw new Error(`DANGER_BITBUCKETCLOUD_PASSWORD is not set`)
}
return {
type: "PASSWORD",
username: env["DANGER_BITBUCKETCLOUD_USERNAME"],
password: env["DANGER_BITBUCKETCLOUD_PASSWORD"],
uuid,
}
}
throw new Error(`Either DANGER_BITBUCKETCLOUD_OAUTH_KEY or DANGER_BITBUCKETCLOUD_USERNAME is not set`)
}
export class BitBucketCloudAPI {
fetch: typeof fetch
accessToken: string | undefined
uuid: string | undefined
private readonly d = debug("BitBucketCloudAPI")
private pr: BitBucketCloudPRDSL | undefined
private commits: BitBucketCloudCommit[] | undefined
private baseURL = "https://api.bitbucket.org/2.0"
private oauthURL = "https://bitbucket.org/site/oauth2/access_token"
constructor(public readonly repoMetadata: RepoMetaData, public readonly credentials: BitBucketCloudCredentials) {
// This allows Peril to DI in a new Fetch function
// which can handle unique API edge-cases around integrations
this.fetch = fetch
// Backward compatible,
this.uuid = credentials.uuid
}
getBaseRepoURL() {
const { repoSlug } = this.repoMetadata
return `${this.baseURL}/repositories/${repoSlug}`
}
getPRURL() {
const { pullRequestID } = this.repoMetadata
return `${this.getBaseRepoURL()}/pullrequests/${pullRequestID}`
}
getPullRequestsFromBranch = async (branch: string): Promise<BitBucketCloudPRDSL[]> => {
// Need to encode URI here because it used special characters in query params.
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests
let nextPageURL: string | undefined = encodeURI(
`${this.getBaseRepoURL()}/pullrequests?q=source.branch.name = "${branch}"`
)
let values: BitBucketCloudPRDSL[] = []
do {
const res = await this.get(nextPageURL)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketCloudPagedResponse<BitBucketCloudPRDSL>
values = values.concat(data.values)
nextPageURL = data.next
} while (nextPageURL != null)
return values
}
getPullRequestInfo = async (): Promise<BitBucketCloudPRDSL> => {
if (this.pr) {
return this.pr
}
const res = await this.get(this.getPRURL())
throwIfNotOk(res)
const prDSL = (await res.json()) as BitBucketCloudPRDSL
this.pr = prDSL
return prDSL
}
getPullRequestCommits = async (): Promise<BitBucketCloudCommit[]> => {
if (this.commits) {
return this.commits
}
let values: BitBucketCloudCommit[] = []
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests/%7Bpull_request_id%7D/commits
let nextPageURL: string | undefined = `${this.getPRURL()}/commits`
do {
const res = await this.get(nextPageURL)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketCloudPagedResponse<BitBucketCloudCommit>
values = values.concat(data.values)
nextPageURL = data.next
} while (nextPageURL != null)
this.commits = values
return values
}
getPullRequestDiff = async () => {
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests/%7Bpull_request_id%7D/diff
const res = await this.get(`${this.getPRURL()}/diff`)
return res.ok ? res.text() : ""
}
getPullRequestComments = async (): Promise<BitBucketCloudPRComment[]> => {
let values: BitBucketCloudPRComment[] = []
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests/%7Bpull_request_id%7D/comments
let nextPageURL: string | undefined = `${this.getPRURL()}/comments?q=deleted=false`
do {
const res = await this.get(nextPageURL)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketCloudPagedResponse<BitBucketCloudPRComment>
values = values.concat(data.values)
nextPageURL = data.next
} while (nextPageURL != null)
return values
}
getPullRequestActivities = async (): Promise<BitBucketCloudPRActivity[]> => {
let values: BitBucketCloudPRActivity[] = []
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/pullrequests/%7Bpull_request_id%7D/activity
let nextPageURL: string | undefined = `${this.getPRURL()}/activity`
do {
const res = await this.get(nextPageURL)
throwIfNotOk(res)
const data = (await res.json()) as BitBucketCloudPagedResponse<BitBucketCloudPRActivity>
values = values.concat(data.values)
nextPageURL = data.next
} while (nextPageURL != null)
return values
}
getFileContents = async (filePath: string, repoSlug?: string, ref?: string) => {
if (!repoSlug || !ref) {
const prJSON = await this.getPullRequestInfo()
repoSlug = prJSON.source.repository.full_name
ref = prJSON.source.commit.hash
}
const url = `${this.baseURL}/repositories/${repoSlug}/src/${ref}/${filePath}`
const res = await this.get(url, undefined, true)
if (res.status === 404) {
return ""
}
throwIfNotOk(res)
return await res.text()
}
getDangerMainComments = async (dangerID: string): Promise<BitBucketCloudPRComment[]> => {
const comments = await this.getPullRequestComments()
const dangerIDMessage = dangerIDToString(dangerID)
return comments
.filter(comment => comment.inline == null)
.filter(comment => comment.content.raw.includes(dangerIDMessage))
.filter(comment => comment.user.uuid === this.uuid)
}
getDangerInlineComments = async (dangerID: string): Promise<Comment[]> => {
const comments = await this.getPullRequestComments()
const dangerIDMessage = dangerIDToString(dangerID)
return comments.filter(comment => comment.inline).map(comment => ({
id: comment.id.toString(),
ownedByDanger: comment.content.raw.includes(dangerIDMessage) && comment.user.uuid === this.uuid,
body: comment.content.raw,
}))
}
postBuildStatus = async (
commitId: string,
payload: {
state: "SUCCESSFUL" | "FAILED" | "INPROGRESS" | "STOPPED"
key: string
name: string
url: string
description: string
}
) => {
// https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build
const res = await this.post(`${this.getBaseRepoURL()}/commit/${commitId}/statuses/build`, {}, payload)
throwIfNotOk(res)
return await res.json()
}
postPRComment = async (comment: string) => {
const url = `${this.getPRURL()}/comments`
const res = await this.post(url, {}, { content: { raw: comment } })
return await res.json()
}
postInlinePRComment = async (comment: string, line: number, filePath: string) => {
const url = `${this.getPRURL()}/comments`
const res = await this.post(
url,
{},
{
content: {
raw: comment,
},
inline: {
to: line,
path: filePath,
},
}
)
if (res.ok) {
return res.json()
} else {
throw await res.json()
}
}
deleteComment = async (id: string) => {
const path = `${this.getPRURL()}/comments/${id}`
const res = await this.delete(path)
if (!res.ok) {
throw new Error(`Failed to delete comment "${id}`)
}
}
updateComment = async (id: string, comment: string) => {
const path = `${this.getPRURL()}/comments/${id}`
const res = await this.put(
path,
{},
{
content: {
raw: comment,
},
}
)
if (res.ok) {
return res.json()
} else {
throw await res.json()
}
}
// API implementation
private api = async (url: string, headers: any = {}, body: any = {}, method: string, suppressErrors?: boolean) => {
if (this.credentials.type === "PASSWORD") {
headers["Authorization"] = `Basic ${new Buffer(
this.credentials.username + ":" + this.credentials.password
).toString("base64")}`
} else {
if (this.accessToken == null) {
this.d(`accessToken not found, trying to get from ${this.oauthURL}.`)
const params = new URLSearchParams()
params.append("grant_type", "client_credentials")
const authResponse = await this.performAPI(
this.oauthURL,
{
...headers,
Authorization: `Basic ${new Buffer(this.credentials.oauthKey + ":" + this.credentials.oauthSecret).toString(
"base64"
)}`,
"Content-Type": "application/x-www-form-urlencoded",
},
params,
"POST",
suppressErrors
)
if (authResponse.ok) {
const jsonResp = await authResponse.json()
this.accessToken = jsonResp["access_token"]
} else {
throwIfNotOk(authResponse)
}
}
headers["Authorization"] = `Bearer ${this.accessToken}`
}
if (this.uuid == null) {
this.d(`UUID not found, trying to get from ${this.baseURL}/user`)
const profileResponse = await this.performAPI(`${this.baseURL}/user`, headers, null, "GET", suppressErrors)
if (profileResponse.ok) {
const jsonResp = await profileResponse.json()
this.uuid = jsonResp["uuid"]
} else {
let message = `${profileResponse.status} - ${profileResponse.statusText}`
if (profileResponse.status >= 400 && profileResponse.status < 500) {
message += ` (Have you allowed permission 'account' for this credential?)`
}
throw new Error(message)
}
}
return this.performAPI(url, headers, body, method, suppressErrors)
}
private performAPI = (url: string, headers: any = {}, body: any = {}, method: string, suppressErrors?: boolean) => {
this.d(`${method} ${url}`)
// Allow using a proxy configured through environmental variables
// Remember that to avoid the error "Error: self signed certificate in certificate chain"
// you should also do: "export NODE_TLS_REJECT_UNAUTHORIZED=0". See: https://github.com/request/request/issues/2061
let agent: Agent | undefined = undefined
let proxy = process.env.http_proxy || process.env.https_proxy
if (proxy) {
agent = new HttpsProxyAgent(proxy)
}
return this.fetch(
url,
{
method,
body,
headers: {
"Content-Type": "application/json",
...headers,
},
agent,
},
suppressErrors
)
}
get = (url: string, headers: any = {}, suppressErrors?: boolean): Promise<node_fetch.Response> =>
this.api(url, headers, null, "GET", suppressErrors)
post = (url: string, headers: any = {}, body: any = {}, suppressErrors?: boolean): Promise<node_fetch.Response> =>
this.api(url, headers, JSON.stringify(body), "POST", suppressErrors)
put = (url: string, headers: any = {}, body: any = {}): Promise<node_fetch.Response> =>
this.api(url, headers, JSON.stringify(body), "PUT")
delete = (url: string, headers: any = {}, body: any = {}): Promise<node_fetch.Response> =>
this.api(url, headers, JSON.stringify(body), "DELETE")
}
function throwIfNotOk(res: node_fetch.Response) {
if (!res.ok) {
let message = `${res.status} - ${res.statusText}`
if (res.status >= 400 && res.status < 500) {
message += ` (Have you set DANGER_BITBUCKETCLOUD_USERNAME or DANGER_BITBUCKETCLOUD_OAUTH_KEY?)`
}
throw new Error(message)
}
} | the_stack |
import React, {useState, useEffect, useContext} from "react";
import {Button, Modal, Tooltip} from "antd";
import {UserContext} from "../../util/user-context";
import {SearchContext} from "../../util/search-context";
import SelectedFacets from "../../components/selected-facets/selected-facets";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPencilAlt, faSave, faCopy, faUndo, faWindowClose} from "@fortawesome/free-solid-svg-icons";
import SaveQueryModal from "../../components/queries/saving/save-query-modal/save-query-modal";
import SaveQueriesDropdown from "../../components/queries/saving/save-queries-dropdown/save-queries-dropdown";
import {fetchQueries, creatNewQuery, fetchQueryById} from "../../api/queries";
import styles from "./queries.module.scss";
import EditQueryDetails from "./saving/edit-save-query/edit-query-details";
import SaveChangesModal from "./saving/edit-save-query/save-changes-modal";
import DiscardChangesModal from "./saving/discard-changes/discard-changes-modal";
import {QueryOptions} from "../../types/query-types";
import {MLButton, MLTooltip} from "@marklogic/design-system";
import {getUserPreferences} from "../../services/user-preferences";
interface Props {
queries: any[];
isSavedQueryUser: boolean;
columns: string[];
entities: any[];
selectedFacets: any[];
greyFacets: any[];
isColumnSelectorTouched: boolean;
entityDefArray: any[];
setColumnSelectorTouched: (state: boolean) => void;
setQueries: (state: boolean) => void;
setIsLoading: (state: boolean) => void;
database: string;
setCardView: any;
cardView: boolean;
}
const Query: React.FC<Props> = (props) => {
const {
user,
handleError
} = useContext(UserContext);
const {
searchOptions,
applySaveQuery,
clearAllGreyFacets,
setEntity,
setNextEntity,
setSavedQueries,
savedQueries
} = useContext(SearchContext);
const [openSaveModal, setOpenSaveModal] = useState(false);
const [showApply, toggleApply] = useState(false);
const [applyClicked, toggleApplyClicked] = useState(false);
const [openEditDetail, setOpenEditDetail] = useState(false);
const [currentQuery, setCurrentQuery] = useState<any>({});
const [hoverOverDropdown, setHoverOverDropdown] = useState(false);
const [showSaveNewIcon, toggleSaveNewIcon] = useState(false);
const [showSaveChangesIcon, toggleSaveChangesIcon] = useState(false);
const [openSaveChangesModal, setOpenSaveChangesModal] = useState(false);
const [showDiscardIcon, toggleDiscardIcon] = useState(false);
const [openSaveCopyModal, setOpenSaveCopyModal] = useState(false);
const [openDiscardChangesModal, setOpenDiscardChangesModal] = useState(false);
const [currentQueryName, setCurrentQueryName] = useState(searchOptions.selectedQuery);
const [nextQueryName, setNextQueryName] = useState("");
const [currentQueryDescription, setCurrentQueryDescription] = useState("");
const [showEntityConfirmation, toggleEntityConfirmation] = useState(false);
const [entityQueryUpdate, toggleEntityQueryUpdate] = useState(false);
const [entityCancelClicked, toggleEntityCancelClicked] = useState(false);
const [resetQueryIcon, setResetQueryIcon] = useState(true); // eslint-disable-line @typescript-eslint/no-unused-vars
const [showResetQueryNewConfirmation, toggleResetQueryNewConfirmation] = useState(false);
const [showResetQueryEditedConfirmation, toggleResetQueryEditedConfirmation] = useState(false);
const [existingQueryYesClicked, toggleExistingQueryYesClicked] = useState(false);
const [resetYesClicked, toggleResetYesClicked] = useState(false);
const saveNewQuery = async (queryName, queryDescription, facets) => {
let query = {
savedQuery: {
id: "",
name: queryName,
description: queryDescription,
query: {
searchText: searchOptions.query,
entityTypeIds: searchOptions.entityTypeIds.length ? searchOptions.entityTypeIds : props.entities,
selectedFacets: facets,
},
propertiesToDisplay: searchOptions.selectedTableProperties,
sortOrder: searchOptions.sortOrder
}
};
props.setIsLoading(true);
await creatNewQuery(query);
setOpenSaveModal(false);
getSaveQueries();
};
const getSaveQueries = async () => {
try {
if (props.isSavedQueryUser) {
const response = await fetchQueries();
if (response.data) {
props.setQueries(response.data);
setSavedQueries(response.data);
}
}
} catch (error) {
handleError(error);
}
};
const getSaveQueryWithId = async (key) => {
try {
const response = await fetchQueryById(key);
if (props.isSavedQueryUser) {
if (response.data) {
let options: QueryOptions = {
searchText: response.data.savedQuery.query.searchText,
entityTypeIds: response.data.savedQuery.query.entityTypeIds,
selectedFacets: response.data.savedQuery.query.selectedFacets,
selectedQuery: response.data.savedQuery.name,
propertiesToDisplay: response.data.savedQuery.propertiesToDisplay,
zeroState: searchOptions.zeroState,
sortOrder: response.data.savedQuery.sortOrder,
database: searchOptions.database,
};
applySaveQuery(options);
setCurrentQuery(response.data);
if (props.greyFacets.length > 0) {
clearAllGreyFacets();
}
toggleApply(false);
if (response.data.savedQuery.hasOwnProperty("description") && response.data.savedQuery.description) {
setCurrentQueryDescription(response.data.savedQuery.description);
} else {
setCurrentQueryDescription("");
}
}
}
} catch (error) {
handleError(error);
}
};
const isSaveQueryChanged = () => {
if (currentQuery && currentQuery.hasOwnProperty("savedQuery") && currentQuery.savedQuery.hasOwnProperty("query")) {
if (currentQuery.savedQuery.name !== searchOptions.selectedQuery) {
if (Array.isArray(savedQueries) === false) {
if (savedQueries.savedQuery.name === searchOptions.selectedQuery) {
setCurrentQuery(savedQueries.savedQuery);
setCurrentQueryName(savedQueries.savedQuery.name);
setCurrentQueryDescription(savedQueries.savedQuery.description);
}
} else {
for (let key of savedQueries) {
if (key.savedQuery.name === searchOptions.selectedQuery) {
setCurrentQuery(key);
setCurrentQueryName(key.savedQuery.name);
setCurrentQueryDescription(key.savedQuery.description);
}
}
}
}
if ((
(JSON.stringify(currentQuery.savedQuery.query.selectedFacets) !== JSON.stringify(searchOptions.selectedFacets)) ||
(currentQuery.savedQuery.query.searchText !== searchOptions.query) ||
(JSON.stringify(currentQuery.savedQuery.sortOrder) !== JSON.stringify(searchOptions.sortOrder)) ||
(JSON.stringify(currentQuery.savedQuery.propertiesToDisplay) !== JSON.stringify(searchOptions.selectedTableProperties)) ||
(props.greyFacets.length > 0) || props.isColumnSelectorTouched) &&
searchOptions.selectedQuery !== "select a query") {
return true;
}
}
return false;
};
const isNewQueryChanged = () => {
if (currentQuery && Object.keys(currentQuery).length === 0) {
if (props.isSavedQueryUser && searchOptions.entityTypeIds.length > 0 &&
(props.selectedFacets.length > 0 || searchOptions.query.length > 0
|| searchOptions.sortOrder.length > 0 || props.isColumnSelectorTouched)
&& searchOptions.selectedQuery === "select a query") {
return true;
}
}
return false;
};
useEffect(() => {
setCurrentQuery({});
}, [searchOptions.database]);
useEffect(() => {
if (props.queries.length > 0) {
for (let key of props.queries) {
if (key.savedQuery.name === currentQueryName) {
setCurrentQuery(key);
// setCurrentQueryDescription(key['savedQuery']['description']);
}
}
}
}, [props.queries]);
useEffect(() => {
getSaveQueries();
}, [searchOptions.entityTypeIds]);
useEffect(() => {
props.setQueries(savedQueries);
}, [savedQueries]);
useEffect(() => {
if (savedQueries && savedQueries.length > 0) {
for (let key of savedQueries) {
if (key.savedQuery.name === currentQueryName) {
setCurrentQuery(key);
}
}
}
if (searchOptions.selectedQuery === "select a query") {
setCurrentQueryDescription("");
}
}, [savedQueries]);
useEffect(() => {
initializeUserPreferences();
}, []);
useEffect(() => {
if (searchOptions.nextEntityType && !entityCancelClicked && searchOptions.nextEntityType !== searchOptions.entityTypeIds[0]) {
// TO CHECK IF THERE HAS BEEN A CANCEL CLICKED WHILE CHANGING ENTITY
if ((isSaveQueryChanged() || isNewQueryChanged()) && !searchOptions.zeroState) {
toggleEntityConfirmation(true);
} else {
setCurrentQueryOnEntityChange();
}
} else {
toggleEntityCancelClicked(false); // RESETTING THE STATE TO FALSE
}
}, [searchOptions.nextEntityType]);
const initializeUserPreferences = async () => {
let defaultPreferences = getUserPreferences(user.name);
if (defaultPreferences !== null) {
let parsedPreferences = JSON.parse(defaultPreferences);
if (parsedPreferences.selectedQuery !== "select a query" && JSON.stringify(parsedPreferences) !== JSON.stringify([])) {
if (parsedPreferences.queries && Array.isArray(parsedPreferences.queries)) {
let queryObject = parsedPreferences.queries.find(obj => parsedPreferences.selectedQuery === obj.savedQuery?.name);
if (queryObject?.savedQuery && queryObject.savedQuery.hasOwnProperty("description") && queryObject.savedQuery.description) {
setCurrentQueryDescription(queryObject?.savedQuery.description);
}
}
}
}
};
// Switching between entity confirmation modal buttons
const onCancel = () => {
toggleEntityConfirmation(false);
toggleEntityCancelClicked(true);
setNextEntity(searchOptions.entityTypeIds[0]);
};
const onNoClick = () => {
toggleEntityConfirmation(false);
setCurrentQueryOnEntityChange();
};
const onOk = () => {
if (Object.keys(currentQuery).length === 0) {
toggleEntityConfirmation(false);
toggleExistingQueryYesClicked(true);
setOpenSaveModal(true);
} else {
setOpenSaveChangesModal(true);
toggleEntityConfirmation(false);
toggleEntityQueryUpdate(true);
}
};
const setCurrentQueryOnEntityChange = () => {
if (searchOptions.nextEntityType === "All Data") {
props.setCardView(true);
} else {
props.setCardView(false);
}
setEntity(searchOptions.nextEntityType);
toggleSaveNewIcon(false);
props.setColumnSelectorTouched(false);
setCurrentQuery({});
setCurrentQueryName("select a query");
setCurrentQueryDescription("");
};
// Reset confirmation modal buttons when making changes to saved query
const onResetCancel = () => {
toggleResetQueryNewConfirmation(false);
toggleResetQueryEditedConfirmation(false);
};
const onResetOk = () => {
if (showResetQueryNewConfirmation) {
setOpenSaveModal(true);
toggleResetYesClicked(true);
} else {
setOpenSaveChangesModal(true);
toggleResetYesClicked(true);
}
toggleResetQueryNewConfirmation(false);
toggleResetQueryEditedConfirmation(false);
};
const onNoResetClick = () => {
let options: QueryOptions = {
searchText: "",
entityTypeIds: [],
selectedFacets: {},
selectedQuery: "select a query",
propertiesToDisplay: [],
zeroState: true,
sortOrder: [],
database: "final",
};
applySaveQuery(options);
toggleResetQueryEditedConfirmation(false);
toggleResetQueryNewConfirmation(false);
props.setColumnSelectorTouched(false);
};
const resetIconClicked = () => {
const resetQueryEditedConfirmation = props.isSavedQueryUser && props.queries.length > 0
&& searchOptions.selectedQuery !== "select a query" && isSaveQueryChanged();
const resetQueryNewConfirmation = props.isSavedQueryUser && props.queries.length > 0 && searchOptions.entityTypeIds.length > 0 &&
(props.selectedFacets.length > 0 || searchOptions.query.length > 0
|| searchOptions.sortOrder.length > 0)
&& searchOptions.selectedQuery === "select a query";
if (resetQueryNewConfirmation) {
toggleResetQueryNewConfirmation(true);
} else if (resetQueryEditedConfirmation) {
toggleResetQueryEditedConfirmation(true);
} else {
let options: QueryOptions = {
searchText: "",
entityTypeIds: [],
selectedFacets: {},
selectedQuery: "select a query",
propertiesToDisplay: [],
zeroState: true,
sortOrder: [],
database: "final",
};
applySaveQuery(options);
clearAllGreyFacets();
}
};
useEffect(() => {
if (Object.entries(currentQuery).length !== 0 && searchOptions.selectedQuery !== "select a query") {
setHoverOverDropdown(true);
setCurrentQueryName(currentQuery.hasOwnProperty("name") ? currentQuery["name"] : currentQuery["savedQuery"]["name"]);
setCurrentQueryDescription(currentQuery.hasOwnProperty("description") ? currentQuery["description"] : currentQuery["savedQuery"]["description"]);
} else {
setHoverOverDropdown(false);
setCurrentQueryDescription("");
}
}, [currentQuery]);
useEffect(() => {
if (isSaveQueryChanged() && searchOptions.selectedQuery !== "select a query") {
toggleSaveChangesIcon(true);
toggleDiscardIcon(true);
toggleSaveNewIcon(false);
} else {
toggleSaveChangesIcon(false);
toggleDiscardIcon(false);
toggleSaveNewIcon(true);
}
}, [searchOptions, props.greyFacets, isSaveQueryChanged()]);
return (
<>
<div>
{props.cardView === false && <div>
<div className={styles.queryBar}>
<div className={styles.saveDropdown}>
{props.queries.length > 0 &&
<SaveQueriesDropdown
savedQueryList={props.queries}
setSaveNewIconVisibility={(visibility) => toggleSaveNewIcon(visibility)}
greyFacets={props.greyFacets}
toggleApply={(clicked) => toggleApply(clicked)}
currentQueryName={currentQueryName}
setCurrentQueryName={setCurrentQueryName}
currentQuery={currentQuery}
setSaveChangesIconVisibility={(visibility) => toggleSaveChangesIcon(visibility)}
setDiscardChangesIconVisibility={(visibility) => toggleDiscardIcon(visibility)}
setSaveChangesModal={(visiblity) => setOpenSaveChangesModal(visiblity)}
setNextQueryName={(nextQueryName) => setNextQueryName(nextQueryName)}
getSaveQueryWithId={getSaveQueryWithId}
isSaveQueryChanged={isSaveQueryChanged}
/>
}
</div>
<div className={styles.iconBar}>
{(props.selectedFacets.length > 0 || searchOptions.query
|| props.isColumnSelectorTouched || searchOptions.sortOrder.length > 0) &&
showSaveNewIcon && searchOptions.entityTypeIds.length > 0 && searchOptions.selectedQuery === "select a query" &&
<div>
<MLTooltip title={props.isSavedQueryUser ? "Save the current query" : "Save Query: Contact your security administrator to get the roles and permissions to access this functionality"}>
<FontAwesomeIcon
icon={faSave}
onClick={props.isSavedQueryUser ? () => setOpenSaveModal(true) : () => setOpenSaveModal(false)}
className={props.isSavedQueryUser ? styles.enabledSaveIcon : styles.disabledSaveIcon}
data-testid="save-modal"
size="lg"
style={{width: "15px", color: "#5b69af", cursor: "pointer"}}
/>
</MLTooltip>
<div id={"savedQueries"}>
{openSaveModal &&
<SaveQueryModal
setSaveModalVisibility={() => setOpenSaveModal(false)}
setSaveNewIconVisibility={(visibility) => toggleSaveNewIcon(visibility)}
saveNewQuery={saveNewQuery}
greyFacets={props.greyFacets}
toggleApply={(clicked) => toggleApply(clicked)}
toggleApplyClicked={(clicked) => toggleApplyClicked(clicked)}
currentQueryName={currentQueryName}
setCurrentQueryName={setCurrentQueryName}
currentQueryDescription={currentQueryDescription}
setCurrentQueryDescription={setCurrentQueryDescription}
resetYesClicked={resetYesClicked}
setColumnSelectorTouched={props.setColumnSelectorTouched}
existingQueryYesClicked={existingQueryYesClicked}
/>}
</div>
</div>}
{props.isSavedQueryUser && showSaveChangesIcon && props.queries.length > 0 &&
<div>
<MLTooltip title={"Save changes"}>
<FontAwesomeIcon
icon={faSave}
className={styles.iconHover}
title="save-changes"
onClick={() => setOpenSaveChangesModal(true)}
data-testid="save-changes-modal"
size="lg"
style={{width: "15px", color: "#5b69af", cursor: "pointer"}}
/>
</MLTooltip>
<div id={"saveChangedQueries"}>
{openSaveChangesModal &&
<SaveChangesModal
setSaveChangesModalVisibility={() => setOpenSaveChangesModal(false)}
setSaveNewIconVisibility={(visibility) => toggleSaveNewIcon(visibility)}
greyFacets={props.greyFacets}
toggleApply={(clicked) => toggleApply(clicked)}
toggleApplyClicked={(clicked) => toggleApplyClicked(clicked)}
currentQuery={currentQuery}
currentQueryName={currentQueryName}
setCurrentQueryDescription={(description) => setCurrentQueryDescription(description)}
setCurrentQueryName={(name) => setCurrentQueryName(name)}
nextQueryName={nextQueryName}
savedQueryList={props.queries}
setCurrentQueryOnEntityChange={setCurrentQueryOnEntityChange}
getSaveQueryWithId={(key) => getSaveQueryWithId(key)}
isSaveQueryChanged={isSaveQueryChanged}
entityQueryUpdate={entityQueryUpdate}
toggleEntityQueryUpdate={() => toggleEntityQueryUpdate(false)}
resetYesClicked={resetYesClicked}
setColumnSelectorTouched={props.setColumnSelectorTouched}
/>}
</div>
</div>}
{props.isSavedQueryUser && showDiscardIcon && props.queries.length > 0 &&
<div>
<MLTooltip title={"Discard changes"}>
<FontAwesomeIcon
icon={faUndo}
className={styles.iconHover}
title="discard-changes"
onClick={() => setOpenDiscardChangesModal(true)}
size="lg"
style={{width: "15px", color: "#5b69af", cursor: "pointer"}}
/>
</MLTooltip>
<div>
{openDiscardChangesModal &&
<DiscardChangesModal
setDiscardChangesModalVisibility={() => setOpenDiscardChangesModal(false)}
savedQueryList={props.queries}
toggleApply={(clicked) => toggleApply(clicked)}
toggleApplyClicked={(clicked) => toggleApplyClicked(clicked)}
/>}
</div>
</div>}
{props.isSavedQueryUser && searchOptions.selectedQuery !== "select a query" && props.queries.length > 0 && <div>
<MLTooltip title={"Edit query details"}>
{hoverOverDropdown && <FontAwesomeIcon
icon={faPencilAlt}
className={styles.iconHover}
title="edit-query"
size="lg"
onClick={() => setOpenEditDetail(true)}
style={{width: "16px", color: "#5b69af", cursor: "pointer"}}
/>}
</MLTooltip>
{openEditDetail &&
<EditQueryDetails
setEditQueryDetailVisibility={() => setOpenEditDetail(false)}
currentQuery={currentQuery}
currentQueryName={currentQueryName}
setCurrentQueryName={setCurrentQueryName}
currentQueryDescription={currentQueryDescription}
setCurrentQueryDescription={setCurrentQueryDescription}
/>
}
</div>}
{props.isSavedQueryUser && searchOptions.selectedQuery !== "select a query" && props.queries.length > 0 &&
<div>
<MLTooltip title={"Save a copy"}>
{hoverOverDropdown && <FontAwesomeIcon
icon={faCopy}
className={styles.iconHover}
size="lg"
onClick={() => setOpenSaveCopyModal(true)}
style={{width: "15px", color: "#5b69af", cursor: "pointer"}}
/>}
</MLTooltip>
{openSaveCopyModal &&
<SaveQueryModal
setSaveModalVisibility={() => setOpenSaveCopyModal(false)}
setSaveNewIconVisibility={(visibility) => toggleSaveNewIcon(visibility)}
saveNewQuery={saveNewQuery}
greyFacets={props.greyFacets}
toggleApply={(clicked) => toggleApply(clicked)}
toggleApplyClicked={(clicked) => toggleApplyClicked(clicked)}
currentQueryName={currentQueryName}
setCurrentQueryName={setCurrentQueryName}
currentQueryDescription={currentQueryDescription}
setCurrentQueryDescription={setCurrentQueryDescription}
resetYesClicked={resetYesClicked}
setColumnSelectorTouched={props.setColumnSelectorTouched}
existingQueryYesClicked={existingQueryYesClicked}
/>}
</div>}
{resetQueryIcon && props.isSavedQueryUser && props.queries.length > 0 &&
<div>
<Tooltip title={"Clear query"}>
<FontAwesomeIcon
className={styles.iconHover}
icon={faWindowClose}
title={"reset-changes"}
size="lg"
onClick={() => resetIconClicked()}
style={{width: "18px", color: "#5b69af", cursor: "pointer"}}
id="reset-changes"
/>
</Tooltip>
<Modal
visible={showResetQueryEditedConfirmation || showResetQueryNewConfirmation}
title={"Confirmation"}
onCancel={() => onResetCancel()}
footer={[
<Button key="cancel" id="reset-confirmation-cancel-button" onClick={() => onResetCancel()}>Cancel</Button>,
<Button key="back" id="reset-confirmation-no-button" onClick={() => onNoResetClick()}>
No
</Button>,
<Button key="submit" id="reset-confirmation-yes-button" type="primary" onClick={() => onResetOk()}>
Yes
</Button>
]}>
{showResetQueryEditedConfirmation &&
<div><p>Your unsaved changes in the query <strong>{searchOptions.selectedQuery}</strong> will be lost.</p>
<br />
<p>Would you like to save the changes before switching to another query?</p>
</div>}
{showResetQueryNewConfirmation && (<p>Would you like to save your search before resetting?</p>)}
</Modal>
</div>}
</div>
</div>
<div id="selected-query-description" style={props.isSavedQueryUser ? {marginTop: "10px"} : {marginTop: "-36px"}}
className={currentQueryDescription.length > 50 ? styles.longDescription : styles.description}>
<MLTooltip title={currentQueryDescription}>
{
searchOptions.selectedQuery === "select a query" ? "" : searchOptions.selectedQuery && searchOptions.selectedQuery !== "select a query" &&
currentQueryDescription.length > 50 ? currentQueryDescription.substring(0, 50).concat("...") : currentQueryDescription
}
</MLTooltip>
</div>
</div>}
<div className={styles.selectedFacets}>
<SelectedFacets
selectedFacets={props.selectedFacets}
greyFacets={props.greyFacets}
applyClicked={applyClicked}
showApply={showApply}
toggleApply={(clicked) => toggleApply(clicked)}
toggleApplyClicked={(clicked) => toggleApplyClicked(clicked)}
/>
</div>
<Modal
visible={showEntityConfirmation}
title={"Existing Query"}
onCancel={() => onCancel()}
footer={[
<MLButton key="cancel" id="entity-confirmation-cancel-button" onClick={() => onCancel()}>Cancel</MLButton>,
<MLButton key="back" id="entity-confirmation-no-button" onClick={() => onNoClick()}>
No
</MLButton>,
<MLButton key="submit" id="entity-confirmation-yes-button" type="primary" onClick={() => onOk()}>
Yes
</MLButton>
]}>
<p>Changing the entity selection starts a new query. Would you like to save the existing query before changing the selection?</p>
</Modal>
</div>
{/* } */}
</>
);
};
export default Query; | the_stack |
import {multipleEvents, PolimerHandlerMap, PolimerModel} from '../../src/';
import {defaultOOModelTestStateFactory, EventConst, OOModelTestState, ReceivedEvent, TestEvent, TestState, TestImmutableModel} from './testModel';
import {EventContext, DefaultEventContext, ObservationStage, observeEvent, PolimerEventPredicate, ObserveEventPredicate, DisposableBase, Router} from 'esp-js';
function processEvent(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
let receivedEvent = <ReceivedEvent>{
eventType: eventContext.eventType,
receivedEvent: ev,
observationStage: eventContext.currentStage,
stateName: draft.stateName,
stateReceived: isTestState(draft),
modelReceived: isImmutableTestModel(model),
eventContextReceived: eventContext instanceof DefaultEventContext,
};
if (eventContext.currentStage === ObservationStage.preview) {
draft.receivedEventsAtPreview.push(receivedEvent);
} else if (eventContext.currentStage === ObservationStage.normal) {
draft.receivedEventsAtNormal.push(receivedEvent);
} else if (eventContext.currentStage === ObservationStage.committed) {
draft.receivedEventsAtCommitted.push(receivedEvent);
} else if (eventContext.currentStage === ObservationStage.final) {
draft.receivedEventsAtFinal.push(receivedEvent);
}
draft.receivedEventsAll.push(receivedEvent);
if (ev.stateTakingAction === draft.stateName) {
if (ev.shouldCancel && eventContext.currentStage === ev.cancelAtStage) {
eventContext.cancel();
}
if (ev.shouldCommit && ev.commitAtStages && ev.commitAtStages.includes(eventContext.currentStage)) {
eventContext.commit();
}
}
}
function isTestState(state: any): state is TestState {
let testState = <TestState>state;
return testState && testState.stateName !== undefined;
}
function isImmutableTestModel(model: any): model is TestImmutableModel {
let testModel = <TestImmutableModel>model;
return testModel && (
testModel.handlerMapState !== undefined &&
testModel.handlerModelState !== undefined &&
testModel.handlerObjectState !== undefined
);
}
const polimerEventPredicate: PolimerEventPredicate = (draft: TestState, event: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
if (event.shouldCancel && event.cancelInEventFilter) {
eventContext.cancel();
}
if (event.shouldCommit && event.commitInEventFilter) {
eventContext.commit();
}
return !event.shouldFilter;
};
const observeEventPredicate: ObserveEventPredicate = (model?: any, event?: TestEvent, eventContext?: EventContext) => {
if (event.shouldCancel && event.cancelInEventFilter) {
eventContext.cancel();
}
if (event.shouldCommit && event.commitInEventFilter) {
eventContext.commit();
}
return !event.shouldFilter;
};
export const TestStateHandlerMap: PolimerHandlerMap<TestState, TestImmutableModel> = {
[EventConst.event1]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
processEvent(draft, ev, model, eventContext);
},
[EventConst.event2]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
processEvent(draft, ev, model, eventContext);
},
[multipleEvents(EventConst.event3, EventConst.event4)]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
processEvent(draft, ev, model, eventContext);
},
[EventConst.event5]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
if (ev.replacementState) {
return ev.replacementState;
}
processEvent(draft, ev, model, eventContext);
},
[EventConst.event7]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
processEvent(draft, ev, model, eventContext);
},
[EventConst.event8]: (draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) => {
processEvent(draft, ev, model, eventContext);
},
};
export class TestStateObjectHandler {
constructor(private _router: Router) {
}
@observeEvent(EventConst.event1, ObservationStage.preview)
@observeEvent(EventConst.event1) // defaults to ObservationStage.normal
@observeEvent(EventConst.event1, ObservationStage.committed)
@observeEvent(EventConst.event1, ObservationStage.final)
_event1Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
}
@observeEvent(EventConst.event2, ObservationStage.preview)
@observeEvent(EventConst.event2, ObservationStage.normal)
@observeEvent(EventConst.event2, ObservationStage.committed)
@observeEvent(EventConst.event2, ObservationStage.final)
_event2Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
}
@observeEvent(EventConst.event3)
@observeEvent(EventConst.event4)
_event3And4Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
}
@observeEvent(EventConst.event5, polimerEventPredicate)
_event5Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
if (ev.replacementState) {
return ev.replacementState;
}
processEvent(draft, ev, model, eventContext);
}
@observeEvent(EventConst.event6)
_event6Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
this._router.publishEvent(model.modelId, EventConst.event5, <TestEvent>{ stateTakingAction: 'handlerObjectState' });
}
@observeEvent(EventConst.event7)
_event7Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
}
@observeEvent(EventConst.event8)
_event8Handler(draft: TestState, ev: TestEvent, model: TestImmutableModel, eventContext: EventContext) {
processEvent(draft, ev, model, eventContext);
}
}
// this model is a more classic esp based model which can interop with polimer state handlers,
// it won't receive an immer based model to mutate state, rather state is maintained internally
export class TestStateHandlerModel extends DisposableBase {
private _currentState: OOModelTestState;
constructor(private _modelId, private _router: Router) {
super();
this._currentState = defaultOOModelTestStateFactory('handlerModelState');
}
public preProcess() {
let preProcessInvokeCount = this._currentState.preProcessInvokeCount + 1;
this._currentState = {
...this._currentState,
preProcessInvokeCount
};
};
public postProcess() {
let postProcessInvokeCount = this._currentState.postProcessInvokeCount + 1;
this._currentState = {
...this._currentState,
postProcessInvokeCount
};
}
public initialise(): void {
this.addDisposable(this._router.observeEventsOn(this._modelId, this));
}
public get currentState(): OOModelTestState {
return this._currentState;
}
public dispose() {
super.dispose();
}
@observeEvent(EventConst.event1, ObservationStage.preview)
@observeEvent(EventConst.event1) // defaults to ObservationStage.normal
@observeEvent(EventConst.event1, ObservationStage.committed)
@observeEvent(EventConst.event1, ObservationStage.final)
_event1Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
@observeEvent(EventConst.event2, ObservationStage.preview)
@observeEvent(EventConst.event2, ObservationStage.normal)
@observeEvent(EventConst.event2, ObservationStage.committed)
@observeEvent(EventConst.event2, ObservationStage.final)
_event2Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
@observeEvent(EventConst.event3)
@observeEvent(EventConst.event4)
_event3And4Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
@observeEvent(EventConst.event5, observeEventPredicate)
_event5Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
@observeEvent(EventConst.event7)
_event7Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
@observeEvent(EventConst.event8)
_event8Handler(ev: TestEvent, eventContext: EventContext, model: PolimerModel<TestImmutableModel>) {
this._ensureModelStateMatchesLocal(model);
processEvent(this._currentState, ev, model.getImmutableModel(), eventContext);
this._replaceState();
}
private _ensureModelStateMatchesLocal(model: PolimerModel<TestImmutableModel>) {
let localStateMatchesModelsCopy = this._currentState === model.getImmutableModel().handlerModelState;
this._currentState = {
...this._currentState,
eventHandlersReceivedStateOnModelMatchesLocalState: localStateMatchesModelsCopy
};
}
private _replaceState() {
// emulate internal update of immutable state
this._currentState = { ... this._currentState };
}
public getEspPolimerState(): OOModelTestState {
return this._currentState;
}
} | the_stack |
import { expect } from 'chai';
import { buildContractClass, signTx, toHex, bsv, Ripemd160, PubKey, Sig, Bytes, VerifyResult, Bool, getPreimage, num2bin} from 'scryptlib';
import { compileContract, newTx, sighashType2Hex } from "../../helper";
const crypto = require('crypto');
/**
* an example SuperAssetNFT test for contract containing signature verification
*/
const privateKey = new bsv.PrivateKey.fromRandom('testnet')
const publicKey = privateKey.publicKey
const pkh = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer())
const privateKey2 = new bsv.PrivateKey.fromRandom('testnet')
const MSB_THRESHOLD = 0x7e;
const Signature = bsv.crypto.Signature;
const sighashType = Signature.SIGHASH_ANYONECANPAY | Signature.SIGHASH_SINGLE | Signature.SIGHASH_FORKID;
const dummyTxId = '8709ff8d2452897beacabc174e06654b6b1753116c44e37924c7cc1e0c93732d';
const reversedDummyTxId = Buffer.from(dummyTxId, 'hex').reverse().toString('hex');
const inputSatoshis = 10000;
function newTx() {
const utxo = {
txId: dummyTxId,
outputIndex: 0,
script: '', // placeholder
satoshis: inputSatoshis
};
return new bsv.Transaction().from(utxo);
}
function buildNFTMintMetadataOpReturn() {
return bsv.Script.fromASM(`OP_FALSE OP_RETURN ${Buffer.from("Image: https://i1.sndcdn.com/artworks-000299901567-oiw8tq-t500x500.jpg", 'utf8').toString('hex')}`);
}
/**
* Replace the asset and PKH arguments of the locking script.
* @param {*} asm The locking script as generated by scrypt compiler
* @param {*} asset The assetid
* @param {*} pkh the pubKeyHash
*/
function replaceAssetAndPkh(asm, asset, pkh) {
const replacedAssetPkh = asset + ' ' + pkh + asm.toASM().substring(113);
return bsv.Script.fromASM(replacedAssetPkh);
}
function generatePreimage(isOpt, tx, lockingScriptASM, satValue, sighashType, idx = 0) {
let preimage: any = null;
if (isOpt) {
for (let i = 0; ; i++) {
// malleate tx and thus sighash to satisfy constraint
tx.nLockTime = i;
const preimage_ = getPreimage(tx, lockingScriptASM, satValue, idx, sighashType);
let preimageHex = toHex(preimage_);
preimage = preimage_;
const h = bsv.crypto.Hash.sha256sha256(Buffer.from(preimageHex, 'hex'));
const msb = h.readUInt8();
if (msb < MSB_THRESHOLD) {
// the resulting MSB of sighash must be less than the threshold
break;
}
}
} else {
preimage = getPreimage(tx, lockingScriptASM, satValue, idx, sighashType);
}
return preimage;
}
describe('Test sCrypt contract SuperAssetNFT In Typescript', () => {
const outputSize = 'fc'; // Change to fc for debug or f2 for release
before(() => {
});
it('signature check should succeed when right private key signs', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('000000000000000000000000000000000000000000000000000000000000000000000000'), new Ripemd160(toHex(publicKeyHash)));
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashType)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
const assetId = reversedDummyTxId + '00000000';
console.log('assetId', assetId);
const newLockingScript = replaceAssetAndPkh(nft.lockingScript, assetId, privateKey.toAddress().toHex().substring(2));
tx
.setOutput(0, (tx) => {
return new bsv.Transaction.Output({
script: newLockingScript,
satoshis: inputSatoshis,
});
})
// Add another output to show that SIGHASH_SINGLE will ignore it
.setOutput(1, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 0,
})
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashType);
let sig = signTx(tx, privateKey, nft.lockingScript, inputSatoshis, 0, sighashType)
console.log('debug info');
console.log('tx', tx.toString());
console.log('preimage', preimage);
console.log('outputSatsWithSize', outputSatsWithSize);
console.log('receiveAddressWithSize', receiveAddressWithSize);
console.log('sig', sig);
console.log('pubKey', toHex(publicKey));
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(false),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.true
});
it('signature check should fail when wrong private key signs', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('000000000000000000000000000000000000000000000000000000000000000000000000'), new Ripemd160(toHex(publicKeyHash)));
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashType)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
const assetId = reversedDummyTxId + '00000000';
const newLockingScript = replaceAssetAndPkh(nft.lockingScript, assetId, privateKey.toAddress().toHex().substring(2));
tx
.setOutput(0, (tx) => {
return new bsv.Transaction.Output({
script: newLockingScript,
satoshis: inputSatoshis,
});
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashType);
let sig = signTx(tx, privateKey2, nft.lockingScript, inputSatoshis, 0, sighashType)
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(false),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.false
});
it('should fail when non-SIGHASH_SINGLE flag is used when there are other outputs', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('000000000000000000000000000000000000000000000000000000000000000000000000'), new Ripemd160(toHex(publicKeyHash)));
const sighashTypeNotSighashSingle = Signature.SIGHASH_ANYONECANPAY | Signature.SIGHASH_ALL| Signature.SIGHASH_FORKID;
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashTypeNotSighashSingle)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
const assetId = reversedDummyTxId + '00000000';
const newLockingScript = replaceAssetAndPkh(nft.lockingScript, assetId, privateKey.toAddress().toHex().substring(2));
tx
.setOutput(0, (tx) => {
return new bsv.Transaction.Output({
script: newLockingScript,
satoshis: inputSatoshis,
});
})
.setOutput(1, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 0,
})
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashTypeNotSighashSingle);
let sig = signTx(tx, privateKey, nft.lockingScript, inputSatoshis, 0, sighashTypeNotSighashSingle)
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(false),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.false
});
it('should allow arbitrary change when isTransform is true', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('000000000000000000000000000000000000000000000000000000000000000000000000'), new Ripemd160(toHex(publicKeyHash)));
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashType)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
tx
.setOutput(0, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 0,
})
})
.setOutput(1, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 10,
})
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashType);
let sig = signTx(tx, privateKey, nft.lockingScript, inputSatoshis, 0, sighashType)
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(true),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.true
});
it('signature check should succeed when right private key signs (after mint)', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('0a0000000000000000000000000000000000000000000000000000000000000000000001'), new Ripemd160(toHex(publicKeyHash)));
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashType)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
const assetId = '0a0000000000000000000000000000000000000000000000000000000000000000000001';
console.log('assetId', assetId);
const newLockingScript = replaceAssetAndPkh(nft.lockingScript, assetId, privateKey.toAddress().toHex().substring(2));
tx
.setOutput(0, (tx) => {
return new bsv.Transaction.Output({
script: newLockingScript,
satoshis: inputSatoshis,
});
})
// Add another output to show that SIGHASH_SINGLE will ignore it
.setOutput(1, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 0,
})
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashType);
let sig = signTx(tx, privateKey, nft.lockingScript, inputSatoshis, 0, sighashType)
console.log('debug info');
console.log('tx', tx.toString());
console.log('preimage', preimage);
console.log('outputSatsWithSize', outputSatsWithSize);
console.log('receiveAddressWithSize', receiveAddressWithSize);
console.log('sig', sig);
console.log('pubKey', toHex(publicKey));
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(false),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.true
});
it('op_verify should fail when provided with the wrong pkh in the constructor', () => {
const SuperAssetNFT = buildContractClass(compileContract('SuperAssetNFT.scrypt'));
const publicKeyHash = bsv.crypto.Hash.sha256ripemd160(publicKey.toBuffer());
let nft = new SuperAssetNFT(new Bytes('0a0000000000000000000000000000000000000000000000000000000000000000000001'), new Ripemd160('4f3c913a459603496db9399aa12c8c9fc7f74932'));
const asmVars = {
'Tx.checkPreimageOpt_.sigHashType':
sighashType2Hex(sighashType)
};
let tx: any = newTx();
nft.replaceAsmVars(asmVars);
nft.txContext = {
tx,
inputIndex: 0,
inputSatoshis
}
const assetId = '0a0000000000000000000000000000000000000000000000000000000000000000000001';
const newLockingScript = replaceAssetAndPkh(nft.lockingScript, assetId, privateKey.toAddress().toHex().substring(2));
tx
.setOutput(0, (tx) => {
return new bsv.Transaction.Output({
script: newLockingScript,
satoshis: inputSatoshis,
});
})
// Add another output to show that SIGHASH_SINGLE will ignore it
.setOutput(1, (tx) => {
const deployData = buildNFTMintMetadataOpReturn()
return new bsv.Transaction.Output({
script: deployData,
satoshis: 0,
})
})
const receiveAddressWithSize = new Bytes('14' + privateKey.toAddress().toHex().substring(2));
const outputSatsWithSize = new Bytes(num2bin(inputSatoshis, 8) + `${outputSize}24`);
const preimage = generatePreimage(true, tx, nft.lockingScript, inputSatoshis, sighashType);
let sig = signTx(tx, privateKey, nft.lockingScript, inputSatoshis, 0, sighashType)
let result = nft.unlock(
preimage,
outputSatsWithSize,
receiveAddressWithSize,
new Bool(false),
new Sig(toHex(sig)),
new PubKey(toHex(publicKey))).verify()
expect(result.success, result.error).to.be.false
});
}); | the_stack |
import * as DatatypeForTestLibjoynr from "../../../generated/joynr/vehicle/radiotypes/DatatypeForTestLibjoynr";
import * as ChildProcessUtils from "../ChildProcessUtils";
import joynr from "joynr";
import provisioning from "../../../resources/joynr/provisioning/provisioning_cc";
import RadioProvider from "../../../generated/joynr/vehicle/RadioProvider";
import RadioStation from "../../../generated/joynr/vehicle/radiotypes/RadioStation";
import Country from "../../../generated/joynr/datatypes/exampleTypes/Country";
import ErrorList from "../../../generated/joynr/vehicle/radiotypes/ErrorList";
import StringMap = require("../../../generated/joynr/datatypes/exampleTypes/StringMap");
import ComplexStructMap = require("../../../generated/joynr/datatypes/exampleTypes/ComplexStructMap");
import InProcessRuntime = require("../../../../main/js/joynr/start/InProcessRuntime");
let providerDomain: string;
// this delay tries to correct the initialization delay between the web worker and the test driver
const valueChangedInterval = 500;
const mixedSubscriptionDelay = 1500;
let radioProvider: RadioProvider;
let providerQos: any;
const store: Record<string, any> = {};
store.numberOfStations = -1;
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function createAttributeImpl<T>(key: string, defaultValue?: T) {
if (defaultValue !== undefined) {
store[key] = defaultValue;
}
return {
get: (): T => store[key],
set: (value: T) => {
store[key] = value;
}
};
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function createReadAttributeImpl<T>(key: string, defaultValue?: T) {
store[key] = defaultValue;
return {
get: (): T => store[key]
};
}
async function initializeTest(provisioningSuffix: string, providedDomain: string): Promise<any> {
// set joynr provisioning
providerDomain = providedDomain;
// @ts-ignore
provisioning.persistency = "localStorage";
// @ts-ignore
provisioning.channelId = `End2EndCommTestParticipantId${provisioningSuffix}`;
joynr.selectRuntime(InProcessRuntime);
await joynr.load(provisioning as any);
providerQos = new joynr.types.ProviderQos({
customParameters: [],
priority: Date.now(),
scope: joynr.types.ProviderScope.GLOBAL,
supportsOnChangeSubscriptions: true
});
const isCountryEnum = (parameter: any): boolean =>
typeof parameter === "object" &&
Object.getPrototypeOf(parameter) instanceof joynr.JoynrObject &&
parameter._typeName === Country.GERMANY._typeName;
const checkEnumInputs = (opArgs: any): void => {
let enumElement;
if (!isCountryEnum(opArgs.enumInput)) {
throw new Error(
`Argument enumInput with value ${opArgs.enumInput} is not correctly typed ${Country.GERMANY._typeName}`
);
}
for (enumElement in opArgs.enumArrayInput) {
if (opArgs.enumArrayInput.hasOwnProperty(enumElement)) {
if (!isCountryEnum(opArgs.enumArrayInput[enumElement])) {
throw new Error(
`Argument enumInput with value ${opArgs.enumArrayInput[enumElement]} is not correctly typed ${
Country.GERMANY._typeName
}`
);
}
}
}
};
function triggerBroadcastsInternal(opArgs: any): any {
let outputParams, broadcast;
if (opArgs.broadcastName === "broadcastWithEnum") {
//broadcastWithEnum
broadcast = radioProvider.broadcastWithEnum;
outputParams = broadcast.createBroadcastOutputParameters();
outputParams.setEnumOutput(Country.CANADA);
outputParams.setEnumArrayOutput([Country.GERMANY, Country.ITALY]);
} else if (opArgs.broadcastName === "emptyBroadcast") {
broadcast = radioProvider.emptyBroadcast;
outputParams = broadcast.createBroadcastOutputParameters();
} else if (opArgs.broadcastName === "weakSignal") {
//weakSignal
broadcast = radioProvider.weakSignal;
outputParams = broadcast.createBroadcastOutputParameters();
outputParams.setRadioStation("radioStation");
outputParams.setByteBuffer([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
} else if (opArgs.broadcastName === "broadcastWithTypeDefs") {
//broadcastWithTypeDefs
broadcast = radioProvider.broadcastWithTypeDefs;
outputParams = broadcast.createBroadcastOutputParameters();
outputParams.setTypeDefStructOutput(
new RadioStation({
name: "TestEnd2EndCommProviderProcess.broadcastWithTypeDefs.RadioStation",
byteBuffer: []
})
);
outputParams.setTypeDefPrimitiveOutput(123456);
}
setTimeout(
(opArgs, broadcast, outputParams) => {
let i;
for (i = 0; i < opArgs.times; i++) {
if (opArgs.hierarchicBroadcast && opArgs.partitions !== undefined) {
const hierarchicPartitions: any[] = [];
broadcast.fire(outputParams, hierarchicPartitions);
for (let j = 0; j < opArgs.partitions.length; j++) {
hierarchicPartitions.push(opArgs.partitions[j]);
broadcast.fire(outputParams, hierarchicPartitions);
}
} else {
broadcast.fire(outputParams, opArgs.partitions);
}
}
},
0,
opArgs,
broadcast,
outputParams
);
}
// build the provider
radioProvider = joynr.providerBuilder.build<typeof RadioProvider, RadioProvider.RadioProviderImplementation>(
RadioProvider,
{
numberOfStations: createAttributeImpl<number>("numberOfStations"),
attrProvidedImpl: createAttributeImpl<boolean>("attrProvidedImpl"),
mixedSubscriptions: createAttributeImpl<string>("mixedSubscriptions", "interval"),
StartWithCapitalLetter: createAttributeImpl<boolean>("StartWithCapitalLetter", true),
attributeTestingProviderInterface: createReadAttributeImpl<DatatypeForTestLibjoynr>(
"attributeTestingProviderInterface"
),
failingSyncAttribute: {
get: () => {
throw new joynr.exceptions.ProviderRuntimeException({
detailMessage: "failure in failingSyncAttribute getter"
});
}
},
failingAsyncAttribute: {
get: (): Promise<number> => {
return Promise.reject(
new joynr.exceptions.ProviderRuntimeException({
detailMessage: "failure in failingSyncAttribute getter"
})
);
}
},
isOn: createAttributeImpl<boolean>("inOn", true),
enumAttribute: createAttributeImpl<Country>("enumAttribute", Country.GERMANY),
enumArrayAttribute: createAttributeImpl<Country[]>("enumArrayAttribute", [Country.GERMANY]),
byteBufferAttribute: createAttributeImpl<number[]>("byteBufferAttribute"),
typeDefForStruct: createAttributeImpl<RadioStation>("typeDefForStruct"),
typeDefForPrimitive: createAttributeImpl<number>("typeDefForPrimitive"),
stringMapAttribute: createAttributeImpl<StringMap>("stringMapAttribute"),
complexStructMapAttribute: createAttributeImpl<ComplexStructMap>("complexStructMapAttribute"),
addFavoriteStation: (opArgs: { radioStation: string | RadioStation }) => {
// retrieve radioStation name for both overloaded version
const name = (opArgs.radioStation as RadioStation).name || (opArgs.radioStation as string);
// If name contains the string "async" it will work asynchronously
// returning a Promise, otherwise synchronously (return/throw directly).
// If name contains the string "error" it will throw error or reject
// Promise. If name contains "ApplicationException" it will use
// the Franca defined error exception for this case, otherwise
// ProviderRuntimeException.
// If no error handling is active, it will return or resolve true/false
// depending on whether radiostation name contains the string "true"
if (name.match(/async/)) {
// async
if (name.match(/error/)) {
if (name.match(/ApplicationException/)) {
return Promise.reject(ErrorList.EXAMPLE_ERROR_1);
} else {
return Promise.reject(
new joynr.exceptions.ProviderRuntimeException({
detailMessage: "example message async"
})
);
}
} else {
return Promise.resolve({
returnValue: !!name.match(/true/)
});
}
}
// sync
if (name.match(/error/)) {
if (name.match(/ApplicationException/)) {
throw ErrorList.EXAMPLE_ERROR_2;
} else {
throw new joynr.exceptions.ProviderRuntimeException({
detailMessage: "example message sync"
});
}
}
return {
returnValue: !!name.match(/true/)
};
},
operationWithEnumsAsInputAndOutput: (opArgs: any) => {
/* the dummy implemetnation returns the first element of the enumArrayInput.
* If the input array is empty, it returns the enumInput
*/
checkEnumInputs(opArgs);
let returnValue = opArgs.enumInput;
if (opArgs.enumArrayInput.length !== 0) {
returnValue = opArgs.enumArrayInput[0];
}
return {
enumOutput: returnValue
};
},
operationWithMultipleOutputParameters: (opArgs: any) => {
const returnValue = {
enumArrayOutput: opArgs.enumArrayInput,
enumOutput: opArgs.enumInput,
stringOutput: opArgs.stringInput,
booleanOutput: opArgs.syncTest
};
if (opArgs.syncTest) {
return returnValue;
}
return Promise.resolve(returnValue);
},
operationWithEnumsAsInputAndEnumArrayAsOutput: (opArgs: any) => {
/* the dummy implementation returns the enumArrayInput.
* If the enumInput is not empty, it add this entry to the return value as well
*/
checkEnumInputs(opArgs);
const returnValue = opArgs.enumArrayInput;
if (opArgs.enumInput !== undefined) {
returnValue.push(opArgs.enumInput);
}
return {
enumOutput: returnValue
};
},
methodWithSingleArrayParameters: (opArgs: any) => {
// the dummy implementation transforms the incoming double values into strings.
const stringArrayOut = [];
if (opArgs.doubleArrayArg !== undefined) {
for (const element in opArgs.doubleArrayArg) {
if (opArgs.doubleArrayArg.hasOwnProperty(element)) {
stringArrayOut.push(opArgs.doubleArrayArg[element].toString());
}
}
}
return {
stringArrayOut
};
},
methodWithByteBuffer: (opArgs: { input: any }) => {
/* the dummy implementation returns the incoming byteBuffer
*/
return {
result: opArgs.input
};
},
methodWithTypeDef: (opArgs: { typeDefStructInput: any; typeDefPrimitiveInput: any }) => {
/* the dummy implementation returns the incoming data
*/
return {
typeDefStructOutput: opArgs.typeDefStructInput,
typeDefPrimitiveOutput: opArgs.typeDefPrimitiveInput
};
},
methodWithComplexMap: () => {
return;
},
methodProvidedImpl: (opArgs: { arg: any }) => ({
returnValue: opArgs.arg
}),
triggerBroadcasts: triggerBroadcastsInternal,
triggerBroadcastsWithPartitions: triggerBroadcastsInternal,
methodFireAndForgetWithoutParams: () => {
const broadcast = radioProvider.fireAndForgetCallArrived;
const outputParams = broadcast.createBroadcastOutputParameters();
outputParams.setMethodName("methodFireAndForgetWithoutParams");
broadcast.fire(outputParams);
},
methodFireAndForget: () => {
const broadcast = radioProvider.fireAndForgetCallArrived;
const outputParams = broadcast.createBroadcastOutputParameters();
outputParams.setMethodName("methodFireAndForget");
broadcast.fire(outputParams);
}
}
);
providerQos.priority = Date.now();
// register provider at the given providerDomain
await joynr.registration.registerProvider(providerDomain, radioProvider, providerQos);
}
function startTest(): Promise<any> {
// change attribute value of numberOfStations periodically
joynr.util.LongTimer.setInterval(() => {
radioProvider.numberOfStations.valueChanged(++store.numberOfStations);
}, valueChangedInterval);
joynr.util.LongTimer.setTimeout(() => {
store.mixedSubscriptions = "valueChanged1";
radioProvider.mixedSubscriptions.valueChanged(store.mixedSubscriptions);
joynr.util.LongTimer.setTimeout(() => {
store.mixedSubscriptions = "valueChanged2";
radioProvider.mixedSubscriptions.valueChanged(store.mixedSubscriptions);
}, 10);
}, mixedSubscriptionDelay);
return Promise.resolve(joynr.participantIdStorage.getParticipantId(providerDomain, radioProvider));
}
function terminateTest(): Promise<void> {
return joynr.registration.unregisterProvider(providerDomain, radioProvider);
}
ChildProcessUtils.registerHandlers(initializeTest, startTest, terminateTest); | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the ApplyRecoveryPointProviderSpecificInput class.
* @constructor
* Provider specific input for apply recovery point.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ApplyRecoveryPointProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AApplyRecoveryPointInput class.
* @constructor
* ApplyRecoveryPoint input specific to A2A provider.
*
*/
export interface A2AApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput {
}
/**
* @class
* Initializes a new instance of the ReplicationProviderSpecificContainerCreationInput class.
* @constructor
* Provider specific input for container creation operation.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ReplicationProviderSpecificContainerCreationInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AContainerCreationInput class.
* @constructor
* A2A cloud creation input.
*
*/
export interface A2AContainerCreationInput extends ReplicationProviderSpecificContainerCreationInput {
}
/**
* @class
* Initializes a new instance of the ReplicationProviderSpecificContainerMappingInput class.
* @constructor
* Provider specific input for pairing operations.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ReplicationProviderSpecificContainerMappingInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AContainerMappingInput class.
* @constructor
* A2A container mapping input.
*
* @member {string} [agentAutoUpdateStatus] A value indicating whether the auto
* update is enabled. Possible values include: 'Disabled', 'Enabled'
* @member {string} [automationAccountArmId] The automation account arm id.
*/
export interface A2AContainerMappingInput extends ReplicationProviderSpecificContainerMappingInput {
agentAutoUpdateStatus?: string;
automationAccountArmId?: string;
}
/**
* @class
* Initializes a new instance of the A2AVmDiskInputDetails class.
* @constructor
* Azure VM disk input details.
*
* @member {string} [diskUri] The disk Uri.
* @member {string} [recoveryAzureStorageAccountId] The recovery VHD storage
* account Id.
* @member {string} [primaryStagingAzureStorageAccountId] The primary staging
* storage account Id.
*/
export interface A2AVmDiskInputDetails {
diskUri?: string;
recoveryAzureStorageAccountId?: string;
primaryStagingAzureStorageAccountId?: string;
}
/**
* @class
* Initializes a new instance of the A2AVmManagedDiskInputDetails class.
* @constructor
* Azure VM managed disk input details.
*
* @member {string} [diskId] The disk Id.
* @member {string} [primaryStagingAzureStorageAccountId] The primary staging
* storage account Arm Id.
* @member {string} [recoveryResourceGroupId] The target resource group Arm Id.
* @member {string} [recoveryReplicaDiskAccountType] The replica disk type. Its
* an optional value and will be same as source disk type if not user provided.
* @member {string} [recoveryTargetDiskAccountType] The target disk type after
* failover. Its an optional value and will be same as source disk type if not
* user provided.
*/
export interface A2AVmManagedDiskInputDetails {
diskId?: string;
primaryStagingAzureStorageAccountId?: string;
recoveryResourceGroupId?: string;
recoveryReplicaDiskAccountType?: string;
recoveryTargetDiskAccountType?: string;
}
/**
* @class
* Initializes a new instance of the DiskEncryptionKeyInfo class.
* @constructor
* Disk Encryption Key Information (BitLocker Encryption Key (BEK) on Windows).
*
* @member {string} [secretIdentifier] The secret url / identifier.
* @member {string} [keyVaultResourceArmId] The KeyVault resource ARM id for
* secret.
*/
export interface DiskEncryptionKeyInfo {
secretIdentifier?: string;
keyVaultResourceArmId?: string;
}
/**
* @class
* Initializes a new instance of the KeyEncryptionKeyInfo class.
* @constructor
* Key Encryption Key (KEK) information.
*
* @member {string} [keyIdentifier] The key url / identifier.
* @member {string} [keyVaultResourceArmId] The KeyVault resource ARM id for
* key.
*/
export interface KeyEncryptionKeyInfo {
keyIdentifier?: string;
keyVaultResourceArmId?: string;
}
/**
* @class
* Initializes a new instance of the DiskEncryptionInfo class.
* @constructor
* Recovery disk encryption info (BEK and KEK).
*
* @member {object} [diskEncryptionKeyInfo] The recovery KeyVault reference for
* secret.
* @member {string} [diskEncryptionKeyInfo.secretIdentifier] The secret url /
* identifier.
* @member {string} [diskEncryptionKeyInfo.keyVaultResourceArmId] The KeyVault
* resource ARM id for secret.
* @member {object} [keyEncryptionKeyInfo] The recovery KeyVault reference for
* key.
* @member {string} [keyEncryptionKeyInfo.keyIdentifier] The key url /
* identifier.
* @member {string} [keyEncryptionKeyInfo.keyVaultResourceArmId] The KeyVault
* resource ARM id for key.
*/
export interface DiskEncryptionInfo {
diskEncryptionKeyInfo?: DiskEncryptionKeyInfo;
keyEncryptionKeyInfo?: KeyEncryptionKeyInfo;
}
/**
* @class
* Initializes a new instance of the EnableProtectionProviderSpecificInput class.
* @constructor
* Enable protection provider specific input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface EnableProtectionProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AEnableProtectionInput class.
* @constructor
* A2A enable protection input.
*
* @member {string} [fabricObjectId] The fabric specific object Id of the
* virtual machine.
* @member {string} [recoveryContainerId] The recovery container Id.
* @member {string} [recoveryResourceGroupId] The recovery resource group Id.
* Valid for V2 scenarios.
* @member {string} [recoveryCloudServiceId] The recovery cloud service Id.
* Valid for V1 scenarios.
* @member {string} [recoveryAvailabilitySetId] The recovery availability set
* Id.
* @member {array} [vmDisks] The list of vm disk details.
* @member {array} [vmManagedDisks] The list of vm managed disk details.
* @member {string} [multiVmGroupName] The multi vm group name.
* @member {string} [recoveryBootDiagStorageAccountId] The boot diagnostic
* storage account.
* @member {object} [diskEncryptionInfo] The recovery disk encryption
* information.
* @member {object} [diskEncryptionInfo.diskEncryptionKeyInfo] The recovery
* KeyVault reference for secret.
* @member {string} [diskEncryptionInfo.diskEncryptionKeyInfo.secretIdentifier]
* The secret url / identifier.
* @member {string}
* [diskEncryptionInfo.diskEncryptionKeyInfo.keyVaultResourceArmId] The
* KeyVault resource ARM id for secret.
* @member {object} [diskEncryptionInfo.keyEncryptionKeyInfo] The recovery
* KeyVault reference for key.
* @member {string} [diskEncryptionInfo.keyEncryptionKeyInfo.keyIdentifier] The
* key url / identifier.
* @member {string}
* [diskEncryptionInfo.keyEncryptionKeyInfo.keyVaultResourceArmId] The KeyVault
* resource ARM id for key.
*/
export interface A2AEnableProtectionInput extends EnableProtectionProviderSpecificInput {
fabricObjectId?: string;
recoveryContainerId?: string;
recoveryResourceGroupId?: string;
recoveryCloudServiceId?: string;
recoveryAvailabilitySetId?: string;
vmDisks?: A2AVmDiskInputDetails[];
vmManagedDisks?: A2AVmManagedDiskInputDetails[];
multiVmGroupName?: string;
recoveryBootDiagStorageAccountId?: string;
diskEncryptionInfo?: DiskEncryptionInfo;
}
/**
* @class
* Initializes a new instance of the EventProviderSpecificDetails class.
* @constructor
* Model class for provider specific details for an event.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface EventProviderSpecificDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AEventDetails class.
* @constructor
* Model class for event details of a A2A event.
*
* @member {string} [protectedItemName] The protected item arm name.
* @member {string} [fabricObjectId] The azure vm arm id.
* @member {string} [fabricName] Fabric arm name.
* @member {string} [fabricLocation] The fabric location.
* @member {string} [remoteFabricName] Remote fabric arm name.
* @member {string} [remoteFabricLocation] Remote fabric location.
*/
export interface A2AEventDetails extends EventProviderSpecificDetails {
protectedItemName?: string;
fabricObjectId?: string;
fabricName?: string;
fabricLocation?: string;
remoteFabricName?: string;
remoteFabricLocation?: string;
}
/**
* @class
* Initializes a new instance of the ProviderSpecificFailoverInput class.
* @constructor
* Provider specific failover input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ProviderSpecificFailoverInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AFailoverProviderInput class.
* @constructor
* A2A provider specific input for failover.
*
* @member {string} [recoveryPointId] The recovery point id to be passed to
* failover to a particular recovery point. In case of latest recovery point,
* null should be passed.
* @member {string} [cloudServiceCreationOption] A value indicating whether to
* use recovery cloud service for TFO or not.
*/
export interface A2AFailoverProviderInput extends ProviderSpecificFailoverInput {
recoveryPointId?: string;
cloudServiceCreationOption?: string;
}
/**
* @class
* Initializes a new instance of the PolicyProviderSpecificInput class.
* @constructor
* Base class for provider specific input
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface PolicyProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2APolicyCreationInput class.
* @constructor
* A2A Policy creation input.
*
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency (in minutes).
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency (in minutes).
* @member {string} multiVmSyncStatus A value indicating whether multi-VM sync
* has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values
* include: 'Enable', 'Disable'
*/
export interface A2APolicyCreationInput extends PolicyProviderSpecificInput {
recoveryPointHistory?: number;
crashConsistentFrequencyInMinutes?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus: string;
}
/**
* @class
* Initializes a new instance of the PolicyProviderSpecificDetails class.
* @constructor
* Base class for Provider specific details for policies.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface PolicyProviderSpecificDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2APolicyDetails class.
* @constructor
* A2A specific policy details.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {string} [multiVmSyncStatus] A value indicating whether multi-VM
* sync has to be enabled.
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency in minutes.
*/
export interface A2APolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus?: string;
crashConsistentFrequencyInMinutes?: number;
}
/**
* @class
* Initializes a new instance of the A2AProtectedDiskDetails class.
* @constructor
* A2A protected disk details.
*
* @member {string} [diskUri] The disk uri.
* @member {string} [recoveryAzureStorageAccountId] The recovery disk storage
* account.
* @member {string} [primaryDiskAzureStorageAccountId] The primary disk storage
* account.
* @member {string} [recoveryDiskUri] Recovery disk uri.
* @member {string} [diskName] The disk name.
* @member {number} [diskCapacityInBytes] The disk capacity in bytes.
* @member {string} [primaryStagingAzureStorageAccountId] The primary staging
* storage account.
* @member {string} [diskType] The type of disk.
* @member {boolean} [resyncRequired] A value indicating whether resync is
* required for this disk.
* @member {number} [monitoringPercentageCompletion] The percentage of the
* monitoring job. The type of the monitoring job is defined by
* MonitoringJobType property.
* @member {string} [monitoringJobType] The type of the monitoring job. The
* progress is contained in MonitoringPercentageCompletion property.
* @member {number} [dataPendingInStagingStorageAccountInMB] The data pending
* for replication in MB at staging account.
* @member {number} [dataPendingAtSourceAgentInMB] The data pending at source
* virtual machine in MB.
* @member {boolean} [isDiskEncrypted] A value indicating whether vm has
* encrypted os disk or not.
* @member {string} [secretIdentifier] The secret URL / identifier (BEK).
* @member {string} [dekKeyVaultArmId] The KeyVault resource id for secret
* (BEK).
* @member {boolean} [isDiskKeyEncrypted] A value indicating whether disk key
* got encrypted or not.
* @member {string} [keyIdentifier] The key URL / identifier (KEK).
* @member {string} [kekKeyVaultArmId] The KeyVault resource id for key (KEK).
*/
export interface A2AProtectedDiskDetails {
diskUri?: string;
recoveryAzureStorageAccountId?: string;
primaryDiskAzureStorageAccountId?: string;
recoveryDiskUri?: string;
diskName?: string;
diskCapacityInBytes?: number;
primaryStagingAzureStorageAccountId?: string;
diskType?: string;
resyncRequired?: boolean;
monitoringPercentageCompletion?: number;
monitoringJobType?: string;
dataPendingInStagingStorageAccountInMB?: number;
dataPendingAtSourceAgentInMB?: number;
isDiskEncrypted?: boolean;
secretIdentifier?: string;
dekKeyVaultArmId?: string;
isDiskKeyEncrypted?: boolean;
keyIdentifier?: string;
kekKeyVaultArmId?: string;
}
/**
* @class
* Initializes a new instance of the A2AProtectedManagedDiskDetails class.
* @constructor
* A2A protected managed disk details.
*
* @member {string} [diskId] The managed disk Arm id.
* @member {string} [recoveryResourceGroupId] The recovery disk resource group
* Arm Id.
* @member {string} [recoveryTargetDiskId] Recovery target disk Arm Id.
* @member {string} [recoveryReplicaDiskId] Recovery replica disk Arm Id.
* @member {string} [recoveryReplicaDiskAccountType] The replica disk type. Its
* an optional value and will be same as source disk type if not user provided.
* @member {string} [recoveryTargetDiskAccountType] The target disk type after
* failover. Its an optional value and will be same as source disk type if not
* user provided.
* @member {string} [diskName] The disk name.
* @member {number} [diskCapacityInBytes] The disk capacity in bytes.
* @member {string} [primaryStagingAzureStorageAccountId] The primary staging
* storage account.
* @member {string} [diskType] The type of disk.
* @member {boolean} [resyncRequired] A value indicating whether resync is
* required for this disk.
* @member {number} [monitoringPercentageCompletion] The percentage of the
* monitoring job. The type of the monitoring job is defined by
* MonitoringJobType property.
* @member {string} [monitoringJobType] The type of the monitoring job. The
* progress is contained in MonitoringPercentageCompletion property.
* @member {number} [dataPendingInStagingStorageAccountInMB] The data pending
* for replication in MB at staging account.
* @member {number} [dataPendingAtSourceAgentInMB] The data pending at source
* virtual machine in MB.
* @member {boolean} [isDiskEncrypted] A value indicating whether vm has
* encrypted os disk or not.
* @member {string} [secretIdentifier] The secret URL / identifier (BEK).
* @member {string} [dekKeyVaultArmId] The KeyVault resource id for secret
* (BEK).
* @member {boolean} [isDiskKeyEncrypted] A value indicating whether disk key
* got encrypted or not.
* @member {string} [keyIdentifier] The key URL / identifier (KEK).
* @member {string} [kekKeyVaultArmId] The KeyVault resource id for key (KEK).
*/
export interface A2AProtectedManagedDiskDetails {
diskId?: string;
recoveryResourceGroupId?: string;
recoveryTargetDiskId?: string;
recoveryReplicaDiskId?: string;
recoveryReplicaDiskAccountType?: string;
recoveryTargetDiskAccountType?: string;
diskName?: string;
diskCapacityInBytes?: number;
primaryStagingAzureStorageAccountId?: string;
diskType?: string;
resyncRequired?: boolean;
monitoringPercentageCompletion?: number;
monitoringJobType?: string;
dataPendingInStagingStorageAccountInMB?: number;
dataPendingAtSourceAgentInMB?: number;
isDiskEncrypted?: boolean;
secretIdentifier?: string;
dekKeyVaultArmId?: string;
isDiskKeyEncrypted?: boolean;
keyIdentifier?: string;
kekKeyVaultArmId?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerMappingProviderSpecificDetails class.
* @constructor
* Container mapping provider specific details.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ProtectionContainerMappingProviderSpecificDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AProtectionContainerMappingDetails class.
* @constructor
* A2A provider specific settings.
*
* @member {string} [agentAutoUpdateStatus] A value indicating whether the auto
* update is enabled. Possible values include: 'Disabled', 'Enabled'
* @member {string} [automationAccountArmId] The automation account arm id.
* @member {string} [scheduleName] The schedule arm name.
* @member {string} [jobScheduleName] The job schedule arm name.
*/
export interface A2AProtectionContainerMappingDetails extends ProtectionContainerMappingProviderSpecificDetails {
agentAutoUpdateStatus?: string;
automationAccountArmId?: string;
scheduleName?: string;
jobScheduleName?: string;
}
/**
* @class
* Initializes a new instance of the ProviderSpecificRecoveryPointDetails class.
* @constructor
* Replication provider specific recovery point details.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ProviderSpecificRecoveryPointDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2ARecoveryPointDetails class.
* @constructor
* A2A provider specific recovery point details.
*
* @member {string} [recoveryPointSyncType] A value indicating whether the
* recovery point is multi VM consistent. Possible values include:
* 'MultiVmSyncRecoveryPoint', 'PerVmRecoveryPoint'
*/
export interface A2ARecoveryPointDetails extends ProviderSpecificRecoveryPointDetails {
recoveryPointSyncType?: string;
}
/**
* @class
* Initializes a new instance of the VMNicDetails class.
* @constructor
* Hyper V VM network details.
*
* @member {string} [nicId] The nic Id.
* @member {string} [replicaNicId] The replica nic Id.
* @member {string} [sourceNicArmId] The source nic ARM Id.
* @member {string} [vMSubnetName] VM subnet name.
* @member {string} [vMNetworkName] VM network name.
* @member {string} [recoveryVMNetworkId] Recovery VM network Id.
* @member {string} [recoveryVMSubnetName] Recovery VM subnet name.
* @member {string} [ipAddressType] Ip address type.
* @member {string} [primaryNicStaticIPAddress] Primary nic static IP address.
* @member {string} [replicaNicStaticIPAddress] Replica nic static IP address.
* @member {string} [selectionType] Selection type for failover.
* @member {string} [recoveryNicIpAddressType] IP allocation type for recovery
* VM.
* @member {boolean} [enableAcceleratedNetworkingOnRecovery] A value indicating
* whether the NIC has accerated networking enabled.
*/
export interface VMNicDetails {
nicId?: string;
replicaNicId?: string;
sourceNicArmId?: string;
vMSubnetName?: string;
vMNetworkName?: string;
recoveryVMNetworkId?: string;
recoveryVMSubnetName?: string;
ipAddressType?: string;
primaryNicStaticIPAddress?: string;
replicaNicStaticIPAddress?: string;
selectionType?: string;
recoveryNicIpAddressType?: string;
enableAcceleratedNetworkingOnRecovery?: boolean;
}
/**
* @class
* Initializes a new instance of the RoleAssignment class.
* @constructor
* Azure role assignment details.
*
* @member {string} [id] The ARM Id of the role assignment.
* @member {string} [name] The name of the role assignment.
* @member {string} [scope] Role assignment scope.
* @member {string} [principalId] Principal Id.
* @member {string} [roleDefinitionId] Role definition id.
*/
export interface RoleAssignment {
id?: string;
name?: string;
scope?: string;
principalId?: string;
roleDefinitionId?: string;
}
/**
* @class
* Initializes a new instance of the InputEndpoint class.
* @constructor
* Azure VM input endpoint details.
*
* @member {string} [endpointName] The input endpoint name.
* @member {number} [privatePort] The input endpoint private port.
* @member {number} [publicPort] The input endpoint public port.
* @member {string} [protocol] The input endpoint protocol.
*/
export interface InputEndpoint {
endpointName?: string;
privatePort?: number;
publicPort?: number;
protocol?: string;
}
/**
* @class
* Initializes a new instance of the AzureToAzureVmSyncedConfigDetails class.
* @constructor
* Azure to Azure VM synced configuration details.
*
* @member {object} [tags] The Azure VM tags.
* @member {array} [roleAssignments] The Azure role assignments.
* @member {array} [inputEndpoints] The Azure VM input endpoints.
*/
export interface AzureToAzureVmSyncedConfigDetails {
tags?: { [propertyName: string]: string };
roleAssignments?: RoleAssignment[];
inputEndpoints?: InputEndpoint[];
}
/**
* @class
* Initializes a new instance of the ReplicationProviderSpecificSettings class.
* @constructor
* Replication provider specific settings.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ReplicationProviderSpecificSettings {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AReplicationDetails class.
* @constructor
* A2A provider specific settings.
*
* @member {string} [fabricObjectId] The fabric specific object Id of the
* virtual machine.
* @member {string} [multiVmGroupId] The multi vm group Id.
* @member {string} [multiVmGroupName] The multi vm group name.
* @member {string} [multiVmGroupCreateOption] Whether Multi VM group is auto
* created or specified by user. Possible values include: 'AutoCreated',
* 'UserSpecified'
* @member {string} [managementId] The management Id.
* @member {array} [protectedDisks] The list of protected disks.
* @member {array} [protectedManagedDisks] The list of protected managed disks.
* @member {string} [recoveryBootDiagStorageAccountId] The recovery boot
* diagnostic storage account Arm Id.
* @member {string} [primaryFabricLocation] Primary fabric location.
* @member {string} [recoveryFabricLocation] The recovery fabric location.
* @member {string} [osType] The type of operating system.
* @member {string} [recoveryAzureVMSize] The size of recovery virtual machine.
* @member {string} [recoveryAzureVMName] The name of recovery virtual machine.
* @member {string} [recoveryAzureResourceGroupId] The recovery resource group.
* @member {string} [recoveryCloudService] The recovery cloud service.
* @member {string} [recoveryAvailabilitySet] The recovery availability set.
* @member {string} [selectedRecoveryAzureNetworkId] The recovery virtual
* network.
* @member {array} [vmNics] The virtual machine nic details.
* @member {object} [vmSyncedConfigDetails] The synced configuration details.
* @member {object} [vmSyncedConfigDetails.tags] The Azure VM tags.
* @member {array} [vmSyncedConfigDetails.roleAssignments] The Azure role
* assignments.
* @member {array} [vmSyncedConfigDetails.inputEndpoints] The Azure VM input
* endpoints.
* @member {number} [monitoringPercentageCompletion] The percentage of the
* monitoring job. The type of the monitoring job is defined by
* MonitoringJobType property.
* @member {string} [monitoringJobType] The type of the monitoring job. The
* progress is contained in MonitoringPercentageCompletion property.
* @member {date} [lastHeartbeat] The last heartbeat received from the source
* server.
* @member {string} [agentVersion] The agent version.
* @member {boolean} [isReplicationAgentUpdateRequired] A value indicating
* whether replication agent update is required.
* @member {string} [recoveryFabricObjectId] The recovery fabric object Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {string} [lifecycleId] An id associated with the PE that survives
* actions like switch protection which change the backing PE/CPE objects
* internally.The lifecycle id gets carried forward to have a link/continuity
* in being able to have an Id that denotes the "same" protected item even
* though other internal Ids/ARM Id might be changing.
* @member {string} [testFailoverRecoveryFabricObjectId] The test failover
* fabric object Id.
* @member {number} [rpoInSeconds] The last RPO value in seconds.
* @member {date} [lastRpoCalculatedTime] The time (in UTC) when the last RPO
* value was calculated by Protection Service.
*/
export interface A2AReplicationDetails extends ReplicationProviderSpecificSettings {
fabricObjectId?: string;
multiVmGroupId?: string;
multiVmGroupName?: string;
multiVmGroupCreateOption?: string;
managementId?: string;
protectedDisks?: A2AProtectedDiskDetails[];
protectedManagedDisks?: A2AProtectedManagedDiskDetails[];
recoveryBootDiagStorageAccountId?: string;
primaryFabricLocation?: string;
recoveryFabricLocation?: string;
osType?: string;
recoveryAzureVMSize?: string;
recoveryAzureVMName?: string;
recoveryAzureResourceGroupId?: string;
recoveryCloudService?: string;
recoveryAvailabilitySet?: string;
selectedRecoveryAzureNetworkId?: string;
vmNics?: VMNicDetails[];
vmSyncedConfigDetails?: AzureToAzureVmSyncedConfigDetails;
monitoringPercentageCompletion?: number;
monitoringJobType?: string;
lastHeartbeat?: Date;
agentVersion?: string;
isReplicationAgentUpdateRequired?: boolean;
recoveryFabricObjectId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
lifecycleId?: string;
testFailoverRecoveryFabricObjectId?: string;
rpoInSeconds?: number;
lastRpoCalculatedTime?: Date;
}
/**
* @class
* Initializes a new instance of the ReverseReplicationProviderSpecificInput class.
* @constructor
* Provider specific reverse replication input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ReverseReplicationProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AReprotectInput class.
* @constructor
* Azure specific reprotect input.
*
* @member {string} [recoveryContainerId] The recovery container Id.
* @member {array} [vmDisks] The list of vm disk details.
* @member {string} [recoveryResourceGroupId] The recovery resource group Id.
* Valid for V2 scenarios.
* @member {string} [recoveryCloudServiceId] The recovery cloud service Id.
* Valid for V1 scenarios.
* @member {string} [recoveryAvailabilitySetId] The recovery availability set.
* @member {string} [policyId] The Policy Id.
*/
export interface A2AReprotectInput extends ReverseReplicationProviderSpecificInput {
recoveryContainerId?: string;
vmDisks?: A2AVmDiskInputDetails[];
recoveryResourceGroupId?: string;
recoveryCloudServiceId?: string;
recoveryAvailabilitySetId?: string;
policyId?: string;
}
/**
* @class
* Initializes a new instance of the SwitchProtectionProviderSpecificInput class.
* @constructor
* Provider specific switch protection input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface SwitchProtectionProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2ASwitchProtectionInput class.
* @constructor
* A2A specific switch protection input.
*
* @member {string} [recoveryContainerId] The recovery container Id.
* @member {array} [vmDisks] The list of vm disk details.
* @member {array} [vmManagedDisks] The list of vm managed disk details.
* @member {string} [recoveryResourceGroupId] The recovery resource group Id.
* Valid for V2 scenarios.
* @member {string} [recoveryCloudServiceId] The recovery cloud service Id.
* Valid for V1 scenarios.
* @member {string} [recoveryAvailabilitySetId] The recovery availability set.
* @member {string} [policyId] The Policy Id.
* @member {string} [recoveryBootDiagStorageAccountId] The boot diagnostic
* storage account.
* @member {object} [diskEncryptionInfo] The recovery disk encryption
* information.
* @member {object} [diskEncryptionInfo.diskEncryptionKeyInfo] The recovery
* KeyVault reference for secret.
* @member {string} [diskEncryptionInfo.diskEncryptionKeyInfo.secretIdentifier]
* The secret url / identifier.
* @member {string}
* [diskEncryptionInfo.diskEncryptionKeyInfo.keyVaultResourceArmId] The
* KeyVault resource ARM id for secret.
* @member {object} [diskEncryptionInfo.keyEncryptionKeyInfo] The recovery
* KeyVault reference for key.
* @member {string} [diskEncryptionInfo.keyEncryptionKeyInfo.keyIdentifier] The
* key url / identifier.
* @member {string}
* [diskEncryptionInfo.keyEncryptionKeyInfo.keyVaultResourceArmId] The KeyVault
* resource ARM id for key.
*/
export interface A2ASwitchProtectionInput extends SwitchProtectionProviderSpecificInput {
recoveryContainerId?: string;
vmDisks?: A2AVmDiskInputDetails[];
vmManagedDisks?: A2AVmManagedDiskInputDetails[];
recoveryResourceGroupId?: string;
recoveryCloudServiceId?: string;
recoveryAvailabilitySetId?: string;
policyId?: string;
recoveryBootDiagStorageAccountId?: string;
diskEncryptionInfo?: DiskEncryptionInfo;
}
/**
* @class
* Initializes a new instance of the ReplicationProviderSpecificUpdateContainerMappingInput class.
* @constructor
* Provider specific input for update pairing operations.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ReplicationProviderSpecificUpdateContainerMappingInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AUpdateContainerMappingInput class.
* @constructor
* A2A update protection container mapping.
*
* @member {string} [agentAutoUpdateStatus] A value indicating whether the auto
* update is enabled. Possible values include: 'Disabled', 'Enabled'
* @member {string} [automationAccountArmId] The automation account arm id.
*/
export interface A2AUpdateContainerMappingInput extends ReplicationProviderSpecificUpdateContainerMappingInput {
agentAutoUpdateStatus?: string;
automationAccountArmId?: string;
}
/**
* @class
* Initializes a new instance of the A2AVmManagedDiskUpdateDetails class.
* @constructor
* Azure VM managed disk update input details.
*
* @member {string} [diskId] The disk Id.
* @member {string} [recoveryTargetDiskAccountType] The target disk type before
* failover.
* @member {string} [recoveryReplicaDiskAccountType] The replica disk type
* before failover.
*/
export interface A2AVmManagedDiskUpdateDetails {
diskId?: string;
recoveryTargetDiskAccountType?: string;
recoveryReplicaDiskAccountType?: string;
}
/**
* @class
* Initializes a new instance of the UpdateReplicationProtectedItemProviderInput class.
* @constructor
* Update replication protected item provider specific input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface UpdateReplicationProtectedItemProviderInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the A2AUpdateReplicationProtectedItemInput class.
* @constructor
* InMage Azure V2 input to update replication protected item.
*
* @member {string} [recoveryCloudServiceId] The target cloud service ARM Id
* (for V1).
* @member {string} [recoveryResourceGroupId] The target resource group ARM Id
* (for V2).
* @member {array} [managedDiskUpdateDetails] Managed disk update details.
* @member {string} [recoveryBootDiagStorageAccountId] The boot diagnostic
* storage account.
* @member {object} [diskEncryptionInfo] The recovery os disk encryption
* information.
* @member {object} [diskEncryptionInfo.diskEncryptionKeyInfo] The recovery
* KeyVault reference for secret.
* @member {string} [diskEncryptionInfo.diskEncryptionKeyInfo.secretIdentifier]
* The secret url / identifier.
* @member {string}
* [diskEncryptionInfo.diskEncryptionKeyInfo.keyVaultResourceArmId] The
* KeyVault resource ARM id for secret.
* @member {object} [diskEncryptionInfo.keyEncryptionKeyInfo] The recovery
* KeyVault reference for key.
* @member {string} [diskEncryptionInfo.keyEncryptionKeyInfo.keyIdentifier] The
* key url / identifier.
* @member {string}
* [diskEncryptionInfo.keyEncryptionKeyInfo.keyVaultResourceArmId] The KeyVault
* resource ARM id for key.
*/
export interface A2AUpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput {
recoveryCloudServiceId?: string;
recoveryResourceGroupId?: string;
managedDiskUpdateDetails?: A2AVmManagedDiskUpdateDetails[];
recoveryBootDiagStorageAccountId?: string;
diskEncryptionInfo?: DiskEncryptionInfo;
}
/**
* @class
* Initializes a new instance of the AddVCenterRequestProperties class.
* @constructor
* The properties of an add vCenter request.
*
* @member {string} [friendlyName] The friendly name of the vCenter.
* @member {string} [ipAddress] The IP address of the vCenter to be discovered.
* @member {string} [processServerId] The process server Id from where the
* discovery is orchestrated.
* @member {string} [port] The port number for discovery.
* @member {string} [runAsAccountId] The account Id which has privileges to
* discover the vCenter.
*/
export interface AddVCenterRequestProperties {
friendlyName?: string;
ipAddress?: string;
processServerId?: string;
port?: string;
runAsAccountId?: string;
}
/**
* @class
* Initializes a new instance of the AddVCenterRequest class.
* @constructor
* Input required to add vCenter.
*
* @member {object} [properties] The properties of an add vCenter request.
* @member {string} [properties.friendlyName] The friendly name of the vCenter.
* @member {string} [properties.ipAddress] The IP address of the vCenter to be
* discovered.
* @member {string} [properties.processServerId] The process server Id from
* where the discovery is orchestrated.
* @member {string} [properties.port] The port number for discovery.
* @member {string} [properties.runAsAccountId] The account Id which has
* privileges to discover the vCenter.
*/
export interface AddVCenterRequest {
properties?: AddVCenterRequestProperties;
}
/**
* @class
* Initializes a new instance of the AlertProperties class.
* @constructor
* The proprties of an alert.
*
* @member {string} [sendToOwners] A value indicating whether to send email to
* subscription administrator.
* @member {array} [customEmailAddresses] The custom email address for sending
* emails.
* @member {string} [locale] The locale for the email notification.
*/
export interface AlertProperties {
sendToOwners?: string;
customEmailAddresses?: string[];
locale?: string;
}
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* Azure resource.
*
* @member {string} [id] Resource Id
* @member {string} [name] Resource Name
* @member {string} [type] Resource Type
* @member {string} [location] Resource Location
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location?: string;
}
/**
* @class
* Initializes a new instance of the Alert class.
* @constructor
* Implements the Alert class.
*
* @member {object} [properties] Alert related data.
* @member {string} [properties.sendToOwners] A value indicating whether to
* send email to subscription administrator.
* @member {array} [properties.customEmailAddresses] The custom email address
* for sending emails.
* @member {string} [properties.locale] The locale for the email notification.
*/
export interface Alert extends Resource {
properties?: AlertProperties;
}
/**
* @class
* Initializes a new instance of the ApplyRecoveryPointInputProperties class.
* @constructor
* Input properties to apply recovery point.
*
* @member {string} [recoveryPointId] The recovery point Id.
* @member {object} [providerSpecificDetails] Provider specific input for
* applying recovery point.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface ApplyRecoveryPointInputProperties {
recoveryPointId?: string;
providerSpecificDetails?: ApplyRecoveryPointProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the ApplyRecoveryPointInput class.
* @constructor
* Input to apply recovery point.
*
* @member {object} [properties] The input properties to apply recovery point.
* @member {string} [properties.recoveryPointId] The recovery point Id.
* @member {object} [properties.providerSpecificDetails] Provider specific
* input for applying recovery point.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface ApplyRecoveryPointInput {
properties?: ApplyRecoveryPointInputProperties;
}
/**
* @class
* Initializes a new instance of the JobDetails class.
* @constructor
* Job details based on specific job type.
*
* @member {object} [affectedObjectDetails] The affected object properties like
* source server, source cloud, target server, target cloud etc. based on the
* workflow object details.
* @member {string} instanceType Polymorphic Discriminator
*/
export interface JobDetails {
affectedObjectDetails?: { [propertyName: string]: string };
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AsrJobDetails class.
* @constructor
* This class represents job details based on specific job type.
*
*/
export interface AsrJobDetails extends JobDetails {
}
/**
* @class
* Initializes a new instance of the TaskTypeDetails class.
* @constructor
* Task details based on specific task type.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface TaskTypeDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the GroupTaskDetails class.
* @constructor
* This class represents the group task details when parent child relationship
* exists in the drill down.
*
* @member {array} [childTasks] The child tasks.
* @member {string} instanceType Polymorphic Discriminator
*/
export interface GroupTaskDetails {
childTasks?: ASRTask[];
instanceType: string;
}
/**
* @class
* Initializes a new instance of the ServiceError class.
* @constructor
* ASR error model
*
* @member {string} [code] Error code.
* @member {string} [message] Error message.
* @member {string} [possibleCauses] Possible causes of error.
* @member {string} [recommendedAction] Recommended action to resolve error.
* @member {string} [activityId] Activity Id.
*/
export interface ServiceError {
code?: string;
message?: string;
possibleCauses?: string;
recommendedAction?: string;
activityId?: string;
}
/**
* @class
* Initializes a new instance of the ProviderError class.
* @constructor
* This class contains the error details per object.
*
* @member {number} [errorCode] The Error code.
* @member {string} [errorMessage] The Error message.
* @member {string} [errorId] The Provider error Id.
* @member {string} [possibleCauses] The possible causes for the error.
* @member {string} [recommendedAction] The recommended action to resolve the
* error.
*/
export interface ProviderError {
errorCode?: number;
errorMessage?: string;
errorId?: string;
possibleCauses?: string;
recommendedAction?: string;
}
/**
* @class
* Initializes a new instance of the JobErrorDetails class.
* @constructor
* This class contains the error details per object.
*
* @member {object} [serviceErrorDetails] The Service error details.
* @member {string} [serviceErrorDetails.code] Error code.
* @member {string} [serviceErrorDetails.message] Error message.
* @member {string} [serviceErrorDetails.possibleCauses] Possible causes of
* error.
* @member {string} [serviceErrorDetails.recommendedAction] Recommended action
* to resolve error.
* @member {string} [serviceErrorDetails.activityId] Activity Id.
* @member {object} [providerErrorDetails] The Provider error details.
* @member {number} [providerErrorDetails.errorCode] The Error code.
* @member {string} [providerErrorDetails.errorMessage] The Error message.
* @member {string} [providerErrorDetails.errorId] The Provider error Id.
* @member {string} [providerErrorDetails.possibleCauses] The possible causes
* for the error.
* @member {string} [providerErrorDetails.recommendedAction] The recommended
* action to resolve the error.
* @member {string} [errorLevel] Error level of error.
* @member {date} [creationTime] The creation time of job error.
* @member {string} [taskId] The Id of the task.
*/
export interface JobErrorDetails {
serviceErrorDetails?: ServiceError;
providerErrorDetails?: ProviderError;
errorLevel?: string;
creationTime?: Date;
taskId?: string;
}
/**
* @class
* Initializes a new instance of the ASRTask class.
* @constructor
* Task of the Job.
*
* @member {string} [taskId] The Id.
* @member {string} [name] The unique Task name.
* @member {date} [startTime] The start time.
* @member {date} [endTime] The end time.
* @member {array} [allowedActions] The state/actions applicable on this task.
* @member {string} [friendlyName] The name.
* @member {string} [state] The State. It is one of these values - NotStarted,
* InProgress, Succeeded, Failed, Cancelled, Suspended or Other.
* @member {string} [stateDescription] The description of the task state. For
* example - For Succeeded state, description can be Completed,
* PartiallySucceeded, CompletedWithInformation or Skipped.
* @member {string} [taskType] The type of task. Details in CustomDetails
* property depend on this type.
* @member {object} [customDetails] The custom task details based on the task
* type.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
* @member {object} [groupTaskCustomDetails] The custom task details based on
* the task type, if the task type is GroupTaskDetails or one of the types
* derived from it.
* @member {array} [groupTaskCustomDetails.childTasks] The child tasks.
* @member {string} [groupTaskCustomDetails.instanceType] Polymorphic
* Discriminator
* @member {array} [errors] The task error details.
*/
export interface ASRTask {
taskId?: string;
name?: string;
startTime?: Date;
endTime?: Date;
allowedActions?: string[];
friendlyName?: string;
state?: string;
stateDescription?: string;
taskType?: string;
customDetails?: TaskTypeDetails;
groupTaskCustomDetails?: GroupTaskDetails;
errors?: JobErrorDetails[];
}
/**
* @class
* Initializes a new instance of the AutomationRunbookTaskDetails class.
* @constructor
* This class represents the task details for an automation runbook.
*
* @member {string} [name] The recovery plan task name.
* @member {string} [cloudServiceName] The cloud service of the automation
* runbook account.
* @member {string} [subscriptionId] The subscription Id of the automation
* runbook account.
* @member {string} [accountName] The automation account name of the runbook.
* @member {string} [runbookId] The runbook Id.
* @member {string} [runbookName] The runbook name.
* @member {string} [jobId] The job Id of the runbook execution.
* @member {string} [jobOutput] The execution output of the runbook.
* @member {boolean} [isPrimarySideScript] A value indicating whether it is a
* primary side script or not.
*/
export interface AutomationRunbookTaskDetails extends TaskTypeDetails {
name?: string;
cloudServiceName?: string;
subscriptionId?: string;
accountName?: string;
runbookId?: string;
runbookName?: string;
jobId?: string;
jobOutput?: string;
isPrimarySideScript?: boolean;
}
/**
* @class
* Initializes a new instance of the FabricSpecificCreationInput class.
* @constructor
* Fabric provider specific settings.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface FabricSpecificCreationInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AzureFabricCreationInput class.
* @constructor
* Fabric provider specific settings.
*
* @member {string} [location] The Location.
*/
export interface AzureFabricCreationInput extends FabricSpecificCreationInput {
location?: string;
}
/**
* @class
* Initializes a new instance of the FabricSpecificDetails class.
* @constructor
* Fabric specific details.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface FabricSpecificDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AzureFabricSpecificDetails class.
* @constructor
* Azure Fabric Specific Details.
*
* @member {string} [location] The Location for the Azure fabric.
* @member {array} [containerIds] The container Ids for the Azure fabric.
*/
export interface AzureFabricSpecificDetails extends FabricSpecificDetails {
location?: string;
containerIds?: string[];
}
/**
* @class
* Initializes a new instance of the FabricSpecificCreateNetworkMappingInput class.
* @constructor
* Input details specific to fabrics during Network Mapping.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface FabricSpecificCreateNetworkMappingInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AzureToAzureCreateNetworkMappingInput class.
* @constructor
* Create network mappings input properties/behaviour specific to Azure to
* Azure Network mapping.
*
* @member {string} [primaryNetworkId] The primary azure vnet Id.
*/
export interface AzureToAzureCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput {
primaryNetworkId?: string;
}
/**
* @class
* Initializes a new instance of the NetworkMappingFabricSpecificSettings class.
* @constructor
* Network Mapping fabric specific settings.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface NetworkMappingFabricSpecificSettings {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AzureToAzureNetworkMappingSettings class.
* @constructor
* A2A Network Mapping fabric specific settings.
*
* @member {string} [primaryFabricLocation] The primary fabric location.
* @member {string} [recoveryFabricLocation] The recovery fabric location.
*/
export interface AzureToAzureNetworkMappingSettings extends NetworkMappingFabricSpecificSettings {
primaryFabricLocation?: string;
recoveryFabricLocation?: string;
}
/**
* @class
* Initializes a new instance of the FabricSpecificUpdateNetworkMappingInput class.
* @constructor
* Input details specific to fabrics during Network Mapping.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface FabricSpecificUpdateNetworkMappingInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the AzureToAzureUpdateNetworkMappingInput class.
* @constructor
* Updates network mappings input.
*
* @member {string} [primaryNetworkId] The primary azure vnet Id.
*/
export interface AzureToAzureUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput {
primaryNetworkId?: string;
}
/**
* @class
* Initializes a new instance of the AzureVmDiskDetails class.
* @constructor
* Disk details for E2A provider.
*
* @member {string} [vhdType] VHD type.
* @member {string} [vhdId] The VHD id.
* @member {string} [vhdName] VHD name.
* @member {string} [maxSizeMB] Max side in MB.
* @member {string} [targetDiskLocation] Blob uri of the Azure disk.
* @member {string} [targetDiskName] The target Azure disk name.
* @member {string} [lunId] Ordinal\LunId of the disk for the Azure VM.
*/
export interface AzureVmDiskDetails {
vhdType?: string;
vhdId?: string;
vhdName?: string;
maxSizeMB?: string;
targetDiskLocation?: string;
targetDiskName?: string;
lunId?: string;
}
/**
* @class
* Initializes a new instance of the ComputeSizeErrorDetails class.
* @constructor
* Represents the error used to indicate why the target compute size is not
* applicable.
*
* @member {string} [message] The error message.
* @member {string} [severity] The severity of the error.
*/
export interface ComputeSizeErrorDetails {
message?: string;
severity?: string;
}
/**
* @class
* Initializes a new instance of the ConfigurationSettings class.
* @constructor
* Replication provider specific settings.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface ConfigurationSettings {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the ConfigureAlertRequestProperties class.
* @constructor
* Properties of a configure alert request.
*
* @member {string} [sendToOwners] A value indicating whether to send email to
* subscription administrator.
* @member {array} [customEmailAddresses] The custom email address for sending
* emails.
* @member {string} [locale] The locale for the email notification.
*/
export interface ConfigureAlertRequestProperties {
sendToOwners?: string;
customEmailAddresses?: string[];
locale?: string;
}
/**
* @class
* Initializes a new instance of the ConfigureAlertRequest class.
* @constructor
* Request to configure alerts for the system.
*
* @member {object} [properties] The properties of a configure alert request.
* @member {string} [properties.sendToOwners] A value indicating whether to
* send email to subscription administrator.
* @member {array} [properties.customEmailAddresses] The custom email address
* for sending emails.
* @member {string} [properties.locale] The locale for the email notification.
*/
export interface ConfigureAlertRequest {
properties?: ConfigureAlertRequestProperties;
}
/**
* @class
* Initializes a new instance of the InconsistentVmDetails class.
* @constructor
* This class stores the monitoring details for consistency check of
* inconsistent Protected Entity.
*
* @member {string} [vmName] The Vm name.
* @member {string} [cloudName] The Cloud name.
* @member {array} [details] The list of details regarding state of the
* Protected Entity in SRS and On prem.
* @member {array} [errorIds] The list of error ids.
*/
export interface InconsistentVmDetails {
vmName?: string;
cloudName?: string;
details?: string[];
errorIds?: string[];
}
/**
* @class
* Initializes a new instance of the ConsistencyCheckTaskDetails class.
* @constructor
* This class contains monitoring details of all the inconsistent Protected
* Entites in Vmm.
*
* @member {array} [vmDetails] The list of inconsistent Vm details.
*/
export interface ConsistencyCheckTaskDetails extends TaskTypeDetails {
vmDetails?: InconsistentVmDetails[];
}
/**
* @class
* Initializes a new instance of the CreateNetworkMappingInputProperties class.
* @constructor
* Common input details for network mapping operation.
*
* @member {string} [recoveryFabricName] Recovery fabric Name.
* @member {string} [recoveryNetworkId] Recovery network Id.
* @member {object} [fabricSpecificDetails] Fabric specific input properties.
* @member {string} [fabricSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface CreateNetworkMappingInputProperties {
recoveryFabricName?: string;
recoveryNetworkId?: string;
fabricSpecificDetails?: FabricSpecificCreateNetworkMappingInput;
}
/**
* @class
* Initializes a new instance of the CreateNetworkMappingInput class.
* @constructor
* Create network mappings input.
*
* @member {object} [properties] Input properties for creating network mapping.
* @member {string} [properties.recoveryFabricName] Recovery fabric Name.
* @member {string} [properties.recoveryNetworkId] Recovery network Id.
* @member {object} [properties.fabricSpecificDetails] Fabric specific input
* properties.
* @member {string} [properties.fabricSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface CreateNetworkMappingInput {
properties?: CreateNetworkMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the CreatePolicyInputProperties class.
* @constructor
* Policy creation properties.
*
* @member {object} [providerSpecificInput] The ReplicationProviderSettings.
* @member {string} [providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface CreatePolicyInputProperties {
providerSpecificInput?: PolicyProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the CreatePolicyInput class.
* @constructor
* Protection Policy input.
*
* @member {object} [properties] Policy creation properties.
* @member {object} [properties.providerSpecificInput] The
* ReplicationProviderSettings.
* @member {string} [properties.providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface CreatePolicyInput {
properties?: CreatePolicyInputProperties;
}
/**
* @class
* Initializes a new instance of the CreateProtectionContainerInputProperties class.
* @constructor
* Create protection container input properties.
*
* @member {array} [providerSpecificInput] Provider specific inputs for
* container creation.
*/
export interface CreateProtectionContainerInputProperties {
providerSpecificInput?: ReplicationProviderSpecificContainerCreationInput[];
}
/**
* @class
* Initializes a new instance of the CreateProtectionContainerInput class.
* @constructor
* Create protection container input.
*
* @member {object} [properties] Create protection container input properties.
* @member {array} [properties.providerSpecificInput] Provider specific inputs
* for container creation.
*/
export interface CreateProtectionContainerInput {
properties?: CreateProtectionContainerInputProperties;
}
/**
* @class
* Initializes a new instance of the CreateProtectionContainerMappingInputProperties class.
* @constructor
* Configure pairing input properties.
*
* @member {string} [targetProtectionContainerId] The target unique protection
* container name.
* @member {string} [policyId] Applicable policy.
* @member {object} [providerSpecificInput] Provider specific input for
* pairing.
* @member {string} [providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface CreateProtectionContainerMappingInputProperties {
targetProtectionContainerId?: string;
policyId?: string;
providerSpecificInput?: ReplicationProviderSpecificContainerMappingInput;
}
/**
* @class
* Initializes a new instance of the CreateProtectionContainerMappingInput class.
* @constructor
* Configure pairing input.
*
* @member {object} [properties] Configure protection input properties.
* @member {string} [properties.targetProtectionContainerId] The target unique
* protection container name.
* @member {string} [properties.policyId] Applicable policy.
* @member {object} [properties.providerSpecificInput] Provider specific input
* for pairing.
* @member {string} [properties.providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface CreateProtectionContainerMappingInput {
properties?: CreateProtectionContainerMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanProtectedItem class.
* @constructor
* Recovery plan protected item.
*
* @member {string} [id] The ARM Id of the recovery plan protected item.
* @member {string} [virtualMachineId] The virtual machine Id.
*/
export interface RecoveryPlanProtectedItem {
id?: string;
virtualMachineId?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanActionDetails class.
* @constructor
* Recovery plan action custom details.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface RecoveryPlanActionDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanAction class.
* @constructor
* Recovery plan action details.
*
* @member {string} actionName The action name.
* @member {array} failoverTypes The list of failover types.
* @member {array} failoverDirections The list of failover directions.
* @member {object} customDetails The custom details.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
*/
export interface RecoveryPlanAction {
actionName: string;
failoverTypes: string[];
failoverDirections: string[];
customDetails: RecoveryPlanActionDetails;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanGroup class.
* @constructor
* Recovery plan group details.
*
* @member {string} groupType The group type. Possible values include:
* 'Shutdown', 'Boot', 'Failover'
* @member {array} [replicationProtectedItems] The list of protected items.
* @member {array} [startGroupActions] The start group actions.
* @member {array} [endGroupActions] The end group actions.
*/
export interface RecoveryPlanGroup {
groupType: string;
replicationProtectedItems?: RecoveryPlanProtectedItem[];
startGroupActions?: RecoveryPlanAction[];
endGroupActions?: RecoveryPlanAction[];
}
/**
* @class
* Initializes a new instance of the CreateRecoveryPlanInputProperties class.
* @constructor
* Recovery plan creation properties.
*
* @member {string} primaryFabricId The primary fabric Id.
* @member {string} recoveryFabricId The recovery fabric Id.
* @member {string} [failoverDeploymentModel] The failover deployment model.
* Possible values include: 'NotApplicable', 'Classic', 'ResourceManager'
* @member {array} groups The recovery plan groups.
*/
export interface CreateRecoveryPlanInputProperties {
primaryFabricId: string;
recoveryFabricId: string;
failoverDeploymentModel?: string;
groups: RecoveryPlanGroup[];
}
/**
* @class
* Initializes a new instance of the CreateRecoveryPlanInput class.
* @constructor
* Create recovery plan input class.
*
* @member {object} properties Recovery plan creation properties.
* @member {string} [properties.primaryFabricId] The primary fabric Id.
* @member {string} [properties.recoveryFabricId] The recovery fabric Id.
* @member {string} [properties.failoverDeploymentModel] The failover
* deployment model. Possible values include: 'NotApplicable', 'Classic',
* 'ResourceManager'
* @member {array} [properties.groups] The recovery plan groups.
*/
export interface CreateRecoveryPlanInput {
properties: CreateRecoveryPlanInputProperties;
}
/**
* @class
* Initializes a new instance of the CurrentScenarioDetails class.
* @constructor
* Current scenario details of the protected entity.
*
* @member {string} [scenarioName] Scenario name.
* @member {string} [jobId] ARM Id of the job being executed.
* @member {date} [startTime] Start time of the workflow.
*/
export interface CurrentScenarioDetails {
scenarioName?: string;
jobId?: string;
startTime?: Date;
}
/**
* @class
* Initializes a new instance of the DataStore class.
* @constructor
* The datastore details of the MT.
*
* @member {string} [symbolicName] The symbolic name of data store.
* @member {string} [uuid] The uuid of data store.
* @member {string} [capacity] The capacity of data store in GBs.
* @member {string} [freeSpace] The free space of data store in GBs.
* @member {string} [type] The type of data store.
*/
export interface DataStore {
symbolicName?: string;
uuid?: string;
capacity?: string;
freeSpace?: string;
type?: string;
}
/**
* @class
* Initializes a new instance of the DisableProtectionProviderSpecificInput class.
* @constructor
* Disable protection provider specific input.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface DisableProtectionProviderSpecificInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the DisableProtectionInputProperties class.
* @constructor
* Disable protection input properties.
*
* @member {string} [disableProtectionReason] Disable protection reason. It can
* have values NotSpecified/MigrationComplete. Possible values include:
* 'NotSpecified', 'MigrationComplete'
* @member {object} [replicationProviderInput] Replication provider specific
* input.
* @member {string} [replicationProviderInput.instanceType] Polymorphic
* Discriminator
*/
export interface DisableProtectionInputProperties {
disableProtectionReason?: string;
replicationProviderInput?: DisableProtectionProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the DisableProtectionInput class.
* @constructor
* Disable protection input.
*
* @member {object} [properties] Disable protection input properties.
* @member {string} [properties.disableProtectionReason] Disable protection
* reason. It can have values NotSpecified/MigrationComplete. Possible values
* include: 'NotSpecified', 'MigrationComplete'
* @member {object} [properties.replicationProviderInput] Replication provider
* specific input.
* @member {string} [properties.replicationProviderInput.instanceType]
* Polymorphic Discriminator
*/
export interface DisableProtectionInput {
properties?: DisableProtectionInputProperties;
}
/**
* @class
* Initializes a new instance of the DiscoverProtectableItemRequestProperties class.
* @constructor
* Discover protectable item properties.
*
* @member {string} [friendlyName] The friendly name of the physical machine.
* @member {string} [ipAddress] The IP address of the physical machine to be
* discovered.
* @member {string} [osType] The OS type on the physical machine.
*/
export interface DiscoverProtectableItemRequestProperties {
friendlyName?: string;
ipAddress?: string;
osType?: string;
}
/**
* @class
* Initializes a new instance of the DiscoverProtectableItemRequest class.
* @constructor
* Request to add a physical machine as a protectable item in a container.
*
* @member {object} [properties] The properties of a discover protectable item
* request.
* @member {string} [properties.friendlyName] The friendly name of the physical
* machine.
* @member {string} [properties.ipAddress] The IP address of the physical
* machine to be discovered.
* @member {string} [properties.osType] The OS type on the physical machine.
*/
export interface DiscoverProtectableItemRequest {
properties?: DiscoverProtectableItemRequestProperties;
}
/**
* @class
* Initializes a new instance of the DiskDetails class.
* @constructor
* Onprem disk details data.
*
* @member {number} [maxSizeMB] The hard disk max size in MB.
* @member {string} [vhdType] The type of the volume.
* @member {string} [vhdId] The VHD Id.
* @member {string} [vhdName] The VHD name.
*/
export interface DiskDetails {
maxSizeMB?: number;
vhdType?: string;
vhdId?: string;
vhdName?: string;
}
/**
* @class
* Initializes a new instance of the DiskVolumeDetails class.
* @constructor
* Volume details.
*
* @member {string} [label] The volume label.
* @member {string} [name] The volume name.
*/
export interface DiskVolumeDetails {
label?: string;
name?: string;
}
/**
* @class
* Initializes a new instance of the Display class.
* @constructor
* Contains the localized display information for this particular operation /
* action. These value will be used by several clients for (1) custom role
* definitions for RBAC; (2) complex query filters for the event service; and
* (3) audit history / records for management operations.
*
* @member {string} [provider] The provider. The localized friendly form of the
* resource provider name – it is expected to also include the
* publisher/company responsible. It should use Title Casing and begin with
* "Microsoft" for 1st party services. e.g. "Microsoft Monitoring Insights" or
* "Microsoft Compute."
* @member {string} [resource] The resource. The localized friendly form of the
* resource related to this action/operation – it should match the public
* documentation for the resource provider. It should use Title Casing. This
* value should be unique for a particular URL type (e.g. nested types should
* *not* reuse their parent’s display.resource field). e.g. "Virtual Machines"
* or "Scheduler Job Collections", or "Virtual Machine VM Sizes" or "Scheduler
* Jobs"
* @member {string} [operation] The operation. The localized friendly name for
* the operation, as it should be shown to the user. It should be concise (to
* fit in drop downs) but clear (i.e. self-documenting). It should use Title
* Casing. Prescriptive guidance: Read Create or Update Delete 'ActionName'
* @member {string} [description] The description. The localized friendly
* description for the operation, as it should be shown to the user. It should
* be thorough, yet concise – it will be used in tool tips and detailed views.
* Prescriptive guidance for namespaces: Read any 'display.provider' resource
* Create or Update any 'display.provider' resource Delete any
* 'display.provider' resource Perform any other action on any
* 'display.provider' resource Prescriptive guidance for namespaces: Read any
* 'display.resource' Create or Update any 'display.resource' Delete any
* 'display.resource' 'ActionName' any 'display.resources'
*/
export interface Display {
provider?: string;
resource?: string;
operation?: string;
description?: string;
}
/**
* @class
* Initializes a new instance of the EnableProtectionInputProperties class.
* @constructor
* Enable protection input properties.
*
* @member {string} [policyId] The Policy Id.
* @member {string} [protectableItemId] The protectable item Id.
* @member {object} [providerSpecificDetails] The ReplicationProviderInput. For
* HyperVReplicaAzure provider, it will be AzureEnableProtectionInput object.
* For San provider, it will be SanEnableProtectionInput object. For
* HyperVReplicaAzure provider, it can be null.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface EnableProtectionInputProperties {
policyId?: string;
protectableItemId?: string;
providerSpecificDetails?: EnableProtectionProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the EnableProtectionInput class.
* @constructor
* Enable protection input.
*
* @member {object} [properties] Enable protection input properties.
* @member {string} [properties.policyId] The Policy Id.
* @member {string} [properties.protectableItemId] The protectable item Id.
* @member {object} [properties.providerSpecificDetails] The
* ReplicationProviderInput. For HyperVReplicaAzure provider, it will be
* AzureEnableProtectionInput object. For San provider, it will be
* SanEnableProtectionInput object. For HyperVReplicaAzure provider, it can be
* null.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface EnableProtectionInput {
properties?: EnableProtectionInputProperties;
}
/**
* @class
* Initializes a new instance of the EncryptionDetails class.
* @constructor
* Encryption details for the fabric.
*
* @member {string} [kekState] The key encryption key state for the Vmm.
* @member {string} [kekCertThumbprint] The key encryption key certificate
* thumbprint.
* @member {date} [kekCertExpiryDate] The key encryption key certificate expiry
* date.
*/
export interface EncryptionDetails {
kekState?: string;
kekCertThumbprint?: string;
kekCertExpiryDate?: Date;
}
/**
* @class
* Initializes a new instance of the EventSpecificDetails class.
* @constructor
* Model class for event specific details for an event.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface EventSpecificDetails {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the InnerHealthError class.
* @constructor
* Implements InnerHealthError class. HealthError object has a list of
* InnerHealthErrors as child errors. InnerHealthError is used because this
* will prevent an infinite loop of structures when Hydra tries to
* auto-generate the contract. We are exposing the related health errors as
* inner health errors and all API consumers can utilize this in the same
* fashion as Exception -> InnerException.
*
* @member {string} [errorSource] Source of error.
* @member {string} [errorType] Type of error.
* @member {string} [errorLevel] Level of error.
* @member {string} [errorCategory] Category of error.
* @member {string} [errorCode] Error code.
* @member {string} [summaryMessage] Summary message of the entity.
* @member {string} [errorMessage] Error message.
* @member {string} [possibleCauses] Possible causes of error.
* @member {string} [recommendedAction] Recommended action to resolve error.
* @member {date} [creationTimeUtc] Error creation time (UTC)
* @member {string} [recoveryProviderErrorMessage] DRA error message.
* @member {string} [entityId] ID of the entity.
*/
export interface InnerHealthError {
errorSource?: string;
errorType?: string;
errorLevel?: string;
errorCategory?: string;
errorCode?: string;
summaryMessage?: string;
errorMessage?: string;
possibleCauses?: string;
recommendedAction?: string;
creationTimeUtc?: Date;
recoveryProviderErrorMessage?: string;
entityId?: string;
}
/**
* @class
* Initializes a new instance of the HealthError class.
* @constructor
* Health Error
*
* @member {array} [innerHealthErrors] The inner health errors. HealthError
* having a list of HealthError as child errors is problematic.
* InnerHealthError is used because this will prevent an infinite loop of
* structures when Hydra tries to auto-generate the contract. We are exposing
* the related health errors as inner health errors and all API consumers can
* utilize this in the same fashion as Exception -> InnerException.
* @member {string} [errorSource] Source of error.
* @member {string} [errorType] Type of error.
* @member {string} [errorLevel] Level of error.
* @member {string} [errorCategory] Category of error.
* @member {string} [errorCode] Error code.
* @member {string} [summaryMessage] Summary message of the entity.
* @member {string} [errorMessage] Error message.
* @member {string} [possibleCauses] Possible causes of error.
* @member {string} [recommendedAction] Recommended action to resolve error.
* @member {date} [creationTimeUtc] Error creation time (UTC)
* @member {string} [recoveryProviderErrorMessage] DRA error message.
* @member {string} [entityId] ID of the entity.
*/
export interface HealthError {
innerHealthErrors?: InnerHealthError[];
errorSource?: string;
errorType?: string;
errorLevel?: string;
errorCategory?: string;
errorCode?: string;
summaryMessage?: string;
errorMessage?: string;
possibleCauses?: string;
recommendedAction?: string;
creationTimeUtc?: Date;
recoveryProviderErrorMessage?: string;
entityId?: string;
}
/**
* @class
* Initializes a new instance of the EventProperties class.
* @constructor
* The properties of a monitoring event.
*
* @member {string} [eventCode] The Id of the monitoring event.
* @member {string} [description] The event name.
* @member {string} [eventType] The type of the event. for example: VM Health,
* Server Health, Job Failure etc.
* @member {string} [affectedObjectFriendlyName] The friendly name of the
* source of the event on which it is raised (for example, VM, VMM etc).
* @member {string} [severity] The severity of the event.
* @member {date} [timeOfOccurrence] The time of occurence of the event.
* @member {string} [fabricId] The ARM ID of the fabric.
* @member {object} [providerSpecificDetails] The provider specific settings.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
* @member {object} [eventSpecificDetails] The event specific settings.
* @member {string} [eventSpecificDetails.instanceType] Polymorphic
* Discriminator
* @member {array} [healthErrors] The list of errors / warnings capturing
* details associated with the issue(s).
*/
export interface EventProperties {
eventCode?: string;
description?: string;
eventType?: string;
affectedObjectFriendlyName?: string;
severity?: string;
timeOfOccurrence?: Date;
fabricId?: string;
providerSpecificDetails?: EventProviderSpecificDetails;
eventSpecificDetails?: EventSpecificDetails;
healthErrors?: HealthError[];
}
/**
* @class
* Initializes a new instance of the Event class.
* @constructor
* Implements the Event class.
*
* @member {object} [properties] Event related data.
* @member {string} [properties.eventCode] The Id of the monitoring event.
* @member {string} [properties.description] The event name.
* @member {string} [properties.eventType] The type of the event. for example:
* VM Health, Server Health, Job Failure etc.
* @member {string} [properties.affectedObjectFriendlyName] The friendly name
* of the source of the event on which it is raised (for example, VM, VMM etc).
* @member {string} [properties.severity] The severity of the event.
* @member {date} [properties.timeOfOccurrence] The time of occurence of the
* event.
* @member {string} [properties.fabricId] The ARM ID of the fabric.
* @member {object} [properties.providerSpecificDetails] The provider specific
* settings.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
* @member {object} [properties.eventSpecificDetails] The event specific
* settings.
* @member {string} [properties.eventSpecificDetails.instanceType] Polymorphic
* Discriminator
* @member {array} [properties.healthErrors] The list of errors / warnings
* capturing details associated with the issue(s).
*/
export interface Event extends Resource {
properties?: EventProperties;
}
/**
* @class
* Initializes a new instance of the EventQueryParameter class.
* @constructor
* Implements the event query parameter.
*
* @member {string} [eventCode] The source id of the events to be queried.
* @member {string} [severity] The severity of the events to be queried.
* @member {string} [eventType] The type of the events to be queried.
* @member {string} [fabricName] The affected object server id of the events to
* be queried.
* @member {string} [affectedObjectFriendlyName] The affected object name of
* the events to be queried.
* @member {date} [startTime] The start time of the time range within which the
* events are to be queried.
* @member {date} [endTime] The end time of the time range within which the
* events are to be queried.
*/
export interface EventQueryParameter {
eventCode?: string;
severity?: string;
eventType?: string;
fabricName?: string;
affectedObjectFriendlyName?: string;
startTime?: Date;
endTime?: Date;
}
/**
* @class
* Initializes a new instance of the ExportJobDetails class.
* @constructor
* This class represents details for export jobs workflow.
*
* @member {string} [blobUri] BlobUri of the exported jobs.
* @member {string} [sasToken] The sas token to access blob.
*/
export interface ExportJobDetails extends JobDetails {
blobUri?: string;
sasToken?: string;
}
/**
* @class
* Initializes a new instance of the FabricProperties class.
* @constructor
* Fabric properties.
*
* @member {string} [friendlyName] Friendly name of the fabric.
* @member {object} [encryptionDetails] Encryption details for the fabric.
* @member {string} [encryptionDetails.kekState] The key encryption key state
* for the Vmm.
* @member {string} [encryptionDetails.kekCertThumbprint] The key encryption
* key certificate thumbprint.
* @member {date} [encryptionDetails.kekCertExpiryDate] The key encryption key
* certificate expiry date.
* @member {object} [rolloverEncryptionDetails] Rollover encryption details for
* the fabric.
* @member {string} [rolloverEncryptionDetails.kekState] The key encryption key
* state for the Vmm.
* @member {string} [rolloverEncryptionDetails.kekCertThumbprint] The key
* encryption key certificate thumbprint.
* @member {date} [rolloverEncryptionDetails.kekCertExpiryDate] The key
* encryption key certificate expiry date.
* @member {string} [internalIdentifier] Dra Registration Id.
* @member {string} [bcdrState] BCDR state of the fabric.
* @member {object} [customDetails] Fabric specific settings.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
* @member {array} [healthErrorDetails] Fabric health error details.
* @member {string} [health] Health of fabric.
*/
export interface FabricProperties {
friendlyName?: string;
encryptionDetails?: EncryptionDetails;
rolloverEncryptionDetails?: EncryptionDetails;
internalIdentifier?: string;
bcdrState?: string;
customDetails?: FabricSpecificDetails;
healthErrorDetails?: HealthError[];
health?: string;
}
/**
* @class
* Initializes a new instance of the Fabric class.
* @constructor
* Fabric definition.
*
* @member {object} [properties] Fabric related data.
* @member {string} [properties.friendlyName] Friendly name of the fabric.
* @member {object} [properties.encryptionDetails] Encryption details for the
* fabric.
* @member {string} [properties.encryptionDetails.kekState] The key encryption
* key state for the Vmm.
* @member {string} [properties.encryptionDetails.kekCertThumbprint] The key
* encryption key certificate thumbprint.
* @member {date} [properties.encryptionDetails.kekCertExpiryDate] The key
* encryption key certificate expiry date.
* @member {object} [properties.rolloverEncryptionDetails] Rollover encryption
* details for the fabric.
* @member {string} [properties.rolloverEncryptionDetails.kekState] The key
* encryption key state for the Vmm.
* @member {string} [properties.rolloverEncryptionDetails.kekCertThumbprint]
* The key encryption key certificate thumbprint.
* @member {date} [properties.rolloverEncryptionDetails.kekCertExpiryDate] The
* key encryption key certificate expiry date.
* @member {string} [properties.internalIdentifier] Dra Registration Id.
* @member {string} [properties.bcdrState] BCDR state of the fabric.
* @member {object} [properties.customDetails] Fabric specific settings.
* @member {string} [properties.customDetails.instanceType] Polymorphic
* Discriminator
* @member {array} [properties.healthErrorDetails] Fabric health error details.
* @member {string} [properties.health] Health of fabric.
*/
export interface Fabric extends Resource {
properties?: FabricProperties;
}
/**
* @class
* Initializes a new instance of the FabricCreationInputProperties class.
* @constructor
* Properties of site details provided during the time of site creation
*
* @member {object} [customDetails] Fabric provider specific creation input.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
*/
export interface FabricCreationInputProperties {
customDetails?: FabricSpecificCreationInput;
}
/**
* @class
* Initializes a new instance of the FabricCreationInput class.
* @constructor
* Site details provided during the time of site creation
*
* @member {object} [properties] Fabric creation input.
* @member {object} [properties.customDetails] Fabric provider specific
* creation input.
* @member {string} [properties.customDetails.instanceType] Polymorphic
* Discriminator
*/
export interface FabricCreationInput {
properties?: FabricCreationInputProperties;
}
/**
* @class
* Initializes a new instance of the JobEntity class.
* @constructor
* This class contains the minimal job details required to navigate to the
* desired drill down.
*
* @member {string} [jobId] The job id.
* @member {string} [jobFriendlyName] The job display name.
* @member {string} [targetObjectId] The object id.
* @member {string} [targetObjectName] The object name.
* @member {string} [targetInstanceType] The workflow affected object type.
* @member {string} [jobScenarioName] The job name. Enum type ScenarioName.
*/
export interface JobEntity {
jobId?: string;
jobFriendlyName?: string;
targetObjectId?: string;
targetObjectName?: string;
targetInstanceType?: string;
jobScenarioName?: string;
}
/**
* @class
* Initializes a new instance of the FabricReplicationGroupTaskDetails class.
* @constructor
* This class represents the fabric replication group task details.
*
* @member {string} [skippedReason] The skipped reason.
* @member {string} [skippedReasonString] The skipped reason string.
* @member {object} [jobTask] The job entity.
* @member {string} [jobTask.jobId] The job id.
* @member {string} [jobTask.jobFriendlyName] The job display name.
* @member {string} [jobTask.targetObjectId] The object id.
* @member {string} [jobTask.targetObjectName] The object name.
* @member {string} [jobTask.targetInstanceType] The workflow affected object
* type.
* @member {string} [jobTask.jobScenarioName] The job name. Enum type
* ScenarioName.
*/
export interface FabricReplicationGroupTaskDetails extends TaskTypeDetails {
skippedReason?: string;
skippedReasonString?: string;
jobTask?: JobEntity;
}
/**
* @class
* Initializes a new instance of the FailoverReplicationProtectedItemDetails class.
* @constructor
* Failover details for a replication protected item.
*
* @member {string} [name] The name.
* @member {string} [friendlyName] The friendly name.
* @member {string} [testVmName] The test Vm name.
* @member {string} [testVmFriendlyName] The test Vm friendly name.
* @member {string} [networkConnectionStatus] The network connection status.
* @member {string} [networkFriendlyName] The network friendly name.
* @member {string} [subnet] The network subnet.
* @member {string} [recoveryPointId] The recovery point Id.
* @member {date} [recoveryPointTime] The recovery point time.
*/
export interface FailoverReplicationProtectedItemDetails {
name?: string;
friendlyName?: string;
testVmName?: string;
testVmFriendlyName?: string;
networkConnectionStatus?: string;
networkFriendlyName?: string;
subnet?: string;
recoveryPointId?: string;
recoveryPointTime?: Date;
}
/**
* @class
* Initializes a new instance of the FailoverJobDetails class.
* @constructor
* This class represents the details for a failover job.
*
* @member {array} [protectedItemDetails] The test VM details.
*/
export interface FailoverJobDetails extends JobDetails {
protectedItemDetails?: FailoverReplicationProtectedItemDetails[];
}
/**
* @class
* Initializes a new instance of the FailoverProcessServerRequestProperties class.
* @constructor
* The properties of the Failover Process Server request.
*
* @member {string} [containerName] The container identifier.
* @member {string} [sourceProcessServerId] The source process server.
* @member {string} [targetProcessServerId] The new process server.
* @member {array} [vmsToMigrate] The VMS to migrate.
* @member {string} [updateType] A value for failover type. It can be
* systemlevel/serverlevel
*/
export interface FailoverProcessServerRequestProperties {
containerName?: string;
sourceProcessServerId?: string;
targetProcessServerId?: string;
vmsToMigrate?: string[];
updateType?: string;
}
/**
* @class
* Initializes a new instance of the FailoverProcessServerRequest class.
* @constructor
* Request to failover a process server.
*
* @member {object} [properties] The properties of the PS Failover request.
* @member {string} [properties.containerName] The container identifier.
* @member {string} [properties.sourceProcessServerId] The source process
* server.
* @member {string} [properties.targetProcessServerId] The new process server.
* @member {array} [properties.vmsToMigrate] The VMS to migrate.
* @member {string} [properties.updateType] A value for failover type. It can
* be systemlevel/serverlevel
*/
export interface FailoverProcessServerRequest {
properties?: FailoverProcessServerRequestProperties;
}
/**
* @class
* Initializes a new instance of the HealthErrorSummary class.
* @constructor
* class to define the summary of the health error details.
*
* @member {string} [summaryCode] The code of the health error.
* @member {string} [category] The category of the health error. Possible
* values include: 'None', 'Replication', 'TestFailover', 'Configuration',
* 'FabricInfrastructure', 'VersionExpiry', 'AgentAutoUpdate'
* @member {string} [severity] Severity of error. Possible values include:
* 'NONE', 'Warning', 'Error', 'Info'
* @member {string} [summaryMessage] The summary message of the health error.
* @member {string} [affectedResourceType] The type of affected ARM resource.
* @member {string} [affectedResourceSubtype] The sub type of any subcomponent
* within the ARM resource that this might be applicable. Value remains null if
* not applicable.
* @member {array} [affectedResourceCorrelationIds] The list of affected
* resource correlation Ids. This can be used to uniquely identify the count of
* items affected by a specific category and severity as well as count of item
* affected by an specific issue.
*/
export interface HealthErrorSummary {
summaryCode?: string;
category?: string;
severity?: string;
summaryMessage?: string;
affectedResourceType?: string;
affectedResourceSubtype?: string;
affectedResourceCorrelationIds?: string[];
}
/**
* @class
* Initializes a new instance of the HyperVReplica2012EventDetails class.
* @constructor
* Model class for event details of a HyperVReplica E2E event.
*
* @member {string} [containerName] The container friendly name.
* @member {string} [fabricName] The fabric friendly name.
* @member {string} [remoteContainerName] The remote container name.
* @member {string} [remoteFabricName] The remote fabric name.
*/
export interface HyperVReplica2012EventDetails extends EventProviderSpecificDetails {
containerName?: string;
fabricName?: string;
remoteContainerName?: string;
remoteFabricName?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplica2012R2EventDetails class.
* @constructor
* Model class for event details of a HyperVReplica blue E2E event.
*
* @member {string} [containerName] The container friendly name.
* @member {string} [fabricName] The fabric friendly name.
* @member {string} [remoteContainerName] The remote container name.
* @member {string} [remoteFabricName] The remote fabric name.
*/
export interface HyperVReplica2012R2EventDetails extends EventProviderSpecificDetails {
containerName?: string;
fabricName?: string;
remoteContainerName?: string;
remoteFabricName?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureApplyRecoveryPointInput class.
* @constructor
* ApplyRecoveryPoint input specific to HyperVReplicaAzure provider.
*
* @member {string} [vaultLocation] The vault location where the recovery Vm
* resides.
* @member {string} [primaryKekCertificatePfx] The primary kek certificate pfx.
* @member {string} [secondaryKekCertificatePfx] The secondary kek certificate
* pfx.
*/
export interface HyperVReplicaAzureApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput {
vaultLocation?: string;
primaryKekCertificatePfx?: string;
secondaryKekCertificatePfx?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureEnableProtectionInput class.
* @constructor
* Azure specific enable protection input.
*
* @member {string} [hvHostVmId] The Hyper-V host Vm Id.
* @member {string} [vmName] The Vm Name.
* @member {string} [osType] The OS type associated with vm.
* @member {string} [vhdId] The OS disk VHD id associated with vm.
* @member {string} [targetStorageAccountId] The storage account name.
* @member {string} [targetAzureNetworkId] The selected target Azure network
* Id.
* @member {string} [targetAzureSubnetId] The selected target Azure subnet Id.
* @member {string} [enableRdpOnTargetOption] The selected option to enable
* RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {string} [targetAzureVmName] The target azure Vm Name.
* @member {string} [logStorageAccountId] The storage account to be used for
* logging during replication.
* @member {array} [disksToInclude] The list of VHD IDs of disks to be
* protected.
* @member {string} [targetAzureV1ResourceGroupId] The Id of the target
* resource group (for classic deployment) in which the failover VM is to be
* created.
* @member {string} [targetAzureV2ResourceGroupId] The Id of the target
* resource group (for resource manager deployment) in which the failover VM is
* to be created.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
*/
export interface HyperVReplicaAzureEnableProtectionInput extends EnableProtectionProviderSpecificInput {
hvHostVmId?: string;
vmName?: string;
osType?: string;
vhdId?: string;
targetStorageAccountId?: string;
targetAzureNetworkId?: string;
targetAzureSubnetId?: string;
enableRdpOnTargetOption?: string;
targetAzureVmName?: string;
logStorageAccountId?: string;
disksToInclude?: string[];
targetAzureV1ResourceGroupId?: string;
targetAzureV2ResourceGroupId?: string;
useManagedDisks?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureEventDetails class.
* @constructor
* Model class for event details of a HyperVReplica E2A event.
*
* @member {string} [containerName] The container friendly name.
* @member {string} [fabricName] The fabric friendly name.
* @member {string} [remoteContainerName] The remote container name.
*/
export interface HyperVReplicaAzureEventDetails extends EventProviderSpecificDetails {
containerName?: string;
fabricName?: string;
remoteContainerName?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureFailbackProviderInput class.
* @constructor
* HvrA provider specific input for failback.
*
* @member {string} [dataSyncOption] Data sync option.
* @member {string} [recoveryVmCreationOption] ALR options to create alternate
* recovery.
* @member {string} [providerIdForAlternateRecovery] Provider ID for alternate
* location
*/
export interface HyperVReplicaAzureFailbackProviderInput extends ProviderSpecificFailoverInput {
dataSyncOption?: string;
recoveryVmCreationOption?: string;
providerIdForAlternateRecovery?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureFailoverProviderInput class.
* @constructor
* HvrA provider specific input for failover.
*
* @member {string} [vaultLocation] Location of the vault.
* @member {string} [primaryKekCertificatePfx] Primary kek certificate pfx.
* @member {string} [secondaryKekCertificatePfx] Secondary kek certificate pfx.
* @member {string} [recoveryPointId] The recovery point id to be passed to
* failover to a particular recovery point. In case of latest recovery point,
* null should be passed.
*/
export interface HyperVReplicaAzureFailoverProviderInput extends ProviderSpecificFailoverInput {
vaultLocation?: string;
primaryKekCertificatePfx?: string;
secondaryKekCertificatePfx?: string;
recoveryPointId?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzurePolicyDetails class.
* @constructor
* Hyper-V Replica Azure specific protection profile details.
*
* @member {number} [recoveryPointHistoryDurationInHours] The duration (in
* hours) to which point the recovery history needs to be maintained.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] The
* interval (in hours) at which Hyper-V Replica should create an application
* consistent snapshot within the VM.
* @member {number} [replicationInterval] The replication interval.
* @member {string} [onlineReplicationStartTime] The scheduled start time for
* the initial replication. If this parameter is Null, the initial replication
* starts immediately.
* @member {string} [encryption] A value indicating whether encryption is
* enabled for virtual machines in this cloud.
* @member {string} [activeStorageAccountId] The active storage account Id.
*/
export interface HyperVReplicaAzurePolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointHistoryDurationInHours?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
replicationInterval?: number;
onlineReplicationStartTime?: string;
encryption?: string;
activeStorageAccountId?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzurePolicyInput class.
* @constructor
* Hyper-V Replica Azure specific input for creating a protection profile.
*
* @member {number} [recoveryPointHistoryDuration] The duration (in hours) to
* which point the recovery history needs to be maintained.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] The
* interval (in hours) at which Hyper-V Replica should create an application
* consistent snapshot within the VM.
* @member {number} [replicationInterval] The replication interval.
* @member {string} [onlineReplicationStartTime] The scheduled start time for
* the initial replication. If this parameter is Null, the initial replication
* starts immediately.
* @member {array} [storageAccounts] The list of storage accounts to which the
* VMs in the primary cloud can replicate to.
*/
export interface HyperVReplicaAzurePolicyInput extends PolicyProviderSpecificInput {
recoveryPointHistoryDuration?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
replicationInterval?: number;
onlineReplicationStartTime?: string;
storageAccounts?: string[];
}
/**
* @class
* Initializes a new instance of the InitialReplicationDetails class.
* @constructor
* Initial replication details.
*
* @member {string} [initialReplicationType] Initial replication type.
* @member {string} [initialReplicationProgressPercentage] The initial
* replication progress percentage.
*/
export interface InitialReplicationDetails {
initialReplicationType?: string;
initialReplicationProgressPercentage?: string;
}
/**
* @class
* Initializes a new instance of the OSDetails class.
* @constructor
* Disk Details.
*
* @member {string} [osType] VM Disk details.
* @member {string} [productType] Product type.
* @member {string} [osEdition] The OSEdition.
* @member {string} [oSVersion] The OS Version.
* @member {string} [oSMajorVersion] The OS Major Version.
* @member {string} [oSMinorVersion] The OS Minor Version.
*/
export interface OSDetails {
osType?: string;
productType?: string;
osEdition?: string;
oSVersion?: string;
oSMajorVersion?: string;
oSMinorVersion?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureReplicationDetails class.
* @constructor
* Hyper V Replica Azure provider specific settings.
*
* @member {array} [azureVmDiskDetails] Azure VM Disk details.
* @member {string} [recoveryAzureVmName] Recovery Azure given name.
* @member {string} [recoveryAzureVMSize] The Recovery Azure VM size.
* @member {string} [recoveryAzureStorageAccount] The recovery Azure storage
* account.
* @member {string} [recoveryAzureLogStorageAccountId] The ARM id of the log
* storage account used for replication. This will be set to null if no log
* storage account was provided during enable protection.
* @member {date} [lastReplicatedTime] The Last replication time.
* @member {number} [rpoInSeconds] Last RPO value.
* @member {date} [lastRpoCalculatedTime] The last RPO calculated time.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {object} [initialReplicationDetails] Initial replication details.
* @member {string} [initialReplicationDetails.initialReplicationType] Initial
* replication type.
* @member {string}
* [initialReplicationDetails.initialReplicationProgressPercentage] The initial
* replication progress percentage.
* @member {array} [vmNics] The PE Network details.
* @member {string} [selectedRecoveryAzureNetworkId] The selected recovery
* azure network Id.
* @member {string} [selectedSourceNicId] The selected source nic Id which will
* be used as the primary nic during failover.
* @member {string} [encryption] The encryption info.
* @member {object} [oSDetails] The operating system info.
* @member {string} [oSDetails.osType] VM Disk details.
* @member {string} [oSDetails.productType] Product type.
* @member {string} [oSDetails.osEdition] The OSEdition.
* @member {string} [oSDetails.oSVersion] The OS Version.
* @member {string} [oSDetails.oSMajorVersion] The OS Major Version.
* @member {string} [oSDetails.oSMinorVersion] The OS Minor Version.
* @member {number} [sourceVmRamSizeInMB] The RAM size of the VM on the primary
* side.
* @member {number} [sourceVmCpuCount] The CPU count of the VM on the primary
* side.
* @member {string} [enableRdpOnTargetOption] The selected option to enable
* RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {string} [recoveryAzureResourceGroupId] The target resource group
* Id.
* @member {string} [recoveryAvailabilitySetId] The recovery availability set
* Id.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
* @member {string} [licenseType] License Type of the VM to be used.
*/
export interface HyperVReplicaAzureReplicationDetails extends ReplicationProviderSpecificSettings {
azureVmDiskDetails?: AzureVmDiskDetails[];
recoveryAzureVmName?: string;
recoveryAzureVMSize?: string;
recoveryAzureStorageAccount?: string;
recoveryAzureLogStorageAccountId?: string;
lastReplicatedTime?: Date;
rpoInSeconds?: number;
lastRpoCalculatedTime?: Date;
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
initialReplicationDetails?: InitialReplicationDetails;
vmNics?: VMNicDetails[];
selectedRecoveryAzureNetworkId?: string;
selectedSourceNicId?: string;
encryption?: string;
oSDetails?: OSDetails;
sourceVmRamSizeInMB?: number;
sourceVmCpuCount?: number;
enableRdpOnTargetOption?: string;
recoveryAzureResourceGroupId?: string;
recoveryAvailabilitySetId?: string;
useManagedDisks?: string;
licenseType?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureReprotectInput class.
* @constructor
* Azure specific reprotect input.
*
* @member {string} [hvHostVmId] The Hyper-V host Vm Id.
* @member {string} [vmName] The Vm Name.
* @member {string} [osType] The OS type associated with vm.
* @member {string} [vHDId] The OS disk VHD id associated with vm.
* @member {string} [storageAccountId] The storage account name.
* @member {string} [logStorageAccountId] The storage account to be used for
* logging during replication.
*/
export interface HyperVReplicaAzureReprotectInput extends ReverseReplicationProviderSpecificInput {
hvHostVmId?: string;
vmName?: string;
osType?: string;
vHDId?: string;
storageAccountId?: string;
logStorageAccountId?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaAzureUpdateReplicationProtectedItemInput class.
* @constructor
* HyperV replica Azure input to update replication protected item.
*
* @member {string} [recoveryAzureV1ResourceGroupId] The recovery Azure
* resource group Id for classic deployment.
* @member {string} [recoveryAzureV2ResourceGroupId] The recovery Azure
* resource group Id for resource manager deployment.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
*/
export interface HyperVReplicaAzureUpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput {
recoveryAzureV1ResourceGroupId?: string;
recoveryAzureV2ResourceGroupId?: string;
useManagedDisks?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBaseEventDetails class.
* @constructor
* Abstract model class for event details of a HyperVReplica E2E event.
*
* @member {string} [containerName] The container friendly name.
* @member {string} [fabricName] The fabric friendly name.
* @member {string} [remoteContainerName] The remote container name.
* @member {string} [remoteFabricName] The remote fabric name.
*/
export interface HyperVReplicaBaseEventDetails extends EventProviderSpecificDetails {
containerName?: string;
fabricName?: string;
remoteContainerName?: string;
remoteFabricName?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBasePolicyDetails class.
* @constructor
* Base class for HyperVReplica policy details.
*
* @member {number} [recoveryPoints] A value indicating the number of recovery
* points.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] A value
* indicating the application consistent frequency.
* @member {string} [compression] A value indicating whether compression has to
* be enabled.
* @member {string} [initialReplicationMethod] A value indicating whether IR is
* online.
* @member {string} [onlineReplicationStartTime] A value indicating the online
* IR start time.
* @member {string} [offlineReplicationImportPath] A value indicating the
* offline IR import path.
* @member {string} [offlineReplicationExportPath] A value indicating the
* offline IR export path.
* @member {number} [replicationPort] A value indicating the recovery HTTPS
* port.
* @member {number} [allowedAuthenticationType] A value indicating the
* authentication type.
* @member {string} [replicaDeletionOption] A value indicating whether the VM
* has to be auto deleted. Supported Values: String.Empty, None,
* OnRecoveryCloud
*/
export interface HyperVReplicaBasePolicyDetails extends PolicyProviderSpecificDetails {
recoveryPoints?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
compression?: string;
initialReplicationMethod?: string;
onlineReplicationStartTime?: string;
offlineReplicationImportPath?: string;
offlineReplicationExportPath?: string;
replicationPort?: number;
allowedAuthenticationType?: number;
replicaDeletionOption?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBaseReplicationDetails class.
* @constructor
* Hyper V replica provider specific settings base class.
*
* @member {date} [lastReplicatedTime] The Last replication time.
* @member {array} [vmNics] The PE Network details.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {object} [initialReplicationDetails] Initial replication details.
* @member {string} [initialReplicationDetails.initialReplicationType] Initial
* replication type.
* @member {string}
* [initialReplicationDetails.initialReplicationProgressPercentage] The initial
* replication progress percentage.
* @member {array} [vMDiskDetails] VM disk details.
*/
export interface HyperVReplicaBaseReplicationDetails extends ReplicationProviderSpecificSettings {
lastReplicatedTime?: Date;
vmNics?: VMNicDetails[];
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
initialReplicationDetails?: InitialReplicationDetails;
vMDiskDetails?: DiskDetails[];
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBluePolicyDetails class.
* @constructor
* Hyper-V Replica Blue specific protection profile details.
*
* @member {number} [replicationFrequencyInSeconds] A value indicating the
* replication interval.
* @member {number} [recoveryPoints] A value indicating the number of recovery
* points.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] A value
* indicating the application consistent frequency.
* @member {string} [compression] A value indicating whether compression has to
* be enabled.
* @member {string} [initialReplicationMethod] A value indicating whether IR is
* online.
* @member {string} [onlineReplicationStartTime] A value indicating the online
* IR start time.
* @member {string} [offlineReplicationImportPath] A value indicating the
* offline IR import path.
* @member {string} [offlineReplicationExportPath] A value indicating the
* offline IR export path.
* @member {number} [replicationPort] A value indicating the recovery HTTPS
* port.
* @member {number} [allowedAuthenticationType] A value indicating the
* authentication type.
* @member {string} [replicaDeletionOption] A value indicating whether the VM
* has to be auto deleted. Supported Values: String.Empty, None,
* OnRecoveryCloud
*/
export interface HyperVReplicaBluePolicyDetails extends PolicyProviderSpecificDetails {
replicationFrequencyInSeconds?: number;
recoveryPoints?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
compression?: string;
initialReplicationMethod?: string;
onlineReplicationStartTime?: string;
offlineReplicationImportPath?: string;
offlineReplicationExportPath?: string;
replicationPort?: number;
allowedAuthenticationType?: number;
replicaDeletionOption?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBluePolicyInput class.
* @constructor
* HyperV Replica Blue policy input.
*
* @member {number} [replicationFrequencyInSeconds] A value indicating the
* replication interval.
* @member {number} [recoveryPoints] A value indicating the number of recovery
* points.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] A value
* indicating the application consistent frequency.
* @member {string} [compression] A value indicating whether compression has to
* be enabled.
* @member {string} [initialReplicationMethod] A value indicating whether IR is
* online.
* @member {string} [onlineReplicationStartTime] A value indicating the online
* IR start time.
* @member {string} [offlineReplicationImportPath] A value indicating the
* offline IR import path.
* @member {string} [offlineReplicationExportPath] A value indicating the
* offline IR export path.
* @member {number} [replicationPort] A value indicating the recovery HTTPS
* port.
* @member {number} [allowedAuthenticationType] A value indicating the
* authentication type.
* @member {string} [replicaDeletion] A value indicating whether the VM has to
* be auto deleted.
*/
export interface HyperVReplicaBluePolicyInput extends PolicyProviderSpecificInput {
replicationFrequencyInSeconds?: number;
recoveryPoints?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
compression?: string;
initialReplicationMethod?: string;
onlineReplicationStartTime?: string;
offlineReplicationImportPath?: string;
offlineReplicationExportPath?: string;
replicationPort?: number;
allowedAuthenticationType?: number;
replicaDeletion?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaBlueReplicationDetails class.
* @constructor
* HyperV replica 2012 R2 (Blue) replication details.
*
* @member {date} [lastReplicatedTime] The Last replication time.
* @member {array} [vmNics] The PE Network details.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {object} [initialReplicationDetails] Initial replication details.
* @member {string} [initialReplicationDetails.initialReplicationType] Initial
* replication type.
* @member {string}
* [initialReplicationDetails.initialReplicationProgressPercentage] The initial
* replication progress percentage.
* @member {array} [vMDiskDetails] VM disk details.
*/
export interface HyperVReplicaBlueReplicationDetails extends ReplicationProviderSpecificSettings {
lastReplicatedTime?: Date;
vmNics?: VMNicDetails[];
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
initialReplicationDetails?: InitialReplicationDetails;
vMDiskDetails?: DiskDetails[];
}
/**
* @class
* Initializes a new instance of the HyperVReplicaPolicyDetails class.
* @constructor
* Hyper-V Replica Blue specific protection profile details.
*
* @member {number} [recoveryPoints] A value indicating the number of recovery
* points.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] A value
* indicating the application consistent frequency.
* @member {string} [compression] A value indicating whether compression has to
* be enabled.
* @member {string} [initialReplicationMethod] A value indicating whether IR is
* online.
* @member {string} [onlineReplicationStartTime] A value indicating the online
* IR start time.
* @member {string} [offlineReplicationImportPath] A value indicating the
* offline IR import path.
* @member {string} [offlineReplicationExportPath] A value indicating the
* offline IR export path.
* @member {number} [replicationPort] A value indicating the recovery HTTPS
* port.
* @member {number} [allowedAuthenticationType] A value indicating the
* authentication type.
* @member {string} [replicaDeletionOption] A value indicating whether the VM
* has to be auto deleted. Supported Values: String.Empty, None,
* OnRecoveryCloud
*/
export interface HyperVReplicaPolicyDetails extends PolicyProviderSpecificDetails {
recoveryPoints?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
compression?: string;
initialReplicationMethod?: string;
onlineReplicationStartTime?: string;
offlineReplicationImportPath?: string;
offlineReplicationExportPath?: string;
replicationPort?: number;
allowedAuthenticationType?: number;
replicaDeletionOption?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaPolicyInput class.
* @constructor
* Hyper-V Replica specific policy Input.
*
* @member {number} [recoveryPoints] A value indicating the number of recovery
* points.
* @member {number} [applicationConsistentSnapshotFrequencyInHours] A value
* indicating the application consistent frequency.
* @member {string} [compression] A value indicating whether compression has to
* be enabled.
* @member {string} [initialReplicationMethod] A value indicating whether IR is
* online.
* @member {string} [onlineReplicationStartTime] A value indicating the online
* IR start time.
* @member {string} [offlineReplicationImportPath] A value indicating the
* offline IR import path.
* @member {string} [offlineReplicationExportPath] A value indicating the
* offline IR export path.
* @member {number} [replicationPort] A value indicating the recovery HTTPS
* port.
* @member {number} [allowedAuthenticationType] A value indicating the
* authentication type.
* @member {string} [replicaDeletion] A value indicating whether the VM has to
* be auto deleted.
*/
export interface HyperVReplicaPolicyInput extends PolicyProviderSpecificInput {
recoveryPoints?: number;
applicationConsistentSnapshotFrequencyInHours?: number;
compression?: string;
initialReplicationMethod?: string;
onlineReplicationStartTime?: string;
offlineReplicationImportPath?: string;
offlineReplicationExportPath?: string;
replicationPort?: number;
allowedAuthenticationType?: number;
replicaDeletion?: string;
}
/**
* @class
* Initializes a new instance of the HyperVReplicaReplicationDetails class.
* @constructor
* HyperV replica 2012 replication details.
*
* @member {date} [lastReplicatedTime] The Last replication time.
* @member {array} [vmNics] The PE Network details.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {object} [initialReplicationDetails] Initial replication details.
* @member {string} [initialReplicationDetails.initialReplicationType] Initial
* replication type.
* @member {string}
* [initialReplicationDetails.initialReplicationProgressPercentage] The initial
* replication progress percentage.
* @member {array} [vMDiskDetails] VM disk details.
*/
export interface HyperVReplicaReplicationDetails extends ReplicationProviderSpecificSettings {
lastReplicatedTime?: Date;
vmNics?: VMNicDetails[];
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
initialReplicationDetails?: InitialReplicationDetails;
vMDiskDetails?: DiskDetails[];
}
/**
* @class
* Initializes a new instance of the HyperVSiteDetails class.
* @constructor
* HyperVSite fabric specific details.
*
*/
export interface HyperVSiteDetails extends FabricSpecificDetails {
}
/**
* @class
* Initializes a new instance of the HyperVVirtualMachineDetails class.
* @constructor
* Single Host fabric provider specific VM settings.
*
* @member {string} [sourceItemId] The source id of the object.
* @member {string} [generation] The id of the object in fabric.
* @member {object} [osDetails] The Last replication time.
* @member {string} [osDetails.osType] VM Disk details.
* @member {string} [osDetails.productType] Product type.
* @member {string} [osDetails.osEdition] The OSEdition.
* @member {string} [osDetails.oSVersion] The OS Version.
* @member {string} [osDetails.oSMajorVersion] The OS Major Version.
* @member {string} [osDetails.oSMinorVersion] The OS Minor Version.
* @member {array} [diskDetails] The Last successful failover time.
* @member {string} [hasPhysicalDisk] A value indicating whether the VM has a
* physical disk attached. String value of {SrsDataContract.PresenceStatus}
* enum. Possible values include: 'Unknown', 'Present', 'NotPresent'
* @member {string} [hasFibreChannelAdapter] A value indicating whether the VM
* has a fibre channel adapter attached. String value of
* {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown',
* 'Present', 'NotPresent'
* @member {string} [hasSharedVhd] A value indicating whether the VM has a
* shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum.
* Possible values include: 'Unknown', 'Present', 'NotPresent'
*/
export interface HyperVVirtualMachineDetails extends ConfigurationSettings {
sourceItemId?: string;
generation?: string;
osDetails?: OSDetails;
diskDetails?: DiskDetails[];
hasPhysicalDisk?: string;
hasFibreChannelAdapter?: string;
hasSharedVhd?: string;
}
/**
* @class
* Initializes a new instance of the IdentityInformation class.
* @constructor
* Identity details.
*
* @member {string} [identityProviderType] The identity provider type. Value is
* the ToString() of a IdentityProviderType value. Possible values include:
* 'RecoveryServicesActiveDirectory'
* @member {string} [tenantId] The tenant Id for the service principal with
* which the on-premise management/data plane components would communicate with
* our Azure services.
* @member {string} [applicationId] The application/client Id for the service
* principal with which the on-premise management/data plane components would
* communicate with our Azure services.
* @member {string} [objectId] The object Id of the service principal with
* which the on-premise management/data plane components would communicate with
* our Azure services.
* @member {string} [audience] The intended Audience of the service principal
* with which the on-premise management/data plane components would communicate
* with our Azure services.
* @member {string} [aadAuthority] The base authority for Azure Active
* Directory authentication.
* @member {string} [certificateThumbprint] The certificate thumbprint.
* Applicable only if IdentityProviderType is RecoveryServicesActiveDirectory.
*/
export interface IdentityInformation {
identityProviderType?: string;
tenantId?: string;
applicationId?: string;
objectId?: string;
audience?: string;
aadAuthority?: string;
certificateThumbprint?: string;
}
/**
* @class
* Initializes a new instance of the InlineWorkflowTaskDetails class.
* @constructor
* This class represents the inline workflow task details.
*
* @member {array} [workflowIds] The list of child workflow ids.
*/
export interface InlineWorkflowTaskDetails extends GroupTaskDetails {
workflowIds?: string[];
}
/**
* @class
* Initializes a new instance of the InMageAgentDetails class.
* @constructor
* The details of the InMage agent.
*
* @member {string} [agentVersion] The agent version.
* @member {string} [agentUpdateStatus] A value indicating whether installed
* agent needs to be updated.
* @member {string} [postUpdateRebootStatus] A value indicating whether reboot
* is required after update is applied.
* @member {date} [agentExpiryDate] Agent expiry date.
*/
export interface InMageAgentDetails {
agentVersion?: string;
agentUpdateStatus?: string;
postUpdateRebootStatus?: string;
agentExpiryDate?: Date;
}
/**
* @class
* Initializes a new instance of the InMageAgentVersionDetails class.
* @constructor
* InMage agent version details.
*
* @member {string} [postUpdateRebootStatus] A value indicating whether reboot
* is required after update is applied.
* @member {string} [version] The agent version.
* @member {date} [expiryDate] Version expiry date.
* @member {string} [status] A value indicating whether security update
* required. Possible values include: 'Supported', 'NotSupported',
* 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface InMageAgentVersionDetails {
postUpdateRebootStatus?: string;
version?: string;
expiryDate?: Date;
status?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2ApplyRecoveryPointInput class.
* @constructor
* ApplyRecoveryPoint input specific to InMageAzureV2 provider.
*
* @member {string} [vaultLocation] The vault location where the recovery Vm
* resides.
*/
export interface InMageAzureV2ApplyRecoveryPointInput extends ApplyRecoveryPointProviderSpecificInput {
vaultLocation?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2EnableProtectionInput class.
* @constructor
* VMware Azure specific enable protection input.
*
* @member {string} [masterTargetId] The Master target Id.
* @member {string} [processServerId] The Process Server Id.
* @member {string} storageAccountId The storage account name.
* @member {string} [runAsAccountId] The CS account Id.
* @member {string} [multiVmGroupId] The multi vm group Id.
* @member {string} [multiVmGroupName] The multi vm group name.
* @member {array} [disksToInclude] The disks to include list.
* @member {string} [targetAzureNetworkId] The selected target Azure network
* Id.
* @member {string} [targetAzureSubnetId] The selected target Azure subnet Id.
* @member {string} [enableRdpOnTargetOption] The selected option to enable
* RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {string} [targetAzureVmName] The target azure Vm Name.
* @member {string} [logStorageAccountId] The storage account to be used for
* logging during replication.
* @member {string} [targetAzureV1ResourceGroupId] The Id of the target
* resource group (for classic deployment) in which the failover VM is to be
* created.
* @member {string} [targetAzureV2ResourceGroupId] The Id of the target
* resource group (for resource manager deployment) in which the failover VM is
* to be created.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
*/
export interface InMageAzureV2EnableProtectionInput extends EnableProtectionProviderSpecificInput {
masterTargetId?: string;
processServerId?: string;
storageAccountId: string;
runAsAccountId?: string;
multiVmGroupId?: string;
multiVmGroupName?: string;
disksToInclude?: string[];
targetAzureNetworkId?: string;
targetAzureSubnetId?: string;
enableRdpOnTargetOption?: string;
targetAzureVmName?: string;
logStorageAccountId?: string;
targetAzureV1ResourceGroupId?: string;
targetAzureV2ResourceGroupId?: string;
useManagedDisks?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2EventDetails class.
* @constructor
* Model class for event details of a VMwareAzureV2 event.
*
* @member {string} [eventType] InMage Event type. Takes one of the values of
* {InMageDataContract.InMageMonitoringEventType}.
* @member {string} [category] InMage Event Category.
* @member {string} [component] InMage Event Component.
* @member {string} [correctiveAction] Corrective Action string for the event.
* @member {string} [details] InMage Event Details.
* @member {string} [summary] InMage Event Summary.
* @member {string} [siteName] VMware Site name.
*/
export interface InMageAzureV2EventDetails extends EventProviderSpecificDetails {
eventType?: string;
category?: string;
component?: string;
correctiveAction?: string;
details?: string;
summary?: string;
siteName?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2FailoverProviderInput class.
* @constructor
* InMageAzureV2 provider specific input for failover.
*
* @member {string} [vaultLocation] Location of the vault.
* @member {string} [recoveryPointId] The recovery point id to be passed to
* failover to a particular recovery point. In case of latest recovery point,
* null should be passed.
*/
export interface InMageAzureV2FailoverProviderInput extends ProviderSpecificFailoverInput {
vaultLocation?: string;
recoveryPointId?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2PolicyDetails class.
* @constructor
* InMage Azure v2 specific protection profile details.
*
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency in minutes.
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {string} [multiVmSyncStatus] A value indicating whether multi-VM
* sync has to be enabled.
*/
export interface InMageAzureV2PolicyDetails extends PolicyProviderSpecificDetails {
crashConsistentFrequencyInMinutes?: number;
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2PolicyInput class.
* @constructor
* VMWare Azure specific policy Input.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency (in minutes).
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency (in minutes).
* @member {string} multiVmSyncStatus A value indicating whether multi-VM sync
* has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values
* include: 'Enable', 'Disable'
*/
export interface InMageAzureV2PolicyInput extends PolicyProviderSpecificInput {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
crashConsistentFrequencyInMinutes?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2ProtectedDiskDetails class.
* @constructor
* InMageAzureV2 protected disk details.
*
* @member {string} [diskId] The disk id.
* @member {string} [diskName] The disk name.
* @member {string} [protectionStage] The protection stage.
* @member {string} [healthErrorCode] The health error code for the disk.
* @member {number} [rpoInSeconds] The RPO in seconds.
* @member {string} [resyncRequired] A value indicating whether resync is
* required for this disk.
* @member {number} [resyncProgressPercentage] The resync progress percentage.
* @member {number} [resyncDurationInSeconds] The resync duration in seconds.
* @member {number} [diskCapacityInBytes] The disk capacity in bytes.
* @member {number} [fileSystemCapacityInBytes] The disk file system capacity
* in bytes.
* @member {number} [sourceDataInMegaBytes] The source data transit in MB.
* @member {number} [psDataInMegaBytes] The PS data transit in MB.
* @member {number} [targetDataInMegaBytes] The target data transit in MB.
* @member {string} [diskResized] A value indicating whether disk is resized.
* @member {date} [lastRpoCalculatedTime] The last RPO calculated time.
*/
export interface InMageAzureV2ProtectedDiskDetails {
diskId?: string;
diskName?: string;
protectionStage?: string;
healthErrorCode?: string;
rpoInSeconds?: number;
resyncRequired?: string;
resyncProgressPercentage?: number;
resyncDurationInSeconds?: number;
diskCapacityInBytes?: number;
fileSystemCapacityInBytes?: number;
sourceDataInMegaBytes?: number;
psDataInMegaBytes?: number;
targetDataInMegaBytes?: number;
diskResized?: string;
lastRpoCalculatedTime?: Date;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2RecoveryPointDetails class.
* @constructor
* InMage Azure V2 provider specific recovery point details.
*
* @member {string} [isMultiVmSyncPoint] A value indicating whether the
* recovery point is multi VM consistent.
*/
export interface InMageAzureV2RecoveryPointDetails extends ProviderSpecificRecoveryPointDetails {
isMultiVmSyncPoint?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2ReplicationDetails class.
* @constructor
* InMageAzureV2 provider specific settings
*
* @member {string} [infrastructureVmId] The infrastructure VM Id.
* @member {string} [vCenterInfrastructureId] The vCenter infrastructure Id.
* @member {string} [protectionStage] The protection stage.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {number} [resyncProgressPercentage] The resync progress percentage.
* @member {number} [rpoInSeconds] The RPO in seconds.
* @member {number} [compressedDataRateInMB] The compressed data change rate in
* MB.
* @member {number} [uncompressedDataRateInMB] The uncompressed data change
* rate in MB.
* @member {string} [ipAddress] The source IP address.
* @member {string} [agentVersion] The agent version.
* @member {date} [agentExpiryDate] Agent expiry date.
* @member {string} [isAgentUpdateRequired] A value indicating whether
* installed agent needs to be updated.
* @member {string} [isRebootAfterUpdateRequired] A value indicating whether
* the source server requires a restart after update.
* @member {date} [lastHeartbeat] The last heartbeat received from the source
* server.
* @member {string} [processServerId] The process server Id.
* @member {string} [multiVmGroupId] The multi vm group Id.
* @member {string} [multiVmGroupName] The multi vm group name.
* @member {string} [multiVmSyncStatus] A value indicating whether multi vm
* sync is enabled or disabled.
* @member {array} [protectedDisks] The list of protected disks.
* @member {string} [diskResized] A value indicating whether any disk is
* resized for this VM.
* @member {string} [masterTargetId] The master target Id.
* @member {number} [sourceVmCpuCount] The CPU count of the VM on the primary
* side.
* @member {number} [sourceVmRamSizeInMB] The RAM size of the VM on the primary
* side.
* @member {string} [osType] The type of the OS on the VM.
* @member {string} [vhdName] The OS disk VHD name.
* @member {string} [osDiskId] The id of the disk containing the OS.
* @member {array} [azureVMDiskDetails] Azure VM Disk details.
* @member {string} [recoveryAzureVMName] Recovery Azure given name.
* @member {string} [recoveryAzureVMSize] The Recovery Azure VM size.
* @member {string} [recoveryAzureStorageAccount] The recovery Azure storage
* account.
* @member {string} [recoveryAzureLogStorageAccountId] The ARM id of the log
* storage account used for replication. This will be set to null if no log
* storage account was provided during enable protection.
* @member {array} [vmNics] The PE Network details.
* @member {string} [selectedRecoveryAzureNetworkId] The selected recovery
* azure network Id.
* @member {string} [selectedSourceNicId] The selected source nic Id which will
* be used as the primary nic during failover.
* @member {string} [discoveryType] A value indicating the discovery type of
* the machine. Value can be vCenter or physical.
* @member {string} [enableRdpOnTargetOption] The selected option to enable
* RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {array} [datastores] The datastores of the on-premise machine. Value
* can be list of strings that contain datastore names.
* @member {string} [targetVmId] The ARM Id of the target Azure VM. This value
* will be null until the VM is failed over. Only after failure it will be
* populated with the ARM Id of the Azure VM.
* @member {string} [recoveryAzureResourceGroupId] The target resource group
* Id.
* @member {string} [recoveryAvailabilitySetId] The recovery availability set
* Id.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
* @member {string} [licenseType] License Type of the VM to be used.
* @member {array} [validationErrors] The validation errors of the on-premise
* machine Value can be list of validation errors.
* @member {date} [lastRpoCalculatedTime] The last RPO calculated time.
* @member {date} [lastUpdateReceivedTime] The last update time received from
* on-prem components.
* @member {string} [replicaId] The replica id of the protected item.
* @member {string} [osVersion] The OS Version of the protected item.
*/
export interface InMageAzureV2ReplicationDetails extends ReplicationProviderSpecificSettings {
infrastructureVmId?: string;
vCenterInfrastructureId?: string;
protectionStage?: string;
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
resyncProgressPercentage?: number;
rpoInSeconds?: number;
compressedDataRateInMB?: number;
uncompressedDataRateInMB?: number;
ipAddress?: string;
agentVersion?: string;
agentExpiryDate?: Date;
isAgentUpdateRequired?: string;
isRebootAfterUpdateRequired?: string;
lastHeartbeat?: Date;
processServerId?: string;
multiVmGroupId?: string;
multiVmGroupName?: string;
multiVmSyncStatus?: string;
protectedDisks?: InMageAzureV2ProtectedDiskDetails[];
diskResized?: string;
masterTargetId?: string;
sourceVmCpuCount?: number;
sourceVmRamSizeInMB?: number;
osType?: string;
vhdName?: string;
osDiskId?: string;
azureVMDiskDetails?: AzureVmDiskDetails[];
recoveryAzureVMName?: string;
recoveryAzureVMSize?: string;
recoveryAzureStorageAccount?: string;
recoveryAzureLogStorageAccountId?: string;
vmNics?: VMNicDetails[];
selectedRecoveryAzureNetworkId?: string;
selectedSourceNicId?: string;
discoveryType?: string;
enableRdpOnTargetOption?: string;
datastores?: string[];
targetVmId?: string;
recoveryAzureResourceGroupId?: string;
recoveryAvailabilitySetId?: string;
useManagedDisks?: string;
licenseType?: string;
validationErrors?: HealthError[];
lastRpoCalculatedTime?: Date;
lastUpdateReceivedTime?: Date;
replicaId?: string;
osVersion?: string;
}
/**
* @class
* Initializes a new instance of the InMageAzureV2ReprotectInput class.
* @constructor
* InMageAzureV2 specific provider input.
*
* @member {string} [masterTargetId] The Master target Id.
* @member {string} [processServerId] The Process Server Id.
* @member {string} [storageAccountId] The storage account id.
* @member {string} [runAsAccountId] The CS account Id.
* @member {string} [policyId] The Policy Id.
* @member {string} [logStorageAccountId] The storage account to be used for
* logging during replication.
* @member {array} [disksToInclude] The disks to include list.
*/
export interface InMageAzureV2ReprotectInput extends ReverseReplicationProviderSpecificInput {
masterTargetId?: string;
processServerId?: string;
storageAccountId?: string;
runAsAccountId?: string;
policyId?: string;
logStorageAccountId?: string;
disksToInclude?: string[];
}
/**
* @class
* Initializes a new instance of the InMageAzureV2UpdateReplicationProtectedItemInput class.
* @constructor
* InMage Azure V2 input to update replication protected item.
*
* @member {string} [recoveryAzureV1ResourceGroupId] The recovery Azure
* resource group Id for classic deployment.
* @member {string} [recoveryAzureV2ResourceGroupId] The recovery Azure
* resource group Id for resource manager deployment.
* @member {string} [useManagedDisks] A value indicating whether managed disks
* should be used during failover.
*/
export interface InMageAzureV2UpdateReplicationProtectedItemInput extends UpdateReplicationProtectedItemProviderInput {
recoveryAzureV1ResourceGroupId?: string;
recoveryAzureV2ResourceGroupId?: string;
useManagedDisks?: string;
}
/**
* @class
* Initializes a new instance of the InMageBasePolicyDetails class.
* @constructor
* Base class for the policies of providers using InMage replication.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {string} [multiVmSyncStatus] A value indicating whether multi-VM
* sync has to be enabled.
*/
export interface InMageBasePolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus?: string;
}
/**
* @class
* Initializes a new instance of the InMageDisableProtectionProviderSpecificInput class.
* @constructor
* InMage disable protection provider specific input.
*
* @member {string} [replicaVmDeletionStatus] A value indicating whether the
* replica VM should be destroyed or retained. Values from Delete and Retain.
*/
export interface InMageDisableProtectionProviderSpecificInput extends DisableProtectionProviderSpecificInput {
replicaVmDeletionStatus?: string;
}
/**
* @class
* Initializes a new instance of the InMageDiskDetails class.
* @constructor
* VMware/Physical specific Disk Details
*
* @member {string} [diskId] The disk Id.
* @member {string} [diskName] The disk name.
* @member {string} [diskSizeInMB] The disk size in MB.
* @member {string} [diskType] Whether disk is system disk or data disk.
* @member {string} [diskConfiguration] Whether disk is dynamic disk or basic
* disk.
* @member {array} [volumeList] Volumes of the disk.
*/
export interface InMageDiskDetails {
diskId?: string;
diskName?: string;
diskSizeInMB?: string;
diskType?: string;
diskConfiguration?: string;
volumeList?: DiskVolumeDetails[];
}
/**
* @class
* Initializes a new instance of the InMageVolumeExclusionOptions class.
* @constructor
* Guest disk signature based disk exclusion option when doing enable
* protection of virtual machine in InMage provider.
*
* @member {string} [volumeLabel] The volume label. The disk having any volume
* with this label will be excluded from replication.
* @member {string} [onlyExcludeIfSingleVolume] The value indicating whether to
* exclude multi volume disk or not. If a disk has multiple volumes and one of
* the volume has label matching with VolumeLabel this disk will be excluded
* from replication if OnlyExcludeIfSingleVolume is false.
*/
export interface InMageVolumeExclusionOptions {
volumeLabel?: string;
onlyExcludeIfSingleVolume?: string;
}
/**
* @class
* Initializes a new instance of the InMageDiskSignatureExclusionOptions class.
* @constructor
* Guest disk signature based disk exclusion option when doing enable
* protection of virtual machine in InMage provider.
*
* @member {string} [diskSignature] The guest signature of disk to be excluded
* from replication.
*/
export interface InMageDiskSignatureExclusionOptions {
diskSignature?: string;
}
/**
* @class
* Initializes a new instance of the InMageDiskExclusionInput class.
* @constructor
* DiskExclusionInput when doing enable protection of virtual machine in InMage
* provider.
*
* @member {array} [volumeOptions] The volume label based option for disk
* exclusion.
* @member {array} [diskSignatureOptions] The guest disk signature based option
* for disk exclusion.
*/
export interface InMageDiskExclusionInput {
volumeOptions?: InMageVolumeExclusionOptions[];
diskSignatureOptions?: InMageDiskSignatureExclusionOptions[];
}
/**
* @class
* Initializes a new instance of the InMageEnableProtectionInput class.
* @constructor
* VMware Azure specific enable protection input.
*
* @member {string} [vmFriendlyName] The Vm Name.
* @member {string} masterTargetId The Master Target Id.
* @member {string} processServerId The Process Server Id.
* @member {string} retentionDrive The retention drive to use on the MT.
* @member {string} [runAsAccountId] The CS account Id.
* @member {string} multiVmGroupId The multi vm group Id.
* @member {string} multiVmGroupName The multi vm group name.
* @member {string} [datastoreName] The target datastore name.
* @member {object} [diskExclusionInput] The enable disk exclusion input.
* @member {array} [diskExclusionInput.volumeOptions] The volume label based
* option for disk exclusion.
* @member {array} [diskExclusionInput.diskSignatureOptions] The guest disk
* signature based option for disk exclusion.
* @member {array} [disksToInclude] The disks to include list.
*/
export interface InMageEnableProtectionInput extends EnableProtectionProviderSpecificInput {
vmFriendlyName?: string;
masterTargetId: string;
processServerId: string;
retentionDrive: string;
runAsAccountId?: string;
multiVmGroupId: string;
multiVmGroupName: string;
datastoreName?: string;
diskExclusionInput?: InMageDiskExclusionInput;
disksToInclude?: string[];
}
/**
* @class
* Initializes a new instance of the InMageFailoverProviderInput class.
* @constructor
* Provider specific input for InMage failover.
*
* @member {string} [recoveryPointType] The recovery point type. Values from
* LatestTime, LatestTag or Custom. In the case of custom, the recovery point
* provided by RecoveryPointId will be used. In the other two cases, recovery
* point id will be ignored. Possible values include: 'LatestTime',
* 'LatestTag', 'Custom'
* @member {string} [recoveryPointId] The recovery point id to be passed to
* failover to a particular recovery point. In case of latest recovery point,
* null should be passed.
*/
export interface InMageFailoverProviderInput extends ProviderSpecificFailoverInput {
recoveryPointType?: string;
recoveryPointId?: string;
}
/**
* @class
* Initializes a new instance of the InMagePolicyDetails class.
* @constructor
* InMage specific protection profile details.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {string} [multiVmSyncStatus] A value indicating whether multi-VM
* sync has to be enabled.
*/
export interface InMagePolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus?: string;
}
/**
* @class
* Initializes a new instance of the InMagePolicyInput class.
* @constructor
* VMWare Azure specific protection profile Input.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency (in minutes).
* @member {string} multiVmSyncStatus A value indicating whether multi-VM sync
* has to be enabled. Value should be 'Enabled' or 'Disabled'. Possible values
* include: 'Enable', 'Disable'
*/
export interface InMagePolicyInput extends PolicyProviderSpecificInput {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus: string;
}
/**
* @class
* Initializes a new instance of the InMageProtectedDiskDetails class.
* @constructor
* InMage protected disk details.
*
* @member {string} [diskId] The disk id.
* @member {string} [diskName] The disk name.
* @member {string} [protectionStage] The protection stage.
* @member {string} [healthErrorCode] The health error code for the disk.
* @member {number} [rpoInSeconds] The RPO in seconds.
* @member {string} [resyncRequired] A value indicating whether resync is
* required for this disk.
* @member {number} [resyncProgressPercentage] The resync progress percentage.
* @member {number} [resyncDurationInSeconds] The resync duration in seconds.
* @member {number} [diskCapacityInBytes] The disk capacity in bytes.
* @member {number} [fileSystemCapacityInBytes] The file system capacity in
* bytes.
* @member {number} [sourceDataInMB] The source data transit in MB.
* @member {number} [psDataInMB] The PS data transit in MB.
* @member {number} [targetDataInMB] The target data transit in MB.
* @member {string} [diskResized] A value indicating whether disk is resized.
* @member {date} [lastRpoCalculatedTime] The last RPO calculated time.
*/
export interface InMageProtectedDiskDetails {
diskId?: string;
diskName?: string;
protectionStage?: string;
healthErrorCode?: string;
rpoInSeconds?: number;
resyncRequired?: string;
resyncProgressPercentage?: number;
resyncDurationInSeconds?: number;
diskCapacityInBytes?: number;
fileSystemCapacityInBytes?: number;
sourceDataInMB?: number;
psDataInMB?: number;
targetDataInMB?: number;
diskResized?: string;
lastRpoCalculatedTime?: Date;
}
/**
* @class
* Initializes a new instance of the OSDiskDetails class.
* @constructor
* Details of the OS Disk.
*
* @member {string} [osVhdId] The id of the disk containing the OS.
* @member {string} [osType] The type of the OS on the VM.
* @member {string} [vhdName] The OS disk VHD name.
*/
export interface OSDiskDetails {
osVhdId?: string;
osType?: string;
vhdName?: string;
}
/**
* @class
* Initializes a new instance of the InMageReplicationDetails class.
* @constructor
* InMage provider specific settings
*
* @member {string} [activeSiteType] The active location of the VM. If the VM
* is being protected from Azure, this field will take values from { Azure,
* OnPrem }. If the VM is being protected between two data-centers, this field
* will be OnPrem always.
* @member {number} [sourceVmCpuCount] The CPU count of the VM on the primary
* side.
* @member {number} [sourceVmRamSizeInMB] The RAM size of the VM on the primary
* side.
* @member {object} [osDetails] The OS details.
* @member {string} [osDetails.osVhdId] The id of the disk containing the OS.
* @member {string} [osDetails.osType] The type of the OS on the VM.
* @member {string} [osDetails.vhdName] The OS disk VHD name.
* @member {string} [protectionStage] The protection stage.
* @member {string} [vmId] The virtual machine Id.
* @member {string} [vmProtectionState] The protection state for the vm.
* @member {string} [vmProtectionStateDescription] The protection state
* description for the vm.
* @member {object} [resyncDetails] The resync details of the machine
* @member {string} [resyncDetails.initialReplicationType] Initial replication
* type.
* @member {string} [resyncDetails.initialReplicationProgressPercentage] The
* initial replication progress percentage.
* @member {date} [retentionWindowStart] The retention window start time.
* @member {date} [retentionWindowEnd] The retention window end time.
* @member {number} [compressedDataRateInMB] The compressed data change rate in
* MB.
* @member {number} [uncompressedDataRateInMB] The uncompressed data change
* rate in MB.
* @member {number} [rpoInSeconds] The RPO in seconds.
* @member {array} [protectedDisks] The list of protected disks.
* @member {string} [ipAddress] The source IP address.
* @member {date} [lastHeartbeat] The last heartbeat received from the source
* server.
* @member {string} [processServerId] The process server Id.
* @member {string} [masterTargetId] The master target Id.
* @member {object} [consistencyPoints] The collection of Consistency points.
* @member {string} [diskResized] A value indicating whether any disk is
* resized for this VM.
* @member {string} [rebootAfterUpdateStatus] A value indicating whether the
* source server requires a restart after update.
* @member {string} [multiVmGroupId] The multi vm group Id, if any.
* @member {string} [multiVmGroupName] The multi vm group name, if any.
* @member {string} [multiVmSyncStatus] A value indicating whether the multi vm
* sync is enabled or disabled.
* @member {object} [agentDetails] The agent details.
* @member {string} [agentDetails.agentVersion] The agent version.
* @member {string} [agentDetails.agentUpdateStatus] A value indicating whether
* installed agent needs to be updated.
* @member {string} [agentDetails.postUpdateRebootStatus] A value indicating
* whether reboot is required after update is applied.
* @member {date} [agentDetails.agentExpiryDate] Agent expiry date.
* @member {string} [vCenterInfrastructureId] The vCenter infrastructure Id.
* @member {string} [infrastructureVmId] The infrastructure VM Id.
* @member {array} [vmNics] The PE Network details.
* @member {string} [discoveryType] A value indicating the discovery type of
* the machine.
* @member {string} [azureStorageAccountId] A value indicating the underlying
* Azure storage account. If the VM is not running in Azure, this value shall
* be set to null.
* @member {array} [datastores] The datastores of the on-premise machine Value
* can be list of strings that contain datastore names
* @member {array} [validationErrors] The validation errors of the on-premise
* machine Value can be list of validation errors
* @member {date} [lastRpoCalculatedTime] The last RPO calculated time.
* @member {date} [lastUpdateReceivedTime] The last update time received from
* on-prem components.
* @member {string} [replicaId] The replica id of the protected item.
* @member {string} [osVersion] The OS Version of the protected item.
*/
export interface InMageReplicationDetails extends ReplicationProviderSpecificSettings {
activeSiteType?: string;
sourceVmCpuCount?: number;
sourceVmRamSizeInMB?: number;
osDetails?: OSDiskDetails;
protectionStage?: string;
vmId?: string;
vmProtectionState?: string;
vmProtectionStateDescription?: string;
resyncDetails?: InitialReplicationDetails;
retentionWindowStart?: Date;
retentionWindowEnd?: Date;
compressedDataRateInMB?: number;
uncompressedDataRateInMB?: number;
rpoInSeconds?: number;
protectedDisks?: InMageProtectedDiskDetails[];
ipAddress?: string;
lastHeartbeat?: Date;
processServerId?: string;
masterTargetId?: string;
consistencyPoints?: { [propertyName: string]: Date };
diskResized?: string;
rebootAfterUpdateStatus?: string;
multiVmGroupId?: string;
multiVmGroupName?: string;
multiVmSyncStatus?: string;
agentDetails?: InMageAgentDetails;
vCenterInfrastructureId?: string;
infrastructureVmId?: string;
vmNics?: VMNicDetails[];
discoveryType?: string;
azureStorageAccountId?: string;
datastores?: string[];
validationErrors?: HealthError[];
lastRpoCalculatedTime?: Date;
lastUpdateReceivedTime?: Date;
replicaId?: string;
osVersion?: string;
}
/**
* @class
* Initializes a new instance of the InMageReprotectInput class.
* @constructor
* InMageAzureV2 specific provider input.
*
* @member {string} masterTargetId The Master Target Id.
* @member {string} processServerId The Process Server Id.
* @member {string} retentionDrive The retention drive to use on the MT.
* @member {string} [runAsAccountId] The CS account Id.
* @member {string} [datastoreName] The target datastore name.
* @member {object} [diskExclusionInput] The enable disk exclusion input.
* @member {array} [diskExclusionInput.volumeOptions] The volume label based
* option for disk exclusion.
* @member {array} [diskExclusionInput.diskSignatureOptions] The guest disk
* signature based option for disk exclusion.
* @member {string} profileId The Policy Id.
* @member {array} [disksToInclude] The disks to include list.
*/
export interface InMageReprotectInput extends ReverseReplicationProviderSpecificInput {
masterTargetId: string;
processServerId: string;
retentionDrive: string;
runAsAccountId?: string;
datastoreName?: string;
diskExclusionInput?: InMageDiskExclusionInput;
profileId: string;
disksToInclude?: string[];
}
/**
* @class
* Initializes a new instance of the JobProperties class.
* @constructor
* Job custom data details.
*
* @member {string} [activityId] The activity id.
* @member {string} [scenarioName] The ScenarioName.
* @member {string} [friendlyName] The DisplayName.
* @member {string} [state] The status of the Job. It is one of these values -
* NotStarted, InProgress, Succeeded, Failed, Cancelled, Suspended or Other.
* @member {string} [stateDescription] The description of the state of the Job.
* For e.g. - For Succeeded state, description can be Completed,
* PartiallySucceeded, CompletedWithInformation or Skipped.
* @member {array} [tasks] The tasks.
* @member {array} [errors] The errors.
* @member {date} [startTime] The start time.
* @member {date} [endTime] The end time.
* @member {array} [allowedActions] The Allowed action the job.
* @member {string} [targetObjectId] The affected Object Id.
* @member {string} [targetObjectName] The name of the affected object.
* @member {string} [targetInstanceType] The type of the affected object which
* is of {Microsoft.Azure.SiteRecovery.V2015_11_10.AffectedObjectType} class.
* @member {object} [customDetails] The custom job details like test failover
* job details.
* @member {object} [customDetails.affectedObjectDetails] The affected object
* properties like source server, source cloud, target server, target cloud
* etc. based on the workflow object details.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
*/
export interface JobProperties {
activityId?: string;
scenarioName?: string;
friendlyName?: string;
state?: string;
stateDescription?: string;
tasks?: ASRTask[];
errors?: JobErrorDetails[];
startTime?: Date;
endTime?: Date;
allowedActions?: string[];
targetObjectId?: string;
targetObjectName?: string;
targetInstanceType?: string;
customDetails?: JobDetails;
}
/**
* @class
* Initializes a new instance of the Job class.
* @constructor
* Job details.
*
* @member {object} [properties] The custom data.
* @member {string} [properties.activityId] The activity id.
* @member {string} [properties.scenarioName] The ScenarioName.
* @member {string} [properties.friendlyName] The DisplayName.
* @member {string} [properties.state] The status of the Job. It is one of
* these values - NotStarted, InProgress, Succeeded, Failed, Cancelled,
* Suspended or Other.
* @member {string} [properties.stateDescription] The description of the state
* of the Job. For e.g. - For Succeeded state, description can be Completed,
* PartiallySucceeded, CompletedWithInformation or Skipped.
* @member {array} [properties.tasks] The tasks.
* @member {array} [properties.errors] The errors.
* @member {date} [properties.startTime] The start time.
* @member {date} [properties.endTime] The end time.
* @member {array} [properties.allowedActions] The Allowed action the job.
* @member {string} [properties.targetObjectId] The affected Object Id.
* @member {string} [properties.targetObjectName] The name of the affected
* object.
* @member {string} [properties.targetInstanceType] The type of the affected
* object which is of
* {Microsoft.Azure.SiteRecovery.V2015_11_10.AffectedObjectType} class.
* @member {object} [properties.customDetails] The custom job details like test
* failover job details.
* @member {object} [properties.customDetails.affectedObjectDetails] The
* affected object properties like source server, source cloud, target server,
* target cloud etc. based on the workflow object details.
* @member {string} [properties.customDetails.instanceType] Polymorphic
* Discriminator
*/
export interface Job extends Resource {
properties?: JobProperties;
}
/**
* @class
* Initializes a new instance of the JobQueryParameter class.
* @constructor
* Query parameter to enumerate jobs.
*
* @member {string} [startTime] Date time to get jobs from.
* @member {string} [endTime] Date time to get jobs upto.
* @member {string} [fabricId] The Id of the fabric to search jobs under.
* @member {string} [affectedObjectTypes] The type of objects.
* @member {string} [jobStatus] The states of the job to be filtered can be in.
*/
export interface JobQueryParameter {
startTime?: string;
endTime?: string;
fabricId?: string;
affectedObjectTypes?: string;
jobStatus?: string;
}
/**
* @class
* Initializes a new instance of the JobStatusEventDetails class.
* @constructor
* Model class for event details of a job status event.
*
* @member {string} [jobId] Job arm id for the event.
* @member {string} [jobFriendlyName] JobName for the Event.
* @member {string} [jobStatus] JobStatus for the Event.
* @member {string} [affectedObjectType] AffectedObjectType for the event.
*/
export interface JobStatusEventDetails extends EventSpecificDetails {
jobId?: string;
jobFriendlyName?: string;
jobStatus?: string;
affectedObjectType?: string;
}
/**
* @class
* Initializes a new instance of the JobTaskDetails class.
* @constructor
* This class represents a task which is actually a workflow so that one can
* navigate to its individual drill down.
*
* @member {object} [jobTask] The job entity.
* @member {string} [jobTask.jobId] The job id.
* @member {string} [jobTask.jobFriendlyName] The job display name.
* @member {string} [jobTask.targetObjectId] The object id.
* @member {string} [jobTask.targetObjectName] The object name.
* @member {string} [jobTask.targetInstanceType] The workflow affected object
* type.
* @member {string} [jobTask.jobScenarioName] The job name. Enum type
* ScenarioName.
*/
export interface JobTaskDetails extends TaskTypeDetails {
jobTask?: JobEntity;
}
/**
* @class
* Initializes a new instance of the LogicalNetworkProperties class.
* @constructor
* Logical Network Properties.
*
* @member {string} [friendlyName] The Friendly Name.
* @member {string} [networkVirtualizationStatus] A value indicating whether
* Network Virtualization is enabled for the logical network.
* @member {string} [logicalNetworkUsage] A value indicating whether logical
* network is used as private test network by test failover.
* @member {string} [logicalNetworkDefinitionsStatus] A value indicating
* whether logical network definitions are isolated.
*/
export interface LogicalNetworkProperties {
friendlyName?: string;
networkVirtualizationStatus?: string;
logicalNetworkUsage?: string;
logicalNetworkDefinitionsStatus?: string;
}
/**
* @class
* Initializes a new instance of the LogicalNetwork class.
* @constructor
* Logical network data model.
*
* @member {object} [properties] The Logical Network Properties.
* @member {string} [properties.friendlyName] The Friendly Name.
* @member {string} [properties.networkVirtualizationStatus] A value indicating
* whether Network Virtualization is enabled for the logical network.
* @member {string} [properties.logicalNetworkUsage] A value indicating whether
* logical network is used as private test network by test failover.
* @member {string} [properties.logicalNetworkDefinitionsStatus] A value
* indicating whether logical network definitions are isolated.
*/
export interface LogicalNetwork extends Resource {
properties?: LogicalNetworkProperties;
}
/**
* @class
* Initializes a new instance of the ManualActionTaskDetails class.
* @constructor
* This class represents the manual action task details.
*
* @member {string} [name] The name.
* @member {string} [instructions] The instructions.
* @member {string} [observation] The observation.
*/
export interface ManualActionTaskDetails extends TaskTypeDetails {
name?: string;
instructions?: string;
observation?: string;
}
/**
* @class
* Initializes a new instance of the RetentionVolume class.
* @constructor
* The retention details of the MT.
*
* @member {string} [volumeName] The volume name.
* @member {number} [capacityInBytes] The volume capacity.
* @member {number} [freeSpaceInBytes] The free space available in this volume.
* @member {number} [thresholdPercentage] The threshold percentage.
*/
export interface RetentionVolume {
volumeName?: string;
capacityInBytes?: number;
freeSpaceInBytes?: number;
thresholdPercentage?: number;
}
/**
* @class
* Initializes a new instance of the VersionDetails class.
* @constructor
* Version related details.
*
* @member {string} [version] The agent version.
* @member {date} [expiryDate] Version expiry date.
* @member {string} [status] A value indicating whether security update
* required. Possible values include: 'Supported', 'NotSupported',
* 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface VersionDetails {
version?: string;
expiryDate?: Date;
status?: string;
}
/**
* @class
* Initializes a new instance of the MasterTargetServer class.
* @constructor
* Details of a Master Target Server.
*
* @member {string} [id] The server Id.
* @member {string} [ipAddress] The IP address of the server.
* @member {string} [name] The server name.
* @member {string} [osType] The OS type of the server.
* @member {string} [agentVersion] The version of the scout component on the
* server.
* @member {date} [lastHeartbeat] The last heartbeat received from the server.
* @member {string} [versionStatus] Version status
* @member {array} [retentionVolumes] The retention volumes of Master target
* Server.
* @member {array} [dataStores] The list of data stores in the fabric.
* @member {array} [validationErrors] Validation errors.
* @member {array} [healthErrors] Health errors.
* @member {number} [diskCount] Disk count of the master target.
* @member {string} [osVersion] OS Version of the master target.
* @member {date} [agentExpiryDate] Agent expiry date.
* @member {string} [marsAgentVersion] MARS agent version.
* @member {date} [marsAgentExpiryDate] MARS agent expiry date.
* @member {object} [agentVersionDetails] Agent version details.
* @member {string} [agentVersionDetails.version] The agent version.
* @member {date} [agentVersionDetails.expiryDate] Version expiry date.
* @member {string} [agentVersionDetails.status] A value indicating whether
* security update required. Possible values include: 'Supported',
* 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
* @member {object} [marsAgentVersionDetails] Mars agent version details.
* @member {string} [marsAgentVersionDetails.version] The agent version.
* @member {date} [marsAgentVersionDetails.expiryDate] Version expiry date.
* @member {string} [marsAgentVersionDetails.status] A value indicating whether
* security update required. Possible values include: 'Supported',
* 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface MasterTargetServer {
id?: string;
ipAddress?: string;
name?: string;
osType?: string;
agentVersion?: string;
lastHeartbeat?: Date;
versionStatus?: string;
retentionVolumes?: RetentionVolume[];
dataStores?: DataStore[];
validationErrors?: HealthError[];
healthErrors?: HealthError[];
diskCount?: number;
osVersion?: string;
agentExpiryDate?: Date;
marsAgentVersion?: string;
marsAgentExpiryDate?: Date;
agentVersionDetails?: VersionDetails;
marsAgentVersionDetails?: VersionDetails;
}
/**
* @class
* Initializes a new instance of the MobilityServiceUpdate class.
* @constructor
* The Mobility Service update details.
*
* @member {string} [version] The version of the latest update.
* @member {string} [rebootStatus] The reboot status of the update - whether it
* is required or not.
* @member {string} [osType] The OS type.
*/
export interface MobilityServiceUpdate {
version?: string;
rebootStatus?: string;
osType?: string;
}
/**
* @class
* Initializes a new instance of the Subnet class.
* @constructor
* Subnets of the network.
*
* @member {string} [name] The subnet name.
* @member {string} [friendlyName] The subnet friendly name.
* @member {array} [addressList] The list of addresses for the subnet.
*/
export interface Subnet {
name?: string;
friendlyName?: string;
addressList?: string[];
}
/**
* @class
* Initializes a new instance of the NetworkProperties class.
* @constructor
* Network Properties
*
* @member {string} [fabricType] The Fabric Type.
* @member {array} [subnets] The List of subnets.
* @member {string} [friendlyName] The Friendly Name.
* @member {string} [networkType] The Network Type.
*/
export interface NetworkProperties {
fabricType?: string;
subnets?: Subnet[];
friendlyName?: string;
networkType?: string;
}
/**
* @class
* Initializes a new instance of the Network class.
* @constructor
* Network model.
*
* @member {object} [properties] The Network Properties.
* @member {string} [properties.fabricType] The Fabric Type.
* @member {array} [properties.subnets] The List of subnets.
* @member {string} [properties.friendlyName] The Friendly Name.
* @member {string} [properties.networkType] The Network Type.
*/
export interface Network extends Resource {
properties?: NetworkProperties;
}
/**
* @class
* Initializes a new instance of the NetworkMappingProperties class.
* @constructor
* Network Mapping Properties.
*
* @member {string} [state] The pairing state for network mapping.
* @member {string} [primaryNetworkFriendlyName] The primary network friendly
* name.
* @member {string} [primaryNetworkId] The primary network id for network
* mapping.
* @member {string} [primaryFabricFriendlyName] The primary fabric friendly
* name.
* @member {string} [recoveryNetworkFriendlyName] The recovery network friendly
* name.
* @member {string} [recoveryNetworkId] The recovery network id for network
* mapping.
* @member {string} [recoveryFabricArmId] The recovery fabric ARM id.
* @member {string} [recoveryFabricFriendlyName] The recovery fabric friendly
* name.
* @member {object} [fabricSpecificSettings] The fabric specific settings.
* @member {string} [fabricSpecificSettings.instanceType] Polymorphic
* Discriminator
*/
export interface NetworkMappingProperties {
state?: string;
primaryNetworkFriendlyName?: string;
primaryNetworkId?: string;
primaryFabricFriendlyName?: string;
recoveryNetworkFriendlyName?: string;
recoveryNetworkId?: string;
recoveryFabricArmId?: string;
recoveryFabricFriendlyName?: string;
fabricSpecificSettings?: NetworkMappingFabricSpecificSettings;
}
/**
* @class
* Initializes a new instance of the NetworkMapping class.
* @constructor
* Network Mapping model. Ideally it should have been possible to inherit this
* class from prev version in InheritedModels as long as there is no difference
* in structure or method signature. Since there were no base Models for
* certain fields and methods viz NetworkMappingProperties and Load with
* required return type, the class has been introduced in its entirety with
* references to base models to facilitate exensions in subsequent versions.
*
* @member {object} [properties] The Network Mapping Properties.
* @member {string} [properties.state] The pairing state for network mapping.
* @member {string} [properties.primaryNetworkFriendlyName] The primary network
* friendly name.
* @member {string} [properties.primaryNetworkId] The primary network id for
* network mapping.
* @member {string} [properties.primaryFabricFriendlyName] The primary fabric
* friendly name.
* @member {string} [properties.recoveryNetworkFriendlyName] The recovery
* network friendly name.
* @member {string} [properties.recoveryNetworkId] The recovery network id for
* network mapping.
* @member {string} [properties.recoveryFabricArmId] The recovery fabric ARM
* id.
* @member {string} [properties.recoveryFabricFriendlyName] The recovery fabric
* friendly name.
* @member {object} [properties.fabricSpecificSettings] The fabric specific
* settings.
* @member {string} [properties.fabricSpecificSettings.instanceType]
* Polymorphic Discriminator
*/
export interface NetworkMapping extends Resource {
properties?: NetworkMappingProperties;
}
/**
* @class
* Initializes a new instance of the OperationsDiscovery class.
* @constructor
* Operations discovery class.
*
* @member {string} [name] Name of the API. The name of the operation being
* performed on this particular object. It should match the action name that
* appears in RBAC / the event service. Examples of operations include: *
* Microsoft.Compute/virtualMachine/capture/action *
* Microsoft.Compute/virtualMachine/restart/action *
* Microsoft.Compute/virtualMachine/write *
* Microsoft.Compute/virtualMachine/read *
* Microsoft.Compute/virtualMachine/delete Each action should include, in
* order: (1) Resource Provider Namespace (2) Type hierarchy for which the
* action applies (e.g. server/databases for a SQL Azure database) (3) Read,
* Write, Action or Delete indicating which type applies. If it is a PUT/PATCH
* on a collection or named value, Write should be used. If it is a GET, Read
* should be used. If it is a DELETE, Delete should be used. If it is a POST,
* Action should be used. As a note: all resource providers would need to
* include the "{Resource Provider Namespace}/register/action" operation in
* their response. This API is used to register for their service, and should
* include details about the operation (e.g. a localized name for the resource
* provider + any special considerations like PII release)
* @member {object} [display] Object type
* @member {string} [display.provider] The provider. The localized friendly
* form of the resource provider name – it is expected to also include the
* publisher/company responsible. It should use Title Casing and begin with
* "Microsoft" for 1st party services. e.g. "Microsoft Monitoring Insights" or
* "Microsoft Compute."
* @member {string} [display.resource] The resource. The localized friendly
* form of the resource related to this action/operation – it should match the
* public documentation for the resource provider. It should use Title Casing.
* This value should be unique for a particular URL type (e.g. nested types
* should *not* reuse their parent’s display.resource field). e.g. "Virtual
* Machines" or "Scheduler Job Collections", or "Virtual Machine VM Sizes" or
* "Scheduler Jobs"
* @member {string} [display.operation] The operation. The localized friendly
* name for the operation, as it should be shown to the user. It should be
* concise (to fit in drop downs) but clear (i.e. self-documenting). It should
* use Title Casing. Prescriptive guidance: Read Create or Update Delete
* 'ActionName'
* @member {string} [display.description] The description. The localized
* friendly description for the operation, as it should be shown to the user.
* It should be thorough, yet concise – it will be used in tool tips and
* detailed views. Prescriptive guidance for namespaces: Read any
* 'display.provider' resource Create or Update any 'display.provider' resource
* Delete any 'display.provider' resource Perform any other action on any
* 'display.provider' resource Prescriptive guidance for namespaces: Read any
* 'display.resource' Create or Update any 'display.resource' Delete any
* 'display.resource' 'ActionName' any 'display.resources'
* @member {string} [origin] Origin. The intended executor of the operation;
* governs the display of the operation in the RBAC UX and the audit logs UX.
* Default value is "user,system"
* @member {object} [properties] Properties. Reserved for future use.
*/
export interface OperationsDiscovery {
name?: string;
display?: Display;
origin?: string;
properties?: any;
}
/**
* @class
* Initializes a new instance of the PlannedFailoverInputProperties class.
* @constructor
* Input definition for planned failover input properties.
*
* @member {string} [failoverDirection] Failover direction.
* @member {object} [providerSpecificDetails] Provider specific settings
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface PlannedFailoverInputProperties {
failoverDirection?: string;
providerSpecificDetails?: ProviderSpecificFailoverInput;
}
/**
* @class
* Initializes a new instance of the PlannedFailoverInput class.
* @constructor
* Input definition for planned failover.
*
* @member {object} [properties] Planned failover input properties
* @member {string} [properties.failoverDirection] Failover direction.
* @member {object} [properties.providerSpecificDetails] Provider specific
* settings
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface PlannedFailoverInput {
properties?: PlannedFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the PolicyProperties class.
* @constructor
* Protection profile custom data details.
*
* @member {string} [friendlyName] The FriendlyName.
* @member {object} [providerSpecificDetails] The ReplicationChannelSetting.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface PolicyProperties {
friendlyName?: string;
providerSpecificDetails?: PolicyProviderSpecificDetails;
}
/**
* @class
* Initializes a new instance of the Policy class.
* @constructor
* Protection profile details.
*
* @member {object} [properties] The custom data.
* @member {string} [properties.friendlyName] The FriendlyName.
* @member {object} [properties.providerSpecificDetails] The
* ReplicationChannelSetting.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface Policy extends Resource {
properties?: PolicyProperties;
}
/**
* @class
* Initializes a new instance of the ProcessServer class.
* @constructor
* Details of the Process Server.
*
* @member {string} [friendlyName] The Process Server's friendly name.
* @member {string} [id] The Process Server Id.
* @member {string} [ipAddress] The IP address of the server.
* @member {string} [osType] The OS type of the server.
* @member {string} [agentVersion] The version of the scout component on the
* server.
* @member {date} [lastHeartbeat] The last heartbeat received from the server.
* @member {string} [versionStatus] Version status
* @member {array} [mobilityServiceUpdates] The list of the mobility service
* updates available on the Process Server.
* @member {string} [hostId] The agent generated Id.
* @member {string} [machineCount] The servers configured with this PS.
* @member {string} [replicationPairCount] The number of replication pairs
* configured in this PS.
* @member {string} [systemLoad] The percentage of the system load.
* @member {string} [systemLoadStatus] The system load status.
* @member {string} [cpuLoad] The percentage of the CPU load.
* @member {string} [cpuLoadStatus] The CPU load status.
* @member {number} [totalMemoryInBytes] The total memory.
* @member {number} [availableMemoryInBytes] The available memory.
* @member {string} [memoryUsageStatus] The memory usage status.
* @member {number} [totalSpaceInBytes] The total space.
* @member {number} [availableSpaceInBytes] The available space.
* @member {string} [spaceUsageStatus] The space usage status.
* @member {string} [psServiceStatus] The PS service status.
* @member {date} [sslCertExpiryDate] The PS SSL cert expiry date.
* @member {number} [sslCertExpiryRemainingDays] CS SSL cert expiry date.
* @member {string} [osVersion] OS Version of the process server. Note: This
* will get populated if user has CS version greater than 9.12.0.0.
* @member {array} [healthErrors] Health errors.
* @member {date} [agentExpiryDate] Agent expiry date.
* @member {object} [agentVersionDetails] The agent version details.
* @member {string} [agentVersionDetails.version] The agent version.
* @member {date} [agentVersionDetails.expiryDate] Version expiry date.
* @member {string} [agentVersionDetails.status] A value indicating whether
* security update required. Possible values include: 'Supported',
* 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface ProcessServer {
friendlyName?: string;
id?: string;
ipAddress?: string;
osType?: string;
agentVersion?: string;
lastHeartbeat?: Date;
versionStatus?: string;
mobilityServiceUpdates?: MobilityServiceUpdate[];
hostId?: string;
machineCount?: string;
replicationPairCount?: string;
systemLoad?: string;
systemLoadStatus?: string;
cpuLoad?: string;
cpuLoadStatus?: string;
totalMemoryInBytes?: number;
availableMemoryInBytes?: number;
memoryUsageStatus?: string;
totalSpaceInBytes?: number;
availableSpaceInBytes?: number;
spaceUsageStatus?: string;
psServiceStatus?: string;
sslCertExpiryDate?: Date;
sslCertExpiryRemainingDays?: number;
osVersion?: string;
healthErrors?: HealthError[];
agentExpiryDate?: Date;
agentVersionDetails?: VersionDetails;
}
/**
* @class
* Initializes a new instance of the ProtectableItemProperties class.
* @constructor
* Replication protected item custom data details.
*
* @member {string} [friendlyName] The name.
* @member {string} [protectionStatus] The protection status.
* @member {string} [replicationProtectedItemId] The ARM resource of protected
* items.
* @member {string} [recoveryServicesProviderId] The recovery provider ARM Id.
* @member {array} [protectionReadinessErrors] The Current protection readiness
* errors.
* @member {array} [supportedReplicationProviders] The list of replication
* providers supported for the protectable item.
* @member {object} [customDetails] The Replication provider custom settings.
* @member {string} [customDetails.instanceType] Polymorphic Discriminator
*/
export interface ProtectableItemProperties {
friendlyName?: string;
protectionStatus?: string;
replicationProtectedItemId?: string;
recoveryServicesProviderId?: string;
protectionReadinessErrors?: string[];
supportedReplicationProviders?: string[];
customDetails?: ConfigurationSettings;
}
/**
* @class
* Initializes a new instance of the ProtectableItem class.
* @constructor
* Replication protected item
*
* @member {object} [properties] The custom data.
* @member {string} [properties.friendlyName] The name.
* @member {string} [properties.protectionStatus] The protection status.
* @member {string} [properties.replicationProtectedItemId] The ARM resource of
* protected items.
* @member {string} [properties.recoveryServicesProviderId] The recovery
* provider ARM Id.
* @member {array} [properties.protectionReadinessErrors] The Current
* protection readiness errors.
* @member {array} [properties.supportedReplicationProviders] The list of
* replication providers supported for the protectable item.
* @member {object} [properties.customDetails] The Replication provider custom
* settings.
* @member {string} [properties.customDetails.instanceType] Polymorphic
* Discriminator
*/
export interface ProtectableItem extends Resource {
properties?: ProtectableItemProperties;
}
/**
* @class
* Initializes a new instance of the ProtectableItemQueryParameter class.
* @constructor
* Query parameter to enumerate Protectable items.
*
* @member {string} [state] State of the Protectable item query filter.
*/
export interface ProtectableItemQueryParameter {
state?: string;
}
/**
* @class
* Initializes a new instance of the ProtectedItemsQueryParameter class.
* @constructor
* Query parameter to enumerate protected items.
*
* @member {string} [sourceFabricName] The source fabric name filter.
* @member {string} [recoveryPlanName] The recovery plan filter.
* @member {string} [vCenterName] The vCenter name filter.
* @member {string} [instanceType] The replication provider type.
* @member {string} [multiVmGroupCreateOption] Whether Multi VM group is auto
* created or specified by user. Possible values include: 'AutoCreated',
* 'UserSpecified'
*/
export interface ProtectedItemsQueryParameter {
sourceFabricName?: string;
recoveryPlanName?: string;
vCenterName?: string;
instanceType?: string;
multiVmGroupCreateOption?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerFabricSpecificDetails class.
* @constructor
* Base class for fabric specific details of container.
*
* @member {string} [instanceType] Gets the class type. Overriden in derived
* classes.
*/
export interface ProtectionContainerFabricSpecificDetails {
readonly instanceType?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerProperties class.
* @constructor
* Protection profile custom data details.
*
* @member {string} [fabricFriendlyName] Fabric friendly name.
* @member {string} [friendlyName] The name.
* @member {string} [fabricType] The fabric type.
* @member {number} [protectedItemCount] Number of protected PEs
* @member {string} [pairingStatus] The pairing status of this cloud.
* @member {string} [role] The role of this cloud.
* @member {object} [fabricSpecificDetails] Fabric specific details.
* @member {string} [fabricSpecificDetails.instanceType] Gets the class type.
* Overriden in derived classes.
*/
export interface ProtectionContainerProperties {
fabricFriendlyName?: string;
friendlyName?: string;
fabricType?: string;
protectedItemCount?: number;
pairingStatus?: string;
role?: string;
fabricSpecificDetails?: ProtectionContainerFabricSpecificDetails;
}
/**
* @class
* Initializes a new instance of the ProtectionContainer class.
* @constructor
* Protection container details.
*
* @member {object} [properties] The custom data.
* @member {string} [properties.fabricFriendlyName] Fabric friendly name.
* @member {string} [properties.friendlyName] The name.
* @member {string} [properties.fabricType] The fabric type.
* @member {number} [properties.protectedItemCount] Number of protected PEs
* @member {string} [properties.pairingStatus] The pairing status of this
* cloud.
* @member {string} [properties.role] The role of this cloud.
* @member {object} [properties.fabricSpecificDetails] Fabric specific details.
* @member {string} [properties.fabricSpecificDetails.instanceType] Gets the
* class type. Overriden in derived classes.
*/
export interface ProtectionContainer extends Resource {
properties?: ProtectionContainerProperties;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerMappingProperties class.
* @constructor
* Protection container mapping properties.
*
* @member {string} [targetProtectionContainerId] Paired protection container
* ARM ID.
* @member {string} [targetProtectionContainerFriendlyName] Friendly name of
* paired container.
* @member {object} [providerSpecificDetails] Provider specific provider
* details.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
* @member {string} [health] Health of pairing.
* @member {array} [healthErrorDetails] Health error.
* @member {string} [policyId] Policy ARM Id.
* @member {string} [state] Association Status
* @member {string} [sourceProtectionContainerFriendlyName] Friendly name of
* source protection container.
* @member {string} [sourceFabricFriendlyName] Friendly name of source fabric.
* @member {string} [targetFabricFriendlyName] Friendly name of target fabric.
* @member {string} [policyFriendlyName] Friendly name of replication policy.
*/
export interface ProtectionContainerMappingProperties {
targetProtectionContainerId?: string;
targetProtectionContainerFriendlyName?: string;
providerSpecificDetails?: ProtectionContainerMappingProviderSpecificDetails;
health?: string;
healthErrorDetails?: HealthError[];
policyId?: string;
state?: string;
sourceProtectionContainerFriendlyName?: string;
sourceFabricFriendlyName?: string;
targetFabricFriendlyName?: string;
policyFriendlyName?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerMapping class.
* @constructor
* Protection container mapping object.
*
* @member {object} [properties] The custom data.
* @member {string} [properties.targetProtectionContainerId] Paired protection
* container ARM ID.
* @member {string} [properties.targetProtectionContainerFriendlyName] Friendly
* name of paired container.
* @member {object} [properties.providerSpecificDetails] Provider specific
* provider details.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
* @member {string} [properties.health] Health of pairing.
* @member {array} [properties.healthErrorDetails] Health error.
* @member {string} [properties.policyId] Policy ARM Id.
* @member {string} [properties.state] Association Status
* @member {string} [properties.sourceProtectionContainerFriendlyName] Friendly
* name of source protection container.
* @member {string} [properties.sourceFabricFriendlyName] Friendly name of
* source fabric.
* @member {string} [properties.targetFabricFriendlyName] Friendly name of
* target fabric.
* @member {string} [properties.policyFriendlyName] Friendly name of
* replication policy.
*/
export interface ProtectionContainerMapping extends Resource {
properties?: ProtectionContainerMappingProperties;
}
/**
* @class
* Initializes a new instance of the RcmAzureMigrationPolicyDetails class.
* @constructor
* RCM based Azure migration specific policy details.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {string} [multiVmSyncStatus] A value indicating whether multi-VM
* sync has to be enabled. Possible values include: 'Enabled', 'Disabled'
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency in minutes.
*/
export interface RcmAzureMigrationPolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
multiVmSyncStatus?: string;
crashConsistentFrequencyInMinutes?: number;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanProperties class.
* @constructor
* Recovery plan custom details.
*
* @member {string} [friendlyName] The friendly name.
* @member {string} [primaryFabricId] The primary fabric Id.
* @member {string} [primaryFabricFriendlyName] The primary fabric friendly
* name.
* @member {string} [recoveryFabricId] The recovery fabric Id.
* @member {string} [recoveryFabricFriendlyName] The recovery fabric friendly
* name.
* @member {string} [failoverDeploymentModel] The failover deployment model.
* @member {array} [replicationProviders] The list of replication providers.
* @member {array} [allowedOperations] The list of allowed operations.
* @member {date} [lastPlannedFailoverTime] The start time of the last planned
* failover.
* @member {date} [lastUnplannedFailoverTime] The start time of the last
* unplanned failover.
* @member {date} [lastTestFailoverTime] The start time of the last test
* failover.
* @member {object} [currentScenario] The current scenario details.
* @member {string} [currentScenario.scenarioName] Scenario name.
* @member {string} [currentScenario.jobId] ARM Id of the job being executed.
* @member {date} [currentScenario.startTime] Start time of the workflow.
* @member {string} [currentScenarioStatus] The recovery plan status.
* @member {string} [currentScenarioStatusDescription] The recovery plan status
* description.
* @member {array} [groups] The recovery plan groups.
*/
export interface RecoveryPlanProperties {
friendlyName?: string;
primaryFabricId?: string;
primaryFabricFriendlyName?: string;
recoveryFabricId?: string;
recoveryFabricFriendlyName?: string;
failoverDeploymentModel?: string;
replicationProviders?: string[];
allowedOperations?: string[];
lastPlannedFailoverTime?: Date;
lastUnplannedFailoverTime?: Date;
lastTestFailoverTime?: Date;
currentScenario?: CurrentScenarioDetails;
currentScenarioStatus?: string;
currentScenarioStatusDescription?: string;
groups?: RecoveryPlanGroup[];
}
/**
* @class
* Initializes a new instance of the RecoveryPlan class.
* @constructor
* Recovery plan details.
*
* @member {object} [properties] The custom details.
* @member {string} [properties.friendlyName] The friendly name.
* @member {string} [properties.primaryFabricId] The primary fabric Id.
* @member {string} [properties.primaryFabricFriendlyName] The primary fabric
* friendly name.
* @member {string} [properties.recoveryFabricId] The recovery fabric Id.
* @member {string} [properties.recoveryFabricFriendlyName] The recovery fabric
* friendly name.
* @member {string} [properties.failoverDeploymentModel] The failover
* deployment model.
* @member {array} [properties.replicationProviders] The list of replication
* providers.
* @member {array} [properties.allowedOperations] The list of allowed
* operations.
* @member {date} [properties.lastPlannedFailoverTime] The start time of the
* last planned failover.
* @member {date} [properties.lastUnplannedFailoverTime] The start time of the
* last unplanned failover.
* @member {date} [properties.lastTestFailoverTime] The start time of the last
* test failover.
* @member {object} [properties.currentScenario] The current scenario details.
* @member {string} [properties.currentScenario.scenarioName] Scenario name.
* @member {string} [properties.currentScenario.jobId] ARM Id of the job being
* executed.
* @member {date} [properties.currentScenario.startTime] Start time of the
* workflow.
* @member {string} [properties.currentScenarioStatus] The recovery plan
* status.
* @member {string} [properties.currentScenarioStatusDescription] The recovery
* plan status description.
* @member {array} [properties.groups] The recovery plan groups.
*/
export interface RecoveryPlan extends Resource {
properties?: RecoveryPlanProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanProviderSpecificFailoverInput class.
* @constructor
* Recovery plan provider specific failover input base class.
*
* @member {string} instanceType Polymorphic Discriminator
*/
export interface RecoveryPlanProviderSpecificFailoverInput {
instanceType: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanA2AFailoverInput class.
* @constructor
* Recovery plan A2A failover input.
*
* @member {string} recoveryPointType The recovery point type. Possible values
* include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent',
* 'LatestProcessed'
* @member {string} [cloudServiceCreationOption] A value indicating whether to
* use recovery cloud service for TFO or not.
* @member {string} [multiVmSyncPointOption] A value indicating whether multi
* VM sync enabled VMs should use multi VM sync points for failover. Possible
* values include: 'UseMultiVmSyncRecoveryPoint', 'UsePerVmRecoveryPoint'
*/
export interface RecoveryPlanA2AFailoverInput extends RecoveryPlanProviderSpecificFailoverInput {
recoveryPointType: string;
cloudServiceCreationOption?: string;
multiVmSyncPointOption?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanAutomationRunbookActionDetails class.
* @constructor
* Recovery plan Automation runbook action details.
*
* @member {string} [runbookId] The runbook ARM Id.
* @member {string} [timeout] The runbook timeout.
* @member {string} fabricLocation The fabric location. Possible values
* include: 'Primary', 'Recovery'
*/
export interface RecoveryPlanAutomationRunbookActionDetails extends RecoveryPlanActionDetails {
runbookId?: string;
timeout?: string;
fabricLocation: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanGroupTaskDetails class.
* @constructor
* This class represents the recovery plan group task.
*
* @member {string} [name] The name.
* @member {string} [groupId] The group identifier.
* @member {string} [rpGroupType] The group type.
*/
export interface RecoveryPlanGroupTaskDetails extends GroupTaskDetails {
name?: string;
groupId?: string;
rpGroupType?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanHyperVReplicaAzureFailbackInput class.
* @constructor
* Recovery plan HVR Azure failback input.
*
* @member {string} dataSyncOption The data sync option. Possible values
* include: 'ForDownTime', 'ForSynchronization'
* @member {string} recoveryVmCreationOption The ALR option. Possible values
* include: 'CreateVmIfNotFound', 'NoAction'
*/
export interface RecoveryPlanHyperVReplicaAzureFailbackInput extends RecoveryPlanProviderSpecificFailoverInput {
dataSyncOption: string;
recoveryVmCreationOption: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanHyperVReplicaAzureFailoverInput class.
* @constructor
* Recovery plan HVR Azure failover input.
*
* @member {string} vaultLocation The vault location.
* @member {string} [primaryKekCertificatePfx] The primary KEK certificate PFX.
* @member {string} [secondaryKekCertificatePfx] The secondary KEK certificate
* PFX.
* @member {string} [recoveryPointType] The recovery point type. Possible
* values include: 'Latest', 'LatestApplicationConsistent', 'LatestProcessed'
*/
export interface RecoveryPlanHyperVReplicaAzureFailoverInput extends RecoveryPlanProviderSpecificFailoverInput {
vaultLocation: string;
primaryKekCertificatePfx?: string;
secondaryKekCertificatePfx?: string;
recoveryPointType?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanInMageAzureV2FailoverInput class.
* @constructor
* Recovery plan InMageAzureV2 failover input.
*
* @member {string} vaultLocation The vault location.
* @member {string} recoveryPointType The recovery point type. Possible values
* include: 'Latest', 'LatestApplicationConsistent', 'LatestCrashConsistent',
* 'LatestProcessed'
* @member {string} [useMultiVmSyncPoint] A value indicating whether multi VM
* sync enabled VMs should use multi VM sync points for failover.
*/
export interface RecoveryPlanInMageAzureV2FailoverInput extends RecoveryPlanProviderSpecificFailoverInput {
vaultLocation: string;
recoveryPointType: string;
useMultiVmSyncPoint?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanInMageFailoverInput class.
* @constructor
* Recovery plan InMage failover input.
*
* @member {string} recoveryPointType The recovery point type. Possible values
* include: 'LatestTime', 'LatestTag', 'Custom'
*/
export interface RecoveryPlanInMageFailoverInput extends RecoveryPlanProviderSpecificFailoverInput {
recoveryPointType: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanManualActionDetails class.
* @constructor
* Recovery plan manual action details.
*
* @member {string} [description] The manual action description.
*/
export interface RecoveryPlanManualActionDetails extends RecoveryPlanActionDetails {
description?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanPlannedFailoverInputProperties class.
* @constructor
* Recovery plan planned failover input properties.
*
* @member {string} failoverDirection The failover direction. Possible values
* include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {array} [providerSpecificDetails] The provider specific properties.
*/
export interface RecoveryPlanPlannedFailoverInputProperties {
failoverDirection: string;
providerSpecificDetails?: RecoveryPlanProviderSpecificFailoverInput[];
}
/**
* @class
* Initializes a new instance of the RecoveryPlanPlannedFailoverInput class.
* @constructor
* Recovery plan planned failover input.
*
* @member {object} properties The recovery plan planned failover input
* properties.
* @member {string} [properties.failoverDirection] The failover direction.
* Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {array} [properties.providerSpecificDetails] The provider specific
* properties.
*/
export interface RecoveryPlanPlannedFailoverInput {
properties: RecoveryPlanPlannedFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanScriptActionDetails class.
* @constructor
* Recovery plan script action details.
*
* @member {string} path The script path.
* @member {string} [timeout] The script timeout.
* @member {string} fabricLocation The fabric location. Possible values
* include: 'Primary', 'Recovery'
*/
export interface RecoveryPlanScriptActionDetails extends RecoveryPlanActionDetails {
path: string;
timeout?: string;
fabricLocation: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanShutdownGroupTaskDetails class.
* @constructor
* This class represents the recovery plan shutdown group task details.
*
* @member {string} [name] The name.
* @member {string} [groupId] The group identifier.
* @member {string} [rpGroupType] The group type.
*/
export interface RecoveryPlanShutdownGroupTaskDetails extends GroupTaskDetails {
name?: string;
groupId?: string;
rpGroupType?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanTestFailoverCleanupInputProperties class.
* @constructor
* Recovery plan test failover cleanup input properties.
*
* @member {string} [comments] The test failover cleanup comments.
*/
export interface RecoveryPlanTestFailoverCleanupInputProperties {
comments?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanTestFailoverCleanupInput class.
* @constructor
* Recovery plan test failover cleanup input.
*
* @member {object} properties The recovery plan test failover cleanup input
* properties.
* @member {string} [properties.comments] The test failover cleanup comments.
*/
export interface RecoveryPlanTestFailoverCleanupInput {
properties: RecoveryPlanTestFailoverCleanupInputProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanTestFailoverInputProperties class.
* @constructor
* Recovery plan test failover input properties.
*
* @member {string} failoverDirection The failover direction. Possible values
* include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {string} networkType The network type to be used for test failover.
* @member {string} [networkId] The Id of the network to be used for test
* failover.
* @member {string} [skipTestFailoverCleanup] A value indicating whether the
* test failover cleanup is to be skipped.
* @member {array} [providerSpecificDetails] The provider specific properties.
*/
export interface RecoveryPlanTestFailoverInputProperties {
failoverDirection: string;
networkType: string;
networkId?: string;
skipTestFailoverCleanup?: string;
providerSpecificDetails?: RecoveryPlanProviderSpecificFailoverInput[];
}
/**
* @class
* Initializes a new instance of the RecoveryPlanTestFailoverInput class.
* @constructor
* Recovery plan test failover input.
*
* @member {object} properties The recovery plan test failover input
* properties.
* @member {string} [properties.failoverDirection] The failover direction.
* Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {string} [properties.networkType] The network type to be used for
* test failover.
* @member {string} [properties.networkId] The Id of the network to be used for
* test failover.
* @member {string} [properties.skipTestFailoverCleanup] A value indicating
* whether the test failover cleanup is to be skipped.
* @member {array} [properties.providerSpecificDetails] The provider specific
* properties.
*/
export interface RecoveryPlanTestFailoverInput {
properties: RecoveryPlanTestFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanUnplannedFailoverInputProperties class.
* @constructor
* Recovery plan unplanned failover input properties.
*
* @member {string} failoverDirection The failover direction. Possible values
* include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {string} sourceSiteOperations A value indicating whether source site
* operations are required. Possible values include: 'Required', 'NotRequired'
* @member {array} [providerSpecificDetails] The provider specific properties.
*/
export interface RecoveryPlanUnplannedFailoverInputProperties {
failoverDirection: string;
sourceSiteOperations: string;
providerSpecificDetails?: RecoveryPlanProviderSpecificFailoverInput[];
}
/**
* @class
* Initializes a new instance of the RecoveryPlanUnplannedFailoverInput class.
* @constructor
* Recovery plan unplanned failover input.
*
* @member {object} properties The recovery plan unplanned failover input
* properties.
* @member {string} [properties.failoverDirection] The failover direction.
* Possible values include: 'PrimaryToRecovery', 'RecoveryToPrimary'
* @member {string} [properties.sourceSiteOperations] A value indicating
* whether source site operations are required. Possible values include:
* 'Required', 'NotRequired'
* @member {array} [properties.providerSpecificDetails] The provider specific
* properties.
*/
export interface RecoveryPlanUnplannedFailoverInput {
properties: RecoveryPlanUnplannedFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryPointProperties class.
* @constructor
* Recovery point properties.
*
* @member {date} [recoveryPointTime] The recovery point time.
* @member {string} [recoveryPointType] The recovery point type:
* ApplicationConsistent, CrashConsistent.
* @member {object} [providerSpecificDetails] The provider specific details for
* the recovery point.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface RecoveryPointProperties {
recoveryPointTime?: Date;
recoveryPointType?: string;
providerSpecificDetails?: ProviderSpecificRecoveryPointDetails;
}
/**
* @class
* Initializes a new instance of the RecoveryPoint class.
* @constructor
* Base class representing a recovery point.
*
* @member {object} [properties] Recovery point related data.
* @member {date} [properties.recoveryPointTime] The recovery point time.
* @member {string} [properties.recoveryPointType] The recovery point type:
* ApplicationConsistent, CrashConsistent.
* @member {object} [properties.providerSpecificDetails] The provider specific
* details for the recovery point.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface RecoveryPoint extends Resource {
properties?: RecoveryPointProperties;
}
/**
* @class
* Initializes a new instance of the RecoveryServicesProviderProperties class.
* @constructor
* Recovery services provider properties.
*
* @member {string} [fabricType] Type of the site.
* @member {string} [friendlyName] Friendly name of the DRA.
* @member {string} [providerVersion] The provider version.
* @member {string} [serverVersion] The fabric provider.
* @member {string} [providerVersionState] DRA version status.
* @member {date} [providerVersionExpiryDate] Expiry date of the version.
* @member {string} [fabricFriendlyName] The fabric friendly name.
* @member {date} [lastHeartBeat] Time when last heartbeat was sent by the DRA.
* @member {string} [connectionStatus] A value indicating whether DRA is
* responsive.
* @member {number} [protectedItemCount] Number of protected VMs currently
* managed by the DRA.
* @member {array} [allowedScenarios] The scenarios allowed on this provider.
* @member {array} [healthErrorDetails] The recovery services provider health
* error details.
* @member {string} [draIdentifier] The DRA Id.
* @member {object} [identityDetails] The identity details.
* @member {string} [identityDetails.identityProviderType] The identity
* provider type. Value is the ToString() of a IdentityProviderType value.
* Possible values include: 'RecoveryServicesActiveDirectory'
* @member {string} [identityDetails.tenantId] The tenant Id for the service
* principal with which the on-premise management/data plane components would
* communicate with our Azure services.
* @member {string} [identityDetails.applicationId] The application/client Id
* for the service principal with which the on-premise management/data plane
* components would communicate with our Azure services.
* @member {string} [identityDetails.objectId] The object Id of the service
* principal with which the on-premise management/data plane components would
* communicate with our Azure services.
* @member {string} [identityDetails.audience] The intended Audience of the
* service principal with which the on-premise management/data plane components
* would communicate with our Azure services.
* @member {string} [identityDetails.aadAuthority] The base authority for Azure
* Active Directory authentication.
* @member {string} [identityDetails.certificateThumbprint] The certificate
* thumbprint. Applicable only if IdentityProviderType is
* RecoveryServicesActiveDirectory.
* @member {object} [providerVersionDetails] The provider version details.
* @member {string} [providerVersionDetails.version] The agent version.
* @member {date} [providerVersionDetails.expiryDate] Version expiry date.
* @member {string} [providerVersionDetails.status] A value indicating whether
* security update required. Possible values include: 'Supported',
* 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface RecoveryServicesProviderProperties {
fabricType?: string;
friendlyName?: string;
providerVersion?: string;
serverVersion?: string;
providerVersionState?: string;
providerVersionExpiryDate?: Date;
fabricFriendlyName?: string;
lastHeartBeat?: Date;
connectionStatus?: string;
protectedItemCount?: number;
allowedScenarios?: string[];
healthErrorDetails?: HealthError[];
draIdentifier?: string;
identityDetails?: IdentityInformation;
providerVersionDetails?: VersionDetails;
}
/**
* @class
* Initializes a new instance of the RecoveryServicesProvider class.
* @constructor
* Provider details.
*
* @member {object} [properties] Provider properties.
* @member {string} [properties.fabricType] Type of the site.
* @member {string} [properties.friendlyName] Friendly name of the DRA.
* @member {string} [properties.providerVersion] The provider version.
* @member {string} [properties.serverVersion] The fabric provider.
* @member {string} [properties.providerVersionState] DRA version status.
* @member {date} [properties.providerVersionExpiryDate] Expiry date of the
* version.
* @member {string} [properties.fabricFriendlyName] The fabric friendly name.
* @member {date} [properties.lastHeartBeat] Time when last heartbeat was sent
* by the DRA.
* @member {string} [properties.connectionStatus] A value indicating whether
* DRA is responsive.
* @member {number} [properties.protectedItemCount] Number of protected VMs
* currently managed by the DRA.
* @member {array} [properties.allowedScenarios] The scenarios allowed on this
* provider.
* @member {array} [properties.healthErrorDetails] The recovery services
* provider health error details.
* @member {string} [properties.draIdentifier] The DRA Id.
* @member {object} [properties.identityDetails] The identity details.
* @member {string} [properties.identityDetails.identityProviderType] The
* identity provider type. Value is the ToString() of a IdentityProviderType
* value. Possible values include: 'RecoveryServicesActiveDirectory'
* @member {string} [properties.identityDetails.tenantId] The tenant Id for the
* service principal with which the on-premise management/data plane components
* would communicate with our Azure services.
* @member {string} [properties.identityDetails.applicationId] The
* application/client Id for the service principal with which the on-premise
* management/data plane components would communicate with our Azure services.
* @member {string} [properties.identityDetails.objectId] The object Id of the
* service principal with which the on-premise management/data plane components
* would communicate with our Azure services.
* @member {string} [properties.identityDetails.audience] The intended Audience
* of the service principal with which the on-premise management/data plane
* components would communicate with our Azure services.
* @member {string} [properties.identityDetails.aadAuthority] The base
* authority for Azure Active Directory authentication.
* @member {string} [properties.identityDetails.certificateThumbprint] The
* certificate thumbprint. Applicable only if IdentityProviderType is
* RecoveryServicesActiveDirectory.
* @member {object} [properties.providerVersionDetails] The provider version
* details.
* @member {string} [properties.providerVersionDetails.version] The agent
* version.
* @member {date} [properties.providerVersionDetails.expiryDate] Version expiry
* date.
* @member {string} [properties.providerVersionDetails.status] A value
* indicating whether security update required. Possible values include:
* 'Supported', 'NotSupported', 'Deprecated', 'UpdateRequired',
* 'SecurityUpdateRequired'
*/
export interface RecoveryServicesProvider extends Resource {
properties?: RecoveryServicesProviderProperties;
}
/**
* @class
* Initializes a new instance of the ReplicationProviderContainerUnmappingInput class.
* @constructor
* Provider specific input for unpairing operations.
*
* @member {string} [instanceType] The class type.
*/
export interface ReplicationProviderContainerUnmappingInput {
instanceType?: string;
}
/**
* @class
* Initializes a new instance of the RemoveProtectionContainerMappingInputProperties class.
* @constructor
* Unpairing input properties.
*
* @member {object} [providerSpecificInput] Provider specific input for
* unpairing.
* @member {string} [providerSpecificInput.instanceType] The class type.
*/
export interface RemoveProtectionContainerMappingInputProperties {
providerSpecificInput?: ReplicationProviderContainerUnmappingInput;
}
/**
* @class
* Initializes a new instance of the RemoveProtectionContainerMappingInput class.
* @constructor
* Container unpairing input.
*
* @member {object} [properties] Configure protection input properties.
* @member {object} [properties.providerSpecificInput] Provider specific input
* for unpairing.
* @member {string} [properties.providerSpecificInput.instanceType] The class
* type.
*/
export interface RemoveProtectionContainerMappingInput {
properties?: RemoveProtectionContainerMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the RenewCertificateInputProperties class.
* @constructor
* Renew Certificate input properties.
*
* @member {string} [renewCertificateType] Renew certificate type.
*/
export interface RenewCertificateInputProperties {
renewCertificateType?: string;
}
/**
* @class
* Initializes a new instance of the RenewCertificateInput class.
* @constructor
* Certificate renewal input.
*
* @member {object} [properties] Renew certificate input properties.
* @member {string} [properties.renewCertificateType] Renew certificate type.
*/
export interface RenewCertificateInput {
properties?: RenewCertificateInputProperties;
}
/**
* @class
* Initializes a new instance of the ReplicationGroupDetails class.
* @constructor
* Replication group details. This will be used in case of San and Wvr.
*
*/
export interface ReplicationGroupDetails extends ConfigurationSettings {
}
/**
* @class
* Initializes a new instance of the ReplicationProtectedItemProperties class.
* @constructor
* Replication protected item custom data details.
*
* @member {string} [friendlyName] The name.
* @member {string} [protectedItemType] The type of protected item type.
* @member {string} [protectableItemId] The protected item ARM Id.
* @member {string} [recoveryServicesProviderId] The recovery provider ARM Id.
* @member {string} [primaryFabricFriendlyName] The friendly name of the
* primary fabric.
* @member {string} [primaryFabricProvider] The fabric provider of the primary
* fabric.
* @member {string} [recoveryFabricFriendlyName] The friendly name of recovery
* fabric.
* @member {string} [recoveryFabricId] The Arm Id of recovery fabric.
* @member {string} [primaryProtectionContainerFriendlyName] The name of
* primary protection container friendly name.
* @member {string} [recoveryProtectionContainerFriendlyName] The name of
* recovery container friendly name.
* @member {string} [protectionState] The protection status.
* @member {string} [protectionStateDescription] The protection state
* description.
* @member {string} [activeLocation] The Current active location of the PE.
* @member {string} [testFailoverState] The Test failover state.
* @member {string} [testFailoverStateDescription] The Test failover state
* description.
* @member {array} [allowedOperations] The allowed operations on the
* Replication protected item.
* @member {string} [replicationHealth] The consolidated protection health for
* the VM taking any issues with SRS as well as all the replication units
* associated with the VM's replication group into account. This is a string
* representation of the ProtectionHealth enumeration.
* @member {string} [failoverHealth] The consolidated failover health for the
* VM.
* @member {array} [healthErrors] List of health errors.
* @member {string} [policyId] The ID of Policy governing this PE.
* @member {string} [policyFriendlyName] The name of Policy governing this PE.
* @member {date} [lastSuccessfulFailoverTime] The Last successful failover
* time.
* @member {date} [lastSuccessfulTestFailoverTime] The Last successful test
* failover time.
* @member {object} [currentScenario] The current scenario.
* @member {string} [currentScenario.scenarioName] Scenario name.
* @member {string} [currentScenario.jobId] ARM Id of the job being executed.
* @member {date} [currentScenario.startTime] Start time of the workflow.
* @member {string} [failoverRecoveryPointId] The recovery point ARM Id to
* which the Vm was failed over.
* @member {object} [providerSpecificDetails] The Replication provider custom
* settings.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
* @member {string} [recoveryContainerId] The recovery container Id.
*/
export interface ReplicationProtectedItemProperties {
friendlyName?: string;
protectedItemType?: string;
protectableItemId?: string;
recoveryServicesProviderId?: string;
primaryFabricFriendlyName?: string;
primaryFabricProvider?: string;
recoveryFabricFriendlyName?: string;
recoveryFabricId?: string;
primaryProtectionContainerFriendlyName?: string;
recoveryProtectionContainerFriendlyName?: string;
protectionState?: string;
protectionStateDescription?: string;
activeLocation?: string;
testFailoverState?: string;
testFailoverStateDescription?: string;
allowedOperations?: string[];
replicationHealth?: string;
failoverHealth?: string;
healthErrors?: HealthError[];
policyId?: string;
policyFriendlyName?: string;
lastSuccessfulFailoverTime?: Date;
lastSuccessfulTestFailoverTime?: Date;
currentScenario?: CurrentScenarioDetails;
failoverRecoveryPointId?: string;
providerSpecificDetails?: ReplicationProviderSpecificSettings;
recoveryContainerId?: string;
}
/**
* @class
* Initializes a new instance of the ReplicationProtectedItem class.
* @constructor
* Replication protected item.
*
* @member {object} [properties] The custom data.
* @member {string} [properties.friendlyName] The name.
* @member {string} [properties.protectedItemType] The type of protected item
* type.
* @member {string} [properties.protectableItemId] The protected item ARM Id.
* @member {string} [properties.recoveryServicesProviderId] The recovery
* provider ARM Id.
* @member {string} [properties.primaryFabricFriendlyName] The friendly name of
* the primary fabric.
* @member {string} [properties.primaryFabricProvider] The fabric provider of
* the primary fabric.
* @member {string} [properties.recoveryFabricFriendlyName] The friendly name
* of recovery fabric.
* @member {string} [properties.recoveryFabricId] The Arm Id of recovery
* fabric.
* @member {string} [properties.primaryProtectionContainerFriendlyName] The
* name of primary protection container friendly name.
* @member {string} [properties.recoveryProtectionContainerFriendlyName] The
* name of recovery container friendly name.
* @member {string} [properties.protectionState] The protection status.
* @member {string} [properties.protectionStateDescription] The protection
* state description.
* @member {string} [properties.activeLocation] The Current active location of
* the PE.
* @member {string} [properties.testFailoverState] The Test failover state.
* @member {string} [properties.testFailoverStateDescription] The Test failover
* state description.
* @member {array} [properties.allowedOperations] The allowed operations on the
* Replication protected item.
* @member {string} [properties.replicationHealth] The consolidated protection
* health for the VM taking any issues with SRS as well as all the replication
* units associated with the VM's replication group into account. This is a
* string representation of the ProtectionHealth enumeration.
* @member {string} [properties.failoverHealth] The consolidated failover
* health for the VM.
* @member {array} [properties.healthErrors] List of health errors.
* @member {string} [properties.policyId] The ID of Policy governing this PE.
* @member {string} [properties.policyFriendlyName] The name of Policy
* governing this PE.
* @member {date} [properties.lastSuccessfulFailoverTime] The Last successful
* failover time.
* @member {date} [properties.lastSuccessfulTestFailoverTime] The Last
* successful test failover time.
* @member {object} [properties.currentScenario] The current scenario.
* @member {string} [properties.currentScenario.scenarioName] Scenario name.
* @member {string} [properties.currentScenario.jobId] ARM Id of the job being
* executed.
* @member {date} [properties.currentScenario.startTime] Start time of the
* workflow.
* @member {string} [properties.failoverRecoveryPointId] The recovery point ARM
* Id to which the Vm was failed over.
* @member {object} [properties.providerSpecificDetails] The Replication
* provider custom settings.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
* @member {string} [properties.recoveryContainerId] The recovery container Id.
*/
export interface ReplicationProtectedItem extends Resource {
properties?: ReplicationProtectedItemProperties;
}
/**
* @class
* Initializes a new instance of the ResourceHealthSummary class.
* @constructor
* Base class to define the health summary of the resources contained under an
* Arm resource.
*
* @member {number} [resourceCount] The count of total resources umder the
* container.
* @member {array} [issues] The list of summary of health errors across the
* resources under the container.
*/
export interface ResourceHealthSummary {
resourceCount?: number;
issues?: HealthErrorSummary[];
}
/**
* @class
* Initializes a new instance of the ResumeJobParamsProperties class.
* @constructor
* Resume job properties.
*
* @member {string} [comments] Resume job comments.
*/
export interface ResumeJobParamsProperties {
comments?: string;
}
/**
* @class
* Initializes a new instance of the ResumeJobParams class.
* @constructor
* Resume job params.
*
* @member {object} [properties] Resume job properties.
* @member {string} [properties.comments] Resume job comments.
*/
export interface ResumeJobParams {
properties?: ResumeJobParamsProperties;
}
/**
* @class
* Initializes a new instance of the ReverseReplicationInputProperties class.
* @constructor
* Reverse replication input properties.
*
* @member {string} [failoverDirection] Failover direction.
* @member {object} [providerSpecificDetails] Provider specific reverse
* replication input.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface ReverseReplicationInputProperties {
failoverDirection?: string;
providerSpecificDetails?: ReverseReplicationProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the ReverseReplicationInput class.
* @constructor
* Reverse replication input.
*
* @member {object} [properties] Reverse replication properties
* @member {string} [properties.failoverDirection] Failover direction.
* @member {object} [properties.providerSpecificDetails] Provider specific
* reverse replication input.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface ReverseReplicationInput {
properties?: ReverseReplicationInputProperties;
}
/**
* @class
* Initializes a new instance of the RunAsAccount class.
* @constructor
* CS Accounts Details.
*
* @member {string} [accountId] The CS RunAs account Id.
* @member {string} [accountName] The CS RunAs account name.
*/
export interface RunAsAccount {
accountId?: string;
accountName?: string;
}
/**
* @class
* Initializes a new instance of the SanEnableProtectionInput class.
* @constructor
* San enable protection provider specific input.
*
*/
export interface SanEnableProtectionInput extends EnableProtectionProviderSpecificInput {
}
/**
* @class
* Initializes a new instance of the ScriptActionTaskDetails class.
* @constructor
* This class represents the script action task details.
*
* @member {string} [name] The name.
* @member {string} [path] The path.
* @member {string} [output] The output.
* @member {boolean} [isPrimarySideScript] A value indicating whether it is a
* primary side script or not.
*/
export interface ScriptActionTaskDetails extends TaskTypeDetails {
name?: string;
path?: string;
output?: string;
isPrimarySideScript?: boolean;
}
/**
* @class
* Initializes a new instance of the StorageClassificationProperties class.
* @constructor
* Storage object properties.
*
* @member {string} [friendlyName] Friendly name of the Storage classification.
*/
export interface StorageClassificationProperties {
friendlyName?: string;
}
/**
* @class
* Initializes a new instance of the StorageClassification class.
* @constructor
* Storage object definition.
*
* @member {object} [properties] Proprties of the storage object.
* @member {string} [properties.friendlyName] Friendly name of the Storage
* classification.
*/
export interface StorageClassification extends Resource {
properties?: StorageClassificationProperties;
}
/**
* @class
* Initializes a new instance of the StorageClassificationMappingProperties class.
* @constructor
* Storage mapping properties.
*
* @member {string} [targetStorageClassificationId] Target storage object Id.
*/
export interface StorageClassificationMappingProperties {
targetStorageClassificationId?: string;
}
/**
* @class
* Initializes a new instance of the StorageClassificationMapping class.
* @constructor
* Storage mapping object.
*
* @member {object} [properties] Proprties of the storage mappping object.
* @member {string} [properties.targetStorageClassificationId] Target storage
* object Id.
*/
export interface StorageClassificationMapping extends Resource {
properties?: StorageClassificationMappingProperties;
}
/**
* @class
* Initializes a new instance of the StorageMappingInputProperties class.
* @constructor
* Storage mapping input properties.
*
* @member {string} [targetStorageClassificationId] The ID of the storage
* object.
*/
export interface StorageMappingInputProperties {
targetStorageClassificationId?: string;
}
/**
* @class
* Initializes a new instance of the StorageClassificationMappingInput class.
* @constructor
* Storage mapping input.
*
* @member {object} [properties] Storage mapping input properties.
* @member {string} [properties.targetStorageClassificationId] The ID of the
* storage object.
*/
export interface StorageClassificationMappingInput {
properties?: StorageMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the SwitchProtectionInputProperties class.
* @constructor
* Switch protection input properties.
*
* @member {string} [replicationProtectedItemName] The unique replication
* protected item name.
* @member {object} [providerSpecificDetails] Provider specific switch
* protection input.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface SwitchProtectionInputProperties {
replicationProtectedItemName?: string;
providerSpecificDetails?: SwitchProtectionProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the SwitchProtectionInput class.
* @constructor
* Switch protection input.
*
* @member {object} [properties] Switch protection properties
* @member {string} [properties.replicationProtectedItemName] The unique
* replication protected item name.
* @member {object} [properties.providerSpecificDetails] Provider specific
* switch protection input.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface SwitchProtectionInput {
properties?: SwitchProtectionInputProperties;
}
/**
* @class
* Initializes a new instance of the SwitchProtectionJobDetails class.
* @constructor
* This class represents details for switch protection job.
*
* @member {string} [newReplicationProtectedItemId] ARM Id of the new
* replication protected item.
*/
export interface SwitchProtectionJobDetails extends JobDetails {
newReplicationProtectedItemId?: string;
}
/**
* @class
* Initializes a new instance of the TargetComputeSizeProperties class.
* @constructor
* Represents applicable recovery vm sizes properties.
*
* @member {string} [name] Target compute size name.
* @member {string} [friendlyName] Target compute size display name.
* @member {number} [cpuCoresCount] The maximum cpu cores count supported by
* target compute size.
* @member {number} [memoryInGB] The maximum memory in GB supported by target
* compute size.
* @member {number} [maxDataDiskCount] The maximum data disks count supported
* by target compute size.
* @member {number} [maxNicsCount] The maximum Nics count supported by target
* compute size.
* @member {array} [errors] The reasons why the target compute size is not
* applicable for the protected item.
* @member {string} [highIopsSupported] The value indicating whether the target
* compute size supports high Iops.
*/
export interface TargetComputeSizeProperties {
name?: string;
friendlyName?: string;
cpuCoresCount?: number;
memoryInGB?: number;
maxDataDiskCount?: number;
maxNicsCount?: number;
errors?: ComputeSizeErrorDetails[];
highIopsSupported?: string;
}
/**
* @class
* Initializes a new instance of the TargetComputeSize class.
* @constructor
* Represents applicable recovery vm sizes.
*
* @member {string} [id] The Id.
* @member {string} [name] The name.
* @member {string} [type] The Type of the object.
* @member {object} [properties] The custom data.
* @member {string} [properties.name] Target compute size name.
* @member {string} [properties.friendlyName] Target compute size display name.
* @member {number} [properties.cpuCoresCount] The maximum cpu cores count
* supported by target compute size.
* @member {number} [properties.memoryInGB] The maximum memory in GB supported
* by target compute size.
* @member {number} [properties.maxDataDiskCount] The maximum data disks count
* supported by target compute size.
* @member {number} [properties.maxNicsCount] The maximum Nics count supported
* by target compute size.
* @member {array} [properties.errors] The reasons why the target compute size
* is not applicable for the protected item.
* @member {string} [properties.highIopsSupported] The value indicating whether
* the target compute size supports high Iops.
*/
export interface TargetComputeSize {
id?: string;
name?: string;
type?: string;
properties?: TargetComputeSizeProperties;
}
/**
* @class
* Initializes a new instance of the TestFailoverCleanupInputProperties class.
* @constructor
* Input definition for test failover cleanup input properties.
*
* @member {string} [comments] Test failover cleanup comments.
*/
export interface TestFailoverCleanupInputProperties {
comments?: string;
}
/**
* @class
* Initializes a new instance of the TestFailoverCleanupInput class.
* @constructor
* Input definition for test failover cleanup.
*
* @member {object} properties Test failover cleanup input properties.
* @member {string} [properties.comments] Test failover cleanup comments.
*/
export interface TestFailoverCleanupInput {
properties: TestFailoverCleanupInputProperties;
}
/**
* @class
* Initializes a new instance of the TestFailoverInputProperties class.
* @constructor
* Input definition for planned failover input properties.
*
* @member {string} [failoverDirection] Failover direction.
* @member {string} [networkType] Network type to be used for test failover.
* @member {string} [networkId] The id of the network to be used for test
* failover
* @member {string} [skipTestFailoverCleanup] A value indicating whether the
* test failover cleanup is to be skipped.
* @member {object} [providerSpecificDetails] Provider specific settings
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface TestFailoverInputProperties {
failoverDirection?: string;
networkType?: string;
networkId?: string;
skipTestFailoverCleanup?: string;
providerSpecificDetails?: ProviderSpecificFailoverInput;
}
/**
* @class
* Initializes a new instance of the TestFailoverInput class.
* @constructor
* Input definition for planned failover.
*
* @member {object} [properties] Planned failover input properties
* @member {string} [properties.failoverDirection] Failover direction.
* @member {string} [properties.networkType] Network type to be used for test
* failover.
* @member {string} [properties.networkId] The id of the network to be used for
* test failover
* @member {string} [properties.skipTestFailoverCleanup] A value indicating
* whether the test failover cleanup is to be skipped.
* @member {object} [properties.providerSpecificDetails] Provider specific
* settings
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface TestFailoverInput {
properties?: TestFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the TestFailoverJobDetails class.
* @constructor
* This class represents the details for a test failover job.
*
* @member {string} [testFailoverStatus] The test failover status.
* @member {string} [comments] The test failover comments.
* @member {string} [networkName] The test network name.
* @member {string} [networkFriendlyName] The test network friendly name.
* @member {string} [networkType] The test network type (see TestFailoverInput
* enum for possible values).
* @member {array} [protectedItemDetails] The test VM details.
*/
export interface TestFailoverJobDetails extends JobDetails {
testFailoverStatus?: string;
comments?: string;
networkName?: string;
networkFriendlyName?: string;
networkType?: string;
protectedItemDetails?: FailoverReplicationProtectedItemDetails[];
}
/**
* @class
* Initializes a new instance of the UnplannedFailoverInputProperties class.
* @constructor
* Input definition for planned failover input properties.
*
* @member {string} [failoverDirection] Failover direction.
* @member {string} [sourceSiteOperations] Source site operations status
* @member {object} [providerSpecificDetails] Provider specific settings
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface UnplannedFailoverInputProperties {
failoverDirection?: string;
sourceSiteOperations?: string;
providerSpecificDetails?: ProviderSpecificFailoverInput;
}
/**
* @class
* Initializes a new instance of the UnplannedFailoverInput class.
* @constructor
* Input definition for planned failover.
*
* @member {object} [properties] Planned failover input properties
* @member {string} [properties.failoverDirection] Failover direction.
* @member {string} [properties.sourceSiteOperations] Source site operations
* status
* @member {object} [properties.providerSpecificDetails] Provider specific
* settings
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface UnplannedFailoverInput {
properties?: UnplannedFailoverInputProperties;
}
/**
* @class
* Initializes a new instance of the UpdateMobilityServiceRequestProperties class.
* @constructor
* The properties of an update mobility service request.
*
* @member {string} [runAsAccountId] The CS run as account Id.
*/
export interface UpdateMobilityServiceRequestProperties {
runAsAccountId?: string;
}
/**
* @class
* Initializes a new instance of the UpdateMobilityServiceRequest class.
* @constructor
* Request to update the mobility service on a protected item.
*
* @member {object} [properties] The properties of the update mobility service
* request.
* @member {string} [properties.runAsAccountId] The CS run as account Id.
*/
export interface UpdateMobilityServiceRequest {
properties?: UpdateMobilityServiceRequestProperties;
}
/**
* @class
* Initializes a new instance of the UpdateNetworkMappingInputProperties class.
* @constructor
* Common input details for network mapping operation.
*
* @member {string} [recoveryFabricName] Recovery fabric name.
* @member {string} [recoveryNetworkId] Recovery network Id.
* @member {object} [fabricSpecificDetails] Fabrics specific input network Id.
* @member {string} [fabricSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface UpdateNetworkMappingInputProperties {
recoveryFabricName?: string;
recoveryNetworkId?: string;
fabricSpecificDetails?: FabricSpecificUpdateNetworkMappingInput;
}
/**
* @class
* Initializes a new instance of the UpdateNetworkMappingInput class.
* @constructor
* Update network mapping input.
*
* @member {object} [properties] The input properties needed to update network
* mapping.
* @member {string} [properties.recoveryFabricName] Recovery fabric name.
* @member {string} [properties.recoveryNetworkId] Recovery network Id.
* @member {object} [properties.fabricSpecificDetails] Fabrics specific input
* network Id.
* @member {string} [properties.fabricSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface UpdateNetworkMappingInput {
properties?: UpdateNetworkMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the UpdatePolicyInputProperties class.
* @constructor
* Policy update properties.
*
* @member {object} [replicationProviderSettings] The
* ReplicationProviderSettings.
* @member {string} [replicationProviderSettings.instanceType] Polymorphic
* Discriminator
*/
export interface UpdatePolicyInputProperties {
replicationProviderSettings?: PolicyProviderSpecificInput;
}
/**
* @class
* Initializes a new instance of the UpdatePolicyInput class.
* @constructor
* Update policy input.
*
* @member {object} [properties] The ReplicationProviderSettings.
* @member {object} [properties.replicationProviderSettings] The
* ReplicationProviderSettings.
* @member {string} [properties.replicationProviderSettings.instanceType]
* Polymorphic Discriminator
*/
export interface UpdatePolicyInput {
properties?: UpdatePolicyInputProperties;
}
/**
* @class
* Initializes a new instance of the UpdateProtectionContainerMappingInputProperties class.
* @constructor
* Container pairing update input.
*
* @member {object} [providerSpecificInput] Provider specific input for
* updating protection container mapping.
* @member {string} [providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface UpdateProtectionContainerMappingInputProperties {
providerSpecificInput?: ReplicationProviderSpecificUpdateContainerMappingInput;
}
/**
* @class
* Initializes a new instance of the UpdateProtectionContainerMappingInput class.
* @constructor
* Container pairing update input.
*
* @member {object} [properties] Update protection container mapping input
* properties.
* @member {object} [properties.providerSpecificInput] Provider specific input
* for updating protection container mapping.
* @member {string} [properties.providerSpecificInput.instanceType] Polymorphic
* Discriminator
*/
export interface UpdateProtectionContainerMappingInput {
properties?: UpdateProtectionContainerMappingInputProperties;
}
/**
* @class
* Initializes a new instance of the UpdateRecoveryPlanInputProperties class.
* @constructor
* Recovery plan updation properties.
*
* @member {array} [groups] The recovery plan groups.
*/
export interface UpdateRecoveryPlanInputProperties {
groups?: RecoveryPlanGroup[];
}
/**
* @class
* Initializes a new instance of the UpdateRecoveryPlanInput class.
* @constructor
* Update recovery plan input class.
*
* @member {object} [properties] Recovery plan update properties.
* @member {array} [properties.groups] The recovery plan groups.
*/
export interface UpdateRecoveryPlanInput {
properties?: UpdateRecoveryPlanInputProperties;
}
/**
* @class
* Initializes a new instance of the VMNicInputDetails class.
* @constructor
* Hyper V VM network input details.
*
* @member {string} [nicId] The nic Id.
* @member {string} [recoveryVMSubnetName] Recovery VM subnet name.
* @member {string} [replicaNicStaticIPAddress] Replica nic static IP address.
* @member {string} [selectionType] Selection type for failover.
* @member {boolean} [enableAcceleratedNetworkingOnRecovery] Whether the NIC
* has accerated networking enabled.
*/
export interface VMNicInputDetails {
nicId?: string;
recoveryVMSubnetName?: string;
replicaNicStaticIPAddress?: string;
selectionType?: string;
enableAcceleratedNetworkingOnRecovery?: boolean;
}
/**
* @class
* Initializes a new instance of the UpdateReplicationProtectedItemInputProperties class.
* @constructor
* Update protected item input properties.
*
* @member {string} [recoveryAzureVMName] Target azure VM name given by the
* user.
* @member {string} [recoveryAzureVMSize] Target Azure Vm size.
* @member {string} [selectedRecoveryAzureNetworkId] Target Azure Network Id.
* @member {string} [selectedSourceNicId] The selected source nic Id which will
* be used as the primary nic during failover.
* @member {string} [enableRdpOnTargetOption] The selected option to enable
* RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {array} [vmNics] The list of vm nic details.
* @member {string} [licenseType] License type. Possible values include:
* 'NotSpecified', 'NoLicenseType', 'WindowsServer'
* @member {string} [recoveryAvailabilitySetId] The target availability set id.
* @member {object} [providerSpecificDetails] The provider specific input to
* update replication protected item.
* @member {string} [providerSpecificDetails.instanceType] Polymorphic
* Discriminator
*/
export interface UpdateReplicationProtectedItemInputProperties {
recoveryAzureVMName?: string;
recoveryAzureVMSize?: string;
selectedRecoveryAzureNetworkId?: string;
selectedSourceNicId?: string;
enableRdpOnTargetOption?: string;
vmNics?: VMNicInputDetails[];
licenseType?: string;
recoveryAvailabilitySetId?: string;
providerSpecificDetails?: UpdateReplicationProtectedItemProviderInput;
}
/**
* @class
* Initializes a new instance of the UpdateReplicationProtectedItemInput class.
* @constructor
* Update replication protected item input.
*
* @member {object} [properties] Update replication protected item properties.
* @member {string} [properties.recoveryAzureVMName] Target azure VM name given
* by the user.
* @member {string} [properties.recoveryAzureVMSize] Target Azure Vm size.
* @member {string} [properties.selectedRecoveryAzureNetworkId] Target Azure
* Network Id.
* @member {string} [properties.selectedSourceNicId] The selected source nic Id
* which will be used as the primary nic during failover.
* @member {string} [properties.enableRdpOnTargetOption] The selected option to
* enable RDP\SSH on target vm after failover. String value of
* {SrsDataContract.EnableRDPOnTargetOption} enum.
* @member {array} [properties.vmNics] The list of vm nic details.
* @member {string} [properties.licenseType] License type. Possible values
* include: 'NotSpecified', 'NoLicenseType', 'WindowsServer'
* @member {string} [properties.recoveryAvailabilitySetId] The target
* availability set id.
* @member {object} [properties.providerSpecificDetails] The provider specific
* input to update replication protected item.
* @member {string} [properties.providerSpecificDetails.instanceType]
* Polymorphic Discriminator
*/
export interface UpdateReplicationProtectedItemInput {
properties?: UpdateReplicationProtectedItemInputProperties;
}
/**
* @class
* Initializes a new instance of the UpdateVCenterRequestProperties class.
* @constructor
* The properties of an update vCenter request.
*
* @member {string} [friendlyName] The friendly name of the vCenter.
* @member {string} [ipAddress] The IP address of the vCenter to be discovered.
* @member {string} [processServerId] The process server Id from where the
* update can be orchestrated.
* @member {string} [port] The port number for discovery.
* @member {string} [runAsAccountId] The CS account Id which has priviliges to
* update the vCenter.
*/
export interface UpdateVCenterRequestProperties {
friendlyName?: string;
ipAddress?: string;
processServerId?: string;
port?: string;
runAsAccountId?: string;
}
/**
* @class
* Initializes a new instance of the UpdateVCenterRequest class.
* @constructor
* Input required to update vCenter.
*
* @member {object} [properties] The update VCenter Request Properties.
* @member {string} [properties.friendlyName] The friendly name of the vCenter.
* @member {string} [properties.ipAddress] The IP address of the vCenter to be
* discovered.
* @member {string} [properties.processServerId] The process server Id from
* where the update can be orchestrated.
* @member {string} [properties.port] The port number for discovery.
* @member {string} [properties.runAsAccountId] The CS account Id which has
* priviliges to update the vCenter.
*/
export interface UpdateVCenterRequest {
properties?: UpdateVCenterRequestProperties;
}
/**
* @class
* Initializes a new instance of the VaultHealthProperties class.
* @constructor
* class to define the health summary of the Vault.
*
* @member {array} [vaultErrors] The list of errors on the vault.
* @member {object} [protectedItemsHealth] The list of the health detail of the
* protected items in the vault.
* @member {number} [protectedItemsHealth.resourceCount] The count of total
* resources umder the container.
* @member {array} [protectedItemsHealth.issues] The list of summary of health
* errors across the resources under the container.
* @member {object} [fabricsHealth] The list of the health detail of the
* fabrics in the vault.
* @member {number} [fabricsHealth.resourceCount] The count of total resources
* umder the container.
* @member {array} [fabricsHealth.issues] The list of summary of health errors
* across the resources under the container.
* @member {object} [containersHealth] The list of the health detail of the
* containers in the vault.
* @member {number} [containersHealth.resourceCount] The count of total
* resources umder the container.
* @member {array} [containersHealth.issues] The list of summary of health
* errors across the resources under the container.
*/
export interface VaultHealthProperties {
vaultErrors?: HealthError[];
protectedItemsHealth?: ResourceHealthSummary;
fabricsHealth?: ResourceHealthSummary;
containersHealth?: ResourceHealthSummary;
}
/**
* @class
* Initializes a new instance of the VaultHealthDetails class.
* @constructor
* Vault health details definition.
*
* @member {object} [properties] The vault health related data.
* @member {array} [properties.vaultErrors] The list of errors on the vault.
* @member {object} [properties.protectedItemsHealth] The list of the health
* detail of the protected items in the vault.
* @member {number} [properties.protectedItemsHealth.resourceCount] The count
* of total resources umder the container.
* @member {array} [properties.protectedItemsHealth.issues] The list of summary
* of health errors across the resources under the container.
* @member {object} [properties.fabricsHealth] The list of the health detail of
* the fabrics in the vault.
* @member {number} [properties.fabricsHealth.resourceCount] The count of total
* resources umder the container.
* @member {array} [properties.fabricsHealth.issues] The list of summary of
* health errors across the resources under the container.
* @member {object} [properties.containersHealth] The list of the health detail
* of the containers in the vault.
* @member {number} [properties.containersHealth.resourceCount] The count of
* total resources umder the container.
* @member {array} [properties.containersHealth.issues] The list of summary of
* health errors across the resources under the container.
*/
export interface VaultHealthDetails extends Resource {
properties?: VaultHealthProperties;
}
/**
* @class
* Initializes a new instance of the VCenterProperties class.
* @constructor
* vCenter properties.
*
* @member {string} [friendlyName] Friendly name of the vCenter.
* @member {string} [internalId] VCenter internal ID.
* @member {date} [lastHeartbeat] The time when the last heartbeat was reveived
* by vCenter.
* @member {string} [discoveryStatus] The VCenter discovery status.
* @member {string} [processServerId] The process server Id.
* @member {string} [ipAddress] The IP address of the vCenter.
* @member {string} [infrastructureId] The infrastructure Id of vCenter.
* @member {string} [port] The port number for discovery.
* @member {string} [runAsAccountId] The account Id which has privileges to
* discover the vCenter.
* @member {string} [fabricArmResourceName] The ARM resource name of the fabric
* containing this VCenter.
* @member {array} [healthErrors] The health errors for this VCenter.
*/
export interface VCenterProperties {
friendlyName?: string;
internalId?: string;
lastHeartbeat?: Date;
discoveryStatus?: string;
processServerId?: string;
ipAddress?: string;
infrastructureId?: string;
port?: string;
runAsAccountId?: string;
fabricArmResourceName?: string;
healthErrors?: HealthError[];
}
/**
* @class
* Initializes a new instance of the VCenter class.
* @constructor
* vCenter definition.
*
* @member {object} [properties] VCenter related data.
* @member {string} [properties.friendlyName] Friendly name of the vCenter.
* @member {string} [properties.internalId] VCenter internal ID.
* @member {date} [properties.lastHeartbeat] The time when the last heartbeat
* was reveived by vCenter.
* @member {string} [properties.discoveryStatus] The VCenter discovery status.
* @member {string} [properties.processServerId] The process server Id.
* @member {string} [properties.ipAddress] The IP address of the vCenter.
* @member {string} [properties.infrastructureId] The infrastructure Id of
* vCenter.
* @member {string} [properties.port] The port number for discovery.
* @member {string} [properties.runAsAccountId] The account Id which has
* privileges to discover the vCenter.
* @member {string} [properties.fabricArmResourceName] The ARM resource name of
* the fabric containing this VCenter.
* @member {array} [properties.healthErrors] The health errors for this
* VCenter.
*/
export interface VCenter extends Resource {
properties?: VCenterProperties;
}
/**
* @class
* Initializes a new instance of the VirtualMachineTaskDetails class.
* @constructor
* This class represents the virtual machine task details.
*
* @member {string} [skippedReason] The skipped reason.
* @member {string} [skippedReasonString] The skipped reason string.
* @member {object} [jobTask] The job entity.
* @member {string} [jobTask.jobId] The job id.
* @member {string} [jobTask.jobFriendlyName] The job display name.
* @member {string} [jobTask.targetObjectId] The object id.
* @member {string} [jobTask.targetObjectName] The object name.
* @member {string} [jobTask.targetInstanceType] The workflow affected object
* type.
* @member {string} [jobTask.jobScenarioName] The job name. Enum type
* ScenarioName.
*/
export interface VirtualMachineTaskDetails extends TaskTypeDetails {
skippedReason?: string;
skippedReasonString?: string;
jobTask?: JobEntity;
}
/**
* @class
* Initializes a new instance of the VmmDetails class.
* @constructor
* VMM fabric specific details.
*
*/
export interface VmmDetails extends FabricSpecificDetails {
}
/**
* @class
* Initializes a new instance of the VmmToAzureCreateNetworkMappingInput class.
* @constructor
* Create network mappings input properties/behaviour specific to Vmm to Azure
* Network mapping.
*
*/
export interface VmmToAzureCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput {
}
/**
* @class
* Initializes a new instance of the VmmToAzureNetworkMappingSettings class.
* @constructor
* E2A Network Mapping fabric specific settings.
*
*/
export interface VmmToAzureNetworkMappingSettings extends NetworkMappingFabricSpecificSettings {
}
/**
* @class
* Initializes a new instance of the VmmToAzureUpdateNetworkMappingInput class.
* @constructor
* Update network mappings input properties/behaviour specific to vmm to azure.
*
*/
export interface VmmToAzureUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput {
}
/**
* @class
* Initializes a new instance of the VmmToVmmCreateNetworkMappingInput class.
* @constructor
* Create network mappings input properties/behaviour specific to vmm to vmm
* Network mapping.
*
*/
export interface VmmToVmmCreateNetworkMappingInput extends FabricSpecificCreateNetworkMappingInput {
}
/**
* @class
* Initializes a new instance of the VmmToVmmNetworkMappingSettings class.
* @constructor
* E2E Network Mapping fabric specific settings.
*
*/
export interface VmmToVmmNetworkMappingSettings extends NetworkMappingFabricSpecificSettings {
}
/**
* @class
* Initializes a new instance of the VmmToVmmUpdateNetworkMappingInput class.
* @constructor
* Update network mappings input properties/behaviour specific to vmm to vmm.
*
*/
export interface VmmToVmmUpdateNetworkMappingInput extends FabricSpecificUpdateNetworkMappingInput {
}
/**
* @class
* Initializes a new instance of the VmmVirtualMachineDetails class.
* @constructor
* VMM fabric provider specific VM settings.
*
* @member {string} [sourceItemId] The source id of the object.
* @member {string} [generation] The id of the object in fabric.
* @member {object} [osDetails] The Last replication time.
* @member {string} [osDetails.osType] VM Disk details.
* @member {string} [osDetails.productType] Product type.
* @member {string} [osDetails.osEdition] The OSEdition.
* @member {string} [osDetails.oSVersion] The OS Version.
* @member {string} [osDetails.oSMajorVersion] The OS Major Version.
* @member {string} [osDetails.oSMinorVersion] The OS Minor Version.
* @member {array} [diskDetails] The Last successful failover time.
* @member {string} [hasPhysicalDisk] A value indicating whether the VM has a
* physical disk attached. String value of {SrsDataContract.PresenceStatus}
* enum. Possible values include: 'Unknown', 'Present', 'NotPresent'
* @member {string} [hasFibreChannelAdapter] A value indicating whether the VM
* has a fibre channel adapter attached. String value of
* {SrsDataContract.PresenceStatus} enum. Possible values include: 'Unknown',
* 'Present', 'NotPresent'
* @member {string} [hasSharedVhd] A value indicating whether the VM has a
* shared VHD attached. String value of {SrsDataContract.PresenceStatus} enum.
* Possible values include: 'Unknown', 'Present', 'NotPresent'
*/
export interface VmmVirtualMachineDetails extends ConfigurationSettings {
sourceItemId?: string;
generation?: string;
osDetails?: OSDetails;
diskDetails?: DiskDetails[];
hasPhysicalDisk?: string;
hasFibreChannelAdapter?: string;
hasSharedVhd?: string;
}
/**
* @class
* Initializes a new instance of the VmNicUpdatesTaskDetails class.
* @constructor
* This class represents the vm NicUpdates task details.
*
* @member {string} [vmId] Virtual machine Id.
* @member {string} [nicId] Nic Id.
* @member {string} [name] Name of the Nic.
*/
export interface VmNicUpdatesTaskDetails extends TaskTypeDetails {
vmId?: string;
nicId?: string;
name?: string;
}
/**
* @class
* Initializes a new instance of the VMwareCbtPolicyCreationInput class.
* @constructor
* VMware Cbt Policy creation input.
*
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency (in minutes).
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency (in minutes).
*/
export interface VMwareCbtPolicyCreationInput extends PolicyProviderSpecificInput {
recoveryPointHistory?: number;
crashConsistentFrequencyInMinutes?: number;
appConsistentFrequencyInMinutes?: number;
}
/**
* @class
* Initializes a new instance of the VmwareCbtPolicyDetails class.
* @constructor
* VMware Cbt specific policy details.
*
* @member {number} [recoveryPointThresholdInMinutes] The recovery point
* threshold in minutes.
* @member {number} [recoveryPointHistory] The duration in minutes until which
* the recovery points need to be stored.
* @member {number} [appConsistentFrequencyInMinutes] The app consistent
* snapshot frequency in minutes.
* @member {number} [crashConsistentFrequencyInMinutes] The crash consistent
* snapshot frequency in minutes.
*/
export interface VmwareCbtPolicyDetails extends PolicyProviderSpecificDetails {
recoveryPointThresholdInMinutes?: number;
recoveryPointHistory?: number;
appConsistentFrequencyInMinutes?: number;
crashConsistentFrequencyInMinutes?: number;
}
/**
* @class
* Initializes a new instance of the VMwareDetails class.
* @constructor
* Store the fabric details specific to the VMware fabric.
*
* @member {array} [processServers] The list of Process Servers associated with
* the fabric.
* @member {array} [masterTargetServers] The list of Master Target servers
* associated with the fabric.
* @member {array} [runAsAccounts] The list of run as accounts created on the
* server.
* @member {string} [replicationPairCount] The number of replication pairs
* configured in this CS.
* @member {string} [processServerCount] The number of process servers.
* @member {string} [agentCount] The number of source and target servers
* configured to talk to this CS.
* @member {string} [protectedServers] The number of protected servers.
* @member {string} [systemLoad] The percentage of the system load.
* @member {string} [systemLoadStatus] The system load status.
* @member {string} [cpuLoad] The percentage of the CPU load.
* @member {string} [cpuLoadStatus] The CPU load status.
* @member {number} [totalMemoryInBytes] The total memory.
* @member {number} [availableMemoryInBytes] The available memory.
* @member {string} [memoryUsageStatus] The memory usage status.
* @member {number} [totalSpaceInBytes] The total space.
* @member {number} [availableSpaceInBytes] The available space.
* @member {string} [spaceUsageStatus] The space usage status.
* @member {string} [webLoad] The web load.
* @member {string} [webLoadStatus] The web load status.
* @member {string} [databaseServerLoad] The database server load.
* @member {string} [databaseServerLoadStatus] The database server load status.
* @member {string} [csServiceStatus] The CS service status.
* @member {string} [ipAddress] The IP address.
* @member {string} [agentVersion] The agent Version.
* @member {string} [hostName] The host name.
* @member {date} [lastHeartbeat] The last heartbeat received from CS server.
* @member {string} [versionStatus] Version status
* @member {date} [sslCertExpiryDate] CS SSL cert expiry date.
* @member {number} [sslCertExpiryRemainingDays] CS SSL cert expiry date.
* @member {string} [psTemplateVersion] PS template version.
* @member {date} [agentExpiryDate] Agent expiry date.
* @member {object} [agentVersionDetails] The agent version details.
* @member {string} [agentVersionDetails.version] The agent version.
* @member {date} [agentVersionDetails.expiryDate] Version expiry date.
* @member {string} [agentVersionDetails.status] A value indicating whether
* security update required. Possible values include: 'Supported',
* 'NotSupported', 'Deprecated', 'UpdateRequired', 'SecurityUpdateRequired'
*/
export interface VMwareDetails extends FabricSpecificDetails {
processServers?: ProcessServer[];
masterTargetServers?: MasterTargetServer[];
runAsAccounts?: RunAsAccount[];
replicationPairCount?: string;
processServerCount?: string;
agentCount?: string;
protectedServers?: string;
systemLoad?: string;
systemLoadStatus?: string;
cpuLoad?: string;
cpuLoadStatus?: string;
totalMemoryInBytes?: number;
availableMemoryInBytes?: number;
memoryUsageStatus?: string;
totalSpaceInBytes?: number;
availableSpaceInBytes?: number;
spaceUsageStatus?: string;
webLoad?: string;
webLoadStatus?: string;
databaseServerLoad?: string;
databaseServerLoadStatus?: string;
csServiceStatus?: string;
ipAddress?: string;
agentVersion?: string;
hostName?: string;
lastHeartbeat?: Date;
versionStatus?: string;
sslCertExpiryDate?: Date;
sslCertExpiryRemainingDays?: number;
psTemplateVersion?: string;
agentExpiryDate?: Date;
agentVersionDetails?: VersionDetails;
}
/**
* @class
* Initializes a new instance of the VMwareV2FabricCreationInput class.
* @constructor
* Fabric provider specific settings.
*
* @member {string} [keyVaultUrl] The Key Vault URL.
* @member {string} [keyVaultResourceArmId] The Key Vault ARM Id.
*/
export interface VMwareV2FabricCreationInput extends FabricSpecificCreationInput {
keyVaultUrl?: string;
keyVaultResourceArmId?: string;
}
/**
* @class
* Initializes a new instance of the VMwareV2FabricSpecificDetails class.
* @constructor
* VMwareV2 fabric Specific Details.
*
* @member {string} [srsServiceEndpoint] The endpoint for making requests to
* the SRS Service.
* @member {string} [rcmServiceEndpoint] The endpoint for making requests to
* the RCM Service.
* @member {string} [keyVaultUrl] The Key Vault URL.
* @member {string} [keyVaultResourceArmId] The Key Vault ARM Id.
*/
export interface VMwareV2FabricSpecificDetails extends FabricSpecificDetails {
srsServiceEndpoint?: string;
rcmServiceEndpoint?: string;
keyVaultUrl?: string;
keyVaultResourceArmId?: string;
}
/**
* @class
* Initializes a new instance of the VMwareVirtualMachineDetails class.
* @constructor
* VMware provider specific settings
*
* @member {string} [agentGeneratedId] The ID generated by the InMage agent
* after it gets installed on guest. This is the ID to be used during InMage
* CreateProtection.
* @member {string} [agentInstalled] The value indicating if InMage scout agent
* is installed on guest.
* @member {string} [osType] The OsType installed on VM.
* @member {string} [agentVersion] The agent version.
* @member {string} [ipAddress] The IP address.
* @member {string} [poweredOn] The value indicating whether VM is powered on.
* @member {string} [vCenterInfrastructureId] The VCenter infrastructure Id.
* @member {string} [discoveryType] A value inidicating the discovery type of
* the machine. Value can be vCenter or physical.
* @member {array} [diskDetails] The disk details.
* @member {array} [validationErrors] The validation errors.
*/
export interface VMwareVirtualMachineDetails extends ConfigurationSettings {
agentGeneratedId?: string;
agentInstalled?: string;
osType?: string;
agentVersion?: string;
ipAddress?: string;
poweredOn?: string;
vCenterInfrastructureId?: string;
discoveryType?: string;
diskDetails?: InMageDiskDetails[];
validationErrors?: HealthError[];
}
/**
* @class
* Initializes a new instance of the OperationsDiscoveryCollection class.
* @constructor
* Collection of ClientDiscovery details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface OperationsDiscoveryCollection extends Array<OperationsDiscovery> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the AlertCollection class.
* @constructor
* Collection of alerts.
*
* @member {string} [nextLink] The value of next link.
*/
export interface AlertCollection extends Array<Alert> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the EventCollection class.
* @constructor
* Collection of fabric details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface EventCollection extends Array<Event> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the FabricCollection class.
* @constructor
* Collection of fabric details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface FabricCollection extends Array<Fabric> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the LogicalNetworkCollection class.
* @constructor
* List of logical networks.
*
* @member {string} [nextLink] The value of next link.
*/
export interface LogicalNetworkCollection extends Array<LogicalNetwork> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the NetworkCollection class.
* @constructor
* List of networks.
*
* @member {string} [nextLink] The value of next link.
*/
export interface NetworkCollection extends Array<Network> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the NetworkMappingCollection class.
* @constructor
* List of network mappings. As with NetworkMapping, it should be possible to
* reuse a prev version of this class. It doesn't seem likely this class could
* be anything more than a slightly bespoke collection of NetworkMapping. Hence
* it makes sense to override Load with Base.NetworkMapping instead of existing
* CurrentVersion.NetworkMapping.
*
* @member {string} [nextLink] The value of next link.
*/
export interface NetworkMappingCollection extends Array<NetworkMapping> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerCollection class.
* @constructor
* Protection Container collection.
*
* @member {string} [nextLink] The value of next link.
*/
export interface ProtectionContainerCollection extends Array<ProtectionContainer> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ProtectableItemCollection class.
* @constructor
* Protectable item collection.
*
* @member {string} [nextLink] The value of next link.
*/
export interface ProtectableItemCollection extends Array<ProtectableItem> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ReplicationProtectedItemCollection class.
* @constructor
* Replication protected item collection.
*
* @member {string} [nextLink] The value of next link.
*/
export interface ReplicationProtectedItemCollection extends Array<ReplicationProtectedItem> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPointCollection class.
* @constructor
* Collection of recovery point details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface RecoveryPointCollection extends Array<RecoveryPoint> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the TargetComputeSizeCollection class.
* @constructor
* Target compute size collection.
*
* @member {string} [nextLink] The value of next link.
*/
export interface TargetComputeSizeCollection extends Array<TargetComputeSize> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ProtectionContainerMappingCollection class.
* @constructor
* Protection container mapping collection class.
*
* @member {string} [nextLink] Link to fetch rest of the data.
*/
export interface ProtectionContainerMappingCollection extends Array<ProtectionContainerMapping> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryServicesProviderCollection class.
* @constructor
* Collection of providers.
*
* @member {string} [nextLink] The value of next link.
*/
export interface RecoveryServicesProviderCollection extends Array<RecoveryServicesProvider> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the StorageClassificationCollection class.
* @constructor
* Collection of storage details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface StorageClassificationCollection extends Array<StorageClassification> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the StorageClassificationMappingCollection class.
* @constructor
* Collection of storage mapping details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface StorageClassificationMappingCollection extends Array<StorageClassificationMapping> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the VCenterCollection class.
* @constructor
* Collection of vCenter details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface VCenterCollection extends Array<VCenter> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the JobCollection class.
* @constructor
* Collection of jobs.
*
* @member {string} [nextLink] The value of next link.
*/
export interface JobCollection extends Array<Job> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the PolicyCollection class.
* @constructor
* Protection Profile Collection details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface PolicyCollection extends Array<Policy> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the RecoveryPlanCollection class.
* @constructor
* Recovery plan collection details.
*
* @member {string} [nextLink] The value of next link.
*/
export interface RecoveryPlanCollection extends Array<RecoveryPlan> {
nextLink?: string;
} | the_stack |
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Animated,
TouchableWithoutFeedback,
} from "react-native";
const STEP_STATUS = {
CURRENT: "current",
FINISHED: "finished",
UNFINISHED: "unfinished",
};
interface CustomStyles {
stepIndicatorSize?: number;
currentStepIndicatorSize?: number;
separatorStrokeWidth?: number;
separatorStrokeUnfinishedWidth?: number;
separatorStrokeFinishedWidth?: number;
currentStepStrokeWidth: number;
stepStrokeWidth?: number;
stepStrokeCurrentColor?: string;
stepStrokeFinishedColor: string;
stepStrokeUnFinishedColor: string;
separatorFinishedColor: string;
separatorUnFinishedColor: string;
stepIndicatorFinishedColor: string;
stepIndicatorUnFinishedColor: string;
stepIndicatorCurrentColor: string;
stepIndicatorLabelFontSize: number;
currentStepIndicatorLabelFontSize?: number;
stepIndicatorLabelCurrentColor: string;
stepIndicatorLabelFinishedColor: string;
stepIndicatorLabelUnFinishedColor: string;
labelColor?: string;
labelSize?: number;
labelAlign?: string;
currentStepLabelColor?: string;
labelFontFamily?: string;
}
type Props = {
stepCount: number;
currentPosition: number;
customStyles: CustomStyles;
};
type State = {
width: number;
height: number;
progressBarSize: number;
customStyles: CustomStyles;
};
export default class StepIndicator extends Component<Props, State> {
constructor(props: Props) {
super(props);
const defaultStyles = {
stepIndicatorSize: 30,
currentStepIndicatorSize: 40,
separatorStrokeWidth: 3,
separatorStrokeUnfinishedWidth: 0,
separatorStrokeFinishedWidth: 0,
currentStepStrokeWidth: 5,
stepStrokeWidth: 0,
stepStrokeCurrentColor: "#4aae4f",
stepStrokeFinishedColor: "#4aae4f",
stepStrokeUnFinishedColor: "#4aae4f",
separatorFinishedColor: "#4aae4f",
separatorUnFinishedColor: "#a4d4a5",
stepIndicatorFinishedColor: "#4aae4f",
stepIndicatorUnFinishedColor: "#a4d4a5",
stepIndicatorCurrentColor: "#ffffff",
stepIndicatorLabelFontSize: 15,
currentStepIndicatorLabelFontSize: 15,
stepIndicatorLabelCurrentColor: "#000000",
stepIndicatorLabelFinishedColor: "#ffffff",
stepIndicatorLabelUnFinishedColor: "rgba(255,255,255,0.5)",
labelColor: "#000000",
labelSize: 13,
labelAlign: "center",
currentStepLabelColor: "#4aae4f",
};
const customStyles = Object.assign(defaultStyles, props.customStyles);
this.state = {
width: 0,
height: 1,
progressBarSize: -2,
customStyles,
};
this.progressAnim = new Animated.Value(0);
this.sizeAnim = new Animated.Value(
this.state.customStyles.stepIndicatorSize
);
this.borderRadiusAnim = new Animated.Value(
this.state.customStyles.stepIndicatorSize / 2
);
}
stepPressed(position) {
if (this.props.onPress) {
this.props.onPress(position);
}
}
render() {
const { labels, direction } = this.props;
return (
<View
style={[
styles.container,
direction === "vertical"
? { flexDirection: "row", flex: 1 }
: { flexDirection: "column" },
]}
>
{this.state.width !== 0 && this.renderProgressBarBackground()}
{this.state.width !== 0 && this.renderProgressBar()}
{this.renderStepIndicator()}
{labels && this.renderStepLabels()}
</View>
);
}
componentDidUpdate(prevProps) {
// if (prevProps.customStyles !== this.props.customStyles) {
// this.setState((state) => ({
// customStyles: Object.assign(
// state.customStyles,
// this.props.customStyles
// ),
// }));
// }
if (prevProps.currentPosition !== this.props.currentPosition) {
this.onCurrentPositionChanged(this.props.currentPosition);
}
}
renderProgressBarBackground = () => {
const { stepCount, direction } = this.props;
let progressBarBackgroundStyle;
if (direction === "vertical") {
progressBarBackgroundStyle = {
backgroundColor: this.state.customStyles.separatorUnFinishedColor,
position: "absolute",
left:
(this.state.width - this.state.customStyles.separatorStrokeWidth) / 2,
top: this.state.height / (2 * stepCount),
bottom: this.state.height / (2 * stepCount),
width:
this.state.customStyles.separatorStrokeUnfinishedWidth === 0
? this.state.customStyles.separatorStrokeWidth
: this.state.customStyles.separatorStrokeUnfinishedWidth,
};
} else {
progressBarBackgroundStyle = {
backgroundColor: this.state.customStyles.separatorUnFinishedColor,
position: "absolute",
top:
(this.state.height - this.state.customStyles.separatorStrokeWidth) /
2,
left: this.state.width / (2 * stepCount),
right: this.state.width / (2 * stepCount),
height:
this.state.customStyles.separatorStrokeUnfinishedWidth === 0
? this.state.customStyles.separatorStrokeWidth
: this.state.customStyles.separatorStrokeUnfinishedWidth,
};
}
return (
<View
onLayout={(event) => {
if (direction === "vertical") {
this.setState(
{ progressBarSize: event.nativeEvent.layout.height },
() => {
this.onCurrentPositionChanged(this.props.currentPosition);
}
);
} else {
this.setState(
{ progressBarSize: event.nativeEvent.layout.width },
() => {
this.onCurrentPositionChanged(this.props.currentPosition);
}
);
}
}}
style={progressBarBackgroundStyle}
/>
);
};
renderProgressBar = () => {
const { stepCount, direction } = this.props;
let progressBarStyle;
if (direction === "vertical") {
progressBarStyle = {
backgroundColor: this.state.customStyles.separatorFinishedColor,
position: "absolute",
left:
(this.state.width - this.state.customStyles.separatorStrokeWidth) / 2,
top: this.state.height / (2 * stepCount),
bottom: this.state.height / (2 * stepCount),
width:
this.state.customStyles.separatorStrokeFinishedWidth === 0
? this.state.customStyles.separatorStrokeWidth
: this.state.customStyles.separatorStrokeFinishedWidth,
height: this.progressAnim,
};
} else {
progressBarStyle = {
backgroundColor: this.state.customStyles.separatorFinishedColor,
position: "absolute",
top:
(this.state.height - this.state.customStyles.separatorStrokeWidth) /
2,
left: this.state.width / (2 * stepCount),
right: this.state.width / (2 * stepCount),
height:
this.state.customStyles.separatorStrokeFinishedWidth === 0
? this.state.customStyles.separatorStrokeWidth
: this.state.customStyles.separatorStrokeFinishedWidth,
width: this.progressAnim,
};
}
return <Animated.View style={progressBarStyle} />;
};
renderStepIndicator = () => {
let steps = [];
const { stepCount, direction } = this.props;
for (let position = 0; position < stepCount; position++) {
steps.push(
<TouchableWithoutFeedback
key={position}
onPress={() => this.stepPressed(position)}
>
<View
style={[
styles.stepContainer,
direction === "vertical"
? { flexDirection: "column" }
: { flexDirection: "row" },
]}
>
{this.renderStep(position)}
</View>
</TouchableWithoutFeedback>
);
}
return (
<View
onLayout={(event) =>
this.setState({
width: event.nativeEvent.layout.width,
height: event.nativeEvent.layout.height,
})
}
style={[
styles.stepIndicatorContainer,
direction === "vertical"
? {
flexDirection: "column",
width: this.state.customStyles.currentStepIndicatorSize,
}
: {
flexDirection: "row",
height: this.state.customStyles.currentStepIndicatorSize,
},
]}
>
{steps}
</View>
);
};
renderStepLabels = () => {
const { labels, direction, currentPosition, renderLabel } = this.props;
var labelViews = labels.map((label, index) => {
const selectedStepLabelStyle =
index === currentPosition
? { color: this.state.customStyles.currentStepLabelColor }
: { color: this.state.customStyles.labelColor };
return (
<TouchableWithoutFeedback
style={styles.stepLabelItem}
key={index}
onPress={() => this.stepPressed(index)}
>
<View style={styles.stepLabelItem}>
{renderLabel ? (
renderLabel({
position: index,
stepStatus: this.getStepStatus(index),
label,
currentPosition,
})
) : (
<Text
style={[
styles.stepLabel,
selectedStepLabelStyle,
{
fontSize: this.state.customStyles.labelSize,
fontFamily: this.state.customStyles.labelFontFamily,
},
]}
>
{label}
</Text>
)}
</View>
</TouchableWithoutFeedback>
);
});
return (
<View
style={[
styles.stepLabelsContainer,
direction === "vertical"
? { flexDirection: "column", paddingHorizontal: 4 }
: { flexDirection: "row", paddingVertical: 4 },
{ alignItems: this.state.customStyles.labelAlign },
]}
>
{labelViews}
</View>
);
};
renderStep = (position) => {
const { renderStepIndicator } = this.props;
let stepStyle;
let indicatorLabelStyle;
switch (this.getStepStatus(position)) {
case STEP_STATUS.CURRENT: {
stepStyle = {
backgroundColor: this.state.customStyles.stepIndicatorCurrentColor,
borderWidth: this.state.customStyles.currentStepStrokeWidth,
borderColor: this.state.customStyles.stepStrokeCurrentColor,
height: this.sizeAnim,
width: this.sizeAnim,
borderRadius: this.borderRadiusAnim,
};
indicatorLabelStyle = {
fontSize: this.state.customStyles.currentStepIndicatorLabelFontSize,
color: this.state.customStyles.stepIndicatorLabelCurrentColor,
};
break;
}
case STEP_STATUS.FINISHED: {
stepStyle = {
backgroundColor: this.state.customStyles.stepIndicatorFinishedColor,
borderWidth: this.state.customStyles.stepStrokeWidth,
borderColor: this.state.customStyles.stepStrokeFinishedColor,
height: this.state.customStyles.stepIndicatorSize,
width: this.state.customStyles.stepIndicatorSize,
borderRadius: this.state.customStyles.stepIndicatorSize / 2,
};
indicatorLabelStyle = {
fontSize: this.state.customStyles.stepIndicatorLabelFontSize,
color: this.state.customStyles.stepIndicatorLabelFinishedColor,
};
break;
}
case STEP_STATUS.UNFINISHED: {
stepStyle = {
backgroundColor: this.state.customStyles.stepIndicatorUnFinishedColor,
borderWidth: this.state.customStyles.stepStrokeWidth,
borderColor: this.state.customStyles.stepStrokeUnFinishedColor,
height: this.state.customStyles.stepIndicatorSize,
width: this.state.customStyles.stepIndicatorSize,
borderRadius: this.state.customStyles.stepIndicatorSize / 2,
};
indicatorLabelStyle = {
overflow: "hidden",
fontSize: this.state.customStyles.stepIndicatorLabelFontSize,
color: this.state.customStyles.stepIndicatorLabelUnFinishedColor,
};
break;
}
default:
}
return (
<Animated.View key={"step-indicator"} style={[styles.step, stepStyle]}>
{renderStepIndicator ? (
renderStepIndicator({
position,
stepStatus: this.getStepStatus(position),
})
) : (
<Text style={indicatorLabelStyle}>{`${position + 1}`}</Text>
)}
</Animated.View>
);
};
getStepStatus = (stepPosition) => {
const { currentPosition } = this.props;
if (stepPosition === currentPosition) {
return STEP_STATUS.CURRENT;
} else if (stepPosition < currentPosition) {
return STEP_STATUS.FINISHED;
} else {
return STEP_STATUS.UNFINISHED;
}
};
onCurrentPositionChanged = (position) => {
let { stepCount } = this.props;
if (position > stepCount - 1) {
position = stepCount - 1;
}
const animateToPosition =
(this.state.progressBarSize / (stepCount - 1)) * position;
this.sizeAnim.setValue(this.state.customStyles.stepIndicatorSize);
this.borderRadiusAnim.setValue(
this.state.customStyles.stepIndicatorSize / 2
);
Animated.sequence([
Animated.timing(this.progressAnim, {
toValue: animateToPosition,
duration: 200,
}),
Animated.parallel([
Animated.timing(this.sizeAnim, {
toValue: this.state.customStyles.currentStepIndicatorSize,
duration: 100,
}),
Animated.timing(this.borderRadiusAnim, {
toValue: this.state.customStyles.currentStepIndicatorSize / 2,
duration: 100,
}),
]),
]).start();
};
}
const styles = StyleSheet.create({
container: {
backgroundColor: "transparent",
},
stepIndicatorContainer: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-around",
backgroundColor: "transparent",
},
stepLabelsContainer: {
justifyContent: "space-around",
},
step: {
alignItems: "center",
justifyContent: "center",
zIndex: 2,
},
stepContainer: {
flex: 1,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
stepLabel: {
fontSize: 12,
textAlign: "center",
fontWeight: "500",
},
stepLabelItem: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
});
StepIndicator.defaultProps = {
currentPosition: 0,
stepCount: 5,
customStyles: {},
direction: "horizontal",
}; | the_stack |
import { IParsingState, IDcsHandler, IEscapeSequenceParser, IParams, IOscHandler, IHandlerCollection, CsiHandlerType, OscFallbackHandlerType, IOscParser, EscHandlerType, IDcsParser, DcsFallbackHandlerType, IFunctionIdentifier, ExecuteFallbackHandlerType, CsiFallbackHandlerType, EscFallbackHandlerType, PrintHandlerType, PrintFallbackHandlerType, ExecuteHandlerType, IParserStackState, ParserStackType, ResumableHandlersType } from 'common/parser/Types';
import { ParserState, ParserAction } from 'common/parser/Constants';
import { Disposable } from 'common/Lifecycle';
import { IDisposable } from 'common/Types';
import { fill } from 'common/TypedArrayUtils';
import { Params } from 'common/parser/Params';
import { OscParser } from 'common/parser/OscParser';
import { DcsParser } from 'common/parser/DcsParser';
/**
* Table values are generated like this:
* index: currentState << TableValue.INDEX_STATE_SHIFT | charCode
* value: action << TableValue.TRANSITION_ACTION_SHIFT | nextState
*/
const enum TableAccess {
TRANSITION_ACTION_SHIFT = 4,
TRANSITION_STATE_MASK = 15,
INDEX_STATE_SHIFT = 8
}
/**
* Transition table for EscapeSequenceParser.
*/
export class TransitionTable {
public table: Uint8Array;
constructor(length: number) {
this.table = new Uint8Array(length);
}
/**
* Set default transition.
* @param action default action
* @param next default next state
*/
public setDefault(action: ParserAction, next: ParserState): void {
fill(this.table, action << TableAccess.TRANSITION_ACTION_SHIFT | next);
}
/**
* Add a transition to the transition table.
* @param code input character code
* @param state current parser state
* @param action parser action to be done
* @param next next parser state
*/
public add(code: number, state: ParserState, action: ParserAction, next: ParserState): void {
this.table[state << TableAccess.INDEX_STATE_SHIFT | code] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
}
/**
* Add transitions for multiple input character codes.
* @param codes input character code array
* @param state current parser state
* @param action parser action to be done
* @param next next parser state
*/
public addMany(codes: number[], state: ParserState, action: ParserAction, next: ParserState): void {
for (let i = 0; i < codes.length; i++) {
this.table[state << TableAccess.INDEX_STATE_SHIFT | codes[i]] = action << TableAccess.TRANSITION_ACTION_SHIFT | next;
}
}
}
// Pseudo-character placeholder for printable non-ascii characters (unicode).
const NON_ASCII_PRINTABLE = 0xA0;
/**
* VT500 compatible transition table.
* Taken from https://vt100.net/emu/dec_ansi_parser.
*/
export const VT500_TRANSITION_TABLE = (function (): TransitionTable {
const table: TransitionTable = new TransitionTable(4095);
// range macro for byte
const BYTE_VALUES = 256;
const blueprint = Array.apply(null, Array(BYTE_VALUES)).map((unused: any, i: number) => i);
const r = (start: number, end: number): number[] => blueprint.slice(start, end);
// Default definitions.
const PRINTABLES = r(0x20, 0x7f); // 0x20 (SP) included, 0x7F (DEL) excluded
const EXECUTABLES = r(0x00, 0x18);
EXECUTABLES.push(0x19);
EXECUTABLES.push.apply(EXECUTABLES, r(0x1c, 0x20));
const states: number[] = r(ParserState.GROUND, ParserState.DCS_PASSTHROUGH + 1);
let state: any;
// set default transition
table.setDefault(ParserAction.ERROR, ParserState.GROUND);
// printables
table.addMany(PRINTABLES, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
// global anywhere rules
for (state in states) {
table.addMany([0x18, 0x1a, 0x99, 0x9a], state, ParserAction.EXECUTE, ParserState.GROUND);
table.addMany(r(0x80, 0x90), state, ParserAction.EXECUTE, ParserState.GROUND);
table.addMany(r(0x90, 0x98), state, ParserAction.EXECUTE, ParserState.GROUND);
table.add(0x9c, state, ParserAction.IGNORE, ParserState.GROUND); // ST as terminator
table.add(0x1b, state, ParserAction.CLEAR, ParserState.ESCAPE); // ESC
table.add(0x9d, state, ParserAction.OSC_START, ParserState.OSC_STRING); // OSC
table.addMany([0x98, 0x9e, 0x9f], state, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
table.add(0x9b, state, ParserAction.CLEAR, ParserState.CSI_ENTRY); // CSI
table.add(0x90, state, ParserAction.CLEAR, ParserState.DCS_ENTRY); // DCS
}
// rules for executables and 7f
table.addMany(EXECUTABLES, ParserState.GROUND, ParserAction.EXECUTE, ParserState.GROUND);
table.addMany(EXECUTABLES, ParserState.ESCAPE, ParserAction.EXECUTE, ParserState.ESCAPE);
table.add(0x7f, ParserState.ESCAPE, ParserAction.IGNORE, ParserState.ESCAPE);
table.addMany(EXECUTABLES, ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
table.addMany(EXECUTABLES, ParserState.CSI_ENTRY, ParserAction.EXECUTE, ParserState.CSI_ENTRY);
table.add(0x7f, ParserState.CSI_ENTRY, ParserAction.IGNORE, ParserState.CSI_ENTRY);
table.addMany(EXECUTABLES, ParserState.CSI_PARAM, ParserAction.EXECUTE, ParserState.CSI_PARAM);
table.add(0x7f, ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_PARAM);
table.addMany(EXECUTABLES, ParserState.CSI_IGNORE, ParserAction.EXECUTE, ParserState.CSI_IGNORE);
table.addMany(EXECUTABLES, ParserState.CSI_INTERMEDIATE, ParserAction.EXECUTE, ParserState.CSI_INTERMEDIATE);
table.add(0x7f, ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_INTERMEDIATE);
table.addMany(EXECUTABLES, ParserState.ESCAPE_INTERMEDIATE, ParserAction.EXECUTE, ParserState.ESCAPE_INTERMEDIATE);
table.add(0x7f, ParserState.ESCAPE_INTERMEDIATE, ParserAction.IGNORE, ParserState.ESCAPE_INTERMEDIATE);
// osc
table.add(0x5d, ParserState.ESCAPE, ParserAction.OSC_START, ParserState.OSC_STRING);
table.addMany(PRINTABLES, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
table.add(0x7f, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
table.addMany([0x9c, 0x1b, 0x18, 0x1a, 0x07], ParserState.OSC_STRING, ParserAction.OSC_END, ParserState.GROUND);
table.addMany(r(0x1c, 0x20), ParserState.OSC_STRING, ParserAction.IGNORE, ParserState.OSC_STRING);
// sos/pm/apc does nothing
table.addMany([0x58, 0x5e, 0x5f], ParserState.ESCAPE, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
table.addMany(PRINTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
table.addMany(EXECUTABLES, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
table.add(0x9c, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.GROUND);
table.add(0x7f, ParserState.SOS_PM_APC_STRING, ParserAction.IGNORE, ParserState.SOS_PM_APC_STRING);
// csi entries
table.add(0x5b, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.CSI_ENTRY);
table.addMany(r(0x40, 0x7f), ParserState.CSI_ENTRY, ParserAction.CSI_DISPATCH, ParserState.GROUND);
table.addMany(r(0x30, 0x3c), ParserState.CSI_ENTRY, ParserAction.PARAM, ParserState.CSI_PARAM);
table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_PARAM);
table.addMany(r(0x30, 0x3c), ParserState.CSI_PARAM, ParserAction.PARAM, ParserState.CSI_PARAM);
table.addMany(r(0x40, 0x7f), ParserState.CSI_PARAM, ParserAction.CSI_DISPATCH, ParserState.GROUND);
table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.CSI_PARAM, ParserAction.IGNORE, ParserState.CSI_IGNORE);
table.addMany(r(0x20, 0x40), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
table.add(0x7f, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
table.addMany(r(0x40, 0x7f), ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.GROUND);
table.addMany(r(0x20, 0x30), ParserState.CSI_ENTRY, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
table.addMany(r(0x20, 0x30), ParserState.CSI_INTERMEDIATE, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
table.addMany(r(0x30, 0x40), ParserState.CSI_INTERMEDIATE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
table.addMany(r(0x40, 0x7f), ParserState.CSI_INTERMEDIATE, ParserAction.CSI_DISPATCH, ParserState.GROUND);
table.addMany(r(0x20, 0x30), ParserState.CSI_PARAM, ParserAction.COLLECT, ParserState.CSI_INTERMEDIATE);
// esc_intermediate
table.addMany(r(0x20, 0x30), ParserState.ESCAPE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
table.addMany(r(0x20, 0x30), ParserState.ESCAPE_INTERMEDIATE, ParserAction.COLLECT, ParserState.ESCAPE_INTERMEDIATE);
table.addMany(r(0x30, 0x7f), ParserState.ESCAPE_INTERMEDIATE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
table.addMany(r(0x30, 0x50), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
table.addMany(r(0x51, 0x58), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
table.addMany([0x59, 0x5a, 0x5c], ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
table.addMany(r(0x60, 0x7f), ParserState.ESCAPE, ParserAction.ESC_DISPATCH, ParserState.GROUND);
// dcs entry
table.add(0x50, ParserState.ESCAPE, ParserAction.CLEAR, ParserState.DCS_ENTRY);
table.addMany(EXECUTABLES, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
table.add(0x7f, ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
table.addMany(r(0x1c, 0x20), ParserState.DCS_ENTRY, ParserAction.IGNORE, ParserState.DCS_ENTRY);
table.addMany(r(0x20, 0x30), ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
table.addMany(r(0x30, 0x3c), ParserState.DCS_ENTRY, ParserAction.PARAM, ParserState.DCS_PARAM);
table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_ENTRY, ParserAction.COLLECT, ParserState.DCS_PARAM);
table.addMany(EXECUTABLES, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.addMany(r(0x20, 0x80), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.addMany(r(0x1c, 0x20), ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.addMany(EXECUTABLES, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
table.add(0x7f, ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
table.addMany(r(0x1c, 0x20), ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_PARAM);
table.addMany(r(0x30, 0x3c), ParserState.DCS_PARAM, ParserAction.PARAM, ParserState.DCS_PARAM);
table.addMany([0x3c, 0x3d, 0x3e, 0x3f], ParserState.DCS_PARAM, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.addMany(r(0x20, 0x30), ParserState.DCS_PARAM, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
table.addMany(EXECUTABLES, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
table.add(0x7f, ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
table.addMany(r(0x1c, 0x20), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_INTERMEDIATE);
table.addMany(r(0x20, 0x30), ParserState.DCS_INTERMEDIATE, ParserAction.COLLECT, ParserState.DCS_INTERMEDIATE);
table.addMany(r(0x30, 0x40), ParserState.DCS_INTERMEDIATE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.addMany(r(0x40, 0x7f), ParserState.DCS_INTERMEDIATE, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
table.addMany(r(0x40, 0x7f), ParserState.DCS_PARAM, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
table.addMany(r(0x40, 0x7f), ParserState.DCS_ENTRY, ParserAction.DCS_HOOK, ParserState.DCS_PASSTHROUGH);
table.addMany(EXECUTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
table.addMany(PRINTABLES, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
table.add(0x7f, ParserState.DCS_PASSTHROUGH, ParserAction.IGNORE, ParserState.DCS_PASSTHROUGH);
table.addMany([0x1b, 0x9c, 0x18, 0x1a], ParserState.DCS_PASSTHROUGH, ParserAction.DCS_UNHOOK, ParserState.GROUND);
// special handling of unicode chars
table.add(NON_ASCII_PRINTABLE, ParserState.GROUND, ParserAction.PRINT, ParserState.GROUND);
table.add(NON_ASCII_PRINTABLE, ParserState.OSC_STRING, ParserAction.OSC_PUT, ParserState.OSC_STRING);
table.add(NON_ASCII_PRINTABLE, ParserState.CSI_IGNORE, ParserAction.IGNORE, ParserState.CSI_IGNORE);
table.add(NON_ASCII_PRINTABLE, ParserState.DCS_IGNORE, ParserAction.IGNORE, ParserState.DCS_IGNORE);
table.add(NON_ASCII_PRINTABLE, ParserState.DCS_PASSTHROUGH, ParserAction.DCS_PUT, ParserState.DCS_PASSTHROUGH);
return table;
})();
/**
* EscapeSequenceParser.
* This class implements the ANSI/DEC compatible parser described by
* Paul Williams (https://vt100.net/emu/dec_ansi_parser).
*
* To implement custom ANSI compliant escape sequences it is not needed to
* alter this parser, instead consider registering a custom handler.
* For non ANSI compliant sequences change the transition table with
* the optional `transitions` constructor argument and
* reimplement the `parse` method.
*
* This parser is currently hardcoded to operate in ZDM (Zero Default Mode)
* as suggested by the original parser, thus empty parameters are set to 0.
* This this is not in line with the latest ECMA-48 specification
* (ZDM was part of the early specs and got completely removed later on).
*
* Other than the original parser from vt100.net this parser supports
* sub parameters in digital parameters separated by colons. Empty sub parameters
* are set to -1 (no ZDM for sub parameters).
*
* About prefix and intermediate bytes:
* This parser follows the assumptions of the vt100.net parser with these restrictions:
* - only one prefix byte is allowed as first parameter byte, byte range 0x3c .. 0x3f
* - max. two intermediates are respected, byte range 0x20 .. 0x2f
* Note that this is not in line with ECMA-48 which does not limit either of those.
* Furthermore ECMA-48 allows the prefix byte range at any param byte position. Currently
* there are no known sequences that follow the broader definition of the specification.
*
* TODO: implement error recovery hook via error handler return values
*/
export class EscapeSequenceParser extends Disposable implements IEscapeSequenceParser {
public initialState: number;
public currentState: number;
public precedingCodepoint: number;
// buffers over several parse calls
protected _params: Params;
protected _collect: number;
// handler lookup containers
protected _printHandler: PrintHandlerType;
protected _executeHandlers: { [flag: number]: ExecuteHandlerType };
protected _csiHandlers: IHandlerCollection<CsiHandlerType>;
protected _escHandlers: IHandlerCollection<EscHandlerType>;
protected _oscParser: IOscParser;
protected _dcsParser: IDcsParser;
protected _errorHandler: (state: IParsingState) => IParsingState;
// fallback handlers
protected _printHandlerFb: PrintFallbackHandlerType;
protected _executeHandlerFb: ExecuteFallbackHandlerType;
protected _csiHandlerFb: CsiFallbackHandlerType;
protected _escHandlerFb: EscFallbackHandlerType;
protected _errorHandlerFb: (state: IParsingState) => IParsingState;
// parser stack save for async handler support
protected _parseStack: IParserStackState = {
state: ParserStackType.NONE,
handlers: [],
handlerPos: 0,
transition: 0,
chunkPos: 0
};
constructor(
protected readonly _transitions: TransitionTable = VT500_TRANSITION_TABLE
) {
super();
this.initialState = ParserState.GROUND;
this.currentState = this.initialState;
this._params = new Params(); // defaults to 32 storable params/subparams
this._params.addParam(0); // ZDM
this._collect = 0;
this.precedingCodepoint = 0;
// set default fallback handlers and handler lookup containers
this._printHandlerFb = (data, start, end): void => { };
this._executeHandlerFb = (code: number): void => { };
this._csiHandlerFb = (ident: number, params: IParams): void => { };
this._escHandlerFb = (ident: number): void => { };
this._errorHandlerFb = (state: IParsingState): IParsingState => state;
this._printHandler = this._printHandlerFb;
this._executeHandlers = Object.create(null);
this._csiHandlers = Object.create(null);
this._escHandlers = Object.create(null);
this._oscParser = new OscParser();
this._dcsParser = new DcsParser();
this._errorHandler = this._errorHandlerFb;
// swallow 7bit ST (ESC+\)
this.registerEscHandler({ final: '\\' }, () => true);
}
protected _identifier(id: IFunctionIdentifier, finalRange: number[] = [0x40, 0x7e]): number {
let res = 0;
if (id.prefix) {
if (id.prefix.length > 1) {
throw new Error('only one byte as prefix supported');
}
res = id.prefix.charCodeAt(0);
if (res && 0x3c > res || res > 0x3f) {
throw new Error('prefix must be in range 0x3c .. 0x3f');
}
}
if (id.intermediates) {
if (id.intermediates.length > 2) {
throw new Error('only two bytes as intermediates are supported');
}
for (let i = 0; i < id.intermediates.length; ++i) {
const intermediate = id.intermediates.charCodeAt(i);
if (0x20 > intermediate || intermediate > 0x2f) {
throw new Error('intermediate must be in range 0x20 .. 0x2f');
}
res <<= 8;
res |= intermediate;
}
}
if (id.final.length !== 1) {
throw new Error('final must be a single byte');
}
const finalCode = id.final.charCodeAt(0);
if (finalRange[0] > finalCode || finalCode > finalRange[1]) {
throw new Error(`final must be in range ${finalRange[0]} .. ${finalRange[1]}`);
}
res <<= 8;
res |= finalCode;
return res;
}
public identToString(ident: number): string {
const res: string[] = [];
while (ident) {
res.push(String.fromCharCode(ident & 0xFF));
ident >>= 8;
}
return res.reverse().join('');
}
public dispose(): void {
this._csiHandlers = Object.create(null);
this._executeHandlers = Object.create(null);
this._escHandlers = Object.create(null);
this._oscParser.dispose();
this._dcsParser.dispose();
}
public setPrintHandler(handler: PrintHandlerType): void {
this._printHandler = handler;
}
public clearPrintHandler(): void {
this._printHandler = this._printHandlerFb;
}
public registerEscHandler(id: IFunctionIdentifier, handler: EscHandlerType): IDisposable {
const ident = this._identifier(id, [0x30, 0x7e]);
if (this._escHandlers[ident] === undefined) {
this._escHandlers[ident] = [];
}
const handlerList = this._escHandlers[ident];
handlerList.push(handler);
return {
dispose: () => {
const handlerIndex = handlerList.indexOf(handler);
if (handlerIndex !== -1) {
handlerList.splice(handlerIndex, 1);
}
}
};
}
public clearEscHandler(id: IFunctionIdentifier): void {
if (this._escHandlers[this._identifier(id, [0x30, 0x7e])]) delete this._escHandlers[this._identifier(id, [0x30, 0x7e])];
}
public setEscHandlerFallback(handler: EscFallbackHandlerType): void {
this._escHandlerFb = handler;
}
public setExecuteHandler(flag: string, handler: ExecuteHandlerType): void {
this._executeHandlers[flag.charCodeAt(0)] = handler;
}
public clearExecuteHandler(flag: string): void {
if (this._executeHandlers[flag.charCodeAt(0)]) delete this._executeHandlers[flag.charCodeAt(0)];
}
public setExecuteHandlerFallback(handler: ExecuteFallbackHandlerType): void {
this._executeHandlerFb = handler;
}
public registerCsiHandler(id: IFunctionIdentifier, handler: CsiHandlerType): IDisposable {
const ident = this._identifier(id);
if (this._csiHandlers[ident] === undefined) {
this._csiHandlers[ident] = [];
}
const handlerList = this._csiHandlers[ident];
handlerList.push(handler);
return {
dispose: () => {
const handlerIndex = handlerList.indexOf(handler);
if (handlerIndex !== -1) {
handlerList.splice(handlerIndex, 1);
}
}
};
}
public clearCsiHandler(id: IFunctionIdentifier): void {
if (this._csiHandlers[this._identifier(id)]) delete this._csiHandlers[this._identifier(id)];
}
public setCsiHandlerFallback(callback: (ident: number, params: IParams) => void): void {
this._csiHandlerFb = callback;
}
public registerDcsHandler(id: IFunctionIdentifier, handler: IDcsHandler): IDisposable {
return this._dcsParser.registerHandler(this._identifier(id), handler);
}
public clearDcsHandler(id: IFunctionIdentifier): void {
this._dcsParser.clearHandler(this._identifier(id));
}
public setDcsHandlerFallback(handler: DcsFallbackHandlerType): void {
this._dcsParser.setHandlerFallback(handler);
}
public registerOscHandler(ident: number, handler: IOscHandler): IDisposable {
return this._oscParser.registerHandler(ident, handler);
}
public clearOscHandler(ident: number): void {
this._oscParser.clearHandler(ident);
}
public setOscHandlerFallback(handler: OscFallbackHandlerType): void {
this._oscParser.setHandlerFallback(handler);
}
public setErrorHandler(callback: (state: IParsingState) => IParsingState): void {
this._errorHandler = callback;
}
public clearErrorHandler(): void {
this._errorHandler = this._errorHandlerFb;
}
/**
* Reset parser to initial values.
*
* This can also be used to lift the improper continuation error condition
* when dealing with async handlers. Use this only as a last resort to silence
* that error when the terminal has no pending data to be processed. Note that
* the interrupted async handler might continue its work in the future messing
* up the terminal state even further.
*/
public reset(): void {
this.currentState = this.initialState;
this._oscParser.reset();
this._dcsParser.reset();
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
this.precedingCodepoint = 0;
// abort pending continuation from async handler
// Here the RESET type indicates, that the next parse call will
// ignore any saved stack, instead continues sync with next codepoint from GROUND
if (this._parseStack.state !== ParserStackType.NONE) {
this._parseStack.state = ParserStackType.RESET;
this._parseStack.handlers = []; // also release handlers ref
}
}
/**
* Async parse support.
*/
protected _preserveStack(
state: ParserStackType,
handlers: ResumableHandlersType,
handlerPos: number,
transition: number,
chunkPos: number
): void {
this._parseStack.state = state;
this._parseStack.handlers = handlers;
this._parseStack.handlerPos = handlerPos;
this._parseStack.transition = transition;
this._parseStack.chunkPos = chunkPos;
}
/**
* Parse UTF32 codepoints in `data` up to `length`.
*
* Note: For several actions with high data load the parsing is optimized
* by using local read ahead loops with hardcoded conditions to
* avoid costly table lookups. Make sure that any change of table values
* will be reflected in the loop conditions as well and vice versa.
* Affected states/actions:
* - GROUND:PRINT
* - CSI_PARAM:PARAM
* - DCS_PARAM:PARAM
* - OSC_STRING:OSC_PUT
* - DCS_PASSTHROUGH:DCS_PUT
*
* Note on asynchronous handler support:
* Any handler returning a promise will be treated as asynchronous.
* To keep the in-band blocking working for async handlers, `parse` pauses execution,
* creates a stack save and returns the promise to the caller.
* For proper continuation of the paused state it is important
* to await the promise resolving. On resolve the parse must be repeated
* with the same chunk of data and the resolved value in `promiseResult`
* until no promise is returned.
*
* Important: With only sync handlers defined, parsing is completely synchronous as well.
* As soon as an async handler is involved, synchronous parsing is not possible anymore.
*
* Boilerplate for proper parsing of multiple chunks with async handlers:
*
* ```typescript
* async function parseMultipleChunks(chunks: Uint32Array[]): Promise<void> {
* for (const chunk of chunks) {
* let result: void | Promise<boolean>;
* let prev: boolean | undefined;
* while (result = parser.parse(chunk, chunk.length, prev)) {
* prev = await result;
* }
* }
* // finished parsing all chunks...
* }
* ```
*/
public parse(data: Uint32Array, length: number, promiseResult?: boolean): void | Promise<boolean> {
let code = 0;
let transition = 0;
let start = 0;
let handlerResult: void | boolean | Promise<boolean>;
// resume from async handler
if (this._parseStack.state) {
// allow sync parser reset even in continuation mode
// Note: can be used to recover parser from improper continuation error below
if (this._parseStack.state === ParserStackType.RESET) {
this._parseStack.state = ParserStackType.NONE;
start = this._parseStack.chunkPos + 1; // continue with next codepoint in GROUND
} else {
if (promiseResult === undefined || this._parseStack.state === ParserStackType.FAIL) {
/**
* Reject further parsing on improper continuation after pausing.
* This is a really bad condition with screwed up execution order and prolly messed up
* terminal state, therefore we exit hard with an exception and reject any further parsing.
*
* Note: With `Terminal.write` usage this exception should never occur, as the top level
* calls are guaranteed to handle async conditions properly. If you ever encounter this
* exception in your terminal integration it indicates, that you injected data chunks to
* `InputHandler.parse` or `EscapeSequenceParser.parse` synchronously without waiting for
* continuation of a running async handler.
*
* It is possible to get rid of this error by calling `reset`. But dont rely on that,
* as the pending async handler still might mess up the terminal later. Instead fix the faulty
* async handling, so this error will not be thrown anymore.
*/
this._parseStack.state = ParserStackType.FAIL;
throw new Error('improper continuation due to previous async handler, giving up parsing');
}
// we have to resume the old handler loop if:
// - return value of the promise was `false`
// - handlers are not exhausted yet
const handlers = this._parseStack.handlers;
let handlerPos = this._parseStack.handlerPos - 1;
switch (this._parseStack.state) {
case ParserStackType.CSI:
if (promiseResult === false && handlerPos > -1) {
for (; handlerPos >= 0; handlerPos--) {
handlerResult = (handlers as CsiHandlerType[])[handlerPos](this._params);
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.handlerPos = handlerPos;
return handlerResult;
}
}
}
this._parseStack.handlers = [];
break;
case ParserStackType.ESC:
if (promiseResult === false && handlerPos > -1) {
for (; handlerPos >= 0; handlerPos--) {
handlerResult = (handlers as EscHandlerType[])[handlerPos]();
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._parseStack.handlerPos = handlerPos;
return handlerResult;
}
}
}
this._parseStack.handlers = [];
break;
case ParserStackType.DCS:
code = data[this._parseStack.chunkPos];
handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a, promiseResult);
if (handlerResult) {
return handlerResult;
}
if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
break;
case ParserStackType.OSC:
code = data[this._parseStack.chunkPos];
handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a, promiseResult);
if (handlerResult) {
return handlerResult;
}
if (code === 0x1b) this._parseStack.transition |= ParserState.ESCAPE;
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
break;
}
// cleanup before continuing with the main sync loop
this._parseStack.state = ParserStackType.NONE;
start = this._parseStack.chunkPos + 1;
this.precedingCodepoint = 0;
this.currentState = this._parseStack.transition & TableAccess.TRANSITION_STATE_MASK;
}
}
// continue with main sync loop
// process input string
for (let i = start; i < length; ++i) {
code = data[i];
// normal transition & action lookup
transition = this._transitions.table[this.currentState << TableAccess.INDEX_STATE_SHIFT | (code < 0xa0 ? code : NON_ASCII_PRINTABLE)];
switch (transition >> TableAccess.TRANSITION_ACTION_SHIFT) {
case ParserAction.PRINT:
// read ahead with loop unrolling
// Note: 0x20 (SP) is included, 0x7F (DEL) is excluded
for (let j = i + 1; ; ++j) {
if (j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
this._printHandler(data, i, j);
i = j - 1;
break;
}
if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
this._printHandler(data, i, j);
i = j - 1;
break;
}
if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
this._printHandler(data, i, j);
i = j - 1;
break;
}
if (++j >= length || (code = data[j]) < 0x20 || (code > 0x7e && code < NON_ASCII_PRINTABLE)) {
this._printHandler(data, i, j);
i = j - 1;
break;
}
}
break;
case ParserAction.EXECUTE:
if (this._executeHandlers[code]) this._executeHandlers[code]();
else this._executeHandlerFb(code);
this.precedingCodepoint = 0;
break;
case ParserAction.IGNORE:
break;
case ParserAction.ERROR:
const inject: IParsingState = this._errorHandler(
{
position: i,
code,
currentState: this.currentState,
collect: this._collect,
params: this._params,
abort: false
});
if (inject.abort) return;
// inject values: currently not implemented
break;
case ParserAction.CSI_DISPATCH:
// Trigger CSI Handler
const handlers = this._csiHandlers[this._collect << 8 | code];
let j = handlers ? handlers.length - 1 : -1;
for (; j >= 0; j--) {
// true means success and to stop bubbling
// a promise indicates an async handler that needs to finish before progressing
handlerResult = handlers[j](this._params);
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._preserveStack(ParserStackType.CSI, handlers, j, transition, i);
return handlerResult;
}
}
if (j < 0) {
this._csiHandlerFb(this._collect << 8 | code, this._params);
}
this.precedingCodepoint = 0;
break;
case ParserAction.PARAM:
// inner loop: digits (0x30 - 0x39) and ; (0x3b) and : (0x3a)
do {
switch (code) {
case 0x3b:
this._params.addParam(0); // ZDM
break;
case 0x3a:
this._params.addSubParam(-1);
break;
default: // 0x30 - 0x39
this._params.addDigit(code - 48);
}
} while (++i < length && (code = data[i]) > 0x2f && code < 0x3c);
i--;
break;
case ParserAction.COLLECT:
this._collect <<= 8;
this._collect |= code;
break;
case ParserAction.ESC_DISPATCH:
const handlersEsc = this._escHandlers[this._collect << 8 | code];
let jj = handlersEsc ? handlersEsc.length - 1 : -1;
for (; jj >= 0; jj--) {
// true means success and to stop bubbling
// a promise indicates an async handler that needs to finish before progressing
handlerResult = handlersEsc[jj]();
if (handlerResult === true) {
break;
} else if (handlerResult instanceof Promise) {
this._preserveStack(ParserStackType.ESC, handlersEsc, jj, transition, i);
return handlerResult;
}
}
if (jj < 0) {
this._escHandlerFb(this._collect << 8 | code);
}
this.precedingCodepoint = 0;
break;
case ParserAction.CLEAR:
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
break;
case ParserAction.DCS_HOOK:
this._dcsParser.hook(this._collect << 8 | code, this._params);
break;
case ParserAction.DCS_PUT:
// inner loop - exit DCS_PUT: 0x18, 0x1a, 0x1b, 0x7f, 0x80 - 0x9f
// unhook triggered by: 0x1b, 0x9c (success) and 0x18, 0x1a (abort)
for (let j = i + 1; ; ++j) {
if (j >= length || (code = data[j]) === 0x18 || code === 0x1a || code === 0x1b || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {
this._dcsParser.put(data, i, j);
i = j - 1;
break;
}
}
break;
case ParserAction.DCS_UNHOOK:
handlerResult = this._dcsParser.unhook(code !== 0x18 && code !== 0x1a);
if (handlerResult) {
this._preserveStack(ParserStackType.DCS, [], 0, transition, i);
return handlerResult;
}
if (code === 0x1b) transition |= ParserState.ESCAPE;
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
this.precedingCodepoint = 0;
break;
case ParserAction.OSC_START:
this._oscParser.start();
break;
case ParserAction.OSC_PUT:
// inner loop: 0x20 (SP) included, 0x7F (DEL) included
for (let j = i + 1; ; j++) {
if (j >= length || (code = data[j]) < 0x20 || (code > 0x7f && code < NON_ASCII_PRINTABLE)) {
this._oscParser.put(data, i, j);
i = j - 1;
break;
}
}
break;
case ParserAction.OSC_END:
handlerResult = this._oscParser.end(code !== 0x18 && code !== 0x1a);
if (handlerResult) {
this._preserveStack(ParserStackType.OSC, [], 0, transition, i);
return handlerResult;
}
if (code === 0x1b) transition |= ParserState.ESCAPE;
this._params.reset();
this._params.addParam(0); // ZDM
this._collect = 0;
this.precedingCodepoint = 0;
break;
}
this.currentState = transition & TableAccess.TRANSITION_STATE_MASK;
}
}
} | the_stack |
import { testConfig } from 'houdini-common'
// locals
import { Cache, rootID } from '../cache'
const config = testConfig()
test('save root object', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// save the data
const data = {
viewer: {
id: '1',
firstName: 'bob',
},
}
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
data,
})
// make sure we can get back what we wrote
expect(cache.internal.getRecord(cache.id('User', data.viewer)!)?.fields).toEqual({
id: '1',
firstName: 'bob',
})
})
test('partial update existing record', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// save the data
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
data: {
viewer: {
id: '1',
firstName: 'bob',
},
},
})
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
lastName: {
type: 'String',
keyRaw: 'lastName',
},
},
},
},
data: {
viewer: {
id: '1',
lastName: 'barker',
},
},
})
// make sure we can get back what we wrote
expect(cache.internal.getRecord(cache.id('User', '1')!)?.fields).toEqual({
id: '1',
firstName: 'bob',
lastName: 'barker',
})
})
test('linked records with updates', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// save the data
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
parent: {
type: 'User',
keyRaw: 'parent',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
data: {
viewer: {
id: '1',
firstName: 'bob',
parent: {
id: '2',
firstName: 'jane',
},
},
},
})
// check user 1
const user1 = cache.internal.getRecord(cache.id('User', '1')!)
expect(user1?.fields).toEqual({
id: '1',
firstName: 'bob',
})
expect(user1?.linkedRecord('parent')?.fields).toEqual({
id: '2',
firstName: 'jane',
})
// check user 2
const user2 = cache.internal.getRecord(cache.id('User', '2')!)
expect(user2?.fields).toEqual({
id: '2',
firstName: 'jane',
})
expect(user2?.linkedRecord('parent')).toBeFalsy()
// associate user2 with a new parent
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
parent: {
type: 'User',
keyRaw: 'parent',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
data: {
viewer: {
id: '2',
firstName: 'jane-prime',
parent: {
id: '3',
firstName: 'mary',
},
},
},
})
// make sure we updated user 2
expect(user2?.fields).toEqual({
id: '2',
firstName: 'jane-prime',
})
expect(user2?.linkedRecord('parent')?.fields).toEqual({
id: '3',
firstName: 'mary',
})
})
test('linked lists', function () {
// instantiate the cache
const cache = new Cache(config)
// add some data to the cache
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary',
},
],
},
},
})
// make sure we can get the linked lists back
const friendData = cache.internal
.getRecord(cache.id('User', '1')!)
?.flatLinkedList('friends')
.map((data) => data!.fields)
expect(friendData).toEqual([
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary',
},
])
})
test('list as value with args', function () {
// instantiate the cache
const cache = new Cache(config)
// add some data to the cache
cache.write({
selection: {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
favoriteColors: {
type: 'String',
keyRaw: 'favoriteColors(where: "foo")',
},
},
},
},
data: {
viewer: {
id: '1',
firstName: 'bob',
favoriteColors: ['red', 'green', 'blue'],
},
},
})
// look up the value
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.fields['favoriteColors(where: "foo")']
).toEqual(['red', 'green', 'blue'])
})
test('root subscribe - field change', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
favoriteColors: {
type: 'String',
keyRaw: 'favoriteColors',
},
},
},
}
// write some data
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
favoriteColors: ['red', 'green', 'blue'],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// somehow write a user to the cache with the same id, but a different name
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'mary',
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
firstName: 'mary',
favoriteColors: ['red', 'green', 'blue'],
id: '1',
},
})
})
test('root subscribe - linked object changed', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
favoriteColors: {
type: 'String',
keyRaw: 'favoriteColors(where: "foo")',
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
favoriteColors: ['red', 'green', 'blue'],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// somehow write a user to the cache with a different id
cache.write({
selection,
data: {
viewer: {
id: '2',
firstName: 'mary',
// ignoring favoriteColors as a sanity check (should get undefined)
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
firstName: 'mary',
// this is a sanity-check. the cache wasn't written with that value
favoriteColors: undefined,
id: '2',
},
})
// make sure we are no longer subscribing to user 1
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test("subscribing to null object doesn't explode", function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
favoriteColors: {
type: 'String',
keyRaw: 'favoriteColors(where: "foo")',
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: null,
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// somehow write a user to the cache with a different id
cache.write({
selection,
data: {
viewer: {
id: '2',
firstName: 'mary',
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
firstName: 'mary',
// this is a sanity-check. the cache wasn't written with that value
favoriteColors: undefined,
id: '2',
},
})
})
test('root subscribe - linked list lost entry', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary',
},
],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// somehow write a user to the cache with a new friends list
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
},
],
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
id: '1',
friends: [
{
firstName: 'jane',
id: '2',
},
],
},
})
// we shouldn't be subscribing to user 3 any more
expect(
cache.internal.getRecord(cache.id('User', '3')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test("subscribing to list with null values doesn't explode", function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
null,
],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// somehow write a user to the cache with a new friends list
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
},
],
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
id: '1',
friends: [
{
firstName: 'jane',
id: '2',
},
],
},
})
})
test('root subscribe - linked list reorder', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary',
},
],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
set,
selection,
})
// somehow write a user to the cache with the same id, but a different name
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '3',
},
{
id: '2',
},
],
},
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
id: '1',
friends: [
{
id: '3',
firstName: 'mary',
},
{
id: '2',
firstName: 'jane',
},
],
},
})
// we should still be subscribing to both users
expect(
cache.internal.getRecord(cache.id('User', '2')!)?.getSubscribers('firstName')
).toHaveLength(1)
expect(
cache.internal.getRecord(cache.id('User', '3')!)?.getSubscribers('firstName')
).toHaveLength(1)
})
test('unsubscribe', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
favoriteColors: {
type: 'String',
keyRaw: 'favoriteColors(where: "foo")',
},
},
},
}
// write some data
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
favoriteColors: ['red', 'green', 'blue'],
},
},
})
// the spec we will register/unregister
const spec = {
rootType: 'Query',
selection,
set: jest.fn(),
}
// subscribe to the fields
cache.subscribe(spec)
// make sure we registered the subscriber
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.getSubscribers('firstName')
).toHaveLength(1)
// unsubscribe
cache.unsubscribe(spec)
// make sure there is no more subscriber
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test('subscribe to new list nodes', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
list: {
name: 'All_Users',
connection: false,
type: 'User',
},
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
set,
selection,
})
// insert an element into the list (no parent ID)
cache.list('All_Users').append(
{ id: { type: 'ID', keyRaw: 'id' }, firstName: { type: 'String', keyRaw: 'firstName' } },
{
id: '3',
firstName: 'mary',
}
)
// update the user we just added
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary-prime',
},
],
},
},
})
// the first time set was called, a new entry was added.
// the second time it's called, we get a new value for mary-prime
expect(set).toHaveBeenNthCalledWith(2, {
viewer: {
id: '1',
friends: [
{
firstName: 'jane',
id: '2',
},
{
firstName: 'mary-prime',
id: '3',
},
],
},
})
})
test('variables in query and subscription', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends(filter: $filter)',
list: {
name: 'All_Users',
connection: false,
type: 'User',
},
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
{
id: '3',
firstName: 'mary',
},
],
},
},
variables: {
filter: 'foo',
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe(
{
rootType: 'Query',
selection,
set,
variables: () => ({ filter: 'foo' }),
},
{
filter: 'foo',
}
)
// make sure we have a cached value for friends(filter: "foo")
expect(cache.list('All_Users').key).toEqual('friends(filter: "foo")')
// somehow write a user to the cache with a new friends list
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
},
],
},
},
variables: {
filter: 'foo',
},
})
// make sure that set got called with the full response
expect(set).toHaveBeenCalledWith({
viewer: {
id: '1',
friends: [
{
firstName: 'jane',
id: '2',
},
],
},
})
// we shouldn't be subscribing to user 3 any more
expect(
cache.internal.getRecord(cache.id('User', '3')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test('deleting a node removes nested subscriptions', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
list: {
name: 'All_Users',
connection: false,
type: 'User',
},
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: [
{
id: '2',
firstName: 'jane',
},
],
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe({
rootType: 'Query',
selection,
set,
})
// sanity check
expect(cache.internal.getRecord('User:2')?.getSubscribers('firstName')).toHaveLength(1)
// delete the parent
cache.delete('User', 'User:1')
// sanity check
expect(cache.internal.getRecord('User:2')?.getSubscribers('firstName')).toHaveLength(0)
})
test('same record twice in a query survives one unsubscribe (reference counting)', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
list: {
name: 'All_Users',
connection: false,
type: 'User',
},
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// start off associated with one object
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [
{
id: '1',
firstName: 'bob',
},
],
},
},
variables: {
filter: 'foo',
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe(
{
rootType: 'Query',
selection,
set,
},
{
filter: 'foo',
}
)
// make sure there is a subscriber for the user's first name
expect(cache.internal.getRecord('User:1')?.getSubscribers('firstName')).toHaveLength(1)
// remove the user from the list
cache.list('All_Users').remove({ id: '1' })
// we should still be subscribing to the user's first name
expect(cache.internal.getRecord('User:1')?.getSubscribers('firstName')).toHaveLength(1)
})
test('embedded references', function () {
// instantiate a cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
edges: {
type: 'UserEdge',
keyRaw: 'edges',
fields: {
node: {
type: 'User',
keyRaw: 'node',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
},
},
},
}
// write an embedded list of embedded objects holding references to an object
cache.write({
selection,
data: {
viewer: {
id: '1',
friends: {
edges: [
{
node: {
id: '2',
firstName: 'jane',
},
},
{
node: {
id: '3',
firstName: 'mary',
},
},
],
},
},
},
})
// a function to spy on that will play the role of set
const set = jest.fn()
// subscribe to the fields
cache.subscribe(
{
rootType: 'Query',
selection,
set,
},
{
filter: 'foo',
}
)
// update one of the embedded references
cache.write({
selection: {
user: {
type: 'User',
keyRaw: 'user',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
data: {
user: {
id: '2',
firstName: 'not-jane',
},
},
})
// make sure we got the updated data
expect(set).toHaveBeenCalledWith({
viewer: {
id: '1',
friends: {
edges: [
{
node: {
id: '2',
firstName: 'not-jane',
},
},
{
node: {
id: '3',
firstName: 'mary',
},
},
],
},
},
})
})
test('writing abstract objects', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// save the data
const data = {
viewer: {
__typename: 'User',
id: '1',
firstName: 'bob',
},
}
cache.write({
selection: {
viewer: {
type: 'Node',
abstract: true,
keyRaw: 'viewer',
fields: {
__typename: {
type: 'String',
keyRaw: '__typename',
},
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
data,
})
// make sure we can get back what we wrote
expect(cache.internal.getRecord(cache.id('User', data.viewer)!)?.fields).toEqual({
__typename: 'User',
id: '1',
firstName: 'bob',
})
})
test('writing abstract lists', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// save the data
const data = {
nodes: [
{
__typename: 'User',
id: '1',
firstName: 'bob',
},
{
__typename: 'User',
id: '2',
firstName: 'bob',
},
],
}
cache.write({
selection: {
nodes: {
type: 'Node',
abstract: true,
keyRaw: 'nodes',
fields: {
__typename: {
type: 'String',
keyRaw: '__typename',
},
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
data,
})
// make sure we can get back what we wrote
expect(cache.internal.getRecord('User:1')?.fields).toEqual({
__typename: 'User',
id: '1',
firstName: 'bob',
})
})
test('can pull enum from cached values', function () {
// instantiate a cache we'll test against
const cache = new Cache(config)
// the selection we are gonna write
const selection = {
node: {
type: 'Node',
keyRaw: 'node',
fields: {
enumValue: {
type: 'MyEnum',
keyRaw: 'enumValue',
},
id: {
type: 'ID',
keyRaw: 'id',
},
},
},
}
// save the data
const data = {
node: {
id: '1',
enumValue: 'Hello',
},
}
// write the data to cache
cache.write({ selection, data })
// pull the data out of the cache
expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({
node: {
id: '1',
enumValue: 'Hello',
},
})
})
test('can store and retrieve lists with null values', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [
{
id: '2',
firstName: 'jane',
},
null,
],
},
},
})
// make sure we can get the linked lists back
expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({
viewer: {
id: '1',
firstName: 'bob',
friends: [
{
id: '2',
firstName: 'jane',
},
null,
],
},
})
})
test('can store and retrieve lists of lists of records', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [
[
{
id: '2',
firstName: 'jane',
},
null,
],
[
{
id: '3',
firstName: 'jane',
},
{
id: '4',
firstName: 'jane',
},
],
],
},
},
})
// make sure we can get the linked lists back
expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({
viewer: {
id: '1',
firstName: 'bob',
friends: [
[
{
id: '2',
firstName: 'jane',
},
null,
],
[
{
id: '3',
firstName: 'jane',
},
{
id: '4',
firstName: 'jane',
},
],
],
},
})
})
test('can store and retrieve links with null values', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: null,
},
})
// make sure we can get the linked record back
expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({
viewer: null,
})
})
test('can write list of just null', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [null],
},
},
})
// make sure we can get the linked lists back
expect(cache.internal.getData(cache.internal.record(rootID), selection, {})).toEqual({
viewer: {
id: '1',
firstName: 'bob',
friends: [null],
},
})
})
test('self-referencing linked lists can be unsubscribed (avoid infinite recursion)', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friends: {
type: 'User',
keyRaw: 'friends',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friends: [
{
id: '1',
firstName: 'bob',
friends: [
{
id: '1',
firstName: 'bob',
},
],
},
],
},
},
})
// subscribe to the list
const spec = {
set: jest.fn(),
selection,
rootType: 'Query',
}
cache.subscribe(spec)
cache.unsubscribe(spec)
// no one should be subscribing to User:1's first name
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test('self-referencing links can be unsubscribed (avoid infinite recursion)', function () {
// instantiate the cache
const cache = new Cache(config)
const selection = {
viewer: {
type: 'User',
keyRaw: 'viewer',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friend: {
type: 'User',
keyRaw: 'friend',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friend: {
type: 'User',
keyRaw: 'friend',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
friend: {
type: 'User',
keyRaw: 'friend',
fields: {
id: {
type: 'ID',
keyRaw: 'id',
},
firstName: {
type: 'String',
keyRaw: 'firstName',
},
},
},
},
},
},
},
},
},
}
// add some data to the cache
cache.write({
selection,
data: {
viewer: {
id: '1',
firstName: 'bob',
friend: {
id: '1',
firstName: 'bob',
friend: {
id: '1',
firstName: 'bob',
friend: {
id: '1',
firstName: 'bob',
},
},
},
},
},
})
// subscribe to the list
const spec = {
set: jest.fn(),
selection,
rootType: 'Query',
}
cache.subscribe(spec)
cache.unsubscribe(spec)
// no one should be subscribing to User:1's first name
expect(
cache.internal.getRecord(cache.id('User', '1')!)?.getSubscribers('firstName')
).toHaveLength(0)
})
test('can check if data exists in cache', function () {})
describe('key evaluation', function () {
const table = [
{
title: 'string',
key: 'fieldName',
variables: {},
expected: 'fieldName',
},
{
title: 'variable',
key: 'fieldName(foo: $bar)',
variables: { bar: 'baz' },
expected: 'fieldName(foo: "baz")',
},
{
title: '$ in string',
key: 'fieldName(foo: "$bar")',
variables: { bar: 'baz' },
expected: 'fieldName(foo: "$bar")',
},
{
title: 'undefined variable',
key: 'fieldName(foo: $bar)',
variables: {},
expected: 'fieldName(foo: undefined)',
},
]
for (const row of table) {
test(row.title, function () {
const cache = new Cache(config)
expect(cache.internal.evaluateKey(row.key, row.variables)).toEqual(row.expected)
})
}
}) | the_stack |
module WinJSTests {
"use strict";
export class RatingKeyboardTests {
setUp(complete) {
RatingUtils.setUp().then(complete);
}
tearDown() {
RatingUtils.cleanUp();
}
//-----------------------------------------------------------------------------------
testRating_Focus = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: 0,
styleExpected: "tentative",
ariaExpected: "user",
userRatingExpected: 0
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Focus_ShowingUser = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating",
{
userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating),
averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating)
}
);
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Focus_ShowingAverage = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: 0,
styleExpected: "tentative",
ariaExpected: "average",
userRatingExpected: 0
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: 0,
userRatingExpected: 0,
styleExpected: "tentative",
ariaExpected: "user"
},
2: {
action: function () { RatingUtils.blur(document.getElementById("rating")); },
expectedEvents: { previewchange: 0, change: 0, cancel: 1 },
tentativeRatingExpected: null,
userRatingExpected: 0
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Blur_ShowingUser = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating",
{
userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating),
averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating)
}
);
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
},
2: {
action: function () { RatingUtils.blur(document.getElementById("rating")); },
expectedEvents: { previewchange: 0, change: 0, cancel: 1 },
tentativeRatingExpected: null,
userRatingExpected: rating.userRating
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Blur_ShowingAverage = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating",
{
averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating)
}
);
// Register the test actions we will be taking
var actions = {
1: {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: 0,
userRatingExpected: 0,
styleExpected: "tentative",
ariaExpected: "average"
},
2: {
action: function () { RatingUtils.blur(document.getElementById("rating")); },
expectedEvents: { previewchange: 0, change: 0, cancel: 1 },
tentativeRatingExpected: null,
userRatingExpected: 0
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Enter key tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.enter);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Tab key tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.tab);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Right arrow key tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Default_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Default_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Default_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Default_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_AverageRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_AverageRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_AverageRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_AverageRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_UserRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_UserRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_UserRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_UserRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_RatingAtMax_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_RatingAtMax_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_RatingAtMax_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_RatingAtMax_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Disabled_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Disabled_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Disabled_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Disabled_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_NoClear_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_NoClear_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_NoClear_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_NoClear_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.rightArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Multiple = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing right key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.rightArrow); },
expectedEvents: { previewchange: (rating.userRating + i <= rating.maxRating) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating + i >= rating.maxRating) ? rating.maxRating : rating.userRating + i,
userRatingExpected: rating.userRating
};
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses,
userRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Right_Multiple_CustomMax = function (signalTestCaseCompleted) {
// Setup the page for test case
var max = RatingUtils.randomNewMaxRating(20, RatingUtils.defaultMaxRating);
var rating = RatingUtils.instantiate("rating", { maxRating: max, userRating: RatingUtils.randomInt(1, max - 2) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing right key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.rightArrow); },
expectedEvents: { previewchange: (rating.userRating + i <= rating.maxRating) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating + i >= rating.maxRating) ? rating.maxRating : rating.userRating + i,
userRatingExpected: rating.userRating
};
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses,
userRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Up arrow key tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Default_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Default_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Default_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Default_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_AverageRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_AverageRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_AverageRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_AverageRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_UserRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_UserRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_UserRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_UserRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_RatingAtMax_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_RatingAtMax_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_RatingAtMax_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_RatingAtMax_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Disabled_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Disabled_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Disabled_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Disabled_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_NoClear_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_NoClear_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_NoClear_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_NoClear_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.upArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Multiple = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating - 2) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing up key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.upArrow); },
expectedEvents: { previewchange: (rating.userRating + i <= rating.maxRating) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating + i >= rating.maxRating) ? rating.maxRating : rating.userRating + i,
userRatingExpected: rating.userRating
};
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses,
userRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Up_Multiple_CustomMax = function (signalTestCaseCompleted) {
// Setup the page for test case
var max = RatingUtils.randomNewMaxRating(20, RatingUtils.defaultMaxRating);
var rating = RatingUtils.instantiate("rating", { maxRating: max, userRating: RatingUtils.randomInt(1, max - 2) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing up key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.upArrow); },
expectedEvents: { previewchange: (rating.userRating + i <= rating.maxRating) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating + i >= rating.maxRating) ? rating.maxRating : rating.userRating + i,
userRatingExpected: rating.userRating
};
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses,
userRatingExpected: (rating.userRating + keyPresses >= rating.maxRating) ? rating.maxRating : rating.userRating + keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Left Arrow Key Tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Default_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Default_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Default_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Default_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_AverageRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_AverageRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_AverageRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_AverageRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_UserRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_UserRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_UserRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_UserRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_RatingAtMax_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_RatingAtMax_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_RatingAtMax_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_RatingAtMax_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Disabled_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Disabled_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Disabled_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Disabled_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_NoClear_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_NoClear_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_NoClear_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_NoClear_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.leftArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Multiple = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing left key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.leftArrow); },
expectedEvents: { previewchange: (rating.userRating - i >= 0) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating - i <= 0) ? 0 : rating.userRating - i,
userRatingExpected: rating.userRating
};
if (rating.userRating - i <= 0) {
actions[i + 1].clearRatingTooltipExpected = true;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses,
userRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Left_Multiple_CustomMax = function (signalTestCaseCompleted) {
// Setup the page for test case
var max = RatingUtils.randomNewMaxRating(20, RatingUtils.defaultMaxRating);
var rating = RatingUtils.instantiate("rating", { maxRating: max, userRating: RatingUtils.randomInt(2, max) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing left key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.leftArrow); },
expectedEvents: { previewchange: (rating.userRating - i >= 0) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating - i <= 0) ? 0 : rating.userRating - i,
userRatingExpected: rating.userRating
};
if (rating.userRating - i <= 0) {
actions[i + 1].clearRatingTooltipExpected = true;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses,
userRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Down Arrow Key Tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Default_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Default_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Default_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Default_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_AverageRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_AverageRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_AverageRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_AverageRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_UserRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_UserRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_UserRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_UserRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_RatingAtMax_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_RatingAtMax_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_RatingAtMax_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_RatingAtMax_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.defaultMaxRating });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Disabled_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Disabled_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Disabled_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Disabled_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_NoClear_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenBlurActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_NoClear_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEscapeActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_NoClear_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenEnterActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_NoClear_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
RatingUtils.instantiate("rating", { userRating: 1, enableClear: false });
// Register the test actions we will be taking
var actions = RatingUtils.generateKeydownThenTabActions(document.getElementById("rating"), WinJS.Utilities.Key.downArrow);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Multiple = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(2, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing down key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.downArrow); },
expectedEvents: { previewchange: (rating.userRating - i >= 0) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating - i <= 0) ? 0 : rating.userRating - i,
userRatingExpected: rating.userRating
};
if (rating.userRating - i <= 0) {
actions[i + 1].clearRatingTooltipExpected = true;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses,
userRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Down_Multiple_CustomMax = function (signalTestCaseCompleted) {
// Setup the page for test case
var max = RatingUtils.randomNewMaxRating(20, RatingUtils.defaultMaxRating);
var rating = RatingUtils.instantiate("rating", { maxRating: max, userRating: RatingUtils.randomInt(2, max) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { window['async'].ratingUtils.focus(rating.element); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
userRatingExpected: rating.userRating,
styleExpected: "user",
ariaExpected: "user"
};
var keyPresses = RatingUtils.randomInt(2, rating.maxRating);
LiveUnit.LoggingCore.logComment("Pressing down key " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
actions[i + 1] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.downArrow); },
expectedEvents: { previewchange: (rating.userRating - i >= 0) ? 1 : 0, change: 0, cancel: 0 },
tentativeRatingExpected: (rating.userRating - i <= 0) ? 0 : rating.userRating - i,
userRatingExpected: rating.userRating
};
if (rating.userRating - i <= 0) {
actions[i + 1].clearRatingTooltipExpected = true;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: 1, cancel: 0 },
tentativeRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses,
userRatingExpected: (rating.userRating - keyPresses <= 0) ? 0 : rating.userRating - keyPresses
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
// Number Key Tests
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Default_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenBlurActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Default_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEscapeActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Default_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEnterActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Default_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating");
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenTabActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_AverageRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenBlurActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_AverageRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEscapeActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_AverageRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEnterActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_AverageRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { averageRating: RatingUtils.random(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenTabActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_UserRating_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenBlurActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_UserRating_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEscapeActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_UserRating_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEnterActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_UserRating_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenTabActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Disabled_Cancel_Blur = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenBlurActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Disabled_Cancel_Escape = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEscapeActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Disabled_Commit_Enter = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenEnterActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Disabled_Commit_Tab = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating), disabled: true });
// Register the test actions we will be taking
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
}
var actions = RatingUtils.generateKeydownThenTabActions(rating.element, key);
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Multiple_Default = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: RatingUtils.randomInt(0, RatingUtils.defaultMaxRating) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
styleExpected: (rating.userRating) ? "user" : "tentative",
ariaExpected: "user",
userRatingExpected: rating.userRating
};
var keyPresses = RatingUtils.randomInt(2, 10);
LiveUnit.LoggingCore.logComment("Pressing random number keys " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
LiveUnit.LoggingCore.logComment("Key " + i + " (action " + (i + 1) + "): " + (key - WinJS.Utilities.Key.num0));
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
LiveUnit.LoggingCore.logComment("Key " + i + " (action " + (i + 1) + "): " + (key - WinJS.Utilities.Key.numPad0));
}
actions[i + 1] = RatingUtils.generateKeydownActions(rating.element, key)[2];
if (actions[i + 1].tentativeRatingExpected === actions[i].tentativeRatingExpected) {
actions[i + 1].expectedEvents.previewchange = 0;
} else {
actions[i + 1].expectedEvents.previewchange = 1;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: (actions[keyPresses + 1].tentativeRatingExpected === rating.userRating) ? 0 : 1, cancel: 0 },
tentativeRatingExpected: actions[keyPresses + 1].tentativeRatingExpected,
userRatingExpected: actions[keyPresses + 1].tentativeRatingExpected
};
actions[keyPresses + 3] = {
action: function () { window['async'].ratingUtils.blur(rating.element); },
expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 /* Win8 631856 */ : (actions[keyPresses + 1].tentativeRatingExpected === rating.userRating) ? 1 : 0 },
tentativeRatingExpected: null,
userRatingExpected: rating.userRating
}
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_Multiple_CustomMax = function (signalTestCaseCompleted) {
// Setup the page for test case
var max = RatingUtils.randomNewMaxRating(20, RatingUtils.defaultMaxRating);
var rating = RatingUtils.instantiate("rating", { maxRating: max, userRating: RatingUtils.randomInt(0, max) });
// Register the test actions we will be taking
var actions = new Object();
actions[1] = {
action: function () { RatingUtils.focus(document.getElementById("rating")); },
expectedEvents: { previewchange: 1, change: 0, cancel: 0 },
tentativeRatingExpected: rating.userRating,
styleExpected: (rating.userRating) ? "user" : "tentative",
ariaExpected: "user",
userRatingExpected: rating.userRating
};
var keyPresses = RatingUtils.randomInt(2, 10);
LiveUnit.LoggingCore.logComment("Pressing random number keys " + keyPresses + " times.");
for (var i = 1; i <= keyPresses; ++i) {
var key = 0;
if (Math.floor(Math.random() * 2)) {
key = RatingUtils.randomInt(WinJS.Utilities.Key.num0, WinJS.Utilities.Key.num9);
LiveUnit.LoggingCore.logComment("Key " + i + " (action " + (i + 1) + "): " + (key - WinJS.Utilities.Key.num0));
} else {
key = RatingUtils.randomInt(WinJS.Utilities.Key.numPad0, WinJS.Utilities.Key.numPad9);
LiveUnit.LoggingCore.logComment("Key " + i + " (action " + (i + 1) + "): " + (key - WinJS.Utilities.Key.numPad0));
}
actions[i + 1] = RatingUtils.generateKeydownActions(rating.element, key)[2];
if (actions[i + 1].tentativeRatingExpected === actions[i].tentativeRatingExpected) {
actions[i + 1].expectedEvents.previewchange = 0;
} else {
actions[i + 1].expectedEvents.previewchange = 1;
}
}
actions[keyPresses + 2] = {
action: function () { window['async'].ratingUtils.keyDown(rating.element, WinJS.Utilities.Key.enter); },
expectedEvents: { previewchange: 0, change: (actions[keyPresses + 1].tentativeRatingExpected === rating.userRating) ? 0 : 1, cancel: 0 },
tentativeRatingExpected: actions[keyPresses + 1].tentativeRatingExpected,
userRatingExpected: actions[keyPresses + 1].tentativeRatingExpected
};
actions[keyPresses + 3] = {
action: function () { window['async'].ratingUtils.blur(rating.element); },
expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 /* Win8 631856 */ : (actions[keyPresses + 1].tentativeRatingExpected === rating.userRating) ? 1 : 0 },
tentativeRatingExpected: null,
userRatingExpected: rating.userRating
}
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_0_enableClear_true = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: 3, enableClear: true });
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted,
RatingUtils.generateKeydownThenTabActions(
rating.element,
WinJS.Utilities.Key.num0
)
);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_Numbers_0_enableClear_false = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: 3, enableClear: false });
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted,
RatingUtils.generateKeydownThenTabActions(
rating.element,
WinJS.Utilities.Key.num0
)
);
};
//-----------------------------------------------------------------------------------
testRating_Keyboard_InvalidKey = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating", { userRating: 3, enableClear: false });
// Generate any random key code other than those the control recognizes (0-1, ESC, TAB, and Arrow keys)
var randomKey = 0;
do {
randomKey = Math.round(Math.random() * 256);
} while (
randomKey >= WinJS.Utilities.Key.num0 && randomKey <= WinJS.Utilities.Key.num9 ||
randomKey >= WinJS.Utilities.Key.numPad0 && randomKey <= WinJS.Utilities.Key.numPad9 ||
randomKey === WinJS.Utilities.Key.leftArrow ||
randomKey === WinJS.Utilities.Key.rightArrow ||
randomKey === WinJS.Utilities.Key.upArrow ||
randomKey === WinJS.Utilities.Key.downArrow ||
randomKey === WinJS.Utilities.Key.enter ||
randomKey === WinJS.Utilities.Key.tab ||
randomKey === WinJS.Utilities.Key.home ||
randomKey === WinJS.Utilities.Key.end ||
randomKey === WinJS.Utilities.Key.escape
);
// Run the test
// Note that generateKeydownThenTabActions pushes a keypress for our randomKey onto the queue
// while expecting 0 previewchange, 0 change, and 0 cancel events. The underlying events
// harness code in RatingUtils.js has a timeout mechanism built in making it pops in
// and verify the right number of events (in this case 0) were thrown between each test action
RatingUtils.startAsyncEventTest(signalTestCaseCompleted,
RatingUtils.generateKeydownThenTabActions(
rating.element,
randomKey
)
);
};
//-----------------------------------------------------------------------------------
testRating_Set_aria_valuenow_Random = function (signalTestCaseCompleted) {
// Setup the page for test case
var rating = RatingUtils.instantiate("rating",
{
userRating: RatingUtils.randomInt(1, RatingUtils.defaultMaxRating),
averageRating: RatingUtils.random(0, RatingUtils.defaultMaxRating)
}
);
// Register the test actions we will be taking
var newRating = RatingUtils.randomInt(0, RatingUtils.defaultMaxRating);
LiveUnit.LoggingCore.logComment("Setting aria-valuenow to " + newRating);
var actions = {
1: {
action: function (newAriaValueNow) {
return function () { document.getElementById("rating").setAttribute("aria-valuenow", newAriaValueNow); };
} (newRating),
expectedEvents: { previewchange: 0, change: (rating.userRating !== newRating) ? 1 : 0, cancel: 0 },
tentativeRatingExpected: newRating,
userRatingExpected: newRating
}
};
// Run the test
RatingUtils.startAsyncEventTest(signalTestCaseCompleted, actions);
};
};
}
// Register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.RatingKeyboardTests"); | the_stack |
import * as Handlebars from "handlebars";
import * as fs from "graceful-fs";
import * as path from "path";
import { promisify } from "util";
import * as globSync from "glob";
import type {
UnknownObject,
FunctionObject,
ConfigOptions,
Engine,
TemplateSpecificationObject,
TemplateDelegateObject,
FsCache,
PartialTemplateOptions,
PartialsDirObject,
RenderOptions,
RenderViewOptions,
RenderCallback,
HandlebarsImport,
CompiledCache,
PrecompiledCache,
RenameFunction,
} from "../types";
const glob = promisify(globSync);
const readFile = promisify(fs.readFile);
// -----------------------------------------------------------------------------
const defaultConfig: ConfigOptions = {
handlebars: Handlebars,
extname: ".handlebars",
encoding: "utf8",
layoutsDir: undefined, // Default layouts directory is relative to `express settings.view` + `layouts/`
partialsDir: undefined, // Default partials directory is relative to `express settings.view` + `partials/`
defaultLayout: "main",
helpers: undefined,
compilerOptions: undefined,
runtimeOptions: undefined,
};
export default class ExpressHandlebars {
config: ConfigOptions;
engine: Engine;
encoding: BufferEncoding;
layoutsDir: string;
extname: string;
compiled: CompiledCache;
precompiled: PrecompiledCache;
_fsCache: FsCache;
partialsDir: string|PartialsDirObject|(string|PartialsDirObject)[];
compilerOptions: CompileOptions;
runtimeOptions: RuntimeOptions;
helpers: FunctionObject;
defaultLayout: string;
handlebars: HandlebarsImport;
constructor (config: ConfigOptions = {}) {
// Config properties with defaults.
Object.assign(this, defaultConfig, config);
// save given config to override other settings.
this.config = config;
// Express view engine integration point.
this.engine = this.renderView.bind(this);
// Normalize `extname`.
if (this.extname.charAt(0) !== ".") {
this.extname = "." + this.extname;
}
// Internal caches of compiled and precompiled templates.
this.compiled = {};
this.precompiled = {};
// Private internal file system cache.
this._fsCache = {};
}
async getPartials (options: PartialTemplateOptions = {}): Promise<TemplateSpecificationObject|TemplateDelegateObject> {
if (typeof this.partialsDir === "undefined") {
return {};
}
const partialsDirs = Array.isArray(this.partialsDir) ? this.partialsDir : [this.partialsDir];
const dirs = await Promise.all(partialsDirs.map(async dir => {
let dirPath: string;
let dirTemplates: TemplateDelegateObject;
let dirNamespace: string;
let dirRename: RenameFunction;
// Support `partialsDir` collection with object entries that contain a
// templates promise and a namespace.
if (typeof dir === "string") {
dirPath = dir;
} else if (typeof dir === "object") {
dirTemplates = dir.templates;
dirNamespace = dir.namespace;
dirRename = dir.rename;
dirPath = dir.dir;
}
// We must have some path to templates, or templates themselves.
if (!dirPath && !dirTemplates) {
throw new Error("A partials dir must be a string or config object");
}
const templates: HandlebarsTemplateDelegate|TemplateSpecification = dirTemplates || await this.getTemplates(dirPath, options);
return {
templates: templates as HandlebarsTemplateDelegate|TemplateSpecification,
namespace: dirNamespace,
rename: dirRename,
};
}));
const partials: TemplateDelegateObject|TemplateSpecificationObject = {};
for (const dir of dirs) {
const { templates, namespace, rename } = dir;
const filePaths = Object.keys(templates);
const getTemplateNameFn = typeof rename === "function"
? rename
: this._getTemplateName.bind(this);
for (const filePath of filePaths) {
const partialName = getTemplateNameFn(filePath, namespace);
partials[partialName] = templates[filePath];
}
}
return partials;
}
async getTemplate (filePath: string, options: PartialTemplateOptions = {}): Promise<HandlebarsTemplateDelegate|TemplateSpecification> {
filePath = path.resolve(filePath);
const encoding = options.encoding || this.encoding;
const cache: PrecompiledCache|CompiledCache = options.precompiled ? this.precompiled : this.compiled;
const template: Promise<HandlebarsTemplateDelegate|TemplateSpecification> = options.cache && cache[filePath];
if (template) {
return template;
}
// Optimistically cache template promise to reduce file system I/O, but
// remove from cache if there was a problem.
try {
cache[filePath] = this._getFile(filePath, { cache: options.cache, encoding })
.then((file: string) => {
const compileTemplate: (file: string, options: RuntimeOptions) => TemplateSpecification|HandlebarsTemplateDelegate = (options.precompiled ? this._precompileTemplate : this._compileTemplate).bind(this);
return compileTemplate(file, this.compilerOptions);
});
return await cache[filePath];
} catch (err) {
delete cache[filePath];
throw err;
}
}
async getTemplates (dirPath: string, options: PartialTemplateOptions = {}): Promise<HandlebarsTemplateDelegate|TemplateSpecification> {
const cache = options.cache;
const filePaths = await this._getDir(dirPath, { cache });
const templates = await Promise.all(filePaths.map(filePath => {
return this.getTemplate(path.join(dirPath, filePath), options);
}));
const hash = {};
for (let i = 0; i < filePaths.length; i++) {
hash[filePaths[i]] = templates[i];
}
return hash;
}
async render (filePath: string, context: UnknownObject = {}, options: RenderOptions = {}): Promise<string> {
const encoding = options.encoding || this.encoding;
const [template, partials] = await Promise.all([
this.getTemplate(filePath, { cache: options.cache, encoding }) as Promise<HandlebarsTemplateDelegate>,
(options.partials || this.getPartials({ cache: options.cache, encoding })) as Promise<TemplateDelegateObject>,
]);
const helpers: FunctionObject = { ...this.helpers, ...options.helpers };
const runtimeOptions = { ...this.runtimeOptions, ...options.runtimeOptions };
// Add ExpressHandlebars metadata to the data channel so that it's
// accessible within the templates and helpers, namespaced under:
// `@exphbs.*`
const data = {
...options.data,
exphbs: {
...options,
filePath,
helpers,
partials,
runtimeOptions,
},
};
const html = this._renderTemplate(template, context, {
...runtimeOptions,
data,
helpers,
partials,
});
return html;
}
async renderView (viewPath: string): Promise<string>;
async renderView (viewPath: string, options: RenderViewOptions): Promise<string>;
async renderView (viewPath: string, callback: RenderCallback): Promise<null>;
async renderView (viewPath: string, options: RenderViewOptions, callback: RenderCallback): Promise<null>;
async renderView (viewPath: string, options: RenderViewOptions|RenderCallback = {}, callback: RenderCallback|null = null): Promise<string|null> {
if (typeof options === "function") {
callback = options;
options = {};
}
const context = options as UnknownObject;
let promise: Promise<string>|null = null;
if (!callback) {
promise = new Promise((resolve, reject) => {
callback = (err, value) => { err !== null ? reject(err) : resolve(value); };
});
}
// Express provides `settings.views` which is the path to the views dir that
// the developer set on the Express app. When this value exists, it's used
// to compute the view's name. Layouts and Partials directories are relative
// to `settings.view` path
let view: string;
const views = options.settings && options.settings.views;
const viewsPath = this._resolveViewsPath(views, viewPath);
if (viewsPath) {
view = this._getTemplateName(path.relative(viewsPath, viewPath));
this.partialsDir = this.config.partialsDir || path.join(viewsPath, "partials/");
this.layoutsDir = this.config.layoutsDir || path.join(viewsPath, "layouts/");
}
const encoding = options.encoding || this.encoding;
// Merge render-level and instance-level helpers together.
const helpers = { ...this.helpers, ...options.helpers };
// Merge render-level and instance-level partials together.
const partials: TemplateDelegateObject = {
...await this.getPartials({ cache: options.cache, encoding }) as TemplateDelegateObject,
...(options.partials || {}),
};
// Pluck-out ExpressHandlebars-specific options and Handlebars-specific
// rendering options.
const renderOptions = {
cache: options.cache,
encoding,
view,
layout: "layout" in options ? options.layout : this.defaultLayout,
data: options.data,
helpers,
partials,
runtimeOptions: options.runtimeOptions,
};
try {
let html = await this.render(viewPath, context, renderOptions);
const layoutPath = this._resolveLayoutPath(renderOptions.layout);
if (layoutPath) {
html = await this.render(
layoutPath,
{ ...context, body: html },
{ ...renderOptions, layout: undefined },
);
}
callback(null, html);
} catch (err) {
callback(err);
}
return promise;
}
// -- Protected Hooks ----------------------------------------------------------
protected _compileTemplate (template: string, options: RuntimeOptions = {}): HandlebarsTemplateDelegate {
return this.handlebars.compile(template.trim(), options);
}
protected _precompileTemplate (template: string, options: RuntimeOptions = {}): TemplateSpecification {
return this.handlebars.precompile(template.trim(), options);
}
protected _renderTemplate (template: HandlebarsTemplateDelegate, context: UnknownObject = {}, options: RuntimeOptions = {}): string {
return template(context, options).trim();
}
// -- Private ------------------------------------------------------------------
private async _getDir (dirPath: string, options: PartialTemplateOptions = {}): Promise<string[]> {
dirPath = path.resolve(dirPath);
const cache = this._fsCache;
let dir = options.cache && (cache[dirPath] as Promise<string[]>);
if (dir) {
return (await dir).concat();
}
const pattern = "**/*" + this.extname;
// Optimistically cache dir promise to reduce file system I/O, but remove
// from cache if there was a problem.
try {
dir = cache[dirPath] = glob(pattern, {
cwd: dirPath,
follow: true,
});
// @ts-ignore FIXME: not sure how to throw error in glob for test coverage
if (options._throwTestError) {
throw new Error("test");
}
return (await dir).concat();
} catch (err) {
delete cache[dirPath];
throw err;
}
}
private async _getFile (filePath: string, options: PartialTemplateOptions = {}): Promise<string> {
filePath = path.resolve(filePath);
const cache = this._fsCache;
const encoding = options.encoding || this.encoding;
const file = options.cache && (cache[filePath] as Promise<string>);
if (file) {
return file;
}
// Optimistically cache file promise to reduce file system I/O, but remove
// from cache if there was a problem.
try {
cache[filePath] = readFile(filePath, { encoding: encoding || "utf8" });
return await cache[filePath] as string;
} catch (err) {
delete cache[filePath];
throw err;
}
}
private _getTemplateName (filePath: string, namespace: string = null): string {
let name = filePath;
if (name.endsWith(this.extname)) {
name = name.substring(0, name.length - this.extname.length);
}
if (namespace) {
name = namespace + "/" + name;
}
return name;
}
private _resolveViewsPath (views: string|string[], file: string): string|null {
if (!Array.isArray(views)) {
return views;
}
let lastDir = path.resolve(file);
let dir = path.dirname(lastDir);
const absoluteViews = views.map(v => path.resolve(v));
// find the closest parent
while (dir !== lastDir) {
const index = absoluteViews.indexOf(dir);
if (index >= 0) {
return views[index];
}
lastDir = dir;
dir = path.dirname(lastDir);
}
// cannot resolve view
return null;
}
private _resolveLayoutPath (layoutPath: string): string|null {
if (!layoutPath) {
return null;
}
if (!path.extname(layoutPath)) {
layoutPath += this.extname;
}
return path.resolve(this.layoutsDir || "", layoutPath);
}
} | the_stack |
import { CoreTextUtils } from '@services/utils/text';
import { Injectable } from '@angular/core';
import { FileTransfer, FileTransferObject, FileUploadResult, FileTransferError } from '@ionic-native/file-transfer/ngx';
import { CoreFile } from '@services/file';
/**
* Mock the File Transfer Error.
*/
export class FileTransferErrorMock implements FileTransferError {
static readonly FILE_NOT_FOUND_ERR = 1;
static readonly INVALID_URL_ERR = 2;
static readonly CONNECTION_ERR = 3;
static readonly ABORT_ERR = 4;
static readonly NOT_MODIFIED_ERR = 5;
constructor(
public code: number,
public source: string,
public target: string,
public http_status: number,
public body: string,
public exception: string,
) { }
}
/**
* Emulates the Cordova FileTransfer plugin in desktop apps and in browser.
*/
@Injectable()
export class FileTransferMock extends FileTransfer {
/**
* Creates a new FileTransferObjectMock object.
*/
create(): FileTransferObjectMock {
return new FileTransferObjectMock();
}
}
/**
* Emulates the FileTransferObject class in desktop apps and in browser.
*/
export class FileTransferObjectMock extends FileTransferObject {
progressListener?: (event: ProgressEvent) => void;
source?: string;
target?: string;
xhr?: XMLHttpRequest;
protected reject?: (reason?: unknown) => void;
/**
* Aborts an in-progress transfer. The onerror callback is passed a FileTransferError
* object which has an error code of FileTransferError.ABORT_ERR.
*/
abort(): void {
if (this.xhr) {
this.xhr.abort();
this.reject!(new FileTransferErrorMock(FileTransferErrorMock.ABORT_ERR, this.source!, this.target!, 0, '', ''));
}
}
/**
* Downloads a file from server.
*
* @param source URL of the server to download the file, as encoded by encodeURI().
* @param target Filesystem url representing the file on the device.
* @param trustAllHosts If set to true, it accepts all security certificates.
* @param options Optional parameters, currently only supports headers.
* @return Returns a Promise that resolves to a FileEntry object.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
download(source: string, target: string, trustAllHosts?: boolean, options?: { [s: string]: any }): Promise<unknown> {
return new Promise((resolve, reject): void => {
// Use XMLHttpRequest instead of HttpClient to support onprogress and abort.
const basicAuthHeader = this.getBasicAuthHeader(source);
const xhr = new XMLHttpRequest();
this.xhr = xhr;
this.source = source;
this.target = target;
this.reject = reject;
if (basicAuthHeader) {
source = source.replace(this.getUrlCredentials(source) + '@', '');
options = options || {};
options.headers = options.headers || {};
options.headers[basicAuthHeader.name] = basicAuthHeader.value;
}
const headers = options?.headers || null;
// Prepare the request.
xhr.open('GET', source, true);
xhr.responseType = 'blob';
for (const name in headers) {
// We can't set the User-Agent in browser.
if (name !== 'User-Agent') {
xhr.setRequestHeader(name, headers[name]);
}
}
xhr.onprogress = (ev: ProgressEvent): void => {
if (this.progressListener) {
this.progressListener(ev);
}
};
xhr.onerror = (): void => {
reject(new FileTransferErrorMock(-1, source, target, xhr.status, xhr.statusText, ''));
};
xhr.onload = async (): Promise<void> => {
// Finished dowloading the file.
let response = xhr.response || xhr.responseText;
const status = Math.max(xhr.status === 1223 ? 204 : xhr.status, 0);
if (status < 200 || status >= 300) {
// Request failed. Try to get the error message.
response = await this.parseResponse(response);
reject(new FileTransferErrorMock(-1, source, target, xhr.status, response || xhr.statusText, ''));
return;
}
if (!response) {
reject();
return;
}
const basePath = CoreFile.getBasePathInstant();
target = target.replace(basePath, ''); // Remove basePath from the target.
target = target.replace(/%20/g, ' '); // Replace all %20 with spaces.
// eslint-disable-next-line promise/catch-or-return
CoreFile.writeFile(target, response).then(resolve, reject);
};
xhr.send();
});
}
/**
* Given a URL, check if it has a credentials in it and, if so, return them in a header object.
* This code is extracted from Cordova FileTransfer plugin.
*
* @param urlString The URL to get the credentials from.
* @return The header with the credentials, null if no credentials.
*/
protected getBasicAuthHeader(urlString: string): {name: string; value: string} | null {
let header: {name: string; value: string} | null = null;
// MS Windows doesn't support credentials in http uris so we detect them by regexp and strip off from result url.
if (window.btoa) {
const credentials = this.getUrlCredentials(urlString);
if (credentials) {
header = {
name: 'Authorization',
value: 'Basic ' + window.btoa(credentials),
};
}
}
return header;
}
/**
* Given an instance of XMLHttpRequest, get the response headers as an object.
*
* @param xhr XMLHttpRequest instance.
* @return Object with the headers.
*/
protected getHeadersAsObject(xhr: XMLHttpRequest): Record<string, string> {
const headersString = xhr.getAllResponseHeaders();
const result = {};
if (headersString) {
const headers = headersString.split('\n');
for (const i in headers) {
const headerString = headers[i];
const separatorPos = headerString.indexOf(':');
if (separatorPos != -1) {
result[headerString.substring(0, separatorPos)] = headerString.substring(separatorPos + 1).trim();
}
}
}
return result;
}
/**
* Get the credentials from a URL.
* This code is extracted from Cordova FileTransfer plugin.
*
* @param urlString The URL to get the credentials from.
* @return Retrieved credentials.
*/
protected getUrlCredentials(urlString: string): string | null {
const credentialsPattern = /^https?:\/\/(?:(?:(([^:@/]*)(?::([^@/]*))?)?@)?([^:/?#]*)(?::(\d*))?).*$/;
const credentials = credentialsPattern.exec(urlString);
return credentials && credentials[1];
}
/**
* Registers a listener that gets called whenever a new chunk of data is transferred.
*
* @param listener Listener that takes a progress event.
*/
onProgress(listener: (event: ProgressEvent) => void): void {
this.progressListener = listener;
}
/**
* Parse a response, converting it into text and the into an object if needed.
*
* @param response The response to parse.
* @return Promise resolved with the parsed response.
*/
protected async parseResponse(response: Blob | ArrayBuffer | string | null): Promise<unknown> {
if (!response) {
return '';
}
let responseText = '';
if (response instanceof Blob) {
responseText = await this.blobToText(response);
} else if (response instanceof ArrayBuffer) {
// Convert the ArrayBuffer into text.
responseText = String.fromCharCode.apply(null, new Uint8Array(response));
} else {
responseText = response;
}
return CoreTextUtils.parseJSON(responseText, '');
}
/**
* Convert a Blob to text.
*
* @param blob Blob to convert.
* @return Promise resolved with blob contents.
*/
protected blobToText(blob: Blob): Promise<string> {
return new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = (): void => {
resolve(<string> reader.result);
};
reader.readAsText(blob);
});
}
/**
* Sends a file to a server.
*
* @param fileUrl Filesystem URL representing the file on the device or a data URI.
* @param url URL of the server to receive the file, as encoded by encodeURI().
* @param options Optional parameters.
* @return Promise that resolves to a FileUploadResult and rejects with FileTransferError.
*/
upload(fileUrl: string, url: string, options?: FileUploadOptions): Promise<FileUploadResult> {
return new Promise((resolve, reject): void => {
const basicAuthHeader = this.getBasicAuthHeader(url);
let fileKey: string | undefined;
let fileName: string | undefined;
let params: any; // eslint-disable-line @typescript-eslint/no-explicit-any
let headers: any; // eslint-disable-line @typescript-eslint/no-explicit-any
let httpMethod: string | undefined;
if (basicAuthHeader) {
url = url.replace(this.getUrlCredentials(url) + '@', '');
options = options || {};
options.headers = options.headers || {};
options.headers[basicAuthHeader.name] = basicAuthHeader.value;
}
if (options) {
fileKey = options.fileKey;
fileName = options.fileName;
headers = options.headers;
httpMethod = options.httpMethod || 'POST';
if (httpMethod.toUpperCase() == 'PUT') {
httpMethod = 'PUT';
} else {
httpMethod = 'POST';
}
params = options.params || {};
}
// Add fileKey and fileName to the headers.
headers = headers || {};
if (!headers['Content-Disposition']) {
headers['Content-Disposition'] = 'form-data;' + (fileKey ? ' name="' + fileKey + '";' : '') +
(fileName ? ' filename="' + fileName + '"' : '');
}
// Adding a Content-Type header with the mimeType makes the request fail (it doesn't detect the token in the params).
// Don't include this header, and delete it if it's supplied.
delete headers['Content-Type'];
// Get the file to upload.
CoreFile.getFile(fileUrl).then((fileEntry) =>
CoreFile.getFileObjectFromFileEntry(fileEntry)).then((file) => {
// Use XMLHttpRequest instead of HttpClient to support onprogress and abort.
const xhr = new XMLHttpRequest();
xhr.open(httpMethod || 'POST', url);
for (const name in headers) {
// Filter "unsafe" headers.
if (name !=='Connection' && name !== 'User-Agent') {
xhr.setRequestHeader(name, headers[name]);
}
}
xhr.onprogress = (ev: ProgressEvent): void => {
if (this.progressListener) {
this.progressListener(ev);
}
};
this.xhr = xhr;
this.source = fileUrl;
this.target = url;
this.reject = reject;
xhr.onerror = (): void => {
reject(new FileTransferErrorMock(-1, fileUrl, url, xhr.status, xhr.statusText, ''));
};
xhr.onload = (): void => {
// Finished uploading the file.
resolve({
bytesSent: file.size,
responseCode: xhr.status,
response: xhr.response,
headers: this.getHeadersAsObject(xhr),
});
};
// Create a form data to send params and the file.
const fd = new FormData();
for (const name in params) {
fd.append(name, params[name]);
}
fd.append('file', file, fileName);
xhr.send(fd);
return;
}).catch(reject);
});
}
} | the_stack |
// tslint:disable: max-func-body-length
import { IDeploymentParametersFile, IPartialDeploymentTemplate } from "./support/diagnostics";
import { parseParametersWithMarkers, parseTemplateWithMarkers } from "./support/parseTemplate";
import { testGetReferences } from "./support/testGetReferences";
suite("Find References for parameters", () => {
suite("#1237 Don't mix up params in param file with params with same name in a nested template", () => {
suite("Nested template", () => {
const templateWithNestedTemplate: IPartialDeploymentTemplate = {
parameters: {
"<!topLevelParameter1Definition!>parameter1": { // TOP-LEVEL Parameter1 definition
type: "string",
metadata: {
description: "top-level parameter1 definition"
}
}
},
resources: [
{
name: "[parameters('<!topLevelParameter1Usage!>parameter1')]", // TOP-LEVEL parameter1 usage
type: "Microsoft.Resources/deployments",
apiVersion: "2020-10-01",
properties: {
expressionEvaluationOptions: {
scope: "inner"
},
mode: "Incremental",
parameters: {
"<!nestedParameter1Value!>parameter1": { // NESTED parameter1 value
value: "nested template param1 value"
}
},
template: {
$schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
contentVersion: "1.0.0.0",
parameters: {
"<!nestedParameter1Definition!>parameter1": { // NESTED Parameter1 definition (different from top-level parameter1)
type: "string",
metadata: {
description: "nested template parameter1 definition"
}
}
},
variables: {},
resources: [],
outputs: {
output1: {
type: "string",
value: "[parameters('<!nestedParameter1Usage!>parameter1')]" // <<<< NESTED Paramter1 usage
}
}
}
}
}
]
};
const paramsFile1: Partial<IDeploymentParametersFile> = {
parameters: {
"<!topLevelParameter1Value!>parameter1": {
value: "Top-level parameter 1 value in parameter file"
}
}
};
const {
dt,
markers: {
topLevelParameter1Definition,
topLevelParameter1Usage,
nestedParameter1Definition,
nestedParameter1Usage,
nestedParameter1Value
}
} = parseTemplateWithMarkers(templateWithNestedTemplate, [], { ignoreWarnings: true });
const {
dp,
markers: {
topLevelParameter1Value
}
} = parseParametersWithMarkers(paramsFile1);
suite("Top-level parameter1", () => {
test("Cursor at definition", () => {
testGetReferences(
dt,
topLevelParameter1Definition.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dp
}
);
});
test("Cursor at usage", () => {
testGetReferences(
dt,
topLevelParameter1Usage.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dp
}
);
});
test("Cursor at value in parameters file", () => {
testGetReferences(
dp,
topLevelParameter1Value.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dt
}
);
});
});
suite("Parameter1 in nested template", () => {
test("Cursor at definition", () => {
testGetReferences(
dt,
nestedParameter1Definition.index,
[nestedParameter1Definition.index, nestedParameter1Usage.index, nestedParameter1Value.index],
{
associatedDoc: dp
}
);
});
test("Cursor at usage", () => {
testGetReferences(
dt,
nestedParameter1Usage.index,
[nestedParameter1Definition.index, nestedParameter1Usage.index, nestedParameter1Value.index],
{
associatedDoc: dp
}
);
});
test("Cursor at value (in template file, in nested param values)", () => {
testGetReferences(
dt,
nestedParameter1Value.index,
[nestedParameter1Definition.index, nestedParameter1Usage.index, nestedParameter1Value.index],
{
associatedDoc: dp
}
);
});
});
});
});
// tslint:disable-next-line: no-suspicious-comment
/* TODO Functionality not yet implemented
suite("Linked template", () => {
const templateWithLinkedTemplate: IPartialDeploymentTemplate = {
parameters: {
"<!topLevelParameter1Definition!>parameter1": { // TOP-LEVEL Parameter1 definition
type: "string",
metadata: {
description: "description"
}
}
},
resources: [
{
name: "linkedDeployment1",
type: "Microsoft.Resources/deployments",
apiVersion: "2020-10-01",
properties: {
mode: "Incremental",
templateLink: {
relativePath: "childTemplate.json",
contentVersion: "1.0.0.0"
},
parameters: {
"<!linkedParameter1Value!>parameter1": { // LINKED TEMPLATE Parameter1 value
value: "[parameters('<!topLevelParameter1Usage!>parameter1')]" // TOP-LEVEL Parameter1 usage
}
}
}
}
]
};
// const linkedTemplate: IPartialDeploymentTemplate = {
// parameters: {
// parameter1: { // LINKED TEMPLATE Parameter1 definition (in child template)
// type: "string",
// metadata: {
// description: "parameter1 definition in linked template"
// }
// }
// },
// variables: {
// variable1: "[parameters('parameter1')]" // LINKED TEMPLATE Parameter1 usage (in child template)
// },
// };
const paramsFile1: IDeploymentParametersFile = {
$schema: "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
contentVersion: "1.0.0.0",
parameters: {
"<!topLevelParameter1Value!>parameter1": {
value: "Top-level parameter 1 value in parameter file"
}
}
};
const {
dt,
markers: {
topLevelParameter1Definition,
topLevelParameter1Usage,
linkedParameter1Value,
}
} = parseTemplateWithMarkers(templateWithLinkedTemplate, [], { ignoreWarnings: true });
// const {
// dtChild,
// markers: {
// linkedParameter1Definition,
// }
// } = parseTemplateWithMarkers(linkedTemplate, [], { ignoreWarnings: true });
const {
dp,
markers: {
topLevelParameter1Value
}
} = parseParametersWithMarkers(paramsFile1);
suite("Top-level parameter1", () => {
test("Cursor at definition", () => {
testGetReferences(
dt,
topLevelParameter1Definition.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dp
}
);
test("Cursor at usage", () => {
testGetReferences(
dt,
topLevelParameter1Usage.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dp
}
);
});
});
test("Cursor at value in parameters file", () => {
testGetReferences(
dp,
topLevelParameter1Value.index,
[topLevelParameter1Definition.index, topLevelParameter1Usage.index, topLevelParameter1Value.index],
{
associatedDoc: dt
}
);
});
});
suite("Parameter1 in linked template", () => {
test("Cursor at value (in main template)", () => {
testGetReferences(
dt,
linkedParameter1Value.index,
[linkedParameter1Value.index],
{
associatedDoc: dp
}
);
});
// test("Cursor at definition (in linked template)", () => {
// testGetReferences(
// dt,
// linkedParameter1Definition.index,
// [nestedParameter1Definition.index, nestedParameter1Usage.index, nestedParameter1Value.index],
// {
// associatedDoc: dp
// }
// );
// });
});
});
*/
}); | the_stack |
import {
createStyle,
selector,
rule,
attribute,
pClass,
pElement,
combinator
} from '../../helpers/style'
import { createTemplate, h, a } from '../../helpers/template'
import { createStyleMatcher } from '@/parser/style/match'
describe('Style matcher', () => {
describe('for universal selector', () => {
const universal = rule([selector({ universal: true })])
const pseudoClass = rule([
selector({
pseudoClass: [pClass('hover')]
})
])
const pseudoElement = rule([
selector({
pseudoElement: pElement('before')
})
])
const style = createStyle([universal, pseudoClass, pseudoElement])
const matcher = createStyleMatcher([style])
// prettier-ignore
const template = createTemplate([
h('div', [], [])
])
it('should always match with universal selector', () => {
const res = matcher(template, [0])
expect(res.length).toBe(3)
expect(res[0]).toEqual(universal)
expect(res[1]).toEqual(pseudoClass)
expect(res[2]).toEqual(pseudoElement)
})
})
describe('for simple selectors', () => {
const tag = rule([selector({ tag: 'a' })])
const id = rule([selector({ id: 'foo' })])
const classes = rule([selector({ class: ['bar'] })])
const attr = rule([
selector({
attributes: [attribute('value')]
})
])
const style = createStyle([tag, id, classes, attr])
const matcher = createStyleMatcher([style])
// prettier-ignore
const template = createTemplate([
h('div', [], [
h('a', [], []),
h('div', [a('id', 'foo')], []),
h('div', [a('class', 'bar baz')], []),
h('div', [a('value', 'test')], [])
])
])
it('should match with tag selector', () => {
const res = matcher(template, [0, 0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(tag)
})
it('should match with id selector', () => {
const res = matcher(template, [0, 1])
expect(res.length).toBe(1)
expect(res[0]).toEqual(id)
})
it('should match with class selector', () => {
const res = matcher(template, [0, 2])
expect(res.length).toBe(1)
expect(res[0]).toEqual(classes)
})
it('should match with attribute selector', () => {
const res = matcher(template, [0, 3])
expect(res.length).toBe(1)
expect(res[0]).toEqual(attr)
})
})
describe('for compound selectors', () => {
const idWithTag = rule([
selector({
id: 'foo',
tag: 'a'
})
])
const idWithClass = rule([
selector({
id: 'foo',
class: ['bar']
})
])
const idWithAttribute = rule([
selector({
id: 'foo',
attributes: [attribute('value')]
})
])
const multiClass = rule([
selector({
class: ['foo', 'bar']
})
])
const multiAttributes = rule([
selector({
attributes: [attribute('title'), attribute('value')]
})
])
const style = createStyle([
idWithTag,
idWithClass,
idWithAttribute,
multiClass,
multiAttributes
])
const matcher = createStyleMatcher([style])
it('should not match if it is not supply compound selector', () => {
// prettier-ignore
const template = createTemplate([
h('div', [a('id', 'foo')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(0)
})
it('should match with id and tag', () => {
// prettier-ignore
const template = createTemplate([
h('a', [a('id', 'foo')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(idWithTag)
})
it('should match with id and class', () => {
// prettier-ignore
const template = createTemplate([
h('div', [a('id', 'foo'), a('class', 'bar')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(idWithClass)
})
it('should match with id and attribute', () => {
// prettier-ignore
const template = createTemplate([
h('div', [a('id', 'foo'), a('value')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(idWithAttribute)
})
it('should match with multi classes', () => {
// prettier-ignore
const template = createTemplate([
h('div', [
a('class', 'foo bar')
], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(multiClass)
})
it('should match with multi attributes', () => {
// prettier-ignore
const template = createTemplate([
h('div', [
a('title'),
a('value')
], [])
])
debugger
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(multiAttributes)
})
})
describe('for complex selectors', () => {
it('should match with child combinator', () => {
const child = rule([
selector(
{ class: ['bar'] },
combinator('>', selector({ class: ['foo'] }))
)
])
const matcher = createStyleMatcher([createStyle([child])])
// prettier-ignore
const template = createTemplate([
h('div', [a('class', 'foo')], [
h('div', [a('class', 'bar')], []),
h('div', [], [
h('div', [a('class', 'bar')], [])
])
])
])
let res = matcher(template, [0, 0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(child)
res = matcher(template, [0, 1, 0])
expect(res.length).toBe(0)
})
it('should match with adjacent sibling combinator', () => {
const sibling = rule([
selector(
{ class: ['bar'] },
combinator('+', selector({ class: ['foo'] }))
)
])
const matcher = createStyleMatcher([createStyle([sibling])])
// prettier-ignore
const template = createTemplate([
h('div', [], [
h('div', [a('class', 'foo')], [
h('div', [a('class', 'bar')], [])
]),
h('div', [a('class', 'bar')], []),
h('div', [a('class', 'bar')], [])
])
])
let res = matcher(template, [0, 1])
expect(res.length).toBe(1)
expect(res[0]).toEqual(sibling)
res = matcher(template, [0, 0, 0])
expect(res.length).toBe(0)
res = matcher(template, [0, 2])
expect(res.length).toBe(0)
})
it('should skip text node during resolving adjacent sibling combinator', () => {
const sibling = rule([
selector(
{ class: ['bar'] },
combinator('+', selector({ class: ['foo'] }))
)
])
const matcher = createStyleMatcher([createStyle([sibling])])
// prettier-ignore
const template = createTemplate([
h('div', [], [
h('div', [a('class', 'foo')], []),
'Test',
h('div', [a('class', 'bar')], []),
])
])
const res = matcher(template, [0, 2])
expect(res.length).toBe(1)
expect(res[0]).toEqual(sibling)
})
it('should match with descendant combinator', () => {
const descendant = rule([
selector(
{ class: ['bar'] },
combinator(' ', selector({ class: ['foo'] }))
)
])
const matcher = createStyleMatcher([createStyle([descendant])])
// prettier-ignore
const template = createTemplate([
h('div', [a('class', 'foo')], [
h('div', [], [
h('div', [a('class', 'bar')], [])
])
]),
h('div', [a('class', 'bar')], [])
])
let res = matcher(template, [0, 0, 0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(descendant)
res = matcher(template, [1])
expect(res.length).toBe(0)
})
it('should match with general sibling combinator', () => {
const sibling = rule([
selector(
{ class: ['bar'] },
combinator('~', selector({ class: ['foo'] }))
)
])
const matcher = createStyleMatcher([createStyle([sibling])])
// prettier-ignore
const template = createTemplate([
h('div', [], [
h('div', [a('class', 'foo')], [
h('div', [a('class', 'bar')], [])
]),
h('div', [], []),
h('div', [a('class', 'bar')], [])
])
])
let res = matcher(template, [0, 2])
expect(res.length).toBe(1)
expect(res[0]).toEqual(sibling)
res = matcher(template, [0, 0, 0])
expect(res.length).toBe(0)
})
})
describe('for attribute selectors', () => {
it('should match with exact attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '=', 'abcdef')]
})
]),
rule([
selector({
attributes: [attribute('value', '=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '=', 'abcdefg')]
})
]),
rule([
selector({
attributes: [attribute('value', '=', 'abcdef test')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abcdef')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(rules[0])
})
it('should match with space-splitted attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '~=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '~=', 'ab')]
})
]),
rule([
selector({
attributes: [attribute('value', '~=', 'def')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abc def ghi')], []),
h('input', [a('value', 'abc')], [])
])
let res = matcher(template, [0])
expect(res.length).toBe(2)
expect(res[0]).toEqual(rules[0])
expect(res[1]).toEqual(rules[2])
res = matcher(template, [1])
expect(res.length).toBe(1)
expect(res[0]).toEqual(rules[0])
})
it('should match hyphen-splitted attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '|=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '|=', 'ab')]
})
]),
rule([
selector({
attributes: [attribute('value', '|=', 'def')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abc-def-ghi')], []),
h('input', [a('value', 'abc')], [])
])
let res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(rules[0])
res = matcher(template, [1])
expect(res.length).toBe(1)
expect(res[0]).toEqual(rules[0])
})
it('should match the start of attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '^=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '^=', 'ab')]
})
]),
rule([
selector({
attributes: [attribute('value', '^=', 'bc')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abc')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(2)
expect(res[0]).toEqual(rules[0])
expect(res[1]).toEqual(rules[1])
})
it('should match the end of attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '$=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '$=', 'ab')]
})
]),
rule([
selector({
attributes: [attribute('value', '$=', 'bc')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abc')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(2)
expect(res[0]).toEqual(rules[0])
expect(res[1]).toEqual(rules[2])
})
it('should match the sub string of attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '*=', 'abc')]
})
]),
rule([
selector({
attributes: [attribute('value', '*=', 'ab')]
})
]),
rule([
selector({
attributes: [attribute('value', '*=', 'b')]
})
]),
rule([
selector({
attributes: [attribute('value', '*=', 'abcd')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'abc')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(3)
expect(res[0]).toEqual(rules[0])
expect(res[1]).toEqual(rules[1])
expect(res[2]).toEqual(rules[2])
})
it('should match with insensitive attribute value', () => {
const rules = [
rule([
selector({
attributes: [attribute('value', '=', 'abc', true)]
})
]),
rule([
selector({
attributes: [attribute('value', '=', 'abc')]
})
])
]
const matcher = createStyleMatcher([createStyle(rules)])
// prettier-ignore
const template = createTemplate([
h('input', [a('value', 'ABC')], [])
])
const res = matcher(template, [0])
expect(res.length).toBe(1)
expect(res[0]).toEqual(rules[0])
})
})
}) | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class Drs extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Drs.Types.ClientConfiguration)
config: Config & Drs.Types.ClientConfiguration;
/**
* Creates a new ReplicationConfigurationTemplate.
*/
createReplicationConfigurationTemplate(params: Drs.Types.CreateReplicationConfigurationTemplateRequest, callback?: (err: AWSError, data: Drs.Types.ReplicationConfigurationTemplate) => void): Request<Drs.Types.ReplicationConfigurationTemplate, AWSError>;
/**
* Creates a new ReplicationConfigurationTemplate.
*/
createReplicationConfigurationTemplate(callback?: (err: AWSError, data: Drs.Types.ReplicationConfigurationTemplate) => void): Request<Drs.Types.ReplicationConfigurationTemplate, AWSError>;
/**
* Deletes a single Job by ID.
*/
deleteJob(params: Drs.Types.DeleteJobRequest, callback?: (err: AWSError, data: Drs.Types.DeleteJobResponse) => void): Request<Drs.Types.DeleteJobResponse, AWSError>;
/**
* Deletes a single Job by ID.
*/
deleteJob(callback?: (err: AWSError, data: Drs.Types.DeleteJobResponse) => void): Request<Drs.Types.DeleteJobResponse, AWSError>;
/**
* Deletes a single Recovery Instance by ID. This deletes the Recovery Instance resource from Elastic Disaster Recovery. The Recovery Instance must be disconnected first in order to delete it.
*/
deleteRecoveryInstance(params: Drs.Types.DeleteRecoveryInstanceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes a single Recovery Instance by ID. This deletes the Recovery Instance resource from Elastic Disaster Recovery. The Recovery Instance must be disconnected first in order to delete it.
*/
deleteRecoveryInstance(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes a single Replication Configuration Template by ID
*/
deleteReplicationConfigurationTemplate(params: Drs.Types.DeleteReplicationConfigurationTemplateRequest, callback?: (err: AWSError, data: Drs.Types.DeleteReplicationConfigurationTemplateResponse) => void): Request<Drs.Types.DeleteReplicationConfigurationTemplateResponse, AWSError>;
/**
* Deletes a single Replication Configuration Template by ID
*/
deleteReplicationConfigurationTemplate(callback?: (err: AWSError, data: Drs.Types.DeleteReplicationConfigurationTemplateResponse) => void): Request<Drs.Types.DeleteReplicationConfigurationTemplateResponse, AWSError>;
/**
* Deletes a single Source Server by ID. The Source Server must be disconnected first.
*/
deleteSourceServer(params: Drs.Types.DeleteSourceServerRequest, callback?: (err: AWSError, data: Drs.Types.DeleteSourceServerResponse) => void): Request<Drs.Types.DeleteSourceServerResponse, AWSError>;
/**
* Deletes a single Source Server by ID. The Source Server must be disconnected first.
*/
deleteSourceServer(callback?: (err: AWSError, data: Drs.Types.DeleteSourceServerResponse) => void): Request<Drs.Types.DeleteSourceServerResponse, AWSError>;
/**
* Retrieves a detailed Job log with pagination.
*/
describeJobLogItems(params: Drs.Types.DescribeJobLogItemsRequest, callback?: (err: AWSError, data: Drs.Types.DescribeJobLogItemsResponse) => void): Request<Drs.Types.DescribeJobLogItemsResponse, AWSError>;
/**
* Retrieves a detailed Job log with pagination.
*/
describeJobLogItems(callback?: (err: AWSError, data: Drs.Types.DescribeJobLogItemsResponse) => void): Request<Drs.Types.DescribeJobLogItemsResponse, AWSError>;
/**
* Returns a list of Jobs. Use the JobsID and fromDate and toDate filters to limit which jobs are returned. The response is sorted by creationDataTime - latest date first. Jobs are created by the StartRecovery, TerminateRecoveryInstances and StartFailbackLaunch APIs. Jobs are also created by DiagnosticLaunch and TerminateDiagnosticInstances, which are APIs available only to *Support* and only used in response to relevant support tickets.
*/
describeJobs(params: Drs.Types.DescribeJobsRequest, callback?: (err: AWSError, data: Drs.Types.DescribeJobsResponse) => void): Request<Drs.Types.DescribeJobsResponse, AWSError>;
/**
* Returns a list of Jobs. Use the JobsID and fromDate and toDate filters to limit which jobs are returned. The response is sorted by creationDataTime - latest date first. Jobs are created by the StartRecovery, TerminateRecoveryInstances and StartFailbackLaunch APIs. Jobs are also created by DiagnosticLaunch and TerminateDiagnosticInstances, which are APIs available only to *Support* and only used in response to relevant support tickets.
*/
describeJobs(callback?: (err: AWSError, data: Drs.Types.DescribeJobsResponse) => void): Request<Drs.Types.DescribeJobsResponse, AWSError>;
/**
* Lists all Recovery Instances or multiple Recovery Instances by ID.
*/
describeRecoveryInstances(params: Drs.Types.DescribeRecoveryInstancesRequest, callback?: (err: AWSError, data: Drs.Types.DescribeRecoveryInstancesResponse) => void): Request<Drs.Types.DescribeRecoveryInstancesResponse, AWSError>;
/**
* Lists all Recovery Instances or multiple Recovery Instances by ID.
*/
describeRecoveryInstances(callback?: (err: AWSError, data: Drs.Types.DescribeRecoveryInstancesResponse) => void): Request<Drs.Types.DescribeRecoveryInstancesResponse, AWSError>;
/**
* Lists all Recovery Snapshots for a single Source Server.
*/
describeRecoverySnapshots(params: Drs.Types.DescribeRecoverySnapshotsRequest, callback?: (err: AWSError, data: Drs.Types.DescribeRecoverySnapshotsResponse) => void): Request<Drs.Types.DescribeRecoverySnapshotsResponse, AWSError>;
/**
* Lists all Recovery Snapshots for a single Source Server.
*/
describeRecoverySnapshots(callback?: (err: AWSError, data: Drs.Types.DescribeRecoverySnapshotsResponse) => void): Request<Drs.Types.DescribeRecoverySnapshotsResponse, AWSError>;
/**
* Lists all ReplicationConfigurationTemplates, filtered by Source Server IDs.
*/
describeReplicationConfigurationTemplates(params: Drs.Types.DescribeReplicationConfigurationTemplatesRequest, callback?: (err: AWSError, data: Drs.Types.DescribeReplicationConfigurationTemplatesResponse) => void): Request<Drs.Types.DescribeReplicationConfigurationTemplatesResponse, AWSError>;
/**
* Lists all ReplicationConfigurationTemplates, filtered by Source Server IDs.
*/
describeReplicationConfigurationTemplates(callback?: (err: AWSError, data: Drs.Types.DescribeReplicationConfigurationTemplatesResponse) => void): Request<Drs.Types.DescribeReplicationConfigurationTemplatesResponse, AWSError>;
/**
* Lists all Source Servers or multiple Source Servers filtered by ID.
*/
describeSourceServers(params: Drs.Types.DescribeSourceServersRequest, callback?: (err: AWSError, data: Drs.Types.DescribeSourceServersResponse) => void): Request<Drs.Types.DescribeSourceServersResponse, AWSError>;
/**
* Lists all Source Servers or multiple Source Servers filtered by ID.
*/
describeSourceServers(callback?: (err: AWSError, data: Drs.Types.DescribeSourceServersResponse) => void): Request<Drs.Types.DescribeSourceServersResponse, AWSError>;
/**
* Disconnect a Recovery Instance from Elastic Disaster Recovery. Data replication is stopped immediately. All AWS resources created by Elastic Disaster Recovery for enabling the replication of the Recovery Instance will be terminated / deleted within 90 minutes. If the agent on the Recovery Instance has not been prevented from communicating with the Elastic Disaster Recovery service, then it will receive a command to uninstall itself (within approximately 10 minutes). The following properties of the Recovery Instance will be changed immediately: dataReplicationInfo.dataReplicationState will be set to DISCONNECTED; The totalStorageBytes property for each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDuration will be nullified.
*/
disconnectRecoveryInstance(params: Drs.Types.DisconnectRecoveryInstanceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Disconnect a Recovery Instance from Elastic Disaster Recovery. Data replication is stopped immediately. All AWS resources created by Elastic Disaster Recovery for enabling the replication of the Recovery Instance will be terminated / deleted within 90 minutes. If the agent on the Recovery Instance has not been prevented from communicating with the Elastic Disaster Recovery service, then it will receive a command to uninstall itself (within approximately 10 minutes). The following properties of the Recovery Instance will be changed immediately: dataReplicationInfo.dataReplicationState will be set to DISCONNECTED; The totalStorageBytes property for each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDuration will be nullified.
*/
disconnectRecoveryInstance(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Disconnects a specific Source Server from Elastic Disaster Recovery. Data replication is stopped immediately. All AWS resources created by Elastic Disaster Recovery for enabling the replication of the Source Server will be terminated / deleted within 90 minutes. You cannot disconnect a Source Server if it has a Recovery Instance. If the agent on the Source Server has not been prevented from communicating with the Elastic Disaster Recovery service, then it will receive a command to uninstall itself (within approximately 10 minutes). The following properties of the SourceServer will be changed immediately: dataReplicationInfo.dataReplicationState will be set to DISCONNECTED; The totalStorageBytes property for each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDuration will be nullified.
*/
disconnectSourceServer(params: Drs.Types.DisconnectSourceServerRequest, callback?: (err: AWSError, data: Drs.Types.SourceServer) => void): Request<Drs.Types.SourceServer, AWSError>;
/**
* Disconnects a specific Source Server from Elastic Disaster Recovery. Data replication is stopped immediately. All AWS resources created by Elastic Disaster Recovery for enabling the replication of the Source Server will be terminated / deleted within 90 minutes. You cannot disconnect a Source Server if it has a Recovery Instance. If the agent on the Source Server has not been prevented from communicating with the Elastic Disaster Recovery service, then it will receive a command to uninstall itself (within approximately 10 minutes). The following properties of the SourceServer will be changed immediately: dataReplicationInfo.dataReplicationState will be set to DISCONNECTED; The totalStorageBytes property for each of dataReplicationInfo.replicatedDisks will be set to zero; dataReplicationInfo.lagDuration and dataReplicationInfo.lagDuration will be nullified.
*/
disconnectSourceServer(callback?: (err: AWSError, data: Drs.Types.SourceServer) => void): Request<Drs.Types.SourceServer, AWSError>;
/**
* Lists all Failback ReplicationConfigurations, filtered by Recovery Instance ID.
*/
getFailbackReplicationConfiguration(params: Drs.Types.GetFailbackReplicationConfigurationRequest, callback?: (err: AWSError, data: Drs.Types.GetFailbackReplicationConfigurationResponse) => void): Request<Drs.Types.GetFailbackReplicationConfigurationResponse, AWSError>;
/**
* Lists all Failback ReplicationConfigurations, filtered by Recovery Instance ID.
*/
getFailbackReplicationConfiguration(callback?: (err: AWSError, data: Drs.Types.GetFailbackReplicationConfigurationResponse) => void): Request<Drs.Types.GetFailbackReplicationConfigurationResponse, AWSError>;
/**
* Gets a LaunchConfiguration, filtered by Source Server IDs.
*/
getLaunchConfiguration(params: Drs.Types.GetLaunchConfigurationRequest, callback?: (err: AWSError, data: Drs.Types.LaunchConfiguration) => void): Request<Drs.Types.LaunchConfiguration, AWSError>;
/**
* Gets a LaunchConfiguration, filtered by Source Server IDs.
*/
getLaunchConfiguration(callback?: (err: AWSError, data: Drs.Types.LaunchConfiguration) => void): Request<Drs.Types.LaunchConfiguration, AWSError>;
/**
* Gets a ReplicationConfiguration, filtered by Source Server ID.
*/
getReplicationConfiguration(params: Drs.Types.GetReplicationConfigurationRequest, callback?: (err: AWSError, data: Drs.Types.ReplicationConfiguration) => void): Request<Drs.Types.ReplicationConfiguration, AWSError>;
/**
* Gets a ReplicationConfiguration, filtered by Source Server ID.
*/
getReplicationConfiguration(callback?: (err: AWSError, data: Drs.Types.ReplicationConfiguration) => void): Request<Drs.Types.ReplicationConfiguration, AWSError>;
/**
* Initialize Elastic Disaster Recovery.
*/
initializeService(params: Drs.Types.InitializeServiceRequest, callback?: (err: AWSError, data: Drs.Types.InitializeServiceResponse) => void): Request<Drs.Types.InitializeServiceResponse, AWSError>;
/**
* Initialize Elastic Disaster Recovery.
*/
initializeService(callback?: (err: AWSError, data: Drs.Types.InitializeServiceResponse) => void): Request<Drs.Types.InitializeServiceResponse, AWSError>;
/**
* List all tags for your Elastic Disaster Recovery resources.
*/
listTagsForResource(params: Drs.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Drs.Types.ListTagsForResourceResponse) => void): Request<Drs.Types.ListTagsForResourceResponse, AWSError>;
/**
* List all tags for your Elastic Disaster Recovery resources.
*/
listTagsForResource(callback?: (err: AWSError, data: Drs.Types.ListTagsForResourceResponse) => void): Request<Drs.Types.ListTagsForResourceResponse, AWSError>;
/**
* Causes the data replication initiation sequence to begin immediately upon next Handshake for the specified Source Server ID, regardless of when the previous initiation started. This command will work only if the Source Server is stalled or is in a DISCONNECTED or STOPPED state.
*/
retryDataReplication(params: Drs.Types.RetryDataReplicationRequest, callback?: (err: AWSError, data: Drs.Types.SourceServer) => void): Request<Drs.Types.SourceServer, AWSError>;
/**
* Causes the data replication initiation sequence to begin immediately upon next Handshake for the specified Source Server ID, regardless of when the previous initiation started. This command will work only if the Source Server is stalled or is in a DISCONNECTED or STOPPED state.
*/
retryDataReplication(callback?: (err: AWSError, data: Drs.Types.SourceServer) => void): Request<Drs.Types.SourceServer, AWSError>;
/**
* Initiates a Job for launching the machine that is being failed back to from the specified Recovery Instance. This will run conversion on the failback client and will reboot your machine, thus completing the failback process.
*/
startFailbackLaunch(params: Drs.Types.StartFailbackLaunchRequest, callback?: (err: AWSError, data: Drs.Types.StartFailbackLaunchResponse) => void): Request<Drs.Types.StartFailbackLaunchResponse, AWSError>;
/**
* Initiates a Job for launching the machine that is being failed back to from the specified Recovery Instance. This will run conversion on the failback client and will reboot your machine, thus completing the failback process.
*/
startFailbackLaunch(callback?: (err: AWSError, data: Drs.Types.StartFailbackLaunchResponse) => void): Request<Drs.Types.StartFailbackLaunchResponse, AWSError>;
/**
* Launches Recovery Instances for the specified Source Servers. For each Source Server you may choose a point in time snapshot to launch from, or use an on demand snapshot.
*/
startRecovery(params: Drs.Types.StartRecoveryRequest, callback?: (err: AWSError, data: Drs.Types.StartRecoveryResponse) => void): Request<Drs.Types.StartRecoveryResponse, AWSError>;
/**
* Launches Recovery Instances for the specified Source Servers. For each Source Server you may choose a point in time snapshot to launch from, or use an on demand snapshot.
*/
startRecovery(callback?: (err: AWSError, data: Drs.Types.StartRecoveryResponse) => void): Request<Drs.Types.StartRecoveryResponse, AWSError>;
/**
* Stops the failback process for a specified Recovery Instance. This changes the Failback State of the Recovery Instance back to FAILBACK_NOT_STARTED.
*/
stopFailback(params: Drs.Types.StopFailbackRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Stops the failback process for a specified Recovery Instance. This changes the Failback State of the Recovery Instance back to FAILBACK_NOT_STARTED.
*/
stopFailback(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Adds or overwrites only the specified tags for the specified Elastic Disaster Recovery resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value.
*/
tagResource(params: Drs.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Adds or overwrites only the specified tags for the specified Elastic Disaster Recovery resource or resources. When you specify an existing tag key, the value is overwritten with the new value. Each resource can have a maximum of 50 tags. Each tag consists of a key and optional value.
*/
tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Initiates a Job for terminating the EC2 resources associated with the specified Recovery Instances, and then will delete the Recovery Instances from the Elastic Disaster Recovery service.
*/
terminateRecoveryInstances(params: Drs.Types.TerminateRecoveryInstancesRequest, callback?: (err: AWSError, data: Drs.Types.TerminateRecoveryInstancesResponse) => void): Request<Drs.Types.TerminateRecoveryInstancesResponse, AWSError>;
/**
* Initiates a Job for terminating the EC2 resources associated with the specified Recovery Instances, and then will delete the Recovery Instances from the Elastic Disaster Recovery service.
*/
terminateRecoveryInstances(callback?: (err: AWSError, data: Drs.Types.TerminateRecoveryInstancesResponse) => void): Request<Drs.Types.TerminateRecoveryInstancesResponse, AWSError>;
/**
* Deletes the specified set of tags from the specified set of Elastic Disaster Recovery resources.
*/
untagResource(params: Drs.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes the specified set of tags from the specified set of Elastic Disaster Recovery resources.
*/
untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Allows you to update the failback replication configuration of a Recovery Instance by ID.
*/
updateFailbackReplicationConfiguration(params: Drs.Types.UpdateFailbackReplicationConfigurationRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Allows you to update the failback replication configuration of a Recovery Instance by ID.
*/
updateFailbackReplicationConfiguration(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Updates a LaunchConfiguration by Source Server ID.
*/
updateLaunchConfiguration(params: Drs.Types.UpdateLaunchConfigurationRequest, callback?: (err: AWSError, data: Drs.Types.LaunchConfiguration) => void): Request<Drs.Types.LaunchConfiguration, AWSError>;
/**
* Updates a LaunchConfiguration by Source Server ID.
*/
updateLaunchConfiguration(callback?: (err: AWSError, data: Drs.Types.LaunchConfiguration) => void): Request<Drs.Types.LaunchConfiguration, AWSError>;
/**
* Allows you to update a ReplicationConfiguration by Source Server ID.
*/
updateReplicationConfiguration(params: Drs.Types.UpdateReplicationConfigurationRequest, callback?: (err: AWSError, data: Drs.Types.ReplicationConfiguration) => void): Request<Drs.Types.ReplicationConfiguration, AWSError>;
/**
* Allows you to update a ReplicationConfiguration by Source Server ID.
*/
updateReplicationConfiguration(callback?: (err: AWSError, data: Drs.Types.ReplicationConfiguration) => void): Request<Drs.Types.ReplicationConfiguration, AWSError>;
/**
* Updates a ReplicationConfigurationTemplate by ID.
*/
updateReplicationConfigurationTemplate(params: Drs.Types.UpdateReplicationConfigurationTemplateRequest, callback?: (err: AWSError, data: Drs.Types.ReplicationConfigurationTemplate) => void): Request<Drs.Types.ReplicationConfigurationTemplate, AWSError>;
/**
* Updates a ReplicationConfigurationTemplate by ID.
*/
updateReplicationConfigurationTemplate(callback?: (err: AWSError, data: Drs.Types.ReplicationConfigurationTemplate) => void): Request<Drs.Types.ReplicationConfigurationTemplate, AWSError>;
}
declare namespace Drs {
export type ARN = string;
export type Boolean = boolean;
export type BoundedString = string;
export interface CPU {
/**
* The number of CPU cores.
*/
cores?: PositiveInteger;
/**
* The model name of the CPU.
*/
modelName?: BoundedString;
}
export type Cpus = CPU[];
export interface CreateReplicationConfigurationTemplateRequest {
/**
* Whether to associate the default Elastic Disaster Recovery Security group with the Replication Configuration Template.
*/
associateDefaultSecurityGroup: Boolean;
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Source Server in Mbps.
*/
bandwidthThrottling: PositiveInteger;
/**
* Whether to create a Public IP for the Recovery Instance by default.
*/
createPublicIP: Boolean;
/**
* The data plane routing mechanism that will be used for replication.
*/
dataPlaneRouting: ReplicationConfigurationDataPlaneRouting;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
defaultLargeStagingDiskType: ReplicationConfigurationDefaultLargeStagingDiskType;
/**
* The type of EBS encryption to be used during replication.
*/
ebsEncryption: ReplicationConfigurationEbsEncryption;
/**
* The ARN of the EBS encryption key to be used during replication.
*/
ebsEncryptionKeyArn?: ARN;
/**
* The Point in time (PIT) policy to manage snapshots taken during replication.
*/
pitPolicy: PITPolicy;
/**
* The instance type to be used for the replication server.
*/
replicationServerInstanceType: EC2InstanceType;
/**
* The security group IDs that will be used by the replication server.
*/
replicationServersSecurityGroupsIDs: ReplicationServersSecurityGroupsIDs;
/**
* The subnet to be used by the replication staging area.
*/
stagingAreaSubnetId: SubnetID;
/**
* A set of tags to be associated with all resources created in the replication staging area: EC2 replication server, EBS volumes, EBS snapshots, etc.
*/
stagingAreaTags: TagsMap;
/**
* A set of tags to be associated with the Replication Configuration Template resource.
*/
tags?: TagsMap;
/**
* Whether to use a dedicated Replication Server in the replication staging area.
*/
useDedicatedReplicationServer: Boolean;
}
export interface DataReplicationError {
/**
* Error in data replication.
*/
error?: DataReplicationErrorString;
/**
* Error in data replication.
*/
rawError?: LargeBoundedString;
}
export type DataReplicationErrorString = "AGENT_NOT_SEEN"|"SNAPSHOTS_FAILURE"|"NOT_CONVERGING"|"UNSTABLE_NETWORK"|"FAILED_TO_CREATE_SECURITY_GROUP"|"FAILED_TO_LAUNCH_REPLICATION_SERVER"|"FAILED_TO_BOOT_REPLICATION_SERVER"|"FAILED_TO_AUTHENTICATE_WITH_SERVICE"|"FAILED_TO_DOWNLOAD_REPLICATION_SOFTWARE"|"FAILED_TO_CREATE_STAGING_DISKS"|"FAILED_TO_ATTACH_STAGING_DISKS"|"FAILED_TO_PAIR_REPLICATION_SERVER_WITH_AGENT"|"FAILED_TO_CONNECT_AGENT_TO_REPLICATION_SERVER"|"FAILED_TO_START_DATA_TRANSFER"|string;
export interface DataReplicationInfo {
/**
* Error in data replication.
*/
dataReplicationError?: DataReplicationError;
/**
* Information about whether the data replication has been initiated.
*/
dataReplicationInitiation?: DataReplicationInitiation;
/**
* The state of the data replication.
*/
dataReplicationState?: DataReplicationState;
/**
* An estimate of when the data replication will be completed.
*/
etaDateTime?: ISO8601DatetimeString;
/**
* Data replication lag duration.
*/
lagDuration?: ISO8601DatetimeString;
/**
* The disks that should be replicated.
*/
replicatedDisks?: DataReplicationInfoReplicatedDisks;
}
export interface DataReplicationInfoReplicatedDisk {
/**
* The size of the replication backlog in bytes.
*/
backloggedStorageBytes?: PositiveInteger;
/**
* The name of the device.
*/
deviceName?: BoundedString;
/**
* The amount of data replicated so far in bytes.
*/
replicatedStorageBytes?: PositiveInteger;
/**
* The amount of data to be rescanned in bytes.
*/
rescannedStorageBytes?: PositiveInteger;
/**
* The total amount of data to be replicated in bytes.
*/
totalStorageBytes?: PositiveInteger;
}
export type DataReplicationInfoReplicatedDisks = DataReplicationInfoReplicatedDisk[];
export interface DataReplicationInitiation {
/**
* The date and time of the next attempt to initiate data replication.
*/
nextAttemptDateTime?: ISO8601DatetimeString;
/**
* The date and time of the current attempt to initiate data replication.
*/
startDateTime?: ISO8601DatetimeString;
/**
* The steps of the current attempt to initiate data replication.
*/
steps?: DataReplicationInitiationSteps;
}
export interface DataReplicationInitiationStep {
/**
* The name of the step.
*/
name?: DataReplicationInitiationStepName;
/**
* The status of the step.
*/
status?: DataReplicationInitiationStepStatus;
}
export type DataReplicationInitiationStepName = "WAIT"|"CREATE_SECURITY_GROUP"|"LAUNCH_REPLICATION_SERVER"|"BOOT_REPLICATION_SERVER"|"AUTHENTICATE_WITH_SERVICE"|"DOWNLOAD_REPLICATION_SOFTWARE"|"CREATE_STAGING_DISKS"|"ATTACH_STAGING_DISKS"|"PAIR_REPLICATION_SERVER_WITH_AGENT"|"CONNECT_AGENT_TO_REPLICATION_SERVER"|"START_DATA_TRANSFER"|string;
export type DataReplicationInitiationStepStatus = "NOT_STARTED"|"IN_PROGRESS"|"SUCCEEDED"|"FAILED"|"SKIPPED"|string;
export type DataReplicationInitiationSteps = DataReplicationInitiationStep[];
export type DataReplicationState = "STOPPED"|"INITIATING"|"INITIAL_SYNC"|"BACKLOG"|"CREATING_SNAPSHOT"|"CONTINUOUS"|"PAUSED"|"RESCAN"|"STALLED"|"DISCONNECTED"|string;
export interface DeleteJobRequest {
/**
* The ID of the Job to be deleted.
*/
jobID: JobID;
}
export interface DeleteJobResponse {
}
export interface DeleteRecoveryInstanceRequest {
/**
* RThe ID of the Recovery Instance to be deleted.
*/
recoveryInstanceID: RecoveryInstanceID;
}
export interface DeleteReplicationConfigurationTemplateRequest {
/**
* The ID of the Replication Configuration Template to be deleted.
*/
replicationConfigurationTemplateID: ReplicationConfigurationTemplateID;
}
export interface DeleteReplicationConfigurationTemplateResponse {
}
export interface DeleteSourceServerRequest {
/**
* The ID of the Source Server to be deleted.
*/
sourceServerID: SourceServerID;
}
export interface DeleteSourceServerResponse {
}
export interface DescribeJobLogItemsRequest {
/**
* The ID of the Job for which Job log items will be retrieved.
*/
jobID: JobID;
/**
* Maximum number of Job log items to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Job log items to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeJobLogItemsResponse {
/**
* An array of Job log items.
*/
items?: JobLogs;
/**
* The token of the next Job log items to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeJobsRequest {
/**
* A set of filters by which to return Jobs.
*/
filters: DescribeJobsRequestFilters;
/**
* Maximum number of Jobs to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Job to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeJobsRequestFilters {
/**
* The start date in a date range query.
*/
fromDate?: ISO8601DatetimeString;
/**
* An array of Job IDs that should be returned. An empty array means all jobs.
*/
jobIDs?: DescribeJobsRequestFiltersJobIDs;
/**
* The end date in a date range query.
*/
toDate?: ISO8601DatetimeString;
}
export type DescribeJobsRequestFiltersJobIDs = JobID[];
export interface DescribeJobsResponse {
/**
* An array of Jobs.
*/
items?: JobsList;
/**
* The token of the next Job to retrieve.
*/
nextToken?: PaginationToken;
}
export type DescribeRecoveryInstancesItems = RecoveryInstance[];
export interface DescribeRecoveryInstancesRequest {
/**
* A set of filters by which to return Recovery Instances.
*/
filters: DescribeRecoveryInstancesRequestFilters;
/**
* Maximum number of Recovery Instances to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Recovery Instance to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeRecoveryInstancesRequestFilters {
/**
* An array of Recovery Instance IDs that should be returned. An empty array means all Recovery Instances.
*/
recoveryInstanceIDs?: RecoveryInstanceIDs;
/**
* An array of Source Server IDs for which associated Recovery Instances should be returned.
*/
sourceServerIDs?: SourceServerIDs;
}
export interface DescribeRecoveryInstancesResponse {
/**
* An array of Recovery Instances.
*/
items?: DescribeRecoveryInstancesItems;
/**
* The token of the next Recovery Instance to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeRecoverySnapshotsRequest {
/**
* A set of filters by which to return Recovery Snapshots.
*/
filters?: DescribeRecoverySnapshotsRequestFilters;
/**
* Maximum number of Recovery Snapshots to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Recovery Snapshot to retrieve.
*/
nextToken?: PaginationToken;
/**
* The sorted ordering by which to return Recovery Snapshots.
*/
order?: RecoverySnapshotsOrder;
/**
* Filter Recovery Snapshots by Source Server ID.
*/
sourceServerID: SourceServerID;
}
export interface DescribeRecoverySnapshotsRequestFilters {
/**
* The start date in a date range query.
*/
fromDateTime?: ISO8601DatetimeString;
/**
* The end date in a date range query.
*/
toDateTime?: ISO8601DatetimeString;
}
export interface DescribeRecoverySnapshotsResponse {
/**
* An array of Recovery Snapshots.
*/
items?: RecoverySnapshotsList;
/**
* The token of the next Recovery Snapshot to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeReplicationConfigurationTemplatesRequest {
/**
* Maximum number of Replication Configuration Templates to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Replication Configuration Template to retrieve.
*/
nextToken?: PaginationToken;
/**
* The IDs of the Replication Configuration Templates to retrieve. An empty list means all Replication Configuration Templates.
*/
replicationConfigurationTemplateIDs: ReplicationConfigurationTemplateIDs;
}
export interface DescribeReplicationConfigurationTemplatesResponse {
/**
* An array of Replication Configuration Templates.
*/
items?: ReplicationConfigurationTemplates;
/**
* The token of the next Replication Configuration Template to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeSourceServersRequest {
/**
* A set of filters by which to return Source Servers.
*/
filters: DescribeSourceServersRequestFilters;
/**
* Maximum number of Source Servers to retrieve.
*/
maxResults?: StrictlyPositiveInteger;
/**
* The token of the next Source Server to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DescribeSourceServersRequestFilters {
/**
* An ID that describes the hardware of the Source Server. This is either an EC2 instance id, a VMware uuid or a mac address.
*/
hardwareId?: BoundedString;
/**
* An array of Source Servers IDs that should be returned. An empty array means all Source Servers.
*/
sourceServerIDs?: DescribeSourceServersRequestFiltersIDs;
}
export type DescribeSourceServersRequestFiltersIDs = SourceServerID[];
export interface DescribeSourceServersResponse {
/**
* An array of Source Servers.
*/
items?: SourceServersList;
/**
* The token of the next Source Server to retrieve.
*/
nextToken?: PaginationToken;
}
export interface DisconnectRecoveryInstanceRequest {
/**
* The ID of the Recovery Instance to disconnect.
*/
recoveryInstanceID: RecoveryInstanceID;
}
export interface DisconnectSourceServerRequest {
/**
* The ID of the Source Server to disconnect.
*/
sourceServerID: SourceServerID;
}
export interface Disk {
/**
* The amount of storage on the disk in bytes.
*/
bytes?: PositiveInteger;
/**
* The disk or device name.
*/
deviceName?: BoundedString;
}
export type Disks = Disk[];
export type EC2InstanceID = string;
export type EC2InstanceState = "PENDING"|"RUNNING"|"STOPPING"|"STOPPED"|"SHUTTING-DOWN"|"TERMINATED"|"NOT_FOUND"|string;
export type EC2InstanceType = string;
export type EbsSnapshotsList = ebsSnapshot[];
export type EbsVolumeID = string;
export type FailbackReplicationError = "AGENT_NOT_SEEN"|"FAILBACK_CLIENT_NOT_SEEN"|"NOT_CONVERGING"|"UNSTABLE_NETWORK"|"FAILED_TO_ESTABLISH_RECOVERY_INSTANCE_COMMUNICATION"|"FAILED_TO_DOWNLOAD_REPLICATION_SOFTWARE_TO_FAILBACK_CLIENT"|"FAILED_TO_CONFIGURE_REPLICATION_SOFTWARE"|"FAILED_TO_PAIR_AGENT_WITH_REPLICATION_SOFTWARE"|"FAILED_TO_ESTABLISH_AGENT_REPLICATOR_SOFTWARE_COMMUNICATION"|string;
export type FailbackState = "FAILBACK_NOT_STARTED"|"FAILBACK_IN_PROGRESS"|"FAILBACK_READY_FOR_LAUNCH"|"FAILBACK_COMPLETED"|"FAILBACK_ERROR"|string;
export interface GetFailbackReplicationConfigurationRequest {
/**
* The ID of the Recovery Instance whose failback replication configuration should be returned.
*/
recoveryInstanceID: RecoveryInstanceID;
}
export interface GetFailbackReplicationConfigurationResponse {
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Recovery Instance in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* The name of the Failback Replication Configuration.
*/
name?: BoundedString;
/**
* The ID of the Recovery Instance.
*/
recoveryInstanceID: RecoveryInstanceID;
/**
* Whether to use Private IP for the failback replication of the Recovery Instance.
*/
usePrivateIP?: Boolean;
}
export interface GetLaunchConfigurationRequest {
/**
* The ID of the Source Server that we want to retrieve a Launch Configuration for.
*/
sourceServerID: SourceServerID;
}
export interface GetReplicationConfigurationRequest {
/**
* The ID of the Source Serve for this Replication Configuration.r
*/
sourceServerID: SourceServerID;
}
export type IPsList = BoundedString[];
export type ISO8601DatetimeString = string;
export interface IdentificationHints {
/**
* AWS Instance ID identification hint.
*/
awsInstanceID?: EC2InstanceID;
/**
* Fully Qualified Domain Name identification hint.
*/
fqdn?: BoundedString;
/**
* Hostname identification hint.
*/
hostname?: BoundedString;
/**
* vCenter VM path identification hint.
*/
vmWareUuid?: BoundedString;
}
export interface InitializeServiceRequest {
}
export interface InitializeServiceResponse {
}
export type InitiatedBy = "START_RECOVERY"|"START_DRILL"|"FAILBACK"|"DIAGNOSTIC"|"TERMINATE_RECOVERY_INSTANCES"|string;
export interface Job {
/**
* The ARN of a Job.
*/
arn?: ARN;
/**
* The date and time of when the Job was created.
*/
creationDateTime?: ISO8601DatetimeString;
/**
* The date and time of when the Job ended.
*/
endDateTime?: ISO8601DatetimeString;
/**
* A string representing who initiated the Job.
*/
initiatedBy?: InitiatedBy;
/**
* The ID of the Job.
*/
jobID: JobID;
/**
* A list of servers that the Job is acting upon.
*/
participatingServers?: ParticipatingServers;
/**
* The status of the Job.
*/
status?: JobStatus;
/**
* A list of tags associated with the Job.
*/
tags?: TagsMap;
/**
* The type of the Job.
*/
type?: JobType;
}
export type JobID = string;
export interface JobLog {
/**
* The event represents the type of a log.
*/
event?: JobLogEvent;
/**
* Metadata associated with a Job log.
*/
eventData?: JobLogEventData;
/**
* The date and time the log was taken.
*/
logDateTime?: ISO8601DatetimeString;
}
export type JobLogEvent = "JOB_START"|"SERVER_SKIPPED"|"CLEANUP_START"|"CLEANUP_END"|"CLEANUP_FAIL"|"SNAPSHOT_START"|"SNAPSHOT_END"|"SNAPSHOT_FAIL"|"USING_PREVIOUS_SNAPSHOT"|"USING_PREVIOUS_SNAPSHOT_FAILED"|"CONVERSION_START"|"CONVERSION_END"|"CONVERSION_FAIL"|"LAUNCH_START"|"LAUNCH_FAILED"|"JOB_CANCEL"|"JOB_END"|string;
export interface JobLogEventData {
/**
* The ID of a conversion server.
*/
conversionServerID?: EC2InstanceID;
/**
* A string representing a job error.
*/
rawError?: LargeBoundedString;
/**
* The ID of a Source Server.
*/
sourceServerID?: SourceServerID;
/**
* The ID of a Recovery Instance.
*/
targetInstanceID?: EC2InstanceID;
}
export type JobLogs = JobLog[];
export type JobStatus = "PENDING"|"STARTED"|"COMPLETED"|string;
export type JobType = "LAUNCH"|"TERMINATE"|string;
export type JobsList = Job[];
export type LargeBoundedString = string;
export type LastLaunchResult = "NOT_STARTED"|"PENDING"|"SUCCEEDED"|"FAILED"|string;
export type LastLaunchType = "RECOVERY"|"DRILL"|string;
export interface LaunchConfiguration {
/**
* Whether we should copy the Private IP of the Source Server to the Recovery Instance.
*/
copyPrivateIp?: Boolean;
/**
* Whether we want to copy the tags of the Source Server to the EC2 machine of the Recovery Instance.
*/
copyTags?: Boolean;
/**
* The EC2 launch template ID of this launch configuration.
*/
ec2LaunchTemplateID?: BoundedString;
/**
* The state of the Recovery Instance in EC2 after the recovery operation.
*/
launchDisposition?: LaunchDisposition;
/**
* The licensing configuration to be used for this launch configuration.
*/
licensing?: Licensing;
/**
* The name of the launch configuration.
*/
name?: SmallBoundedString;
/**
* The ID of the Source Server for this launch configuration.
*/
sourceServerID?: SourceServerID;
/**
* Whether Elastic Disaster Recovery should try to automatically choose the instance type that best matches the OS, CPU, and RAM of your Source Server.
*/
targetInstanceTypeRightSizingMethod?: TargetInstanceTypeRightSizingMethod;
}
export type LaunchDisposition = "STOPPED"|"STARTED"|string;
export type LaunchStatus = "PENDING"|"IN_PROGRESS"|"LAUNCHED"|"FAILED"|"TERMINATED"|string;
export interface Licensing {
/**
* Whether to enable "Bring your own license" or not.
*/
osByol?: Boolean;
}
export interface LifeCycle {
/**
* The date and time of when the Source Server was added to the service.
*/
addedToServiceDateTime?: ISO8601DatetimeString;
/**
* The amount of time that the Source Server has been replicating for.
*/
elapsedReplicationDuration?: ISO8601DatetimeString;
/**
* The date and time of the first byte that was replicated from the Source Server.
*/
firstByteDateTime?: ISO8601DatetimeString;
/**
* An object containing information regarding the last launch of the Source Server.
*/
lastLaunch?: LifeCycleLastLaunch;
/**
* The date and time this Source Server was last seen by the service.
*/
lastSeenByServiceDateTime?: ISO8601DatetimeString;
}
export interface LifeCycleLastLaunch {
/**
* An object containing information regarding the initiation of the last launch of a Source Server.
*/
initiated?: LifeCycleLastLaunchInitiated;
}
export interface LifeCycleLastLaunchInitiated {
/**
* The date and time the last Source Server launch was initiated.
*/
apiCallDateTime?: ISO8601DatetimeString;
/**
* The ID of the Job that was used to last launch the Source Server.
*/
jobID?: JobID;
/**
* The Job type that was used to last launch the Source Server.
*/
type?: LastLaunchType;
}
export interface ListTagsForResourceRequest {
/**
* The ARN of the resource whose tags should be returned.
*/
resourceArn: ARN;
}
export interface ListTagsForResourceResponse {
/**
* The tags of the requested resource.
*/
tags?: TagsMap;
}
export interface NetworkInterface {
/**
* Network interface IPs.
*/
ips?: IPsList;
/**
* Whether this is the primary network interface.
*/
isPrimary?: Boolean;
/**
* The MAC address of the network interface.
*/
macAddress?: BoundedString;
}
export type NetworkInterfaces = NetworkInterface[];
export interface OS {
/**
* The long name of the Operating System.
*/
fullString?: BoundedString;
}
export type PITPolicy = PITPolicyRule[];
export interface PITPolicyRule {
/**
* Whether this rule is enabled or not.
*/
enabled?: Boolean;
/**
* How often, in the chosen units, a snapshot should be taken.
*/
interval: StrictlyPositiveInteger;
/**
* The duration to retain a snapshot for, in the chosen units.
*/
retentionDuration: StrictlyPositiveInteger;
/**
* The ID of the rule.
*/
ruleID?: PositiveInteger;
/**
* The units used to measure the interval and retentionDuration.
*/
units: PITPolicyRuleUnits;
}
export type PITPolicyRuleUnits = "MINUTE"|"HOUR"|"DAY"|string;
export type PaginationToken = string;
export interface ParticipatingServer {
/**
* The launch status of a participating server.
*/
launchStatus?: LaunchStatus;
/**
* The Recovery Instance ID of a participating server.
*/
recoveryInstanceID?: RecoveryInstanceID;
/**
* The Source Server ID of a participating server.
*/
sourceServerID?: SourceServerID;
}
export type ParticipatingServers = ParticipatingServer[];
export type PositiveInteger = number;
export interface RecoveryInstance {
/**
* The ARN of the Recovery Instance.
*/
arn?: ARN;
/**
* The Data Replication Info of the Recovery Instance.
*/
dataReplicationInfo?: RecoveryInstanceDataReplicationInfo;
/**
* The EC2 instance ID of the Recovery Instance.
*/
ec2InstanceID?: EC2InstanceID;
/**
* The state of the EC2 instance for this Recovery Instance.
*/
ec2InstanceState?: EC2InstanceState;
/**
* An object representing failback related information of the Recovery Instance.
*/
failback?: RecoveryInstanceFailback;
/**
* Whether this Recovery Instance was created for a drill or for an actual Recovery event.
*/
isDrill?: Boolean;
/**
* The ID of the Job that created the Recovery Instance.
*/
jobID?: JobID;
/**
* The date and time of the Point in Time (PIT) snapshot that this Recovery Instance was launched from.
*/
pointInTimeSnapshotDateTime?: ISO8601DatetimeString;
/**
* The ID of the Recovery Instance.
*/
recoveryInstanceID?: RecoveryInstanceID;
/**
* Properties of the Recovery Instance machine.
*/
recoveryInstanceProperties?: RecoveryInstanceProperties;
/**
* The Source Server ID that this Recovery Instance is associated with.
*/
sourceServerID?: SourceServerID;
/**
* An array of tags that are associated with the Recovery Instance.
*/
tags?: TagsMap;
}
export interface RecoveryInstanceDataReplicationError {
/**
* Error in data replication.
*/
error?: FailbackReplicationError;
/**
* Error in data replication.
*/
rawError?: LargeBoundedString;
}
export interface RecoveryInstanceDataReplicationInfo {
/**
* Information about Data Replication
*/
dataReplicationError?: RecoveryInstanceDataReplicationError;
/**
* Information about whether the data replication has been initiated.
*/
dataReplicationInitiation?: RecoveryInstanceDataReplicationInitiation;
/**
* The state of the data replication.
*/
dataReplicationState?: RecoveryInstanceDataReplicationState;
/**
* An estimate of when the data replication will be completed.
*/
etaDateTime?: ISO8601DatetimeString;
/**
* Data replication lag duration.
*/
lagDuration?: ISO8601DatetimeString;
/**
* The disks that should be replicated.
*/
replicatedDisks?: RecoveryInstanceDataReplicationInfoReplicatedDisks;
}
export interface RecoveryInstanceDataReplicationInfoReplicatedDisk {
/**
* The size of the replication backlog in bytes.
*/
backloggedStorageBytes?: PositiveInteger;
/**
* The name of the device.
*/
deviceName?: BoundedString;
/**
* The amount of data replicated so far in bytes.
*/
replicatedStorageBytes?: PositiveInteger;
/**
* The amount of data to be rescanned in bytes.
*/
rescannedStorageBytes?: PositiveInteger;
/**
* The total amount of data to be replicated in bytes.
*/
totalStorageBytes?: PositiveInteger;
}
export type RecoveryInstanceDataReplicationInfoReplicatedDisks = RecoveryInstanceDataReplicationInfoReplicatedDisk[];
export interface RecoveryInstanceDataReplicationInitiation {
/**
* The date and time of the current attempt to initiate data replication.
*/
startDateTime?: ISO8601DatetimeString;
/**
* The steps of the current attempt to initiate data replication.
*/
steps?: RecoveryInstanceDataReplicationInitiationSteps;
}
export interface RecoveryInstanceDataReplicationInitiationStep {
/**
* The name of the step.
*/
name?: RecoveryInstanceDataReplicationInitiationStepName;
/**
* The status of the step.
*/
status?: RecoveryInstanceDataReplicationInitiationStepStatus;
}
export type RecoveryInstanceDataReplicationInitiationStepName = "LINK_FAILBACK_CLIENT_WITH_RECOVERY_INSTANCE"|"COMPLETE_VOLUME_MAPPING"|"ESTABLISH_RECOVERY_INSTANCE_COMMUNICATION"|"DOWNLOAD_REPLICATION_SOFTWARE_TO_FAILBACK_CLIENT"|"CONFIGURE_REPLICATION_SOFTWARE"|"PAIR_AGENT_WITH_REPLICATION_SOFTWARE"|"ESTABLISH_AGENT_REPLICATOR_SOFTWARE_COMMUNICATION"|string;
export type RecoveryInstanceDataReplicationInitiationStepStatus = "NOT_STARTED"|"IN_PROGRESS"|"SUCCEEDED"|"FAILED"|"SKIPPED"|string;
export type RecoveryInstanceDataReplicationInitiationSteps = RecoveryInstanceDataReplicationInitiationStep[];
export type RecoveryInstanceDataReplicationState = "STOPPED"|"INITIATING"|"INITIAL_SYNC"|"BACKLOG"|"CREATING_SNAPSHOT"|"CONTINUOUS"|"PAUSED"|"RESCAN"|"STALLED"|"DISCONNECTED"|string;
export interface RecoveryInstanceDisk {
/**
* The amount of storage on the disk in bytes.
*/
bytes?: PositiveInteger;
/**
* The EBS Volume ID of this disk.
*/
ebsVolumeID?: EbsVolumeID;
/**
* The internal device name of this disk. This is the name that is visible on the machine itself and not from the EC2 console.
*/
internalDeviceName?: BoundedString;
}
export type RecoveryInstanceDisks = RecoveryInstanceDisk[];
export interface RecoveryInstanceFailback {
/**
* The date and time the agent on the Recovery Instance was last seen by the service.
*/
agentLastSeenByServiceDateTime?: ISO8601DatetimeString;
/**
* The amount of time that the Recovery Instance has been replicating for.
*/
elapsedReplicationDuration?: ISO8601DatetimeString;
/**
* The ID of the failback client that this Recovery Instance is associated with.
*/
failbackClientID?: BoundedString;
/**
* The date and time that the failback client was last seen by the service.
*/
failbackClientLastSeenByServiceDateTime?: ISO8601DatetimeString;
/**
* The date and time that the failback initiation started.
*/
failbackInitiationTime?: ISO8601DatetimeString;
/**
* The Job ID of the last failback log for this Recovery Instance.
*/
failbackJobID?: JobID;
/**
* Whether we are failing back to the original Source Server for this Recovery Instance.
*/
failbackToOriginalServer?: Boolean;
/**
* The date and time of the first byte that was replicated from the Recovery Instance.
*/
firstByteDateTime?: ISO8601DatetimeString;
/**
* The state of the failback process that this Recovery Instance is in.
*/
state?: FailbackState;
}
export type RecoveryInstanceID = string;
export type RecoveryInstanceIDs = RecoveryInstanceID[];
export interface RecoveryInstanceProperties {
/**
* An array of CPUs.
*/
cpus?: Cpus;
/**
* An array of disks.
*/
disks?: RecoveryInstanceDisks;
/**
* Hints used to uniquely identify a machine.
*/
identificationHints?: IdentificationHints;
/**
* The date and time the Recovery Instance properties were last updated on.
*/
lastUpdatedDateTime?: ISO8601DatetimeString;
/**
* An array of network interfaces.
*/
networkInterfaces?: NetworkInterfaces;
/**
* Operating system.
*/
os?: OS;
/**
* The amount of RAM in bytes.
*/
ramBytes?: PositiveInteger;
}
export type RecoveryInstancesForTerminationRequest = RecoveryInstanceID[];
export interface RecoverySnapshot {
/**
* A list of EBS snapshots.
*/
ebsSnapshots?: EbsSnapshotsList;
/**
* The timestamp of when we expect the snapshot to be taken.
*/
expectedTimestamp: ISO8601DatetimeString;
/**
* The ID of the Recovery Snapshot.
*/
snapshotID: RecoverySnapshotID;
/**
* The ID of the Source Server that the snapshot was taken for.
*/
sourceServerID: SourceServerID;
/**
* The actual timestamp that the snapshot was taken.
*/
timestamp?: ISO8601DatetimeString;
}
export type RecoverySnapshotID = string;
export type RecoverySnapshotsList = RecoverySnapshot[];
export type RecoverySnapshotsOrder = "ASC"|"DESC"|string;
export interface ReplicationConfiguration {
/**
* Whether to associate the default Elastic Disaster Recovery Security group with the Replication Configuration.
*/
associateDefaultSecurityGroup?: Boolean;
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Source Server in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* Whether to create a Public IP for the Recovery Instance by default.
*/
createPublicIP?: Boolean;
/**
* The data plane routing mechanism that will be used for replication.
*/
dataPlaneRouting?: ReplicationConfigurationDataPlaneRouting;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
defaultLargeStagingDiskType?: ReplicationConfigurationDefaultLargeStagingDiskType;
/**
* The type of EBS encryption to be used during replication.
*/
ebsEncryption?: ReplicationConfigurationEbsEncryption;
/**
* The ARN of the EBS encryption key to be used during replication.
*/
ebsEncryptionKeyArn?: ARN;
/**
* The name of the Replication Configuration.
*/
name?: SmallBoundedString;
/**
* The Point in time (PIT) policy to manage snapshots taken during replication.
*/
pitPolicy?: PITPolicy;
/**
* The configuration of the disks of the Source Server to be replicated.
*/
replicatedDisks?: ReplicationConfigurationReplicatedDisks;
/**
* The instance type to be used for the replication server.
*/
replicationServerInstanceType?: EC2InstanceType;
/**
* The security group IDs that will be used by the replication server.
*/
replicationServersSecurityGroupsIDs?: ReplicationServersSecurityGroupsIDs;
/**
* The ID of the Source Server for this Replication Configuration.
*/
sourceServerID?: SourceServerID;
/**
* The subnet to be used by the replication staging area.
*/
stagingAreaSubnetId?: SubnetID;
/**
* A set of tags to be associated with all resources created in the replication staging area: EC2 replication server, EBS volumes, EBS snapshots, etc.
*/
stagingAreaTags?: TagsMap;
/**
* Whether to use a dedicated Replication Server in the replication staging area.
*/
useDedicatedReplicationServer?: Boolean;
}
export type ReplicationConfigurationDataPlaneRouting = "PRIVATE_IP"|"PUBLIC_IP"|string;
export type ReplicationConfigurationDefaultLargeStagingDiskType = "GP2"|"GP3"|"ST1"|string;
export type ReplicationConfigurationEbsEncryption = "DEFAULT"|"CUSTOM"|string;
export interface ReplicationConfigurationReplicatedDisk {
/**
* The name of the device.
*/
deviceName?: BoundedString;
/**
* The requested number of I/O operations per second (IOPS).
*/
iops?: PositiveInteger;
/**
* Whether to boot from this disk or not.
*/
isBootDisk?: Boolean;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
stagingDiskType?: ReplicationConfigurationReplicatedDiskStagingDiskType;
/**
* The throughput to use for the EBS volume in MiB/s. This parameter is valid only for gp3 volumes.
*/
throughput?: PositiveInteger;
}
export type ReplicationConfigurationReplicatedDiskStagingDiskType = "AUTO"|"GP2"|"GP3"|"IO1"|"SC1"|"ST1"|"STANDARD"|string;
export type ReplicationConfigurationReplicatedDisks = ReplicationConfigurationReplicatedDisk[];
export interface ReplicationConfigurationTemplate {
/**
* The Replication Configuration Template ARN.
*/
arn?: ARN;
/**
* Whether to associate the default Elastic Disaster Recovery Security group with the Replication Configuration Template.
*/
associateDefaultSecurityGroup?: Boolean;
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Source Server in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* Whether to create a Public IP for the Recovery Instance by default.
*/
createPublicIP?: Boolean;
/**
* The data plane routing mechanism that will be used for replication.
*/
dataPlaneRouting?: ReplicationConfigurationDataPlaneRouting;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
defaultLargeStagingDiskType?: ReplicationConfigurationDefaultLargeStagingDiskType;
/**
* The type of EBS encryption to be used during replication.
*/
ebsEncryption?: ReplicationConfigurationEbsEncryption;
/**
* The ARN of the EBS encryption key to be used during replication.
*/
ebsEncryptionKeyArn?: ARN;
/**
* The Point in time (PIT) policy to manage snapshots taken during replication.
*/
pitPolicy?: PITPolicy;
/**
* The Replication Configuration Template ID.
*/
replicationConfigurationTemplateID: ReplicationConfigurationTemplateID;
/**
* The instance type to be used for the replication server.
*/
replicationServerInstanceType?: EC2InstanceType;
/**
* The security group IDs that will be used by the replication server.
*/
replicationServersSecurityGroupsIDs?: ReplicationServersSecurityGroupsIDs;
/**
* The subnet to be used by the replication staging area.
*/
stagingAreaSubnetId?: SubnetID;
/**
* A set of tags to be associated with all resources created in the replication staging area: EC2 replication server, EBS volumes, EBS snapshots, etc.
*/
stagingAreaTags?: TagsMap;
/**
* A set of tags to be associated with the Replication Configuration Template resource.
*/
tags?: TagsMap;
/**
* Whether to use a dedicated Replication Server in the replication staging area.
*/
useDedicatedReplicationServer?: Boolean;
}
export type ReplicationConfigurationTemplateID = string;
export type ReplicationConfigurationTemplateIDs = ReplicationConfigurationTemplateID[];
export type ReplicationConfigurationTemplates = ReplicationConfigurationTemplate[];
export type ReplicationServersSecurityGroupsIDs = SecurityGroupID[];
export interface RetryDataReplicationRequest {
/**
* The ID of the Source Server whose data replication should be retried.
*/
sourceServerID: SourceServerID;
}
export type SecurityGroupID = string;
export type SmallBoundedString = string;
export interface SourceProperties {
/**
* An array of CPUs.
*/
cpus?: Cpus;
/**
* An array of disks.
*/
disks?: Disks;
/**
* Hints used to uniquely identify a machine.
*/
identificationHints?: IdentificationHints;
/**
* The date and time the Source Properties were last updated on.
*/
lastUpdatedDateTime?: ISO8601DatetimeString;
/**
* An array of network interfaces.
*/
networkInterfaces?: NetworkInterfaces;
/**
* Operating system.
*/
os?: OS;
/**
* The amount of RAM in bytes.
*/
ramBytes?: PositiveInteger;
/**
* The recommended EC2 instance type that will be used when recovering the Source Server.
*/
recommendedInstanceType?: EC2InstanceType;
}
export interface SourceServer {
/**
* The ARN of the Source Server.
*/
arn?: ARN;
/**
* The Data Replication Info of the Source Server.
*/
dataReplicationInfo?: DataReplicationInfo;
/**
* The status of the last recovery launch of this Source Server.
*/
lastLaunchResult?: LastLaunchResult;
/**
* The lifecycle information of this Source Server.
*/
lifeCycle?: LifeCycle;
/**
* The ID of the Recovery Instance associated with this Source Server.
*/
recoveryInstanceId?: RecoveryInstanceID;
/**
* The source properties of the Source Server.
*/
sourceProperties?: SourceProperties;
/**
* The ID of the Source Server.
*/
sourceServerID?: SourceServerID;
/**
* The tags associated with the Source Server.
*/
tags?: TagsMap;
}
export type SourceServerID = string;
export type SourceServerIDs = SourceServerID[];
export type SourceServersList = SourceServer[];
export interface StartFailbackLaunchRequest {
/**
* The IDs of the Recovery Instance whose failback launch we want to request.
*/
recoveryInstanceIDs: StartFailbackRequestRecoveryInstanceIDs;
/**
* The tags to be associated with the failback launch Job.
*/
tags?: TagsMap;
}
export interface StartFailbackLaunchResponse {
/**
* The failback launch Job.
*/
job?: Job;
}
export type StartFailbackRequestRecoveryInstanceIDs = RecoveryInstanceID[];
export interface StartRecoveryRequest {
/**
* Whether this Source Server Recovery operation is a drill or not.
*/
isDrill?: Boolean;
/**
* The Source Servers that we want to start a Recovery Job for.
*/
sourceServers: StartRecoveryRequestSourceServers;
/**
* The tags to be associated with the Recovery Job.
*/
tags?: TagsMap;
}
export interface StartRecoveryRequestSourceServer {
/**
* The ID of a Recovery Snapshot we want to recover from. Omit this field to launch from the latest data by taking an on-demand snapshot.
*/
recoverySnapshotID?: RecoverySnapshotID;
/**
* The ID of the Source Server you want to recover.
*/
sourceServerID: SourceServerID;
}
export type StartRecoveryRequestSourceServers = StartRecoveryRequestSourceServer[];
export interface StartRecoveryResponse {
/**
* The Recovery Job.
*/
job?: Job;
}
export interface StopFailbackRequest {
/**
* The ID of the Recovery Instance we want to stop failback for.
*/
recoveryInstanceID: RecoveryInstanceID;
}
export type StrictlyPositiveInteger = number;
export type SubnetID = string;
export type TagKey = string;
export type TagKeys = TagKey[];
export interface TagResourceRequest {
/**
* ARN of the resource for which tags are to be added or updated.
*/
resourceArn: ARN;
/**
* Array of tags to be added or updated.
*/
tags: TagsMap;
}
export type TagValue = string;
export type TagsMap = {[key: string]: TagValue};
export type TargetInstanceTypeRightSizingMethod = "NONE"|"BASIC"|string;
export interface TerminateRecoveryInstancesRequest {
/**
* The IDs of the Recovery Instances that should be terminated.
*/
recoveryInstanceIDs: RecoveryInstancesForTerminationRequest;
}
export interface TerminateRecoveryInstancesResponse {
/**
* The Job for terminating the Recovery Instances.
*/
job?: Job;
}
export interface UntagResourceRequest {
/**
* ARN of the resource for which tags are to be removed.
*/
resourceArn: ARN;
/**
* Array of tags to be removed.
*/
tagKeys: TagKeys;
}
export interface UpdateFailbackReplicationConfigurationRequest {
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Recovery Instance in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* The name of the Failback Replication Configuration.
*/
name?: BoundedString;
/**
* The ID of the Recovery Instance.
*/
recoveryInstanceID: RecoveryInstanceID;
/**
* Whether to use Private IP for the failback replication of the Recovery Instance.
*/
usePrivateIP?: Boolean;
}
export interface UpdateLaunchConfigurationRequest {
/**
* Whether we should copy the Private IP of the Source Server to the Recovery Instance.
*/
copyPrivateIp?: Boolean;
/**
* Whether we want to copy the tags of the Source Server to the EC2 machine of the Recovery Instance.
*/
copyTags?: Boolean;
/**
* The state of the Recovery Instance in EC2 after the recovery operation.
*/
launchDisposition?: LaunchDisposition;
/**
* The licensing configuration to be used for this launch configuration.
*/
licensing?: Licensing;
/**
* The name of the launch configuration.
*/
name?: SmallBoundedString;
/**
* The ID of the Source Server that we want to retrieve a Launch Configuration for.
*/
sourceServerID: SourceServerID;
/**
* Whether Elastic Disaster Recovery should try to automatically choose the instance type that best matches the OS, CPU, and RAM of your Source Server.
*/
targetInstanceTypeRightSizingMethod?: TargetInstanceTypeRightSizingMethod;
}
export interface UpdateReplicationConfigurationRequest {
/**
* Whether to associate the default Elastic Disaster Recovery Security group with the Replication Configuration.
*/
associateDefaultSecurityGroup?: Boolean;
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Source Server in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* Whether to create a Public IP for the Recovery Instance by default.
*/
createPublicIP?: Boolean;
/**
* The data plane routing mechanism that will be used for replication.
*/
dataPlaneRouting?: ReplicationConfigurationDataPlaneRouting;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
defaultLargeStagingDiskType?: ReplicationConfigurationDefaultLargeStagingDiskType;
/**
* The type of EBS encryption to be used during replication.
*/
ebsEncryption?: ReplicationConfigurationEbsEncryption;
/**
* The ARN of the EBS encryption key to be used during replication.
*/
ebsEncryptionKeyArn?: ARN;
/**
* The name of the Replication Configuration.
*/
name?: SmallBoundedString;
/**
* The Point in time (PIT) policy to manage snapshots taken during replication.
*/
pitPolicy?: PITPolicy;
/**
* The configuration of the disks of the Source Server to be replicated.
*/
replicatedDisks?: ReplicationConfigurationReplicatedDisks;
/**
* The instance type to be used for the replication server.
*/
replicationServerInstanceType?: EC2InstanceType;
/**
* The security group IDs that will be used by the replication server.
*/
replicationServersSecurityGroupsIDs?: ReplicationServersSecurityGroupsIDs;
/**
* The ID of the Source Server for this Replication Configuration.
*/
sourceServerID: SourceServerID;
/**
* The subnet to be used by the replication staging area.
*/
stagingAreaSubnetId?: SubnetID;
/**
* A set of tags to be associated with all resources created in the replication staging area: EC2 replication server, EBS volumes, EBS snapshots, etc.
*/
stagingAreaTags?: TagsMap;
/**
* Whether to use a dedicated Replication Server in the replication staging area.
*/
useDedicatedReplicationServer?: Boolean;
}
export interface UpdateReplicationConfigurationTemplateRequest {
/**
* The Replication Configuration Template ARN.
*/
arn?: ARN;
/**
* Whether to associate the default Elastic Disaster Recovery Security group with the Replication Configuration Template.
*/
associateDefaultSecurityGroup?: Boolean;
/**
* Configure bandwidth throttling for the outbound data transfer rate of the Source Server in Mbps.
*/
bandwidthThrottling?: PositiveInteger;
/**
* Whether to create a Public IP for the Recovery Instance by default.
*/
createPublicIP?: Boolean;
/**
* The data plane routing mechanism that will be used for replication.
*/
dataPlaneRouting?: ReplicationConfigurationDataPlaneRouting;
/**
* The Staging Disk EBS volume type to be used during replication.
*/
defaultLargeStagingDiskType?: ReplicationConfigurationDefaultLargeStagingDiskType;
/**
* The type of EBS encryption to be used during replication.
*/
ebsEncryption?: ReplicationConfigurationEbsEncryption;
/**
* The ARN of the EBS encryption key to be used during replication.
*/
ebsEncryptionKeyArn?: ARN;
/**
* The Point in time (PIT) policy to manage snapshots taken during replication.
*/
pitPolicy?: PITPolicy;
/**
* The Replication Configuration Template ID.
*/
replicationConfigurationTemplateID: ReplicationConfigurationTemplateID;
/**
* The instance type to be used for the replication server.
*/
replicationServerInstanceType?: EC2InstanceType;
/**
* The security group IDs that will be used by the replication server.
*/
replicationServersSecurityGroupsIDs?: ReplicationServersSecurityGroupsIDs;
/**
* The subnet to be used by the replication staging area.
*/
stagingAreaSubnetId?: SubnetID;
/**
* A set of tags to be associated with all resources created in the replication staging area: EC2 replication server, EBS volumes, EBS snapshots, etc.
*/
stagingAreaTags?: TagsMap;
/**
* Whether to use a dedicated Replication Server in the replication staging area.
*/
useDedicatedReplicationServer?: Boolean;
}
export type ebsSnapshot = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2020-02-26"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Drs client.
*/
export import Types = Drs;
}
export = Drs; | the_stack |
import { logger } from 'vscode-debugadapter';
import { ISetBreakpointResult, BreakOnLoadStrategy } from '../debugAdapterInterfaces';
import { Protocol as Crdp } from 'devtools-protocol';
import { ChromeDebugAdapter } from './chromeDebugAdapter';
import * as ChromeUtils from './chromeUtils';
import * as assert from 'assert';
import { InternalSourceBreakpoint } from './internalSourceBreakpoint';
import { utils, Version } from '..';
export interface UrlRegexAndFileSet {
urlRegex: string;
fileSet: Set<string>;
}
export class BreakOnLoadHelper {
private _doesDOMInstrumentationRecieveExtraEvent = false;
private _instrumentationBreakpointSet = false;
// Break on load: Store some mapping between the requested file names, the regex for the file, and the chrome breakpoint id to perform lookup operations efficiently
private _stopOnEntryBreakpointIdToRequestedFileName = new Map<string, UrlRegexAndFileSet>();
private _stopOnEntryRequestedFileNameToBreakpointId = new Map<string, string>();
private _stopOnEntryRegexToBreakpointId = new Map<string, string>();
private _chromeDebugAdapter: ChromeDebugAdapter;
private _breakOnLoadStrategy: BreakOnLoadStrategy;
public constructor(chromeDebugAdapter: ChromeDebugAdapter, breakOnLoadStrategy: BreakOnLoadStrategy) {
this.validateStrategy(breakOnLoadStrategy);
this._chromeDebugAdapter = chromeDebugAdapter;
this._breakOnLoadStrategy = breakOnLoadStrategy;
}
validateStrategy(breakOnLoadStrategy: BreakOnLoadStrategy): void {
if (breakOnLoadStrategy !== 'regex' && breakOnLoadStrategy !== 'instrument') {
throw new Error('Invalid breakOnLoadStrategy: ' + breakOnLoadStrategy);
}
}
public get stopOnEntryRequestedFileNameToBreakpointId(): Map<string, string> {
return this._stopOnEntryRequestedFileNameToBreakpointId;
}
public get stopOnEntryBreakpointIdToRequestedFileName(): Map<string, UrlRegexAndFileSet> {
return this._stopOnEntryBreakpointIdToRequestedFileName;
}
private get instrumentationBreakpointSet(): boolean {
return this._instrumentationBreakpointSet;
}
private getScriptUrlFromId(scriptId: string): string {
return utils.canonicalizeUrl(this._chromeDebugAdapter.scriptsById.get(scriptId).url);
}
public async setBrowserVersion(version: Version): Promise<void> {
// On version 69 Chrome stopped sending an extra event for DOM Instrumentation: See https://bugs.chromium.org/p/chromium/issues/detail?id=882909
// On Chrome 68 we were relying on that event to make Break on load work on breakpoints on the first line of a file. On Chrome 69 we need an alternative way to make it work.
this._doesDOMInstrumentationRecieveExtraEvent = !version.isAtLeastVersion(69, 0);
}
/**
* Handles the onpaused event.
* Checks if the event is caused by a stopOnEntry breakpoint of using the regex approach, or the paused event due to the Chrome's instrument approach
* Returns whether we should continue or not on this paused event
*/
public async handleOnPaused(notification: Crdp.Debugger.PausedEvent): Promise<boolean> {
if (notification.hitBreakpoints && notification.hitBreakpoints.length) {
// If breakOnLoadStrategy is set to regex, we may have hit a stopOnEntry breakpoint we put.
// So we need to resolve all the pending breakpoints in this script and then decide to continue or not
if (this._breakOnLoadStrategy === 'regex') {
let shouldContinue = await this.handleStopOnEntryBreakpointAndContinue(notification);
return shouldContinue;
}
} else if (this.isInstrumentationPause(notification)) {
// This is fired when Chrome stops on the first line of a script when using the setInstrumentationBreakpoint API
const pausedScriptId = notification.callFrames[0].location.scriptId;
// Now we wait for all the pending breakpoints to be resolved and then continue
await this._chromeDebugAdapter.getBreakpointsResolvedDefer(pausedScriptId).promise;
logger.log('BreakOnLoadHelper: Finished waiting for breakpoints to get resolved.');
let shouldContinue = this._doesDOMInstrumentationRecieveExtraEvent || await this.handleStopOnEntryBreakpointAndContinue(notification);
return shouldContinue;
}
return false;
}
private isInstrumentationPause(notification: Crdp.Debugger.PausedEvent): boolean {
return (notification.reason === 'EventListener' && notification.data.eventName === 'instrumentation:scriptFirstStatement') ||
(notification.reason === 'ambiguous' && Array.isArray(notification.data.reasons) &&
notification.data.reasons.every(r => r.reason === 'EventListener' && r.auxData.eventName === 'instrumentation:scriptFirstStatement'));
}
/**
* Returns whether we should continue on hitting a stopOnEntry breakpoint
* Only used when using regex approach for break on load
*/
private async shouldContinueOnStopOnEntryBreakpoint(pausedLocation: Crdp.Debugger.Location): Promise<boolean> {
// If the file has no unbound breakpoints or none of the resolved breakpoints are at (1,1), we should continue after hitting the stopOnEntry breakpoint
let shouldContinue = true;
// Important: For the logic that verifies if a user breakpoint is set in the paused location, we need to resolve pending breakpoints, and commit them, before
// using committedBreakpointsByUrl for our logic.
await this._chromeDebugAdapter.getBreakpointsResolvedDefer(pausedLocation.scriptId).promise;
const pausedScriptUrl = this.getScriptUrlFromId(pausedLocation.scriptId);
// Important: We need to get the committed breakpoints only after all the pending breakpoints for this file have been resolved. If not this logic won't work
const committedBps = this._chromeDebugAdapter.committedBreakpointsByUrl.get(pausedScriptUrl) || [];
const anyBreakpointsAtPausedLocation = committedBps.filter(bp =>
bp.actualLocation &&
bp.actualLocation.lineNumber === pausedLocation.lineNumber &&
bp.actualLocation.columnNumber === pausedLocation.columnNumber).length > 0;
// If there were any breakpoints at this location (Which generally should be (1,1)) we shouldn't continue
if (anyBreakpointsAtPausedLocation) {
// Here we need to store this information per file, but since we can safely assume that scriptParsed would immediately be followed by onPaused event
// for the breakonload files, this implementation should be fine
shouldContinue = false;
}
return shouldContinue;
}
/**
* Handles a script with a stop on entry breakpoint and returns whether we should continue or not on hitting that breakpoint
* Only used when using regex approach for break on load
*/
private async handleStopOnEntryBreakpointAndContinue(notification: Crdp.Debugger.PausedEvent): Promise<boolean> {
const hitBreakpoints = notification.hitBreakpoints;
let allStopOnEntryBreakpoints = true;
const pausedScriptId = notification.callFrames[0].location.scriptId;
const pausedScriptUrl = this._chromeDebugAdapter.scriptsById.get(pausedScriptId).url;
const mappedUrl = await this._chromeDebugAdapter.pathTransformer.scriptParsed(pausedScriptUrl);
// If there is a breakpoint which is not a stopOnEntry breakpoint, we appear as if we hit that one
// This is particularly done for cases when we end up with a user breakpoint and a stopOnEntry breakpoint on the same line
for (let bp of hitBreakpoints) {
let regexAndFileNames = this._stopOnEntryBreakpointIdToRequestedFileName.get(bp);
if (!regexAndFileNames) {
notification.hitBreakpoints = [bp];
allStopOnEntryBreakpoints = false;
} else {
const normalizedMappedUrl = utils.canonicalizeUrl(mappedUrl);
if (regexAndFileNames.fileSet.has(normalizedMappedUrl)) {
regexAndFileNames.fileSet.delete(normalizedMappedUrl);
assert(this._stopOnEntryRequestedFileNameToBreakpointId.delete(normalizedMappedUrl), `Expected to delete break-on-load information associated with url: ${normalizedMappedUrl}`);
if (regexAndFileNames.fileSet.size === 0) {
logger.log(`Stop on entry breakpoint hit for last remaining file. Removing: ${bp} created for: ${normalizedMappedUrl}`);
await this.removeBreakpointById(bp);
assert(this._stopOnEntryRegexToBreakpointId.delete(regexAndFileNames.urlRegex), `Expected to delete break-on-load information associated with regexp: ${regexAndFileNames.urlRegex}`);
} else {
logger.log(`Stop on entry breakpoint hit but still has remaining files. Keeping: ${bp} that was hit for: ${normalizedMappedUrl} because it's still needed for: ${Array.from(regexAndFileNames.fileSet.entries()).join(', ')}`);
}
}
}
}
// If all the breakpoints on this point are stopOnEntry breakpoints
// This will be true in cases where it's a single breakpoint and it's a stopOnEntry breakpoint
// This can also be true when we have multiple breakpoints and all of them are stopOnEntry breakpoints, for example in cases like index.js and index.bin.js
// Suppose user puts breakpoints in both index.js and index.bin.js files, when the setBreakpoints function is called for index.js it will set a stopOnEntry
// breakpoint on index.* files which will also match index.bin.js. Now when setBreakpoints is called for index.bin.js it will again put a stopOnEntry breakpoint
// in itself. So when the file is actually loaded, we would have 2 stopOnEntry breakpoints */
if (allStopOnEntryBreakpoints) {
const pausedLocation = notification.callFrames[0].location;
let shouldContinue = await this.shouldContinueOnStopOnEntryBreakpoint(pausedLocation);
if (shouldContinue) {
return true;
}
}
return false;
}
/**
* Adds a stopOnEntry breakpoint for the given script url
* Only used when using regex approach for break on load
*/
private async addStopOnEntryBreakpoint(url: string): Promise<ISetBreakpointResult[]> {
let responsePs: ISetBreakpointResult[];
// Check if file already has a stop on entry breakpoint
if (!this._stopOnEntryRequestedFileNameToBreakpointId.has(url)) {
// Generate regex we need for the file
const normalizedUrl = utils.canonicalizeUrl(url);
const urlRegex = ChromeUtils.getUrlRegexForBreakOnLoad(normalizedUrl);
// Check if we already have a breakpoint for this regexp since two different files like script.ts and script.js may have the same regexp
let breakpointId: string;
breakpointId = this._stopOnEntryRegexToBreakpointId.get(urlRegex);
// If breakpointId is undefined it means the breakpoint doesn't exist yet so we add it
if (breakpointId === undefined) {
let result;
try {
result = await this.setStopOnEntryBreakpoint(urlRegex);
} catch (e) {
logger.log(`Exception occured while trying to set stop on entry breakpoint ${e.message}.`);
}
if (result) {
breakpointId = result.breakpointId;
this._stopOnEntryRegexToBreakpointId.set(urlRegex, breakpointId);
} else {
logger.log(`BreakpointId was null when trying to set on urlregex ${urlRegex}. This normally happens if the breakpoint already exists.`);
}
responsePs = [result];
} else {
responsePs = [];
}
// Store the new breakpointId and the file name in the right mappings
this._stopOnEntryRequestedFileNameToBreakpointId.set(normalizedUrl, breakpointId);
let regexAndFileNames = this._stopOnEntryBreakpointIdToRequestedFileName.get(breakpointId);
// If there already exists an entry for the breakpoint Id, we add this file to the list of file mappings
if (regexAndFileNames !== undefined) {
regexAndFileNames.fileSet.add(normalizedUrl);
} else { // else create an entry for this breakpoint id
const fileSet = new Set<string>();
fileSet.add(normalizedUrl);
this._stopOnEntryBreakpointIdToRequestedFileName.set(breakpointId, { urlRegex, fileSet });
}
} else {
responsePs = [];
}
return Promise.all(responsePs);
}
/**
* Handles the AddBreakpoints request when break on load is active
* Takes the action based on the strategy
*/
public async handleAddBreakpoints(url: string, breakpoints: InternalSourceBreakpoint[]): Promise<ISetBreakpointResult[]> {
// If the strategy is set to regex, we try to match the file where user put the breakpoint through a regex and tell Chrome to put a stop on entry breakpoint there
if (this._breakOnLoadStrategy === 'regex') {
await this.addStopOnEntryBreakpoint(url);
} else if (this._breakOnLoadStrategy === 'instrument') {
// Else if strategy is to use Chrome's experimental instrumentation API, we stop on all the scripts at the first statement before execution
if (!this.instrumentationBreakpointSet) {
await this.setInstrumentationBreakpoint();
}
}
// Temporary fix: We return an empty element for each breakpoint that was requested
return breakpoints.map(breakpoint => { return {}; });
}
/**
* Tells Chrome to set instrumentation breakpoint to stop on all the scripts before execution
* Only used when using instrument approach for break on load
*/
private async setInstrumentationBreakpoint(): Promise<void> {
await this._chromeDebugAdapter.chrome.DOMDebugger.setInstrumentationBreakpoint({eventName: 'scriptFirstStatement'});
this._instrumentationBreakpointSet = true;
}
// Sets a breakpoint on (0,0) for the files matching the given regex
private async setStopOnEntryBreakpoint(urlRegex: string): Promise<Crdp.Debugger.SetBreakpointByUrlResponse> {
let result = await this._chromeDebugAdapter.chrome.Debugger.setBreakpointByUrl({ urlRegex, lineNumber: 0, columnNumber: 0 });
return result;
}
// Removes a breakpoint by it's chrome-crdp-id
private async removeBreakpointById(breakpointId: string): Promise<void> {
return await this._chromeDebugAdapter.chrome.Debugger.removeBreakpoint({breakpointId: breakpointId });
}
/**
* Checks if we need to call resolvePendingBPs on scriptParsed event
* If break on load is active and we are using the regex approach, only call the resolvePendingBreakpoint function for files where we do not
* set break on load breakpoints. For those files, it is called from onPaused function.
* For the default Chrome's API approach, we don't need to call resolvePendingBPs from inside scriptParsed
*/
public shouldResolvePendingBPs(mappedUrl: string): boolean {
if (this._breakOnLoadStrategy === 'regex' && !this.stopOnEntryRequestedFileNameToBreakpointId.has(mappedUrl)) {
return true;
}
return false;
}
} | the_stack |
export interface RebaseBinding {
context: object;
endpoint: string;
id: number;
method: string;
}
export interface SyncStateOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property you want to sync with Firebase; can be an
* arbitrarily nested property a là `foo.bar`.
*/
state: string;
/**
* A default value to set when the Firebase endpoint has no value (i.e.,
* on init) (use this if you want a value other than an empty object or
* empty array)
*/
defaultValue?: string | boolean | number | object | undefined;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean | undefined;
/**
* Will keep any firebase generated keys intact when manipulating data
* using the asArray option.
*/
keepKeys?: boolean | undefined;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object | undefined;
/**
* The callback function that will be invoked when the initial listener
* is established with Firebase. Typically used (with syncState) to
* change this.state.loading to false.
*/
then?: (() => void) | undefined;
/**
* A callback function that will be invoked if the current user does
* not have read or write permissions at the location.
*/
onFailure?: (() => void) | undefined;
}
export interface BindToStateOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property you want to sync with Firebase; can be an
* arbitrarily nested property a là `foo.bar` (no arrays).
*/
state: string;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean | undefined;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object | undefined;
/**
* The callback function that will be invoked when the initial listener
* is established with Firebase. Typically used (with bindToState) to
* change this.state.loading to false.
*/
then?: (() => void) | undefined;
/**
* A callback function that will be invoked if the current user does
* not have read permissions at the location.
*/
onFailure?: (() => void) | undefined;
}
export interface ListenToOptions {
/**
* The context of your component.
*/
context: object;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean | undefined;
/**
* The callback function that will be invoked with the data from the
* specified endpoint when the endpoint changes.
*/
then: (result: any) => void;
/**
* The callback function that will be invoked if the current user does
* not have read permissions at the location.
*/
onFailure?: ((error: any) => void) | undefined;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object | undefined;
}
export interface FetchOptions {
/**
* The context of your component.
*/
context: object;
/**
* Returns the Firebase data at the specified endpoint as an Array
* instead of an Object.
*/
asArray?: boolean | undefined;
/**
* The callback function that will be invoked with the data from the
* specified endpoint when the endpoint changes.
*/
then?: ((result: any) => void) | undefined;
/**
* The callback function that will be invoked with an error that occurs
* reading data from the specified endpoint.
*/
onFailure?: (() => void) | undefined;
/**
* Queries to be used with your read operations. See
* [Query Options](https://github.com/tylermcginnis/re-base#queries)
* for more details.
*/
queries?: object | undefined;
}
export interface PostOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: ((result: any) => void) | undefined;
}
export interface PushOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: ((result: any) => void) | undefined;
}
export interface UpdateOptions {
/**
* The data you're wanting to persist to Firebase.
*/
data: any;
/**
* A callback that will get invoked once the new data has been saved to
* Firebase. If there is an error, it will be the only argument to this
* function.
*/
then?: ((result: any) => void) | undefined;
}
export interface bindDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* A property name on your state to bind your document to, if omitted
* the document will be merged into your existing state.
*/
state?: string | undefined;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: (() => void) | undefined;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: (() => void) | undefined;
}
export interface listenToDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: (() => void) | undefined;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: (() => void) | undefined;
}
export interface bindCollectionOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property to bind the collection to.
*/
state?: string | undefined;
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: (() => void) | undefined;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean | undefined;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean | undefined;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: (() => void) | undefined;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: (() => void) | undefined;
}
export interface listenToCollectionOptions {
/**
* The context of your component.
*/
context: object;
/**
* A callback that will be called with the data.
*/
then: () => void;
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: (() => void) | undefined;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean | undefined;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean | undefined;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: (() => void) | undefined;
}
export interface getOptions {
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: (() => void) | undefined;
/**
* Will embed firestore generated document ids inside each document in
* your collections on the `id` property.
*/
withIds?: boolean | undefined;
/**
* will embed the DocumentReference inside each document in your
* collection on the `ref` property.
*/
withRefs?: boolean | undefined;
}
export interface removeFromCollectionOptions {
/**
* A function that receives the created ref as its only argument. You
* can chain any Firestore queries you want to perform. See
* [Using Firestore Queries](https://github.com/tylermcginnis/re-base#firestorequeries).
*/
query?: (() => void) | undefined;
}
export interface syncDocOptions {
/**
* The context of your component.
*/
context: object;
/**
* The state property to sync.
*/
state: string;
/**
* A callback that will be called when the listener is set, use for
* loading indicators.
*/
then?: (() => void) | undefined;
/**
* A callback that will be called with any errors such as permissions
* errors.
*/
onFailure?: (() => void) | undefined;
}
export interface Rebase {
/**
* This property contains the initialized firebase app that was passed
* into re-base. You can access any of the firebase services that you
* are using off this object. For instance, if you want to use some
* firebase database methods that re-base doesn't have helpers for or
* if you are using the auth service and want to quickly access it off
* of re-base.
*/
initializedApp: object;
/**
* This property contains an object that you can use when adding data
* that will be converted to a timestamp by Firebase. See
* [the docs](https://firebase.google.com/docs/reference/js/firebase.database.ServerValue)
* for more info.
*/
timestamp: object;
/**
* Allows you to set up two way data binding between your component's
* state and your Firebase. Whenever your Firebase changes, your
* component's state will change. Whenever your component's state
* changes, Firebase will change.
* @param endpoint The relative Firebase endpoint to which you'd like
* to bind your component's state.
* @param options syncState Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
syncState(endpoint: string, options: SyncStateOptions): RebaseBinding;
/**
* One way data binding from Firebase to your component's state. Allows
* you to bind a component's state property to a Firebase endpoint so
* whenever that Firebase endpoint changes, your component's state will
* be updated with that change.
* @param endpoint The relative Firebase endpoint that you'd like to
* bind to your component's state.
* @param options bindToState Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindToState(endpoint: string, options: BindToStateOptions): RebaseBinding;
/**
* Allows you to listen to Firebase endpoints without binding those
* changes to a state property. Instead, a callback will be invoked
* with the newly updated data.
* @param endpoint The relative Firebase endpoint which contains the
* data with which you'd like to invoke your callback function.
* @param options listenTo Options.
* @returns An object which you can pass to `removeBinding` when your
* component unmounts to remove the Firebase listeners.
*/
listenTo(endpoint: string, options: ListenToOptions): RebaseBinding;
/**
* Allows you to retrieve the data from a Firebase endpoint just once
* without subscribing or listening for data changes.
* @param endpoint The relative Firebase endpoint which contains the
* data you're wanting to fetch.
* @param options fetch Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
fetch(endpoint: string, options: FetchOptions): Promise<any>;
/**
* Allows you to update a Firebase endpoint with new data. *Replace all
* the data at this endpoint with the new data*.
* @param endpoint The relative Firebase endpoint that you'd like to
* update with the new data.
* @param options post Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
post(endpoint: string, options: PostOptions): Promise<any>;
/**
* Allows you to add data to a Firebase endpoint. *Adds data to a child
* of the endpoint with a new Firebase push key*.
* @param endpoint The relative Firebase endpoint that you'd like to
* push the new data to.
* @param options push Options.
* @returns A Firebase [ThenableReference](https://firebase.google.com/docs/reference/js/firebase.database.ThenableReference)
* which is defined by Firebase as a "Combined Promise and reference;
* resolves when write is complete, but can be used immediately as the
* reference to the child location."
*/
push(endpoint: string, options: PushOptions): Promise<any>;
/**
* Allows you to update data at a Firebase endpoint changing only the
* properties you pass to it. **Warning: calling update with
* `options.data` being null will remove all the data at that
* endpoint**.
* @param endpoint The relative Firebase endpoint that you'd like to
* update.
* @param options update Options.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
update(endpoint: string, options: UpdateOptions): Promise<any>;
/**
* Allows you to delete all data at the endpoint location.
* @param endpoint The relative Firebase endpoint that you'd like to
* delete data from.
* @param callback A callback that will get invoked once the data is
* successfully removed Firebase. If there is an error, it will be the
* only argument to this function.
* @returns A Firebase [Promise](https://firebase.google.com/docs/reference/js/firebase.Promise)
* which resolves when the write is complete and rejects if there is an
* error.
*/
remove(
endpoint: string,
callback?: (result: Promise<any>) => void
): Promise<any>;
/**
* Bind a document to your component. When then document changes in
* firestore, your component will re-render with the latest data.
* @param refOrPath DocumentReference or path.
* @param options bindDoc Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindDoc(refOrPath: object | string, options: bindDocOptions): object;
/**
* Listen to a document, when the data changes it will invoke a
* callback passing it the new data from Firestore.
* @param refOrPath DocumentReference or path.
* @param options listenToDoc Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
listenToDoc(
refOrPath: object | string,
options: listenToDocOptions
): object;
/**
* Bind a collection to a state property in your component. When then
* collection changes in firestore, your component will re-render with
* the latest data.
* @param refOrPath CollectionReference or path.
* @param options bindCollection Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
bindCollection(
refOrPath: object | string,
options: bindCollectionOptions
): RebaseBinding;
/**
* Listen to a collection, when the data changes it will invoke a
* callback passing it the new data from Firestore.
* @param refOrPath CollectionReference or path.
* @param options listenToCollection Options.
* @returns An object which you can pass to `removeBinding` if you want
* to remove the listener while the component is still mounted.
*/
listenToCollection(
refOrPath: object | string,
options: listenToCollectionOptions
): RebaseBinding;
/**
* Fetch either a Collection or Document.
* @param refOrPath CollectionReference, DocumentReference or path.
* @param options get Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
get(
refOrPath: object | object | string,
options: listenToCollectionOptions
): Promise<any>;
/**
* Add a new Document to a Collection.
* @param refOrPath CollectionReference or path.
* @param data The document data.
* @param id The id for the document. If omitted, the Firestore will
* generate an id for you.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
addToCollection(
refOrPath: object | string,
data: object,
id?: string
): Promise<any>;
/**
* Update an existing document.
* @param refOrPath DocumentReference or path.
* @param data The document data.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
updateDoc(refOrPath: object | string, data: object): Promise<any>;
/**
* Deletes a document.
* @param refOrPath DocumentReference or path.
* @param data The document data.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
removeDoc(refOrPath: object | string, data: object): Promise<any>;
/**
* Removes documents from a collection. If no query is supplied, it
* will remove all the documents. If a query is supplied, it will only
* remove documents that match the query.
* @param refOrPath CollectionReference or path.
* @param options removeFromCollection Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
removeFromCollection(
refOrPath: object | string,
options: removeFromCollectionOptions
): Promise<any>;
/**
* Syncs a component's local state with a document in Firestore.
* @param refOrPath DocumentReference or path.
* @param options removeFromCollection Options.
* @returns A Promise thats resolve with the resulting data or rejects
* if the document/collection does not exist or there are any read
* errors.
*/
syncDoc(refOrPath: object | string, options: syncDocOptions): object;
/**
* Clean up a listener. Listeners are automatically cleaned up when
* components unmount, however if you wish to remove a listener while
* the component is still mounted this will allow you to do that. An
* example would be if you want to start listening to a new document or
* change a query on all collection in response to a prop change.
* @param ref The return value of syncState`, `bindToState`, `listenTo`,
* `listenToCollection`, `bindCollection`, `listenToDoc`, `bindDoc` or
* `syncDoc`.
*/
removeBinding(ref: object): void;
/**
* Removes every Firebase/Firestore listener.
*/
reset(): void;
}
/**
* Accepts an initialized firebase/firestore database object.
* @param database Initialized firebase/firestore
* database.
* @return An instance of re-base.
*/
export function createClass(database: object): Rebase; | the_stack |
import {
I,
supportedTypes,
queryTypes, resultTypes,
err, errFromJSON, errToJSON,
} from '@statecraft/core'
import * as N from './netmessages'
import {
queryToNet, queryFromNet,
fullVersionToNet, fullVersionFromNet,
fullVersionRangeToNet, fullVersionRangeFromNet,
} from './util'
import {TinyReader, TinyWriter, listen} from './tinystream'
import streamToIter, {Stream} from 'ministreamiterator'
import {Readable, Writable, Duplex} from 'stream'
// import assert from 'assert'
const assert = (a: any) => { if (!a) throw Error('Assertion error: ' + a) }
const parseStoreInfo = (helloMsg: N.HelloMsg): I.StoreInfo => ({
uid: helloMsg.uid,
sources: helloMsg.sources,
sourceIsMonotonic: helloMsg.m,
capabilities: {
queryTypes: helloMsg.capabilities[0],
mutationTypes: helloMsg.capabilities[1]
},
})
const parseTxnsWithMeta = <Val>(type: I.ResultOps<any, any, I.Txn<Val>>, data: N.NetTxnWithMeta[]): I.TxnWithMeta<Val>[] => (
data.map(([op, v, meta]) => (<I.TxnWithMeta<Val>>{
txn: type.opFromJSON(op),
versions: fullVersionFromNet(v),
meta
}))
)
interface RemoteSub<Val> {
query: I.Query,
// This is needed to reestablish the subscription later
opts: I.SubscribeOpts,
// The stream that the client is reading over
stream: Stream<I.CatchupData<Val>>,
// We really need to reuse the stream object between reconnection sessions,
// but it'd be a huge hack to make the stream done function externally
// editable. So instead done calls sub.cleanup(), which is (re-)assigned to
// the current connection.
cleanup: () => void,
}
type ResRej = (val: any) => void
type Details = {
resolve: ResRej,
reject: ResRej,
type: 'fetch' | 'getOps' | 'mutate',
args: any[],
// type: I.QueryType | I.ResultType
}
// When we reconnect, a ReconnectionData object is passed to the caller. This
// contains everything needed to reestablish the connection. This is an opaque
// structure from the outside. Just pass it back into the next client's
// reconnect opt field.
interface ReconnectionData<Val> {
hello: N.HelloMsg,
subs: IterableIterator<RemoteSub<Val>>,
details: IterableIterator<Details>,
}
export interface ClientOpts<Val> {
// preserveOnClose?: (data: ReconnectionData) => void,
onClose?: () => void,
preserveState?: boolean,
restoreFrom?: NetStore<Val>,
syncReady?: (store: NetStore<Val>) => void // working around await not returning syncronously.
}
export type NetStore<Val> = I.Store<Val> & {
getState(): ReconnectionData<Val>
}
const checkHello = (hello: N.HelloMsg, ref?: I.StoreInfo) => {
// TODO: Move these errors into standard errors. Especially important for
// protocol version (& probably want some sort of epoch version too!)
if (hello.a !== N.Action.Hello || hello.p !== 'statecraft') throw Error('Invalid hello message')
if (hello.pv !== 0) throw Error('Incompatible protocol versions')
if (ref && ref.uid !== hello.uid) {
// TODO: Check that the storeinfo is compatible.
console.warn('Warning: Store has changed.')
throw new err.StoreChangedError()
}
}
function storeFromStreams<Val>(reader: TinyReader<N.SCMsg>,
writer: TinyWriter<N.CSMsg>,
hello: N.HelloMsg, opts: ClientOpts<Val> = {}): NetStore<Val> {
let nextRef = 1
const subByRef = new Map<N.Ref, RemoteSub<Val>>()
const detailsByRef = new Map<N.Ref, Details>()
let closed = false
const takeCallback = (ref: N.Ref): Details => {
const dets = detailsByRef.get(ref)
detailsByRef.delete(ref)
assert(dets) // ?? TODO: What should I do in this case?
return dets!
}
const cleanup = () => {
for (const {stream} of subByRef.values()) {
// Tell the receiver they won't get any more messages.
stream.end()
}
subByRef.clear()
for (const {reject} of detailsByRef.values()) {
reject(Error('Store closed before results returned'))
}
detailsByRef.clear()
}
reader.onClose = () => {
if (opts.onClose) opts.onClose()
if (!opts.preserveState) cleanup()
delete reader.onMessage
}
listen(reader, msg => {
// This is needed because we call detailsByRef.clear() in cleanup.
if (closed) return
// console.log('S->C data', msg)
switch (msg.a) {
case N.Action.Fetch: {
const {ref, results, bakedQuery, versions} = <N.FetchResponse>msg
const {resolve, args: [q]} = takeCallback(ref)
const type = queryTypes[q.type]!
resolve(<I.FetchResults<Val>>{
results: type.resultType.snapFromJSON(results),
bakedQuery: bakedQuery ? queryFromNet(bakedQuery) : undefined,
versions: fullVersionRangeFromNet(versions)
})
break
}
case N.Action.GetOps: {
const {ref, ops, v} = <N.GetOpsResponse>msg
const {resolve, args: [q]} = takeCallback(ref)
const type = queryTypes[q.type]!
resolve(<I.GetOpsResult<Val>>{
ops: parseTxnsWithMeta(type.resultType, ops),
versions: fullVersionRangeFromNet(v),
})
break
}
case N.Action.Mutate: {
const {ref, v} = <N.MutateResponse>msg
const {resolve} = takeCallback(ref)
resolve(<I.FullVersion>fullVersionFromNet(v))
break
}
case N.Action.Err: {
// This is used for both normal errors and subscription errors.
// We use the ref to disambiguate.
const {ref, err} = <N.ResponseErr>msg
const errObj = errFromJSON(err)
const sub = subByRef.get(ref)
if (sub) sub.stream.throw(errObj)
else takeCallback(ref).reject(errObj)
break
}
case N.Action.SubUpdate: {
const {ref, q, r, rv, txns, tv, u} = msg
const sub = subByRef.get(ref)
// Will happen if the client closes the sub and the server has
// messages in flight
if (!sub) break
const type = queryTypes[sub.query.type]
const toVersion = fullVersionFromNet(tv)
const update: I.CatchupData<Val> = {
replace: r == null ? undefined : {
q: queryFromNet(q!) as I.ReplaceQuery,
with: type.resultType.snapFromJSON(r),
versions: fullVersionFromNet(rv!),
},
txns: parseTxnsWithMeta(type.resultType, txns),
toVersion,
caughtUp: u,
}
// Update fromVersion so if we need to resubscribe we'll request
// the right version from the server. Note that I'm not updating
// the version if its specified as 'current'. In that mode you
// might miss operations! I have no idea if this is the right
// thing to do.
const fv = sub.opts.fromVersion
if (fv == null) sub.opts.fromVersion = toVersion
else if (fv !== 'current') toVersion.forEach((v, si) => {
if (v != null) fv[si] = v
})
sub.stream.append(update)
break
}
case N.Action.SubClose: {
const {ref} = msg
const sub = subByRef.get(ref)
if (sub != null) {
sub.stream.end()
subByRef.delete(ref)
}
break
}
default: console.error('Invalid or unknown server->client message', msg)
}
})
const registerSub = (sub: RemoteSub<Val>) => {
const ref = nextRef++
sub.cleanup = () => {
writer.write({a:N.Action.SubClose, ref})
subByRef.delete(ref)
}
subByRef.set(ref, sub)
const {opts} = sub
const netOpts: N.SubscribeOpts = {
// TODO more here.
st: Array.from(opts.supportedTypes || supportedTypes),
fv: opts.fromVersion === 'current' ? 'c'
: opts.fromVersion == null ? undefined
: fullVersionToNet(opts.fromVersion),
}
// Advertise that the subscription has been created, but don't wait
// for acknowledgement before returning it locally.
writer.write({a: N.Action.SubCreate, ref, query: queryToNet(sub.query), opts: netOpts})
}
const reqToMessage: {
[k: string]: (ref: number, ...args: any) => N.CSMsg
} = {
fetch: (ref: number, query: I.Query, opts: I.FetchOpts = {}) => ({
a: N.Action.Fetch, ref,
query: queryToNet(query),
opts: opts,
}),
getOps: (ref: number, query: I.Query, versions: I.FullVersionRange, opts: I.GetOpsOptions = {}) => ({
a: N.Action.GetOps, ref,
query: queryToNet(query),
v: fullVersionRangeToNet(versions), opts
}),
mutate: (ref: number, mtype: I.ResultType, txn: I.Txn<Val>, versions: I.FullVersion = [], opts: I.MutateOptions = {}) => ({
a: N.Action.Mutate, ref, mtype,
txn: resultTypes[mtype].opToJSON(txn),
v: fullVersionToNet(versions), opts
})
}
const registerReq = (type: 'fetch' | 'getOps' | 'mutate', resolve: ResRej, reject: ResRej, args: any[]) => {
const ref = nextRef++
const msg = reqToMessage[type](ref, ...args)
detailsByRef.set(ref, {type, args, resolve, reject})
writer.write(msg)
}
const req = (type: 'fetch' | 'getOps' | 'mutate') => (...args: any[]): Promise<any> => {
return new Promise((resolve, reject) => {
if (closed) return reject(Error('Cannot make request from a closed store'))
registerReq(type, resolve, reject, args)
})
}
if (opts.restoreFrom) {
const state = opts.restoreFrom.getState()
// Wire the listed subscriptions back up to the server
for (const sub of state.subs) registerSub(sub)
for (const d of state.details) registerReq(d.type, d.resolve, d.reject, d.args)
}
// const store: I.Store = {
return {
storeInfo: parseStoreInfo(hello),
fetch: req('fetch'),
getOps: req('getOps'),
mutate: req('mutate'),
subscribe(query, opts = {}) {
if (closed) throw Error('Cannot make request from a closed store')
const sub = {
query, opts,
} as RemoteSub<Val>
sub.stream = streamToIter<I.CatchupData<Val>>(() => sub.cleanup())
registerSub(sub)
return sub.stream.iter
},
close() {
closed = true
writer.close()
cleanup()
},
getState() {
return {
hello,
subs: subByRef.values(),
details: detailsByRef.values(),
};
}
}
}
// export function reconnectStore(reader: TinyReader<N.SCMsg>,
// writer: TinyWriter<N.CSMsg>,
// reconnectState: ReconnectionData,
// opts: ClientOpts = {}): NetStore {
// opts.reconnect = reconnectState // Gross.
// return storeFromStreams(reader, writer, reconnectState.hello, opts)
// }
const readNext = <T>(r: TinyReader<T>): Promise<T> => (
// This is a bit overly simple for general use, but it should work ok for what I'm using it for.
new Promise((resolve, reject) => {
if (r.buf.length) return resolve(r.buf.shift())
else {
r.onMessage = msg => {
resolve(msg)
delete r.onMessage // Let subsequent messages flow to r.buf
}
r.onClose = () => reject(new Error('Closed before handshake'))
}
})
)
export default async function createStore<Val>(
reader: TinyReader<N.SCMsg>,
writer: TinyWriter<N.CSMsg>,
opts: ClientOpts<Val> = {}): Promise<NetStore<Val>> {
const hello = await readNext(reader) as N.HelloMsg
checkHello(hello, opts.restoreFrom ? opts.restoreFrom.storeInfo : undefined)
const store = storeFromStreams(reader, writer, hello, opts)
if (opts.syncReady) opts.syncReady(store)
return store
} | the_stack |
import { expect, assert } from 'chai';
import { Keys, DeployUtil, CLValue } from '../../src/lib';
import { humanizerTTL, dehumanizerTTL } from '../../src/lib/DeployUtil';
import { TypedJSON } from 'typedjson';
const testDeploy = () => {
const senderKey = Keys.Ed25519.new();
const recipientKey = Keys.Ed25519.new();
const networkName = 'test-network';
const paymentAmount = 10000000000000;
const transferAmount = 10;
const transferId = 34;
let deployParams = new DeployUtil.DeployParams(
senderKey.publicKey,
networkName
);
let session = DeployUtil.ExecutableDeployItem.newTransfer(
transferAmount,
recipientKey.publicKey,
undefined,
transferId
);
let payment = DeployUtil.standardPayment(paymentAmount);
let deploy = DeployUtil.makeDeploy(deployParams, session, payment);
deploy = DeployUtil.signDeploy(deploy, senderKey);
return deploy;
}
describe('DeployUtil', () => {
it('should stringify/parse DeployHeader correctly', function () {
const ed25519Key = Keys.Ed25519.new();
const deployHeader = new DeployUtil.DeployHeader(
ed25519Key.publicKey,
123456,
654321,
10,
Uint8Array.from(Array(32).fill(42)),
[Uint8Array.from(Array(32).fill(2))],
'test-network'
);
const serializer = new TypedJSON(DeployUtil.DeployHeader);
const json = serializer.stringify(deployHeader);
const deployHeader1 = serializer.parse(json);
expect(deployHeader1).to.deep.equal(deployHeader);
});
it('should allow to extract data from Transfer', function () {
const senderKey = Keys.Ed25519.new();
const recipientKey = Keys.Ed25519.new();
const networkName = 'test-network';
const paymentAmount = 10000000000000;
const transferAmount = 10;
const id = 34;
let deployParams = new DeployUtil.DeployParams(
senderKey.publicKey,
networkName
);
let session = DeployUtil.ExecutableDeployItem.newTransfer(
transferAmount,
recipientKey.publicKey,
undefined,
id
);
let payment = DeployUtil.standardPayment(paymentAmount);
let deploy = DeployUtil.makeDeploy(deployParams, session, payment);
deploy = DeployUtil.signDeploy(deploy, senderKey);
deploy = DeployUtil.signDeploy(deploy, recipientKey);
// Serialize deploy to JSON.
let json = DeployUtil.deployToJson(deploy);
// Deserialize deploy from JSON.
deploy = DeployUtil.deployFromJson(json)!;
assert.isTrue(deploy.isTransfer());
assert.isTrue(deploy.isStandardPayment());
assert.deepEqual(deploy.header.account, senderKey.publicKey);
assert.deepEqual(
deploy.payment.getArgByName('amount')!.asBigNumber().toNumber(),
paymentAmount
);
assert.deepEqual(
deploy.session.getArgByName('amount')!.asBigNumber().toNumber(),
transferAmount
);
assert.deepEqual(
deploy.session.getArgByName('target')!.asBytesArray(),
recipientKey.accountHash()
);
assert.deepEqual(
deploy.session
.getArgByName('id')!
.asOption()
.getSome()
.asBigNumber()
.toNumber(),
id
);
assert.deepEqual(deploy.approvals[0].signer, senderKey.accountHex());
assert.deepEqual(deploy.approvals[1].signer, recipientKey.accountHex());
});
it('should allow to add arg to Deploy', function () {
const senderKey = Keys.Ed25519.new();
const recipientKey = Keys.Ed25519.new();
const networkName = 'test-network';
const paymentAmount = 10000000000000;
const transferAmount = 10;
const id = 34;
const customId = 60;
let deployParams = new DeployUtil.DeployParams(
senderKey.publicKey,
networkName
);
let session = DeployUtil.ExecutableDeployItem.newTransfer(
transferAmount,
recipientKey.publicKey,
undefined,
id
);
let payment = DeployUtil.standardPayment(paymentAmount);
let oldDeploy = DeployUtil.makeDeploy(deployParams, session, payment);
// Add new argument.
let deploy = DeployUtil.addArgToDeploy(
oldDeploy,
'custom_id',
CLValue.u32(customId)
);
// Serialize and deserialize deploy.
let json = DeployUtil.deployToJson(deploy);
deploy = DeployUtil.deployFromJson(json)!;
assert.deepEqual(
deploy.session.getArgByName('custom_id')!.asBigNumber().toNumber(),
customId
);
assert.isTrue(deploy.isTransfer());
assert.isTrue(deploy.isStandardPayment());
assert.deepEqual(deploy.header.account, senderKey.publicKey);
assert.deepEqual(
deploy.payment.getArgByName('amount')!.asBigNumber().toNumber(),
paymentAmount
);
assert.deepEqual(
deploy.session.getArgByName('amount')!.asBigNumber().toNumber(),
transferAmount
);
assert.deepEqual(
deploy.session.getArgByName('target')!.asBytesArray(),
recipientKey.accountHash()
);
assert.deepEqual(
deploy.session
.getArgByName('id')!
.asOption()
.getSome()
.asBigNumber()
.toNumber(),
id
);
assert.notEqual(oldDeploy.hash, deploy.hash);
assert.notEqual(oldDeploy.header.bodyHash, deploy.header.bodyHash);
});
it('should not allow to add arg to a signed Deploy', function () {
expect(() => {
DeployUtil.addArgToDeploy(testDeploy(), 'custom_id', CLValue.u32(1));
}).to.throw('Can not add argument to already signed deploy.');
});
it('should allow to extract additional args from Transfer.', function () {
// const from = Keys.Ed25519.new();
const from = Keys.Secp256K1.new();
const to = Keys.Ed25519.new();
const networkName = 'test-network';
const paymentAmount = 10000000000000;
const transferAmount = 10;
const id = 34;
let deployParams = new DeployUtil.DeployParams(from.publicKey, networkName);
let session = DeployUtil.ExecutableDeployItem.newTransfer(
transferAmount,
to.publicKey,
undefined,
id
);
let payment = DeployUtil.standardPayment(paymentAmount);
let deploy = DeployUtil.makeDeploy(deployParams, session, payment);
let transferDeploy = DeployUtil.addArgToDeploy(
deploy,
'fromPublicKey',
CLValue.publicKey(from.publicKey)
);
assert.deepEqual(
transferDeploy.session.getArgByName('fromPublicKey')?.asPublicKey(),
from.publicKey
);
let newTransferDeploy = DeployUtil.deployFromJson(
DeployUtil.deployToJson(transferDeploy)
);
assert.deepEqual(
newTransferDeploy?.session.getArgByName('fromPublicKey')?.asPublicKey(),
from.publicKey
);
});
it('Should not allow for to deserialize a deploy from JSON with a wrong deploy hash', function () {
let deploy = testDeploy();
let json = DeployUtil.deployToJson(deploy);
Object.assign(json.deploy, { hash: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" });
assert.isUndefined(DeployUtil.deployFromJson(json));
});
it('Should not allow for to deserialize a deploy from JSON with a wrong body_hash', function () {
let deploy = testDeploy();
let json = DeployUtil.deployToJson(deploy);
let header = Object(json.deploy)['header'];
header['body_hash'] = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
Object.assign(json.deploy, { header });
assert.isUndefined(DeployUtil.deployFromJson(json));
});
it('Should convert ms to humanized string', function () {
const strTtl30m = humanizerTTL(1800000);
const strTtl45m = humanizerTTL(2700000);
const strTtl1h = humanizerTTL(3600000);
const strTtl1h30m = humanizerTTL(5400000);
const strTtl1day = humanizerTTL(86400000);
const strTtlCustom = humanizerTTL(86103000);
expect(strTtl30m).to.be.eq("30m");
expect(strTtl45m).to.be.eq("45m");
expect(strTtl1h).to.be.eq("1h");
expect(strTtl1h30m).to.be.eq("1h 30m");
expect(strTtl1day).to.be.eq("1day");
expect(strTtlCustom).to.be.eq("23h 55m 3s");
});
it('Should convert humanized string to ms', function () {
const msTtl30m = dehumanizerTTL("30m");
const msTtl45m = dehumanizerTTL("45m");
const msTtl1h = dehumanizerTTL("1h");
const msTtl1h30m = dehumanizerTTL("1h 30m");
const msTtl1day = dehumanizerTTL("1day");
const msTtlCustom = dehumanizerTTL("23h 55m 3s");
expect(msTtl30m).to.be.eq(1800000);
expect(msTtl45m).to.be.eq(2700000);
expect(msTtl1h).to.be.eq(3600000);
expect(msTtl1h30m).to.be.eq(5400000);
expect(msTtl1day).to.be.eq(86400000);
expect(msTtlCustom).to.be.eq(86103000);
});
it('Should not allow to create new transfer without providing transfer-id', () => {
const recipientKey = Keys.Ed25519.new();
const transferAmount = 10;
/* @ts-ignore */
const badFn = () => DeployUtil.ExecutableDeployItem.newTransfer(
transferAmount,
recipientKey.publicKey,
undefined,
);
expect(badFn).to.throw('transfer-id missing in new transfer.');
});
it('newTransferToUniqAddress should construct proper deploy', () => {
const senderKey = Keys.Ed25519.new();
const recipientKey = Keys.Ed25519.new();
const networkName = 'test-network';
const paymentAmount = 10000000000000;
const transferAmount = 10;
const transferId = 34;
const uniqAddress = new DeployUtil.UniqAddress(recipientKey.publicKey, transferId);
let deploy = DeployUtil.ExecutableDeployItem.newTransferToUniqAddress(
senderKey.publicKey,
uniqAddress,
transferAmount,
paymentAmount,
networkName
);
deploy = DeployUtil.signDeploy(deploy, senderKey);
assert.isTrue(deploy.isTransfer());
assert.isTrue(deploy.isStandardPayment());
assert.deepEqual(deploy.header.account, senderKey.publicKey);
assert.deepEqual(
deploy.payment.getArgByName('amount')!.asBigNumber().toNumber(),
paymentAmount
);
assert.deepEqual(
deploy.session.getArgByName('amount')!.asBigNumber().toNumber(),
transferAmount
);
assert.deepEqual(
deploy.session.getArgByName('target')!.asBytesArray(),
recipientKey.accountHash()
);
assert.deepEqual(
deploy.session
.getArgByName('id')!
.asOption()
.getSome()
.asBigNumber()
.toNumber(),
transferId
);
});
it('DeployUtil.UniqAddress should serialize and deserialize', () => {
const recipientKey = Keys.Ed25519.new();
const hexAddress = recipientKey.publicKey.toAccountHex();
const transferId = "80172309";
const transferIdHex = "0x04c75515";
const uniqAddress = new DeployUtil.UniqAddress(recipientKey.publicKey, transferId);
expect(uniqAddress).to.be.instanceof(DeployUtil.UniqAddress);
expect(uniqAddress.toString()).to.be.eq(`${hexAddress}-${transferIdHex}`);
});
it('DeployUtil.deployToBytes should produce correct byte representation.', () => {
let deploy = DeployUtil.deployFromJson({
"deploy": {
"hash": "d7a68bbe656a883d04bba9f26aa340dbe3f8ec99b2adb63b628f2bc920431998",
"header": {
"account": "017f747b67bd3fe63c2a736739dfe40156d622347346e70f68f51c178a75ce5537",
"timestamp": "2021-05-04T14:20:35.104Z",
"ttl": "30m",
"gas_price": 2,
"body_hash": "f2e0782bba4a0a9663cafc7d707fd4a74421bc5bfef4e368b7e8f38dfab87db8",
"dependencies": [
"0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f",
"1010101010101010101010101010101010101010101010101010101010101010"
],
"chain_name": "mainnet"
},
"payment": {
"ModuleBytes": {
"module_bytes": "",
"args": [
[
"amount",
{
"cl_type": "U512",
"bytes": "0400ca9a3b",
"parsed": "1000000000"
}
]
]
}
},
"session": {
"Transfer": {
"args": [
[
"amount",
{
"cl_type": "U512",
"bytes": "05005550b405",
"parsed": "24500000000"
}
],
[
"target",
{
"cl_type": {
"ByteArray": 32
},
"bytes": "0101010101010101010101010101010101010101010101010101010101010101",
"parsed": "0101010101010101010101010101010101010101010101010101010101010101"
}
],
[
"id",
{
"cl_type": {
"Option": "U64"
},
"bytes": "01e703000000000000",
"parsed": 999
}
],
[
"additional_info",
{
"cl_type": "String",
"bytes": "1000000074686973206973207472616e73666572",
"parsed": "this is transfer"
}
]
]
}
},
"approvals": [
{
"signer": "017f747b67bd3fe63c2a736739dfe40156d622347346e70f68f51c178a75ce5537",
"signature": "0195a68b1a05731b7014e580b4c67a506e0339a7fffeaded9f24eb2e7f78b96bdd900b9be8ca33e4552a9a619dc4fc5e4e3a9f74a4b0537c14a5a8007d62a5dc06"
}
]
}
});
let expected = "017f747b67bd3fe63c2a736739dfe40156d622347346e70f68f51c178a75ce5537a087c0377901000040771b00000000000200000000000000f2e0782bba4a0a9663cafc7d707fd4a74421bc5bfef4e368b7e8f38dfab87db8020000000f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f1010101010101010101010101010101010101010101010101010101010101010070000006d61696e6e6574d7a68bbe656a883d04bba9f26aa340dbe3f8ec99b2adb63b628f2bc92043199800000000000100000006000000616d6f756e74050000000400ca9a3b08050400000006000000616d6f756e740600000005005550b40508060000007461726765742000000001010101010101010101010101010101010101010101010101010101010101010f200000000200000069640900000001e7030000000000000d050f0000006164646974696f6e616c5f696e666f140000001000000074686973206973207472616e736665720a01000000017f747b67bd3fe63c2a736739dfe40156d622347346e70f68f51c178a75ce55370195a68b1a05731b7014e580b4c67a506e0339a7fffeaded9f24eb2e7f78b96bdd900b9be8ca33e4552a9a619dc4fc5e4e3a9f74a4b0537c14a5a8007d62a5dc06";
let result = Buffer.from(DeployUtil.deployToBytes(deploy!)).toString('hex');
assert.equal(result, expected);
});
}); | the_stack |
'use strict'
import { ethers } from 'ethers'
import { task } from 'hardhat/config'
import * as types from 'hardhat/internal/core/params/argumentTypes'
import { hexStringEquals } from '@eth-optimism/core-utils'
import { getContractFactory, getContractDefinition } from '../src/contract-defs'
import { names } from '../src/address-names'
import {
getInput,
color as c,
getArtifactFromManagedName,
getEtherscanUrl,
printSectionHead,
printComparison,
} from '../src/validation-utils'
task('validate:address-dictator')
.addParam(
'dictator',
'Address of the AddressDictator to validate.',
undefined,
types.string
)
.addParam(
'manager',
'Address of the Address Manager contract which would be updated by the Dictator.',
undefined,
types.string
)
.addParam(
'multisig',
'Address of the multisig contract which should be the final owner',
undefined,
types.string
)
.addOptionalParam(
'contractsRpcUrl',
'RPC Endpoint to query for data',
process.env.CONTRACTS_RPC_URL,
types.string
)
.setAction(async (args) => {
if (!args.contractsRpcUrl) {
throw new Error(
c.red('RPC URL must be set in your env, or passed as an argument.')
)
}
const provider = new ethers.providers.JsonRpcProvider(args.contractsRpcUrl)
const network = await provider.getNetwork()
console.log()
printSectionHead("First make sure you're on the right chain:")
console.log(
`Reading from the ${c.red(network.name)} network (Chain ID: ${c.red(
'' + network.chainId
)})`
)
await getInput(c.yellow('OK? Hit enter to continue.'))
const dictatorArtifact = getContractDefinition('AddressDictator')
const dictatorCode = await provider.getCode(args.dictator)
printSectionHead(`
Validate the Address Dictator deployment at\n${getEtherscanUrl(
network,
args.dictator
)}`)
printComparison(
'Comparing deployed AddressDictator bytecode against local build artifacts',
'Deployed AddressDictator code',
{ name: 'Compiled bytecode', value: dictatorArtifact.deployedBytecode },
{ name: 'Deployed bytecode', value: dictatorCode }
)
// Connect to the deployed AddressDictator.
const dictatorContract = getContractFactory('AddressDictator')
.attach(args.dictator)
.connect(provider)
const finalOwner = await dictatorContract.finalOwner()
printComparison(
'Comparing the finalOwner address in the AddressDictator to the multisig address',
'finalOwner',
{ name: 'multisig address', value: args.multisig },
{ name: 'finalOwner ', value: finalOwner }
)
const deployedManager = await dictatorContract.manager()
printComparison(
'Validating the AddressManager address in the AddressDictator',
'addressManager',
{ name: 'manager ', value: args.manager },
{ name: 'Address Manager', value: deployedManager }
)
await getInput(c.yellow('OK? Hit enter to continue.'))
// Get names and addresses from the Dictator.
const namedAddresses = await dictatorContract.getNamedAddresses()
// In order to reduce noise for the user, we query the AddressManager identify addresses that
// will not be changed, and skip over them in this block.
const managerContract = getContractFactory('Lib_AddressManager')
.attach(args.manager)
.connect(provider)
// Now we loop over those and compare the addresses/deployedBytecode to deployment artifacts.
for (const pair of namedAddresses) {
if (pair.name === 'L2CrossDomainMessenger') {
console.log('L2CrossDomainMessenger is set to:', pair.addr)
await getInput(c.yellow('OK? Hit enter to continue.'))
// This is an L2 predeploy, so we skip bytecode and config validation.
continue
}
const currentAddress = await managerContract.getAddress(pair.name)
const artifact = getArtifactFromManagedName(pair.name)
const addressChanged = !hexStringEquals(currentAddress, pair.addr)
if (addressChanged) {
printSectionHead(
`Validate the ${pair.name} deployment.
Current address: ${getEtherscanUrl(network, currentAddress)}
Upgraded address ${getEtherscanUrl(network, pair.addr)}`
)
const code = await provider.getCode(pair.addr)
printComparison(
`Verifying ${pair.name} source code against local deployment artifacts`,
`Deployed ${pair.name} code`,
{
name: 'artifact.deployedBytecode',
value: artifact.deployedBytecode,
},
{ name: 'Deployed bytecode ', value: code }
)
// Identify contracts which inherit from Lib_AddressResolver, and check that they
// have the right manager address.
if (Object.keys(artifact)) {
if (artifact.abi.some((el) => el.name === 'libAddressManager')) {
const libAddressManager = await getContractFactory(
'Lib_AddressResolver'
)
.attach(pair.addr)
.connect(provider)
.libAddressManager()
printComparison(
`Verifying ${pair.name} has the correct AddressManager address`,
`The AddressManager address in ${pair.name}`,
{ name: 'Deployed value', value: libAddressManager },
{ name: 'Expected value', value: deployedManager }
)
await getInput(c.yellow('OK? Hit enter to continue.'))
}
}
}
await validateDeployedConfig(provider, network, args.manager, pair)
}
console.log(c.green('\nAddressManager Validation complete!'))
})
/**
* Validates that the deployed contracts have the expected storage variables.
*
* @param {*} provider
* @param {{ name: string; addr: string }} pair The contract name and address
*/
const validateDeployedConfig = async (
provider,
network,
manager,
pair: { name: string; addr: string }
) => {
printSectionHead(`
Ensure that the ${pair.name} at\n${getEtherscanUrl(
network,
pair.addr
)} is configured correctly`)
if (pair.name === names.managed.contracts.StateCommitmentChain) {
const scc = getContractFactory(pair.name)
.attach(pair.addr)
.connect(provider)
// --scc-fraud-proof-window 604800 \
const fraudProofWindow = await scc.FRAUD_PROOF_WINDOW()
printComparison(
'Checking the fraudProofWindow of the StateCommitmentChain',
'StateCommitmentChain.fraudProofWindow',
{
name: 'Configured fraudProofWindow',
value: ethers.BigNumber.from(604_800).toHexString(),
},
{
name: 'Deployed fraudProofWindow ',
value: ethers.BigNumber.from(fraudProofWindow).toHexString(),
}
)
await getInput(c.yellow('OK? Hit enter to continue.'))
// --scc-sequencer-publish-window 12592000 \
const sequencerPublishWindow = await scc.SEQUENCER_PUBLISH_WINDOW()
printComparison(
'Checking the sequencerPublishWindow of the StateCommitmentChain',
'StateCommitmentChain.sequencerPublishWindow',
{
name: 'Configured sequencerPublishWindow ',
value: ethers.BigNumber.from(12592000).toHexString(),
},
{
name: 'Deployed sequencerPublishWindow',
value: ethers.BigNumber.from(sequencerPublishWindow).toHexString(),
}
)
await getInput(c.yellow('OK? Hit enter to continue.'))
} else if (pair.name === names.managed.contracts.CanonicalTransactionChain) {
const ctc = getContractFactory(pair.name)
.attach(pair.addr)
.connect(provider)
// --ctc-max-transaction-gas-limit 15000000 \
const maxTransactionGasLimit = await ctc.maxTransactionGasLimit()
printComparison(
'Checking the maxTransactionGasLimit of the CanonicalTransactionChain',
'CanonicalTransactionChain.maxTransactionGasLimit',
{
name: 'Configured maxTransactionGasLimit',
value: ethers.BigNumber.from(15_000_000).toHexString(),
},
{
name: 'Deployed maxTransactionGasLimit ',
value: ethers.BigNumber.from(maxTransactionGasLimit).toHexString(),
}
)
await getInput(c.yellow('OK? Hit enter to continue.'))
// --ctc-l2-gas-discount-divisor 32 \
const l2GasDiscountDivisor = await ctc.l2GasDiscountDivisor()
printComparison(
'Checking the l2GasDiscountDivisor of the CanonicalTransactionChain',
'CanonicalTransactionChain.l2GasDiscountDivisor',
{
name: 'Configured l2GasDiscountDivisor',
value: ethers.BigNumber.from(32).toHexString(),
},
{
name: 'Deployed l2GasDiscountDivisor ',
value: ethers.BigNumber.from(l2GasDiscountDivisor).toHexString(),
}
)
await getInput(c.yellow('OK? Hit enter to continue.'))
// --ctc-enqueue-gas-cost 60000 \
const enqueueGasCost = await ctc.enqueueGasCost()
printComparison(
'Checking the enqueueGasCost of the CanonicalTransactionChain',
'CanonicalTransactionChain.enqueueGasCost',
{
name: 'Configured enqueueGasCost',
value: ethers.BigNumber.from(60000).toHexString(),
},
{
name: 'Deployed enqueueGasCost ',
value: ethers.BigNumber.from(enqueueGasCost).toHexString(),
}
)
await getInput(c.yellow('OK? Hit enter to continue.'))
} else if (pair.name === names.managed.contracts.OVM_L1CrossDomainMessenger) {
const messengerManager = await getContractFactory('L1CrossDomainMessenger')
.attach(pair.addr)
.connect(provider)
.libAddressManager()
printComparison(
'Ensure that the L1CrossDomainMessenger (implementation) is initialized with a non-zero Address Manager variable',
"L1CrossDomainMessenger's Lib_AddressManager",
{
name: 'Configured Lib_AddressManager',
value: messengerManager,
},
{
name: 'Deployed Lib_AddressManager ',
value: manager,
}
)
} else {
console.log(c.green(`${pair.name} has no config to check`))
await getInput(c.yellow('OK? Hit enter to continue.'))
}
} | the_stack |
'use strict';
import * as vscode from 'vscode';
import * as chai from 'chai';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import { TestUtil } from '../TestUtil';
import { ExtensionCommands } from '../../ExtensionCommands';
import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter';
import { BlockchainEnvironmentExplorerProvider } from '../../extension/explorer/environmentExplorer';
import { ExtensionUtil } from '../../extension/util/ExtensionUtil';
import { UserInputUtil } from '../../extension/commands/UserInputUtil';
import { FabricEnvironmentManager } from '../../extension/fabric/environments/FabricEnvironmentManager';
import { PeerTreeItem } from '../../extension/explorer/runtimeOps/connectedTree/PeerTreeItem';
import { FabricNode, FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, LogType, FabricEnvironment, EnvironmentType } from 'ibm-blockchain-platform-common';
chai.should();
chai.use(sinonChai);
// tslint:disable no-unused-expression
describe('DeleteNodeCommand', () => {
let mySandBox: sinon.SinonSandbox;
before(async () => {
mySandBox = sinon.createSandbox();
await TestUtil.setupTests(mySandBox);
});
describe('deleteNode', () => {
let environmentRegistryEntry: FabricEnvironmentRegistryEntry;
let opsToolRegistryEntry: FabricEnvironmentRegistryEntry;
let peerNode: FabricNode;
let anotherPeerNode: FabricNode;
let morePeerNode: FabricNode;
let hiddenPeerNode: FabricNode;
let deleteNodeStub: sinon.SinonStub;
let updateNodeStub: sinon.SinonStub;
let getEnvStub: sinon.SinonStub;
let showEnvironmentStub: sinon.SinonStub;
let showNodeStub: sinon.SinonStub;
let executeCommandStub: sinon.SinonStub;
let showConfirmationWarningMessage: sinon.SinonStub;
let logSpy: sinon.SinonSpy;
let getNodesStub: sinon.SinonStub;
beforeEach(async () => {
mySandBox.restore();
logSpy = mySandBox.stub(VSCodeBlockchainOutputAdapter.instance(), 'log');
peerNode = FabricNode.newPeer('peer0.org1.example.com', 'peer0.org1.example.com', 'grpc://localhost:7051', 'Org1', 'admin', 'Org1MSP');
anotherPeerNode = FabricNode.newPeer('peer1.org1.example.com', 'peer1.org1.example.com', 'grpc://localhost:7051', 'Org1', 'admin', 'Org1MSP');
morePeerNode = FabricNode.newPeer('peer2.org1.example.com', 'peer2.org1.example.com', 'grpc://localhost:7051', 'Org1', 'admin', 'Org1MSP');
hiddenPeerNode = FabricNode.newPeer('peer3.org1.example.com', 'peer2.org1.example.com', 'grpc://localhost:7051', 'Org1', 'admin', 'Org1MSP', true);
environmentRegistryEntry = new FabricEnvironmentRegistryEntry();
environmentRegistryEntry.name = 'myEnvironment';
environmentRegistryEntry.environmentType = EnvironmentType.ENVIRONMENT;
opsToolRegistryEntry = new FabricEnvironmentRegistryEntry();
opsToolRegistryEntry.name = 'someName';
opsToolRegistryEntry.url = 'someURL';
opsToolRegistryEntry.environmentType = EnvironmentType.OPS_TOOLS_ENVIRONMENT;
await FabricEnvironmentRegistry.instance().clear();
await FabricEnvironmentRegistry.instance().add(environmentRegistryEntry);
await FabricEnvironmentRegistry.instance().add(opsToolRegistryEntry);
deleteNodeStub = mySandBox.stub(FabricEnvironment.prototype, 'deleteNode').resolves();
updateNodeStub = mySandBox.stub(FabricEnvironment.prototype, 'updateNode').resolves();
getNodesStub = mySandBox.stub(FabricEnvironment.prototype, 'getNodes').resolves([peerNode, anotherPeerNode, morePeerNode]);
getEnvStub = mySandBox.stub(FabricEnvironmentManager.instance(), 'getEnvironmentRegistryEntry').returns(environmentRegistryEntry);
executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_ENVIRONMENT).resolves();
executeCommandStub.withArgs(ExtensionCommands.DELETE_ENVIRONMENT).resolves();
showEnvironmentStub = mySandBox.stub(UserInputUtil, 'showFabricEnvironmentQuickPickBox').resolves({ label: environmentRegistryEntry.name, data: environmentRegistryEntry });
showNodeStub = mySandBox.stub(UserInputUtil, 'showNodesInEnvironmentQuickPick').resolves([{ label: peerNode.name, data: peerNode }]);
showConfirmationWarningMessage = mySandBox.stub(UserInputUtil, 'showConfirmationWarningMessage');
showConfirmationWarningMessage.withArgs(`This will delete the node(s). Do you want to continue?`).resolves(true);
showConfirmationWarningMessage.withArgs(`This will hide the node(s). Do you want to continue?`).resolves(true);
showConfirmationWarningMessage.withArgs('This will delete the remaining node(s), and the environment. Do you want to continue?').resolves(true);
showConfirmationWarningMessage.withArgs('This will hide the remaining node(s), and disconnect from the environment. Do you want to continue?').resolves(true);
});
afterEach(() => {
mySandBox.restore();
});
it('should test multiple nodes can be deleted from the command', async () => {
showNodeStub.resolves([{ label: peerNode.name, data: peerNode }, {label: anotherPeerNode.name, data: anotherPeerNode}]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.have.been.calledTwice;
deleteNodeStub.should.have.been.calledWith(peerNode);
deleteNodeStub.should.have.been.calledWith(anotherPeerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted nodes`);
});
it('should test multiple nodes can be hidden from the command on an Ops Tools environment', async () => {
getEnvStub.returns(opsToolRegistryEntry);
showEnvironmentStub.resolves({ label: opsToolRegistryEntry.name, data: opsToolRegistryEntry });
showNodeStub.resolves([{ label: peerNode.name, data: peerNode }, {label: anotherPeerNode.name, data: anotherPeerNode}]);
await vscode.commands.executeCommand(ExtensionCommands.HIDE_NODE);
updateNodeStub.should.have.been.calledTwice;
updateNodeStub.should.have.been.calledWith(peerNode);
updateNodeStub.should.have.been.calledWith(anotherPeerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, opsToolRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will hide the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `hide node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully hid nodes`);
});
it('should test a node can be deleted from an Ops Tools environment', async () => {
getEnvStub.returns(opsToolRegistryEntry);
getNodesStub.resolves([peerNode, morePeerNode]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE, peerNode);
updateNodeStub.should.have.not.been.called;
showNodeStub.should.have.not.been.called;
deleteNodeStub.should.have.been.calledWith(peerNode);
showEnvironmentStub.should.have.not.been.called;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT);
showConfirmationWarningMessage.should.have.not.been.called;
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Node ${peerNode.name} was removed from ${opsToolRegistryEntry.name}`);
});
it('should test all visible nodes can be deleted from an Ops Tools environment', async () => {
getEnvStub.returns(opsToolRegistryEntry);
getNodesStub.resolves([peerNode, hiddenPeerNode]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE, peerNode);
updateNodeStub.should.have.not.been.called;
showNodeStub.should.have.not.been.called;
deleteNodeStub.should.have.been.calledWith(peerNode);
showEnvironmentStub.should.have.not.been.called;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
showConfirmationWarningMessage.should.have.not.been.called;
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Node ${peerNode.name} was removed from ${opsToolRegistryEntry.name}`);
});
it('should test all nodes can be deleted from an Ops Tools environment', async () => {
getEnvStub.returns(opsToolRegistryEntry);
getNodesStub.resolves([hiddenPeerNode]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE, hiddenPeerNode);
updateNodeStub.should.have.not.been.called;
showNodeStub.should.have.not.been.called;
deleteNodeStub.should.have.been.calledWith(hiddenPeerNode);
showEnvironmentStub.should.have.not.been.called;
showConfirmationWarningMessage.should.have.not.been.called;
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Node ${hiddenPeerNode.name} was removed from ${opsToolRegistryEntry.name}`);
});
it('should test a node can be deleted from the command', async () => {
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted node ${peerNode.name}`);
});
it('should test a node can be hidden from the command', async () => {
getEnvStub.returns(opsToolRegistryEntry);
showEnvironmentStub.resolves({ label: opsToolRegistryEntry.name, data: opsToolRegistryEntry });
showNodeStub.resolves([{ label: peerNode.name, data: peerNode }]);
await vscode.commands.executeCommand(ExtensionCommands.HIDE_NODE);
updateNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, opsToolRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will hide the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `hide node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully hid node ${peerNode.name}`);
});
it('should test a node can be deleted from tree', async () => {
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: PeerTreeItem = new PeerTreeItem(blockchainEnvironmentExplorerProvider, peerNode.name, peerNode.name, environmentRegistryEntry, peerNode);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE, treeItem);
deleteNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted node ${peerNode.name}`);
});
it('should test a node can be hidden from tree', async () => {
const blockchainEnvironmentExplorerProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const treeItem: PeerTreeItem = new PeerTreeItem(blockchainEnvironmentExplorerProvider, peerNode.name, peerNode.name, opsToolRegistryEntry, peerNode);
getEnvStub.returns(opsToolRegistryEntry);
await vscode.commands.executeCommand(ExtensionCommands.HIDE_NODE, treeItem);
updateNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, opsToolRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will hide the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `hide node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully hid node ${peerNode.name}`);
});
it('should test the connect is not called if connected to a different environment from one deleting from', async () => {
const anotherEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry();
anotherEnvironmentRegistryEntry.name = 'another environment';
showEnvironmentStub.resolves({ label: anotherEnvironmentRegistryEntry.name, data: anotherEnvironmentRegistryEntry });
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the node(s). Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted node ${peerNode.name}`);
});
it('should warn will delete environment when all nodes would be deleted and delete nodes and environment', async () => {
getNodesStub.resolves([peerNode]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the remaining node(s), and the environment. Do you want to continue?`);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully deleted node ${peerNode.name}`);
});
it('should warn will disconnect from environment when all nodes would be hidden', async () => {
getEnvStub.returns(opsToolRegistryEntry);
showEnvironmentStub.resolves({ label: opsToolRegistryEntry.name, data: opsToolRegistryEntry });
getEnvStub.returns(opsToolRegistryEntry);
getNodesStub.resolves([peerNode]);
await vscode.commands.executeCommand(ExtensionCommands.HIDE_NODE);
updateNodeStub.should.have.been.calledWith(peerNode);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, opsToolRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will hide the remaining node(s), and disconnect from the environment. Do you want to continue?`);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `hide node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully hid node ${peerNode.name}`);
});
it('should warn will delete environment when all nodes will be deleted and not delete nodes or environment', async () => {
getNodesStub.resolves([peerNode]);
showConfirmationWarningMessage.withArgs(`This will delete the remaining node(s), and the environment. Do you want to continue?`).resolves();
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
showConfirmationWarningMessage.should.have.been.calledWith(`This will delete the remaining node(s), and the environment. Do you want to continue?`);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
});
it('should test can be cancelled when choosing environment', async () => {
showEnvironmentStub.resolves();
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `delete node`);
});
it('should test can be cancelled when choosing node', async () => {
showNodeStub.resolves();
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `delete node`);
});
it('should test get error if no environments', async () => {
await FabricEnvironmentRegistry.instance().clear();
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
logSpy.should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.should.have.been.calledWithExactly(LogType.ERROR, `No environments to choose from. Nodes from local environments cannot be modified.`);
});
it('should test can handle selecting no nodes when choosing node', async () => {
showNodeStub.resolves([]);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `delete node`);
});
it('should test node are not deleted if you are not sure', async () => {
showConfirmationWarningMessage.withArgs('This will delete the node(s). Do you want to continue?').resolves();
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
deleteNodeStub.should.not.have.been.called;
logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `delete node`);
});
it('should handle error', async () => {
const error: Error = new Error('some error');
deleteNodeStub.rejects(error);
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE);
logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `delete node`);
logSpy.getCall(1).should.have.been.calledWithExactly(LogType.ERROR, `Cannot delete node: ${error.message}`, `Cannot delete node: ${error.toString()}`);
});
});
}); | the_stack |
import * as coreRestPipeline from "@azure/core-rest-pipeline";
import {
WebPubSubGenerateClientTokenOptionalParams,
WebPubSubGenerateClientTokenResponse,
WebPubSubCloseAllConnectionsOptionalParams,
ContentType,
WebPubSubSendToAll$binaryOptionalParams,
WebPubSubSendToAll$textOptionalParams,
WebPubSubConnectionExistsOptionalParams,
WebPubSubCloseConnectionOptionalParams,
WebPubSubSendToConnection$binaryOptionalParams,
WebPubSubSendToConnection$textOptionalParams,
WebPubSubGroupExistsOptionalParams,
WebPubSubCloseGroupConnectionsOptionalParams,
WebPubSubSendToGroup$binaryOptionalParams,
WebPubSubSendToGroup$textOptionalParams,
WebPubSubAddConnectionToGroupOptionalParams,
WebPubSubRemoveConnectionFromGroupOptionalParams,
WebPubSubUserExistsOptionalParams,
WebPubSubCloseUserConnectionsOptionalParams,
WebPubSubSendToUser$binaryOptionalParams,
WebPubSubSendToUser$textOptionalParams,
WebPubSubAddUserToGroupOptionalParams,
WebPubSubRemoveUserFromGroupOptionalParams,
WebPubSubRemoveUserFromAllGroupsOptionalParams,
WebPubSubPermission,
WebPubSubGrantPermissionOptionalParams,
WebPubSubRevokePermissionOptionalParams,
WebPubSubCheckPermissionOptionalParams
} from "../models";
/** Interface representing a WebPubSub. */
export interface WebPubSub {
/**
* Generate token for the client to connect Azure Web PubSub service.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param options The options parameters.
*/
generateClientToken(
hub: string,
options?: WebPubSubGenerateClientTokenOptionalParams
): Promise<WebPubSubGenerateClientTokenResponse>;
/**
* Close the connections in the hub.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param options The options parameters.
*/
closeAllConnections(
hub: string,
options?: WebPubSubCloseAllConnectionsOptionalParams
): Promise<void>;
/**
* Broadcast content inside request body to all the connected client connections.
* @param args Includes all the parameters for this operation.
*/
sendToAll(
...args:
| [
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToAll$binaryOptionalParams?
]
| [string, "text/plain", string, WebPubSubSendToAll$textOptionalParams?]
): Promise<void>;
/**
* Check if the connection with the given connectionId exists.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param connectionId The connection Id.
* @param options The options parameters.
*/
connectionExists(
hub: string,
connectionId: string,
options?: WebPubSubConnectionExistsOptionalParams
): Promise<void>;
/**
* Close the client connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
closeConnection(
hub: string,
connectionId: string,
options?: WebPubSubCloseConnectionOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific connection.
* @param args Includes all the parameters for this operation.
*/
sendToConnection(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToConnection$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToConnection$textOptionalParams?
]
): Promise<void>;
/**
* Check if there are any client connections inside the given group
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param options The options parameters.
*/
groupExists(
hub: string,
group: string,
options?: WebPubSubGroupExistsOptionalParams
): Promise<void>;
/**
* Close connections in the specific group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param options The options parameters.
*/
closeGroupConnections(
hub: string,
group: string,
options?: WebPubSubCloseGroupConnectionsOptionalParams
): Promise<void>;
/**
* Send content inside request body to a group of connections.
* @param args Includes all the parameters for this operation.
*/
sendToGroup(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToGroup$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToGroup$textOptionalParams?
]
): Promise<void>;
/**
* Add a connection to the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param connectionId Target connection Id
* @param options The options parameters.
*/
addConnectionToGroup(
hub: string,
group: string,
connectionId: string,
options?: WebPubSubAddConnectionToGroupOptionalParams
): Promise<void>;
/**
* Remove a connection from the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
removeConnectionFromGroup(
hub: string,
group: string,
connectionId: string,
options?: WebPubSubRemoveConnectionFromGroupOptionalParams
): Promise<void>;
/**
* Check if there are any client connections connected for the given user.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param userId Target user Id.
* @param options The options parameters.
*/
userExists(
hub: string,
userId: string,
options?: WebPubSubUserExistsOptionalParams
): Promise<void>;
/**
* Close connections for the specific user.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param userId The user Id.
* @param options The options parameters.
*/
closeUserConnections(
hub: string,
userId: string,
options?: WebPubSubCloseUserConnectionsOptionalParams
): Promise<void>;
/**
* Send content inside request body to the specific user.
* @param args Includes all the parameters for this operation.
*/
sendToUser(
...args:
| [
string,
string,
ContentType,
coreRestPipeline.RequestBodyType,
WebPubSubSendToUser$binaryOptionalParams?
]
| [
string,
string,
"text/plain",
string,
WebPubSubSendToUser$textOptionalParams?
]
): Promise<void>;
/**
* Add a user to the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param userId Target user Id.
* @param options The options parameters.
*/
addUserToGroup(
hub: string,
group: string,
userId: string,
options?: WebPubSubAddUserToGroupOptionalParams
): Promise<void>;
/**
* Remove a user from the target group.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param group Target group name, which length should be greater than 0 and less than 1025.
* @param userId Target user Id.
* @param options The options parameters.
*/
removeUserFromGroup(
hub: string,
group: string,
userId: string,
options?: WebPubSubRemoveUserFromGroupOptionalParams
): Promise<void>;
/**
* Remove a user from all groups.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param userId Target user Id.
* @param options The options parameters.
*/
removeUserFromAllGroups(
hub: string,
userId: string,
options?: WebPubSubRemoveUserFromAllGroupsOptionalParams
): Promise<void>;
/**
* Grant permission to the connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
grantPermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubGrantPermissionOptionalParams
): Promise<void>;
/**
* Revoke permission for the connection.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
revokePermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubRevokePermissionOptionalParams
): Promise<void>;
/**
* Check if a connection has permission to the specified action.
* @param hub Target hub name, which should start with alphabetic characters and only contain
* alpha-numeric characters or underscore.
* @param permission The permission: current supported actions are joinLeaveGroup and sendToGroup.
* @param connectionId Target connection Id.
* @param options The options parameters.
*/
checkPermission(
hub: string,
permission: WebPubSubPermission,
connectionId: string,
options?: WebPubSubCheckPermissionOptionalParams
): Promise<void>;
} | the_stack |
import { ErrorReporter, noopReporter } from './debugger'
import { createScanError, createToken } from './factory'
import { KEYWORDS } from './keywords'
import { SyntaxType, TextLocation, Token } from './types'
function isDigit(value: string): boolean {
return value >= '0' && value <= '9'
}
function isAlpha(value: string): boolean {
return (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z')
}
// The first character of an Identifier can be a letter or underscore
function isAlphaOrUnderscore(value: string): boolean {
return isAlpha(value) || value === '_'
}
function isValidIdentifier(value: string): boolean {
return (
isAlphaOrUnderscore(value) ||
isDigit(value) ||
value === '.' ||
value === '-'
)
}
function isHexDigit(value: string): boolean {
return (
(value >= '0' && value <= '9') ||
(value >= 'A' && value <= 'F') ||
(value >= 'a' && value <= 'f')
)
}
function isWhiteSpace(char: string): boolean {
switch (char) {
case ' ':
case '\r':
case '\t':
case '\n':
return true
default:
return false
}
}
class ScanError extends Error {
public message: string
public loc: TextLocation
constructor(msg: string, loc: TextLocation) {
super(msg)
this.message = msg
this.loc = loc
}
}
export interface Scanner {
scan(): Array<Token>
syncronize(): void
}
export function createScanner(
src: string,
report: ErrorReporter = noopReporter,
) {
const source: string = src
const tokens: Array<Token> = []
let line: number = 1
let column: number = 1
let startLine: number = 1
let startColumn: number = 1
let startIndex: number = 0
let currentIndex: number = 0
function scan(): Array<Token> {
while (!isAtEnd()) {
try {
startIndex = currentIndex
startLine = line
startColumn = column
scanToken()
} catch (e) {
report(createScanError(e.message, e.loc))
}
}
startIndex = currentIndex
addToken(SyntaxType.EOF)
return tokens
}
// Find the beginning of the next word to restart parse after error
function syncronize(): void {
while (!isAtEnd() && !isWhiteSpace(current())) {
advance()
}
}
function scanToken(): void {
const next = advance()
switch (next) {
case ' ':
case '\r':
case '\t':
// Ignore whitespace.
break
case '\n':
nextLine()
break
case '&':
// Thirft supports (undocumented by the grammar) a syntax for c-style pointers
// Pointers are indicated by the '&' token. As these are not relevant to JavaScript we
// drop them here. This may not be the best thing to do, perhaps should leave them in
// the parse tree and allow consumers to deal.
break
case '=':
addToken(SyntaxType.EqualToken)
break
case '(':
addToken(SyntaxType.LeftParenToken)
break
case ')':
addToken(SyntaxType.RightParenToken)
break
case '{':
addToken(SyntaxType.LeftBraceToken)
break
case '}':
addToken(SyntaxType.RightBraceToken)
break
case '[':
addToken(SyntaxType.LeftBracketToken)
break
case ']':
addToken(SyntaxType.RightBracketToken)
break
case ';':
addToken(SyntaxType.SemicolonToken)
break
case ',':
addToken(SyntaxType.CommaToken)
break
// Strings can use single or double quotes
case '"':
case "'":
string(next)
break
case ':':
addToken(SyntaxType.ColonToken)
break
case '#':
singleLineComment()
break
case '/':
if (peek() === '/') {
singleLineComment()
} else if (peek() === '*') {
multilineComment()
} else {
reportError(`Unexpected token: ${next}`)
}
break
case '<':
addToken(SyntaxType.LessThanToken)
break
case '>':
addToken(SyntaxType.GreaterThanToken)
break
case '-':
if (isDigit(peek())) {
number()
} else {
addToken(SyntaxType.MinusToken)
}
break
default:
if (isDigit(next)) {
number()
} else if (isAlphaOrUnderscore(next)) {
identifier()
} else if (isValidIdentifier(next)) {
reportError(
`Invalid identifier '${next}': Identifiers must begin with a letter or underscore`,
)
} else {
reportError(`Unexpected token: ${next}`)
}
}
}
function identifier(): void {
while (!isAtEnd() && peek() !== '\n' && isValidIdentifier(peek())) {
advance()
}
const literal: string = source.substring(startIndex, currentIndex)
const type: SyntaxType = KEYWORDS[literal]
if (type == null) {
addToken(SyntaxType.Identifier, literal)
} else {
addToken(type, literal)
}
}
function number(): void {
if (current() === '0' && (consume('x') || consume('X'))) {
hexadecimal()
} else {
integer()
if (peek() === 'e' || peek() === 'E') {
enotation()
} else if (peek() === '.' && isDigit(peekNext())) {
float()
} else {
commitToken(SyntaxType.IntegerLiteral)
}
}
}
function hexadecimal(): void {
while (!isAtEnd() && peek() !== '\n' && isHexDigit(peek())) {
advance()
}
commitToken(SyntaxType.HexLiteral)
}
function enotation(): void {
consume('e') || consume('E')
consume('-') || consume('+')
if (isDigit(peek())) {
integer()
commitToken(SyntaxType.ExponentialLiteral)
} else {
reportError(`Invalid use of e-notation`)
}
}
function float(): void {
consume('.')
integer()
if (peek() === 'e' || peek() === 'E') {
enotation()
} else {
commitToken(SyntaxType.FloatLiteral)
}
}
function integer(): void {
while (!isAtEnd() && peek() !== '\n' && isDigit(peek())) {
advance()
}
}
function singleLineComment(): void {
let comment: string = ''
while (true) {
if (
current() === '\n' ||
isAtEnd() ||
(current() !== '/' && current() !== '#' && current() !== ' ')
) {
break
} else {
advance()
}
}
if (current() !== '\n') {
// A comment goes until the end of the line.
while (peek() !== '\n' && !isAtEnd()) {
comment += current()
advance()
}
comment += current()
}
addToken(SyntaxType.CommentLine, comment.trim())
}
function multilineComment(): void {
let comment: string = ''
let cursor: number = 0
while (true) {
if (
current() === '\n' ||
isAtEnd() ||
(current() !== '/' && current() !== '*' && current() !== ' ')
) {
break
} else {
advance()
}
}
while (true) {
if (current() === '\n') {
nextLine()
}
if (
comment.charAt(cursor - 1) === '\n' &&
(peek() === ' ' || peek() === '*')
) {
/**
* We ignore stars and spaces after a new line to normalize comment formatting.
* We're only keeping the text of the comment without the extranious formatting.
*/
} else {
comment += current()
cursor += 1
}
advance()
// A comment goes until we find a comment terminator (*/).
if ((peek() === '*' && peekNext() === '/') || isAtEnd()) {
advance()
advance()
break
}
}
addToken(SyntaxType.CommentBlock, comment.trim())
}
function string(terminator: string): void {
while (!isAtEnd() && peek() !== terminator) {
if (peek() === '\n') {
nextLine()
}
if (peek() === '\\') {
advance()
}
advance()
}
if (isAtEnd() && previous() !== terminator) {
reportError(`String must be terminated with ${terminator}`)
} else {
// advance past closing "
advance()
// We use "+ 1" and "- 1" to remove the quote markes from the string and unsescape escaped terminators
const literal: string = source
.substring(startIndex + 1, currentIndex - 1)
.replace(/\\(\"|\')/g, '$1')
addToken(SyntaxType.StringLiteral, literal)
}
}
function consume(text: string): boolean {
if (peek() === text) {
advance()
return true
}
return false
}
function advance(): string {
currentIndex++
column++
return source.charAt(currentIndex - 1)
}
function previous(): string {
return source.charAt(currentIndex - 2)
}
function current(): string {
return source.charAt(currentIndex - 1)
}
function peek(): string {
return source.charAt(currentIndex)
}
function peekNext(): string {
return source.charAt(currentIndex + 1)
}
function nextLine() {
line++
column = 1
}
function commitToken(type: SyntaxType): void {
const literal: string = source.substring(startIndex, currentIndex)
addToken(type, literal)
}
function currentLocation(): TextLocation {
return {
start: {
line: startLine,
column: startColumn,
index: startIndex,
},
end: {
line,
column,
index: currentIndex,
},
}
}
function addToken(type: SyntaxType, value: string = ''): void {
const loc: TextLocation = currentLocation()
tokens.push(createToken(type, value, loc))
}
function isAtEnd(): boolean {
return currentIndex >= source.length
}
function reportError(msg: string): void {
throw new ScanError(msg, currentLocation())
}
return {
scan,
syncronize,
}
} | the_stack |
import {
NumberType,
StringType,
BooleanType,
ColorType,
ObjectType,
ValueType,
ErrorType,
CollatorType,
array,
toString as typeToString,
} from '../types';
import type {Type} from '../types';
import {typeOf, Color, validateRGBA, toString as valueToString} from '../values';
import CompoundExpression from '../compound_expression';
import RuntimeError from '../runtime_error';
import Let from './let';
import Var from './var';
import Literal from './literal';
import Assertion from './assertion';
import Coercion from './coercion';
import At from './at';
import In from './in';
import IndexOf from './index_of';
import Match from './match';
import Case from './case';
import Slice from './slice';
import Step from './step';
import Interpolate from './interpolate';
import Coalesce from './coalesce';
import {
Equals,
NotEquals,
LessThan,
GreaterThan,
LessThanOrEqual,
GreaterThanOrEqual
} from './comparison';
import CollatorExpression from './collator';
import NumberFormat from './number_format';
import FormatExpression from './format';
import ImageExpression from './image';
import Length from './length';
import Within from './within';
import type {Varargs} from '../compound_expression';
import type {ExpressionRegistry} from '../expression';
const expressions: ExpressionRegistry = {
// special forms
'==': Equals,
'!=': NotEquals,
'>': GreaterThan,
'<': LessThan,
'>=': GreaterThanOrEqual,
'<=': LessThanOrEqual,
'array': Assertion,
'at': At,
'boolean': Assertion,
'case': Case,
'coalesce': Coalesce,
'collator': CollatorExpression,
'format': FormatExpression,
'image': ImageExpression,
'in': In,
'index-of': IndexOf,
'interpolate': Interpolate,
'interpolate-hcl': Interpolate,
'interpolate-lab': Interpolate,
'length': Length,
'let': Let,
'literal': Literal,
'match': Match,
'number': Assertion,
'number-format': NumberFormat,
'object': Assertion,
'slice': Slice,
'step': Step,
'string': Assertion,
'to-boolean': Coercion,
'to-color': Coercion,
'to-number': Coercion,
'to-string': Coercion,
'var': Var,
'within': Within
};
function rgba(ctx, [r, g, b, a]) {
r = r.evaluate(ctx);
g = g.evaluate(ctx);
b = b.evaluate(ctx);
const alpha = a ? a.evaluate(ctx) : 1;
const error = validateRGBA(r, g, b, alpha);
if (error) throw new RuntimeError(error);
return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);
}
function has(key, obj) {
return key in obj;
}
function get(key, obj) {
const v = obj[key];
return typeof v === 'undefined' ? null : v;
}
function binarySearch(v, a, i, j) {
while (i <= j) {
const m = (i + j) >> 1;
if (a[m] === v)
return true;
if (a[m] > v)
j = m - 1;
else
i = m + 1;
}
return false;
}
function varargs(type: Type): Varargs {
return {type};
}
CompoundExpression.register(expressions, {
'error': [
ErrorType,
[StringType],
(ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }
],
'typeof': [
StringType,
[ValueType],
(ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))
],
'to-rgba': [
array(NumberType, 4),
[ColorType],
(ctx, [v]) => {
return v.evaluate(ctx).toArray();
}
],
'rgb': [
ColorType,
[NumberType, NumberType, NumberType],
rgba
],
'rgba': [
ColorType,
[NumberType, NumberType, NumberType, NumberType],
rgba
],
'has': {
type: BooleanType,
overloads: [
[
[StringType],
(ctx, [key]) => has(key.evaluate(ctx), ctx.properties())
], [
[StringType, ObjectType],
(ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))
]
]
},
'get': {
type: ValueType,
overloads: [
[
[StringType],
(ctx, [key]) => get(key.evaluate(ctx), ctx.properties())
], [
[StringType, ObjectType],
(ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))
]
]
},
'feature-state': [
ValueType,
[StringType],
(ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})
],
'properties': [
ObjectType,
[],
(ctx) => ctx.properties()
],
'geometry-type': [
StringType,
[],
(ctx) => ctx.geometryType()
],
'id': [
ValueType,
[],
(ctx) => ctx.id()
],
'zoom': [
NumberType,
[],
(ctx) => ctx.globals.zoom
],
'heatmap-density': [
NumberType,
[],
(ctx) => ctx.globals.heatmapDensity || 0
],
'line-progress': [
NumberType,
[],
(ctx) => ctx.globals.lineProgress || 0
],
'accumulated': [
ValueType,
[],
(ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated
],
'+': [
NumberType,
varargs(NumberType),
(ctx, args) => {
let result = 0;
for (const arg of args) {
result += arg.evaluate(ctx);
}
return result;
}
],
'*': [
NumberType,
varargs(NumberType),
(ctx, args) => {
let result = 1;
for (const arg of args) {
result *= arg.evaluate(ctx);
}
return result;
}
],
'-': {
type: NumberType,
overloads: [
[
[NumberType, NumberType],
(ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)
], [
[NumberType],
(ctx, [a]) => -a.evaluate(ctx)
]
]
},
'/': [
NumberType,
[NumberType, NumberType],
(ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)
],
'%': [
NumberType,
[NumberType, NumberType],
(ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)
],
'ln2': [
NumberType,
[],
() => Math.LN2
],
'pi': [
NumberType,
[],
() => Math.PI
],
'e': [
NumberType,
[],
() => Math.E
],
'^': [
NumberType,
[NumberType, NumberType],
(ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))
],
'sqrt': [
NumberType,
[NumberType],
(ctx, [x]) => Math.sqrt(x.evaluate(ctx))
],
'log10': [
NumberType,
[NumberType],
(ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10
],
'ln': [
NumberType,
[NumberType],
(ctx, [n]) => Math.log(n.evaluate(ctx))
],
'log2': [
NumberType,
[NumberType],
(ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2
],
'sin': [
NumberType,
[NumberType],
(ctx, [n]) => Math.sin(n.evaluate(ctx))
],
'cos': [
NumberType,
[NumberType],
(ctx, [n]) => Math.cos(n.evaluate(ctx))
],
'tan': [
NumberType,
[NumberType],
(ctx, [n]) => Math.tan(n.evaluate(ctx))
],
'asin': [
NumberType,
[NumberType],
(ctx, [n]) => Math.asin(n.evaluate(ctx))
],
'acos': [
NumberType,
[NumberType],
(ctx, [n]) => Math.acos(n.evaluate(ctx))
],
'atan': [
NumberType,
[NumberType],
(ctx, [n]) => Math.atan(n.evaluate(ctx))
],
'min': [
NumberType,
varargs(NumberType),
(ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))
],
'max': [
NumberType,
varargs(NumberType),
(ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))
],
'abs': [
NumberType,
[NumberType],
(ctx, [n]) => Math.abs(n.evaluate(ctx))
],
'round': [
NumberType,
[NumberType],
(ctx, [n]) => {
const v = n.evaluate(ctx);
// Javascript's Math.round() rounds towards +Infinity for halfway
// values, even when they're negative. It's more common to round
// away from 0 (e.g., this is what python and C++ do)
return v < 0 ? -Math.round(-v) : Math.round(v);
}
],
'floor': [
NumberType,
[NumberType],
(ctx, [n]) => Math.floor(n.evaluate(ctx))
],
'ceil': [
NumberType,
[NumberType],
(ctx, [n]) => Math.ceil(n.evaluate(ctx))
],
'filter-==': [
BooleanType,
[StringType, ValueType],
(ctx, [k, v]) => ctx.properties()[(k as any).value] === (v as any).value
],
'filter-id-==': [
BooleanType,
[ValueType],
(ctx, [v]) => ctx.id() === (v as any).value
],
'filter-type-==': [
BooleanType,
[StringType],
(ctx, [v]) => ctx.geometryType() === (v as any).value
],
'filter-<': [
BooleanType,
[StringType, ValueType],
(ctx, [k, v]) => {
const a = ctx.properties()[(k as any).value];
const b = (v as any).value;
return typeof a === typeof b && a < b;
}
],
'filter-id-<': [
BooleanType,
[ValueType],
(ctx, [v]) => {
const a = ctx.id();
const b = (v as any).value;
return typeof a === typeof b && a < b;
}
],
'filter->': [
BooleanType,
[StringType, ValueType],
(ctx, [k, v]) => {
const a = ctx.properties()[(k as any).value];
const b = (v as any).value;
return typeof a === typeof b && a > b;
}
],
'filter-id->': [
BooleanType,
[ValueType],
(ctx, [v]) => {
const a = ctx.id();
const b = (v as any).value;
return typeof a === typeof b && a > b;
}
],
'filter-<=': [
BooleanType,
[StringType, ValueType],
(ctx, [k, v]) => {
const a = ctx.properties()[(k as any).value];
const b = (v as any).value;
return typeof a === typeof b && a <= b;
}
],
'filter-id-<=': [
BooleanType,
[ValueType],
(ctx, [v]) => {
const a = ctx.id();
const b = (v as any).value;
return typeof a === typeof b && a <= b;
}
],
'filter->=': [
BooleanType,
[StringType, ValueType],
(ctx, [k, v]) => {
const a = ctx.properties()[(k as any).value];
const b = (v as any).value;
return typeof a === typeof b && a >= b;
}
],
'filter-id->=': [
BooleanType,
[ValueType],
(ctx, [v]) => {
const a = ctx.id();
const b = (v as any).value;
return typeof a === typeof b && a >= b;
}
],
'filter-has': [
BooleanType,
[ValueType],
(ctx, [k]) => (k as any).value in ctx.properties()
],
'filter-has-id': [
BooleanType,
[],
(ctx) => (ctx.id() !== null && ctx.id() !== undefined)
],
'filter-type-in': [
BooleanType,
[array(StringType)],
(ctx, [v]) => (v as any).value.indexOf(ctx.geometryType()) >= 0
],
'filter-id-in': [
BooleanType,
[array(ValueType)],
(ctx, [v]) => (v as any).value.indexOf(ctx.id()) >= 0
],
'filter-in-small': [
BooleanType,
[StringType, array(ValueType)],
// assumes v is an array literal
(ctx, [k, v]) => (v as any).value.indexOf(ctx.properties()[(k as any).value]) >= 0
],
'filter-in-large': [
BooleanType,
[StringType, array(ValueType)],
// assumes v is a array literal with values sorted in ascending order and of a single type
(ctx, [k, v]) => binarySearch(ctx.properties()[(k as any).value], (v as any).value, 0, (v as any).value.length - 1)
],
'all': {
type: BooleanType,
overloads: [
[
[BooleanType, BooleanType],
(ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)
],
[
varargs(BooleanType),
(ctx, args) => {
for (const arg of args) {
if (!arg.evaluate(ctx))
return false;
}
return true;
}
]
]
},
'any': {
type: BooleanType,
overloads: [
[
[BooleanType, BooleanType],
(ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)
],
[
varargs(BooleanType),
(ctx, args) => {
for (const arg of args) {
if (arg.evaluate(ctx))
return true;
}
return false;
}
]
]
},
'!': [
BooleanType,
[BooleanType],
(ctx, [b]) => !b.evaluate(ctx)
],
'is-supported-script': [
BooleanType,
[StringType],
// At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant
(ctx, [s]) => {
const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;
if (isSupportedScript) {
return isSupportedScript(s.evaluate(ctx));
}
return true;
}
],
'upcase': [
StringType,
[StringType],
(ctx, [s]) => s.evaluate(ctx).toUpperCase()
],
'downcase': [
StringType,
[StringType],
(ctx, [s]) => s.evaluate(ctx).toLowerCase()
],
'concat': [
StringType,
varargs(ValueType),
(ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')
],
'resolved-locale': [
StringType,
[CollatorType],
(ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()
]
});
export default expressions; | the_stack |
import { IInputs, IOutputs } from "./generated/ManifestTypes";
export class PortalWebAPIControl implements ComponentFramework.StandardControl<IInputs, IOutputs>
{
private _container: HTMLDivElement;
private _context: ComponentFramework.Context<IInputs>;
private static _entityName = "account";
private static _requiredAttributeName = "name";
private static _requiredAttributeValue = "Web API Custom Control (Sample)";
private static _currencyAttributeName = "revenue";
private static _currencyAttributeNameFriendlyName = "annual revenue";
private _controlViewRendered: boolean;
private _createEntity1Button: HTMLButtonElement;
private _createEntity2Button: HTMLButtonElement;
private _createEntity3Button: HTMLButtonElement;
private _deleteRecordButton: HTMLButtonElement;
private _fetchXmlRefreshButton: HTMLButtonElement;
private _oDataRefreshButton: HTMLButtonElement;
private _odataStatusContainerDiv: HTMLDivElement;
private _resultContainerDiv: HTMLDivElement;
private _dropDownList:HTMLSelectElement;
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container: HTMLDivElement): void {
this._context = context;
this._controlViewRendered = false;
this._container = document.createElement("div");
this._container.classList.add("PortalWebAPIControl_Container");
container.appendChild(this._container);
}
public updateView(context: ComponentFramework.Context<IInputs>): void {
this._context = context;
if (!this._controlViewRendered) {
this._controlViewRendered = true;
// Render Web API Examples
this.renderCreateExample();
this.renderDeleteExample();
this.renderFetchXmlRetrieveMultipleExample();
this.renderODataRetrieveMultipleExample();
// Render result div to display output of Web API calls
this.renderResultsDiv();
}
}
public getOutputs(): IOutputs {
// no-op: method not leveraged by this example custom control
return {};
}
public destroy(): void {
// no-op: method not leveraged by this example custom control
}
private renderCreateExample() {
// Create header label for Web API sample
const headerDiv: HTMLDivElement = this.createHTMLDivElement("create_container", true, `Click to create ${PortalWebAPIControl._entityName} record`);
this._container.appendChild(headerDiv);
// Create button 1 to create record with revenue field set to 100
const value1 = "100";
this._createEntity1Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value1),
this.getCreateButtonId(value1),
value1,
this.createButtonOnClickHandler.bind(this));
// Create button 2 to create record with revenue field set to 200
const value2 = "200";
this._createEntity2Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value2),
this.getCreateButtonId(value2),
value2,
this.createButtonOnClickHandler.bind(this));
// Create button 3 to create record with revenue field set to 300
const value3 = "300";
this._createEntity3Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value3),
this.getCreateButtonId(value3),
value3,
this.createButtonOnClickHandler.bind(this));
// Append all button HTML elements to custom control container div
this._container.appendChild(this._createEntity1Button);
this._container.appendChild(this._createEntity2Button);
this._container.appendChild(this._createEntity3Button);
}
private renderDeleteExample(): void {
// Create header label for Web API sample
const headerDiv: HTMLDivElement = this.createHTMLDivElement("delete_container", true, `Click to delete ${PortalWebAPIControl._entityName} record`);
this._deleteRecordButton = document.createElement("button");
this._deleteRecordButton.innerHTML = "Delete Record";
this._deleteRecordButton.id = "delete_button";
this._deleteRecordButton.classList.add("SampleControl_PortalWebAPIControl_DeleteButtonClass");
this._deleteRecordButton.addEventListener("click", this.deleteButtonOnClickHandler.bind(this));
this._dropDownList = document.createElement("select");
this._dropDownList.name = "Delete Entity";
this._dropDownList.id = "DeleteEntity";
this._dropDownList.classList.add("SampleControl_PortalWebAPIControl_SelectClass");
// Append elements to custom control container div
this._container.appendChild(headerDiv);
this._container.appendChild(this._dropDownList);
this._container.appendChild(this._deleteRecordButton);
this.PopulateItemsToDelete();
}
private renderODataRetrieveMultipleExample(): void {
const containerClassName = "odata_status_container";
// Create header label for Web API sample
const statusDivHeader: HTMLDivElement = this.createHTMLDivElement(containerClassName, true, "Click to refresh record count");
this._odataStatusContainerDiv = this.createHTMLDivElement(containerClassName, false, undefined);
// Create button to invoke OData RetrieveMultiple Example
this._fetchXmlRefreshButton = this.createHTMLButtonElement(
"Refresh record count",
"odata_refresh",
null,
this.refreshRecordCountButtonOnClickHandler.bind(this));
// Append HTML elements to custom control container div
this._container.appendChild(statusDivHeader);
this._container.appendChild(this._odataStatusContainerDiv);
this._container.appendChild(this._fetchXmlRefreshButton);
}
private renderFetchXmlRetrieveMultipleExample(): void {
const containerName = "fetchxml_status_container";
// Create header label for Web API sample
const statusDivHeader: HTMLDivElement = this.createHTMLDivElement(containerName, true,
`Click to calculate average value of ${PortalWebAPIControl._currencyAttributeNameFriendlyName}`);
const statusDiv: HTMLDivElement = this.createHTMLDivElement(containerName, false, undefined);
statusDivHeader.style.marginTop = "40px";
// Create button to invoke Fetch XML RetrieveMultiple Web API example
this._oDataRefreshButton = this.createHTMLButtonElement(
`Calculate average value of ${PortalWebAPIControl._currencyAttributeNameFriendlyName}`,
"odata_refresh",
null,
this.calculateAverageButtonOnClickHandler.bind(this));
// Append HTML Elements to custom control container div
this._container.appendChild(statusDivHeader);
this._container.appendChild(statusDiv);
this._container.appendChild(this._oDataRefreshButton);
}
private renderResultsDiv() {
// Render header label for result container
const resultDivHeader: HTMLDivElement = this.createHTMLDivElement("result_container", true,
"Result of last action");
this._container.appendChild(resultDivHeader);
// Div elements to populate with the result text
this._resultContainerDiv = this.createHTMLDivElement("result_container", false, undefined);
this._container.appendChild(this._resultContainerDiv);
// Init the result container with a notification the control was loaded
this.updateResultContainerText("Web API sample custom control loaded");
}
private createButtonOnClickHandler(event: Event): void {
// Retrieve the value to set the currency field to from the button's attribute
const currencyAttributeValue: number = parseInt(
(event.target as Element)?.attributes?.getNamedItem("buttonvalue")?.value ?? "0"
);
// Generate unique record name by appending timestamp to _requiredAttributeValue
const recordName = `${PortalWebAPIControl._requiredAttributeValue}_${Date.now()}`;
// Set the values for the attributes we want to set on the new record
// If you want to set additional attributes on the new record, add to data dictionary as key/value pair
const data: ComponentFramework.WebApi.Entity = {};
data[PortalWebAPIControl._requiredAttributeName] = recordName;
data[PortalWebAPIControl._currencyAttributeName] = currencyAttributeValue;
// Invoke the Web API to creat the new record
this._context.webAPI.createRecord(PortalWebAPIControl._entityName, data).then(
(response: ComponentFramework.LookupValue) => {
// Callback method for successful creation of new record
// Get the ID of the new record created
const id: string = response.id;
// Generate HTML to inject into the result div to showcase the fields and values of the new record created
let resultHtml = `Created new ${ PortalWebAPIControl._entityName } record with below values:`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `id: ${id}`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `${PortalWebAPIControl._requiredAttributeName}: ${recordName}`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `${PortalWebAPIControl._currencyAttributeName}: ${currencyAttributeValue}`;
this.updateResultContainerText(resultHtml);
this.PopulateItemsToDelete();
},
(errorResponse) => {
// Error handling code here - record failed to be created
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
private PopulateItemsToDelete(): void{
var i, L = this._dropDownList.options.length - 1;
for(i = L; i >= 0; i--)
{
this._dropDownList.options.remove(i);
}
const queryString = `?$select=${PortalWebAPIControl._requiredAttributeName}&$filter=contains(${PortalWebAPIControl._requiredAttributeName},'${PortalWebAPIControl._requiredAttributeValue}')`;
// Invoke the Web API Retrieve Multiple call
this._context.webAPI.retrieveMultipleRecords(PortalWebAPIControl._entityName, queryString).then(
(response: ComponentFramework.WebApi.RetrieveMultipleResponse) => {
var option = document.createElement("option");
option.value = "";
option.text = "";
this._dropDownList.appendChild(option);
for (const entity of response.entities) {
var option = document.createElement("option");
option.value = entity.accountid;
option.text = entity.name;
this._dropDownList.appendChild(option);
}
});
}
private deleteButtonOnClickHandler(): void {
if(this._dropDownList.value != "")
{
var entityId = this._dropDownList.value;
this._context.webAPI.deleteRecord(PortalWebAPIControl._entityName, this._dropDownList.value).then(
(response: ComponentFramework.LookupValue) => {
const responseEntityType: string = response.entityType;
this.updateResultContainerText(`Deleted ${responseEntityType} record with ID: ${entityId}`);
this.PopulateItemsToDelete();
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
});
}
}
private calculateAverageButtonOnClickHandler(): void {
// Build FetchXML to retrieve the average value of _currencyAttributeName field for all _entityName records
// Add a filter to only aggregate on records that have _currencyAttributeName not set to null
let fetchXML = "<fetch distinct='false' mapping='logical' aggregate='true'>";
fetchXML += `<entity name='${PortalWebAPIControl._entityName}'>`;
fetchXML += `<attribute name='${PortalWebAPIControl._currencyAttributeName}' aggregate='avg' alias='average_val' />`;
fetchXML += "<filter>";
fetchXML += `<condition attribute='${PortalWebAPIControl._currencyAttributeName}' operator='not-null' />`;
fetchXML += "</filter>";
fetchXML += "</entity>";
fetchXML += "</fetch>";
// Invoke the Web API RetrieveMultipleRecords method to calculate the aggregate value
this._context.webAPI.retrieveMultipleRecords(PortalWebAPIControl._entityName, `?fetchXml=${ fetchXML}`).then(
(response: ComponentFramework.WebApi.RetrieveMultipleResponse) => {
// Retrieve multiple completed successfully -- retrieve the averageValue
const averageVal: number = response.entities[0].average_val;
// Generate HTML to inject into the result div to showcase the result of the RetrieveMultiple Web API call
const resultHTML = `Average value of ${PortalWebAPIControl._currencyAttributeNameFriendlyName} attribute for all ${PortalWebAPIControl._entityName} records: ${averageVal}`;
this.updateResultContainerText(resultHTML);
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
private refreshRecordCountButtonOnClickHandler(): void {
// Generate OData query string to retrieve the _currencyAttributeName field for all _entityName records
// Add a filter to only retrieve records with _requiredAttributeName field which contains _requiredAttributeValue
const queryString = `?$select=${PortalWebAPIControl._currencyAttributeName }&$filter=contains(${PortalWebAPIControl._requiredAttributeName},'${PortalWebAPIControl._requiredAttributeValue}')`;
// Invoke the Web API Retrieve Multiple call
this._context.webAPI.retrieveMultipleRecords(PortalWebAPIControl._entityName, queryString).then(
(response: ComponentFramework.WebApi.RetrieveMultipleResponse) => {
// Retrieve Multiple Web API call completed successfully
let count1 = 0;
let count2 = 0;
let count3 = 0;
// Loop through each returned record
for (const entity of response.entities) {
// Retrieve the value of _currencyAttributeName field
const value: number = entity[PortalWebAPIControl._currencyAttributeName];
// Check the value of _currencyAttributeName field and increment the correct counter
if (value == 100) {
count1++;
}
else if (value == 200) {
count2++;
}
else if (value == 300) {
count3++;
}
}
// Generate HTML to inject into the fetch xml status div to showcase the results of the OData retrieve example
let innerHtml = "Use above buttons to create or delete a record to see count update";
innerHtml += "<br />";
innerHtml += "<br />";
innerHtml += `Count of ${PortalWebAPIControl._entityName} records with ${PortalWebAPIControl._currencyAttributeName} of 100: ${count1}`;
innerHtml += "<br />";
innerHtml += `Count of ${PortalWebAPIControl._entityName} records with ${PortalWebAPIControl._currencyAttributeName} of 200: ${count2}`;
innerHtml += "<br />";
innerHtml += `Count of ${PortalWebAPIControl._entityName} records with ${PortalWebAPIControl._currencyAttributeName} of 300: ${count3}`;
// Inject the HTML into the fetch xml status div
if (this._odataStatusContainerDiv) {
this._odataStatusContainerDiv.innerHTML = innerHtml;
}
// Inject a success message into the result div
this.updateResultContainerText("Record count refreshed");
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
private updateResultContainerText(statusHTML: string): void {
if (this._resultContainerDiv) {
this._resultContainerDiv.innerHTML = statusHTML;
}
}
private updateResultContainerTextWithErrorResponse(errorResponse: any): void {
if (this._resultContainerDiv) {
// Retrieve the error message from the errorResponse and inject into the result div
let errorHTML = "Error with Web API call:";
errorHTML += "<br />";
errorHTML += errorResponse.message;
this._resultContainerDiv.innerHTML = errorHTML;
}
}
private getCreateRecordButtonLabel(entityNumber: string): string {
return `Create record with ${PortalWebAPIControl._currencyAttributeNameFriendlyName} of ${entityNumber}`;
}
private getCreateButtonId(entityNumber: string): string {
return `create_button_${entityNumber}`;
}
private createHTMLButtonElement(buttonLabel: string, buttonId: string, buttonValue: string | null, onClickHandler: (event?: any) => void): HTMLButtonElement {
const button: HTMLButtonElement = document.createElement("button");
button.innerHTML = buttonLabel;
if (buttonValue) {
button.setAttribute("buttonvalue", buttonValue);
}
button.id = buttonId;
button.classList.add("SampleControl_PortalWebAPIControl_ButtonClass");
button.addEventListener("click", onClickHandler);
return button;
}
private createHTMLDivElement(elementClassName: string, isHeader: boolean, innerText?: string): HTMLDivElement {
const div: HTMLDivElement = document.createElement("div");
if (isHeader) {
div.classList.add("SampleControl_PortalWebAPIControl_Header");
elementClassName += "_header";
}
if (innerText) {
div.innerText = innerText.toUpperCase();
}
div.classList.add(elementClassName);
return div;
}
} | the_stack |
import { injectable, ContainerModule } from 'inversify';
import { DirectoryService, MessageHandler, ConfigurationError, FileSummary, Finding } from '@fimbul/ymir';
import { AbstractCommandRunner, TestCommand } from './base';
import { CachedFileSystem } from '../services/cached-file-system';
import { createBaseline } from '../baseline';
import * as path from 'path';
import * as chalk from 'chalk';
import { unixifyPath } from '../utils';
import * as glob from 'glob';
import { satisfies, SemVer } from 'semver';
import { LintOptions, Runner } from '../runner';
import * as ts from 'typescript';
import * as diff from 'diff';
import { GLOBAL_OPTIONS_SPEC } from '../argparse';
import { OptionParser } from '../optparse';
const enum BaselineKind {
Lint = 'lint',
Fix = 'fix',
}
const TEST_OPTION_SPEC = {
...GLOBAL_OPTIONS_SPEC,
fix: OptionParser.Transform.noDefault(GLOBAL_OPTIONS_SPEC.fix),
typescriptVersion: OptionParser.Factory.parsePrimitive('string'),
};
interface RuleTestHost {
checkResult(file: string, kind: BaselineKind, result: FileSummary): boolean;
}
@injectable()
class FakeDirectoryService implements DirectoryService {
public cwd!: string;
constructor(private realDirectorySerivce: DirectoryService) {}
public getCurrentDirectory() {
return this.cwd;
}
public getRealCurrentDirectory() {
return this.realDirectorySerivce.getCurrentDirectory();
}
}
@injectable()
class TestCommandRunner extends AbstractCommandRunner {
constructor(
private runner: Runner,
private fs: CachedFileSystem,
private logger: MessageHandler,
private directoryService: FakeDirectoryService,
) {
super();
}
public run(options: TestCommand) {
const currentTypescriptVersion = getNormalizedTypescriptVersion();
const basedir = this.directoryService.getRealCurrentDirectory();
let baselineDir: string;
let root: string;
let baselinesSeen: string[];
let success = true;
const host: RuleTestHost = {
checkResult: (file, kind, summary) => {
const relative = path.relative(root, file);
if (relative.startsWith('..' + path.sep))
throw new ConfigurationError(`Testing file '${file}' outside of '${root}'.`);
const actual = kind === BaselineKind.Fix ? summary.content : createBaseline(summary);
const baselineFile = `${path.resolve(baselineDir, relative)}.${kind}`;
const end = (pass: boolean, text: string, baselineDiff?: string) => {
this.logger.log(` ${chalk.grey.dim(path.relative(basedir, baselineFile))} ${chalk[pass ? 'green' : 'red'](text)}`);
if (pass)
return true;
if (baselineDiff !== undefined)
this.logger.log(baselineDiff);
success = false;
return !options.bail;
};
if (kind === BaselineKind.Fix && summary.fixes === 0) {
if (!this.fs.isFile(baselineFile))
return true;
if (options.updateBaselines) {
this.fs.remove(baselineFile);
return end(true, 'REMOVED');
}
baselinesSeen.push(unixifyPath(baselineFile));
return end(false, 'EXISTS');
}
baselinesSeen.push(unixifyPath(baselineFile));
let expected: string;
try {
expected = this.fs.readFile(baselineFile);
} catch {
if (!options.updateBaselines)
return end(false, 'MISSING');
this.fs.createDirectory(path.dirname(baselineFile));
this.fs.writeFile(baselineFile, actual);
return end(true, 'CREATED');
}
if (expected === actual)
return end(true, 'PASSED');
if (options.updateBaselines) {
this.fs.writeFile(baselineFile, actual);
return end(true, 'UPDATED');
}
return end(false, 'FAILED', createBaselineDiff(actual, expected));
},
};
const globOptions = {
absolute: true,
cache: {},
nodir: true,
realpathCache: {},
statCache: {},
symlinks: {},
cwd: basedir,
};
for (const pattern of options.files) {
for (const testcase of glob.sync(pattern, globOptions)) {
const {typescriptVersion, ...testConfig} = OptionParser.parse(
require(testcase),
TEST_OPTION_SPEC,
{validate: true, context: testcase, exhaustive: true},
);
if (typescriptVersion !== undefined && !satisfies(currentTypescriptVersion, typescriptVersion)) {
this.logger.log(
`${path.relative(basedir, testcase)} ${chalk.yellow(`SKIPPED, requires TypeScript ${typescriptVersion}`)}`,
);
continue;
}
root = path.dirname(testcase);
baselineDir = buildBaselineDirectoryName(basedir, 'baselines', testcase);
this.logger.log(path.relative(basedir, testcase));
this.directoryService.cwd = root;
baselinesSeen = [];
if (!this.test(testConfig, host))
return false;
if (options.exact) {
const remainingGlobOptions = {...globOptions, cwd: baselineDir, ignore: baselinesSeen};
for (const unchecked of glob.sync('**', remainingGlobOptions)) {
if (options.updateBaselines) {
this.fs.remove(unchecked);
this.logger.log(` ${chalk.grey.dim(path.relative(basedir, unchecked))} ${chalk.green('REMOVED')}`);
} else {
this.logger.log(` ${chalk.grey.dim(path.relative(basedir, unchecked))} ${chalk.red('UNCHECKED')}`);
if (options.bail)
return false;
success = false;
}
}
}
}
}
return success;
}
private test(config: {[K in keyof LintOptions]: LintOptions[K] | (K extends 'fix' ? undefined : never)}, host: RuleTestHost): boolean {
const lintOptions: LintOptions = {...config, fix: false};
const lintResult = Array.from(this.runner.lintCollection(lintOptions));
let containsFixes = false;
for (const [fileName, summary] of lintResult) {
if (!host.checkResult(fileName, BaselineKind.Lint, summary))
return false;
containsFixes = containsFixes || summary.findings.some(isFixable);
}
if (config.fix || config.fix === undefined) {
lintOptions.fix = config.fix || true; // fix defaults to true if not specified
const fixResult = containsFixes ? this.runner.lintCollection(lintOptions) : lintResult;
for (const [fileName, summary] of fixResult)
if (!host.checkResult(fileName, BaselineKind.Fix, summary))
return false;
}
return true;
}
}
function buildBaselineDirectoryName(basedir: string, baselineDir: string, testcase: string): string {
const parts = path.relative(basedir, path.dirname(testcase)).split(path.sep);
if (/^(__)?tests?(__)?$/.test(parts[0])) {
parts[0] = baselineDir;
} else {
parts.unshift(baselineDir);
}
return path.resolve(basedir, parts.join(path.sep), getTestName(path.basename(testcase)));
}
function getTestName(basename: string): string {
let ext = path.extname(basename);
basename = basename.slice(0, -ext.length);
ext = path.extname(basename);
if (ext === '')
return 'default';
return basename.slice(0, -ext.length);
}
/** Removes everything related to prereleases and just returns MAJOR.MINOR.PATCH, thus treating prereleases like the stable release. */
function getNormalizedTypescriptVersion() {
const v = new SemVer(ts.version);
return new SemVer(`${v.major}.${v.minor}.${v.patch}`);
}
function isFixable(finding: Finding): boolean {
return finding.fix !== undefined;
}
function createBaselineDiff(actual: string, expected: string) {
const result = [
chalk.red('Expected'),
chalk.green('Actual'),
];
const lines = diff.createPatch('', expected, actual, '', '').split(/\n(?!\\)/g).slice(4);
for (let line of lines) {
switch (line[0]) {
case '@':
line = chalk.blueBright(line);
break;
case '+':
line = chalk.green('+' + prettyLine(line.substr(1)));
break;
case '-':
line = chalk.red('-' + prettyLine(line.substr(1)));
}
result.push(line);
}
return result.join('\n');
}
function prettyLine(line: string): string {
return line
.replace(/\t/g, '\u2409') // ␉
.replace(/\r$/, '\u240d') // ␍
.replace(/^\uFEFF/, '<BOM>');
}
export const module = new ContainerModule((bind) => {
bind(FakeDirectoryService).toSelf().inSingletonScope();
bind(DirectoryService).toDynamicValue((context) => {
return context.container.get(FakeDirectoryService);
}).inSingletonScope().when((request) => {
return request.parentRequest == undefined || request.parentRequest.target.serviceIdentifier !== FakeDirectoryService;
});
bind(DirectoryService).toDynamicValue(({container}) => {
if (container.parent && container.parent.isBound(DirectoryService))
return container.parent.get(DirectoryService);
return {
getCurrentDirectory() {
return process.cwd();
},
};
}).inSingletonScope().whenInjectedInto(FakeDirectoryService);
bind(AbstractCommandRunner).to(TestCommandRunner);
}); | the_stack |
import {BaseNodeType} from '../../_Base';
import {BaseParamType} from '../../../params/_Base';
import {ParamOptions} from '../../../params/utils/OptionsController';
import {CoreGraphNode} from '../../../../core/graph/CoreGraphNode';
import {FloatParam} from '../../../params/Float';
import {OperatorPathParam} from '../../../params/OperatorPath';
import {ParamType} from '../../../poly/ParamType';
// import {ParamEvent} from '../../../poly/ParamEvent';
import {NodeParamsConfig} from './ParamsConfig';
import {ParamConstructorMap} from '../../../params/types/ParamConstructorMap';
import {ParamConstructorByType} from '../../../params/types/ParamConstructorByType';
import {ParamInitValuesTypeMap} from '../../../params/types/ParamInitValuesTypeMap';
import {ParamValuesTypeMap} from '../../../params/types/ParamValuesTypeMap';
import {NodeEvent} from '../../../poly/NodeEvent';
import {ParamInitValueSerializedTypeMap} from '../../../params/types/ParamInitValueSerializedTypeMap';
import {ParamsLabelController} from './ParamsLabelController';
import {Poly} from '../../../Poly';
import {ParamInitData} from '../io/IOController';
import {PolyDictionary} from '../../../../types/GlobalTypes';
const NODE_SIMPLE_NAME = 'params';
export type OnSceneLoadHook = () => void;
type PostCreateParamsHook = () => void;
export interface ParamOptionToAdd<T extends ParamType> {
name: string;
type: T;
init_value: ParamInitValueSerializedTypeMap[T];
raw_input: ParamInitValueSerializedTypeMap[T];
options?: ParamOptions;
}
export interface ParamsUpdateOptions {
namesToDelete?: string[];
toAdd?: ParamOptionToAdd<ParamType>[];
}
export class ParamsController {
private _param_create_mode: boolean = false;
private _params_created: boolean = false;
private _params_by_name: PolyDictionary<BaseParamType> = {};
// caches
private _params_list: BaseParamType[] = [];
private _param_names: string[] = [];
private _non_spare_params: BaseParamType[] = [];
private _spare_params: BaseParamType[] = [];
private _non_spare_param_names: string[] = [];
private _spare_param_names: string[] = [];
private _params_node: CoreGraphNode | undefined;
// private _params_eval_key: string;
private _params_added_since_last_params_eval: boolean = false;
// private _current_param_folder_name: string | undefined;
// hooks
private _post_create_params_hook_names: string[] | undefined;
private _post_create_params_hooks: PostCreateParamsHook[] | undefined;
private _on_scene_load_hooks: OnSceneLoadHook[] | undefined;
private _on_scene_load_hook_names: string[] | undefined;
// labels
private _label_controller: ParamsLabelController | undefined;
get label(): ParamsLabelController {
return (this._label_controller = this._label_controller || new ParamsLabelController());
}
hasLabelController(): boolean {
return this._label_controller != null;
}
constructor(public readonly node: BaseNodeType) {}
dispose() {
if (this._params_node) {
this._params_node.dispose();
}
// dispose params
for (let param of this.all) {
param.dispose();
}
// hooks
this._post_create_params_hook_names = undefined;
this._post_create_params_hooks = undefined;
this._on_scene_load_hooks = undefined;
this._on_scene_load_hook_names = undefined;
//
this._label_controller?.dispose();
}
private initDependencyNode() {
if (!this._params_node) {
// TODO: consider not having a params_node for nodes which have no parameters
this._params_node = new CoreGraphNode(this.node.scene(), NODE_SIMPLE_NAME);
// this._params_node.setScene(this.node.scene);
this.node.addGraphInput(this._params_node, false);
}
}
init() {
this.initDependencyNode();
// this.reset_params()
this._param_create_mode = true;
this._initFromParamsConfig();
this.node.createParams();
this._postCreateParams();
}
private _postCreateParams() {
this._updateCaches();
// this._create_params_ui_data_dependencies();
this._initParamAccessors();
this._param_create_mode = false;
this._params_created = true;
this._runPostCreateParamsHooks();
// This was to debug a weird bug where I was adding nodes to the list
// of params, from the DependenciesController
// this._params_list.push = (...items: BaseParamType[]) => {
// if (items[0] && !items[0].compute) {
// Poly.warn('adding params', items);
// }
// for (let i of items) {
// this._params_list[this._params_list.length] = i;
// }
// return 0;
// };
}
postCreateSpareParams() {
this._updateCaches();
this._initParamAccessors();
// param.emit(ParamEvent.DELETED);
this.node.scene().referencesController.notify_params_updated(this.node);
this.node.emit(NodeEvent.PARAMS_UPDATED);
}
updateParams(options: ParamsUpdateOptions) {
let has_created_a_param = false;
let has_deleted_a_param = false;
if (options.namesToDelete) {
for (let param_name of options.namesToDelete) {
if (this.has(param_name)) {
this._deleteParam(param_name);
has_deleted_a_param = true;
}
}
}
if (options.toAdd) {
for (let param_data of options.toAdd) {
const param = this.addParam(
param_data.type,
param_data.name,
param_data.init_value,
param_data.options
);
if (param) {
if (param_data.raw_input != null) {
param.set(param_data.raw_input as never);
}
has_created_a_param = true;
}
}
}
if (has_deleted_a_param || has_created_a_param) {
this.postCreateSpareParams();
}
}
private _initFromParamsConfig() {
const paramsConfig = this.node.paramsConfig as NodeParamsConfig;
let init_values_used = false;
if (paramsConfig) {
for (let name of Object.keys(paramsConfig)) {
const config = paramsConfig[name];
let init_value: ParamInitData<ParamType> | undefined;
if (this.node.params_init_value_overrides) {
init_value = this.node.params_init_value_overrides[name];
init_values_used = true;
}
this.addParam(config.type, name, config.init_value, config.options, init_value);
}
}
// this set dirty may not be necessary, but when starting a scene with a spotlight
// with a non default t (ie: [2,2,0]), it would not be positionned correctly and would require
// a cook
if (init_values_used) {
this.node.setDirty();
}
this.node.params_init_value_overrides = undefined;
}
private _initParamAccessors() {
let current_names_in_accessor = Object.getOwnPropertyNames(this.node.pv);
this._removeUnneededAccessors(current_names_in_accessor);
// update var after having removed accessors
current_names_in_accessor = Object.getOwnPropertyNames(this.node.pv);
for (let param of this.all) {
const is_spare: boolean = param.options.isSpare();
const param_not_yet_in_accessors = !current_names_in_accessor.includes(param.name());
if (param_not_yet_in_accessors || is_spare) {
Object.defineProperty(this.node.pv, param.name(), {
get: () => {
return param.value;
},
// only spare parameters can be removed
configurable: is_spare,
});
Object.defineProperty(this.node.p, param.name(), {
get: () => {
return param;
},
configurable: is_spare,
});
}
}
}
private _removeUnneededAccessors(current_names_in_accessor: string[]) {
const current_param_names = this._param_names;
const names_to_remove = [];
for (let current_name_in_accessor of current_names_in_accessor) {
if (!current_param_names.includes(current_name_in_accessor)) {
names_to_remove.push(current_name_in_accessor);
}
}
for (let name_to_remove of names_to_remove) {
Object.defineProperty(this.node.pv, name_to_remove, {
get: () => {
return undefined;
},
configurable: true,
});
Object.defineProperty(this.node.p, name_to_remove, {
get: () => {
return undefined;
},
configurable: true,
});
}
}
get params_node() {
return this._params_node;
}
get all() {
return this._params_list;
}
get non_spare() {
return this._non_spare_params;
}
get spare() {
return this._spare_params;
}
get names(): string[] {
return this._param_names;
}
get non_spare_names(): string[] {
return this._non_spare_param_names;
}
get spare_names(): string[] {
return this._spare_param_names;
}
private set_with_type<T extends ParamType>(param_name: string, value: ParamInitValuesTypeMap[T], type: T) {
const param = this.param_with_type(param_name, type);
if (param) {
param.set(value as never);
} else {
Poly.warn(`param ${param_name} not found with type ${type}`);
}
}
set_float(param_name: string, value: ParamInitValuesTypeMap[ParamType.FLOAT]) {
this.set_with_type(param_name, value, ParamType.FLOAT);
}
set_vector3(param_name: string, value: ParamInitValuesTypeMap[ParamType.VECTOR3]) {
this.set_with_type(param_name, value, ParamType.VECTOR3);
}
has_param(param_name: string) {
return this._params_by_name[param_name] != null;
}
has(param_name: string) {
return this.has_param(param_name);
}
get(param_name: string) {
return this.param(param_name);
}
param_with_type<T extends ParamType>(param_name: string, type: T): ParamConstructorMap[T] | undefined {
const param = this.param(param_name);
if (param && param.type() == type) {
return param as ParamConstructorMap[T];
}
}
get_float(param_name: string): FloatParam {
return this.param_with_type(param_name, ParamType.FLOAT) as FloatParam;
}
get_operator_path(param_name: string): OperatorPathParam {
return this.param_with_type(param_name, ParamType.OPERATOR_PATH) as OperatorPathParam;
}
value(param_name: string) {
return this.param(param_name)?.value;
}
value_with_type<T extends ParamType>(param_name: string, type: T): ParamValuesTypeMap[T] {
return this.param_with_type(param_name, type)?.value as ParamValuesTypeMap[T];
// const param = this.param(name);
// if (param && param.type() == type) {
// return param.value();
// }
}
boolean(param_name: string) {
return this.value_with_type(param_name, ParamType.BOOLEAN);
}
float(param_name: string) {
return this.value_with_type(param_name, ParamType.FLOAT);
}
integer(param_name: string) {
return this.value_with_type(param_name, ParamType.INTEGER);
}
string(param_name: string) {
return this.value_with_type(param_name, ParamType.STRING);
}
vector2(param_name: string) {
return this.value_with_type(param_name, ParamType.VECTOR2);
}
vector3(param_name: string) {
return this.value_with_type(param_name, ParamType.VECTOR3);
}
color(param_name: string) {
return this.value_with_type(param_name, ParamType.COLOR);
}
param(param_name: string) {
const p = this._params_by_name[param_name];
if (p != null) {
return p;
} else {
Poly.warn(
`tried to access param '${param_name}' in node ${this.node.path()}, but existing params are: ${
this.names
} on node ${this.node.path()}`
);
return null;
}
}
// param_cache_name(param_name: string) {
// return `_param_${param_name}`;
// }
// delete_params(param_names: string[]) {
// for (let param_name of param_names) {
// this.delete_param(param_name);
// }
// }
// call update_params instead
private _deleteParam(param_name: string) {
const param = this._params_by_name[param_name];
if (param) {
if (this._params_node) {
this._params_node.removeGraphInput(this._params_by_name[param_name]);
}
param._setupNodeDependencies(null);
delete this._params_by_name[param_name];
if (param.isMultiple() && param.components) {
for (let component of param.components) {
const child_name = component.name();
delete this._params_by_name[child_name];
}
}
// const name_index = this._param_names.indexOf(param_name)
// if(name_index >= 0){
// this._param_names.splice(name_index, 1)
// }
// param.emit(ParamEvent.DELETED);
} else {
throw new Error(`param '${param_name}' does not exist on node ${this.node.path()}`);
}
}
addParam<T extends ParamType>(
type: T,
param_name: string,
default_value: ParamInitValuesTypeMap[T],
options: ParamOptions = {},
init_data?: ParamInitData<T>
): ParamConstructorMap[T] | undefined {
const is_spare = options['spare'] || false;
if (this._param_create_mode === false && !is_spare) {
Poly.warn(
`node ${this.node.path()} (${this.node.type()}) param '${param_name}' cannot be created outside of create_params`
);
}
if (this.node.scene() == null) {
Poly.warn(`node ${this.node.path()} (${this.node.type()}) has no scene assigned`);
}
const constructor = ParamConstructorByType[type];
if (constructor != null) {
const existing_param = this._params_by_name[param_name];
if (existing_param) {
if (is_spare) {
// delete the old one, otherwise the gl nodes when saved will attempt to set the value
// of a param with the potentially wrong type
if (existing_param.type() != type) {
this._deleteParam(existing_param.name());
}
} else {
// check that the param is spare, so that the ones generated by gl nodes are not generating an exception
Poly.warn(`a param named ${param_name} already exists`, this.node);
}
}
const param: ParamConstructorMap[T] = new constructor(this.node.scene(), this.node);
param.options.set(options);
param.setName(param_name);
param.setInitValue(default_value as never);
param.initComponents();
// set param value
// and overriden options
if (init_data == null) {
param.set(default_value as never);
} else {
// If is_expression_for_entities is true, we need to call param.set with default_value first, such as for attrib_create.
// Otherwise, as it would fail if the attribute was a vector
// since that attribute would have .value equal to {x: undefined, y: undefined, z:undefined}
if (param.options.isExpressionForEntities()) {
param.set(default_value as never);
}
if (init_data.raw_input != null) {
param.set(init_data.raw_input as never);
} else {
if (init_data.simple_data != null) {
param.set(init_data.simple_data as never);
} else {
if (init_data.complex_data != null) {
const raw_input = init_data.complex_data.raw_input;
if (raw_input) {
param.set(raw_input as never);
} else {
param.set(default_value as never);
}
const overriden_options = init_data.complex_data.overriden_options;
if (overriden_options != null) {
const keys = Object.keys(overriden_options);
for (let key of keys) {
param.options.setOption(key as keyof ParamOptions, overriden_options[key]);
}
}
}
}
}
}
param._setupNodeDependencies(this.node);
this._params_by_name[param.name()] = param as BaseParamType;
// we add the components, so that we can access them with expressions like ch('ty')
if (param.isMultiple() && param.components) {
for (let component of param.components) {
this._params_by_name[component.name()] = component as BaseParamType;
}
}
this._params_added_since_last_params_eval = true;
return param;
}
}
private _updateCaches() {
this._params_list = Object.values(this._params_by_name);
this._param_names = Object.keys(this._params_by_name);
this._non_spare_params = Object.values(this._params_by_name).filter((p) => !p.options.isSpare());
this._spare_params = Object.values(this._params_by_name).filter((p) => p.options.isSpare());
this._non_spare_param_names = Object.values(this._params_by_name)
.filter((p) => !p.options.isSpare())
.map((p) => p.name());
this._spare_param_names = Object.values(this._params_by_name)
.filter((p) => p.options.isSpare())
.map((p) => p.name());
}
async _evalParam(param: BaseParamType) {
// return new Promise((resolve, reject)=> {
// const param_cache_name = this.param_cache_name(param.name());
// const cached_value = this[param_cache_name] || null;
if (/*cached_value == null ||*/ param.isDirty() /* || param.is_errored()*/) {
/*const param_value =*/ await param.compute(); //.then(param_value=>{
// this[param_cache_name] = param_value;
if (param.states.error.active()) {
this.node.states.error.set(`param '${param.name()}' error: ${param.states.error.message()}`);
}
// return param_value;
} else {
// return param.value;
}
// });
}
async evalParams(params: BaseParamType[]) {
const promises = [];
for (let param of params) {
if (param.isDirty()) {
promises.push(this._evalParam(param));
}
}
await Promise.all(promises);
if (this.node.states.error.active()) {
this.node._setContainer(null);
}
}
paramsEvalRequired(): boolean {
return this._params_node != null && (this._params_node.isDirty() || this._params_added_since_last_params_eval);
}
async evalAll() {
if (this.paramsEvalRequired()) {
await this.evalParams(this._params_list);
this._params_node?.removeDirtyState();
this._params_added_since_last_params_eval = false;
}
}
//
//
// HOOKS
//
//
onParamsCreated(hook_name: string, hook: PostCreateParamsHook) {
if (this._params_created) {
hook();
} else {
if (this._post_create_params_hook_names && this._post_create_params_hook_names.includes(hook_name)) {
Poly.error(`hook name ${hook_name} already exists`);
return;
}
this._post_create_params_hook_names = this._post_create_params_hook_names || [];
this._post_create_params_hook_names.push(hook_name);
this._post_create_params_hooks = this._post_create_params_hooks || [];
this._post_create_params_hooks.push(hook);
}
}
addOnSceneLoadHook(param_name: string, method: OnSceneLoadHook) {
this._on_scene_load_hook_names = this._on_scene_load_hook_names || [];
this._on_scene_load_hooks = this._on_scene_load_hooks || [];
if (!this._on_scene_load_hook_names.includes(param_name)) {
this._on_scene_load_hook_names.push(param_name);
this._on_scene_load_hooks.push(method);
} else {
Poly.warn(`hook with name ${param_name} already exists`, this.node);
}
}
private _runPostCreateParamsHooks() {
if (this._post_create_params_hooks) {
for (let hook of this._post_create_params_hooks) {
hook();
}
}
}
runOnSceneLoadHooks() {
if (this._on_scene_load_hooks) {
for (let hook of this._on_scene_load_hooks) {
hook();
}
}
}
} | the_stack |
import {TypedRopNode} from './_Base';
import {Mesh} from 'three/src/objects/Mesh';
import {RopType} from '../../poly/registers/nodes/types/Rop';
import {WebGLRenderer, WebGLRendererParameters} from 'three/src/renderers/WebGLRenderer';
import {
// encoding
LinearEncoding,
sRGBEncoding,
GammaEncoding,
RGBEEncoding,
LogLuvEncoding,
RGBM7Encoding,
RGBM16Encoding,
RGBDEncoding,
// BasicDepthPacking,
// RGBADepthPacking,
// tone mapping
NoToneMapping,
LinearToneMapping,
ReinhardToneMapping,
CineonToneMapping,
ACESFilmicToneMapping,
// shadow map
BasicShadowMap,
PCFShadowMap,
PCFSoftShadowMap,
VSMShadowMap,
} from 'three/src/constants';
enum EncodingName {
Linear = 'Linear',
sRGB = 'sRGB',
Gamma = 'Gamma',
RGBE = 'RGBE',
LogLuv = 'LogLuv',
RGBM7 = 'RGBM7',
RGBM16 = 'RGBM16',
RGBD = 'RGBD',
// BasicDepth = 'BasicDepth',
// RGBADepth = 'RGBADepth',
}
enum EncodingValue {
Linear = LinearEncoding as number,
sRGB = sRGBEncoding as number,
Gamma = GammaEncoding as number,
RGBE = RGBEEncoding as number,
LogLuv = LogLuvEncoding as number,
RGBM7 = RGBM7Encoding as number,
RGBM16 = RGBM16Encoding as number,
RGBD = RGBDEncoding as number,
// BasicDepth = BasicDepthPacking as number,
// RGBADepth = RGBADepthPacking as number,
}
const ENCODING_NAMES: EncodingName[] = [
EncodingName.Linear,
EncodingName.sRGB,
EncodingName.Gamma,
EncodingName.RGBE,
EncodingName.LogLuv,
EncodingName.RGBM7,
EncodingName.RGBM16,
EncodingName.RGBD,
// EncodingName.BasicDepth,
// EncodingName.RGBADepth,
];
const ENCODING_VALUES: EncodingValue[] = [
EncodingValue.Linear,
EncodingValue.sRGB,
EncodingValue.Gamma,
EncodingValue.RGBE,
EncodingValue.LogLuv,
EncodingValue.RGBM7,
EncodingValue.RGBM16,
EncodingValue.RGBD,
// EncodingValue.BasicDepth,
// EncodingValue.RGBADepth,
];
export const DEFAULT_OUTPUT_ENCODING = EncodingValue.sRGB as number;
enum ToneMappingName {
No = 'No',
Linear = 'Linear',
Reinhard = 'Reinhard',
Cineon = 'Cineon',
ACESFilmic = 'ACESFilmic',
}
enum ToneMappingValue {
No = NoToneMapping as number,
Linear = LinearToneMapping as number,
Reinhard = ReinhardToneMapping as number,
Cineon = CineonToneMapping as number,
ACESFilmic = ACESFilmicToneMapping as number,
}
const TONE_MAPPING_NAMES: ToneMappingName[] = [
ToneMappingName.No,
ToneMappingName.Linear,
ToneMappingName.Reinhard,
ToneMappingName.Cineon,
ToneMappingName.ACESFilmic,
];
const TONE_MAPPING_VALUES: ToneMappingValue[] = [
ToneMappingValue.No,
ToneMappingValue.Linear,
ToneMappingValue.Reinhard,
ToneMappingValue.Cineon,
ToneMappingValue.ACESFilmic,
];
export const DEFAULT_TONE_MAPPING = ToneMappingValue.ACESFilmic as number;
const TONE_MAPPING_MENU_ENTRIES = TONE_MAPPING_NAMES.map((name, i) => {
return {
name: name,
value: TONE_MAPPING_VALUES[i],
};
});
enum RendererPrecision {
HIGH = 'highp',
MEDIUM = 'mediump',
LOW = 'lowp',
}
const RENDERER_PRECISIONS: RendererPrecision[] = [
RendererPrecision.HIGH,
RendererPrecision.MEDIUM,
RendererPrecision.LOW,
];
enum PowerPreference {
HIGH = 'high-performance',
LOW = 'low-power',
DEFAULT = 'default',
}
const POWER_PREFERENCES: PowerPreference[] = [PowerPreference.HIGH, PowerPreference.LOW, PowerPreference.DEFAULT];
enum ShadowMapTypeName {
Basic = 'Basic',
PCF = 'PCF',
PCFSoft = 'PCFSoft',
VSM = 'VSM',
}
enum ShadowMapTypeValue {
Basic = BasicShadowMap as number,
PCF = PCFShadowMap as number,
PCFSoft = PCFSoftShadowMap as number,
VSM = VSMShadowMap as number,
}
const SHADOW_MAP_TYPE_NAMES: ShadowMapTypeName[] = [
ShadowMapTypeName.Basic,
ShadowMapTypeName.PCF,
ShadowMapTypeName.PCFSoft,
ShadowMapTypeName.VSM,
];
const SHADOW_MAP_TYPE_VALUES: ShadowMapTypeValue[] = [
ShadowMapTypeValue.Basic,
ShadowMapTypeValue.PCF,
ShadowMapTypeValue.PCFSoft,
ShadowMapTypeValue.VSM,
];
export const SHADOW_MAP_TYPES = [BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMap];
export const DEFAULT_SHADOW_MAP_TYPE = ShadowMapTypeValue.PCFSoft as number;
// TODO: set debug.checkShaderErrors to false in prod
const DEFAULT_PARAMS: WebGLRendererParameters = {
alpha: false,
precision: RendererPrecision.HIGH,
premultipliedAlpha: true,
antialias: false,
stencil: true,
preserveDrawingBuffer: false,
powerPreference: PowerPreference.DEFAULT,
depth: true,
logarithmicDepthBuffer: false,
};
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {CoreType} from '../../../core/Type';
import {PolyDictionary} from '../../../types/GlobalTypes';
import {RenderController} from '../obj/utils/cameras/RenderController';
import {Poly} from '../../Poly';
import {isBooleanTrue} from '../../../core/BooleanValue';
class WebGLRendererRopParamsConfig extends NodeParamsConfig {
/** @param toggle on to set the precision */
tprecision = ParamConfig.BOOLEAN(0);
/** @param set the precision */
precision = ParamConfig.INTEGER(RENDERER_PRECISIONS.indexOf(RendererPrecision.HIGH), {
visibleIf: {tprecision: 1},
menu: {
entries: RENDERER_PRECISIONS.map((name, value) => {
return {value, name};
}),
},
});
/** @param toggle on to set the power preferenc */
tpowerPreference = ParamConfig.BOOLEAN(0);
/** @param set the precision */
powerPreference = ParamConfig.INTEGER(POWER_PREFERENCES.indexOf(PowerPreference.DEFAULT), {
visibleIf: {tpowerPreference: 1},
menu: {
entries: POWER_PREFERENCES.map((name, value) => {
return {value, name};
}),
},
});
/** @param toggle on to have alpha on (change requires page reload) */
alpha = ParamConfig.BOOLEAN(1);
/** @param premultipliedAlpha */
premultipliedAlpha = ParamConfig.BOOLEAN(1);
/** @param toggle on to have antialias on (change requires page reload) */
antialias = ParamConfig.BOOLEAN(1);
/** @param stencil */
stencil = ParamConfig.BOOLEAN(1);
/** @param depth */
depth = ParamConfig.BOOLEAN(1);
/** @param logarithmicDepthBuffer */
logarithmicDepthBuffer = ParamConfig.BOOLEAN(0);
/** @param tone mapping */
toneMapping = ParamConfig.INTEGER(DEFAULT_TONE_MAPPING, {
menu: {
entries: TONE_MAPPING_MENU_ENTRIES,
},
});
/** @param tone mapping exposure */
toneMappingExposure = ParamConfig.FLOAT(1, {
range: [0, 2],
});
/** @param output encoding */
outputEncoding = ParamConfig.INTEGER(DEFAULT_OUTPUT_ENCODING, {
menu: {
entries: ENCODING_NAMES.map((name, i) => {
return {
name: name,
value: ENCODING_VALUES[i],
};
}),
},
});
/** @param physically correct lights */
physicallyCorrectLights = ParamConfig.BOOLEAN(1);
/** @param sort objects, which can be necessary when rendering transparent objects */
sortObjects = ParamConfig.BOOLEAN(1);
/** @param toggle to override the default pixel ratio, which is 1 for mobile devices, and Math.max(2, window.devicePixelRatio) for other devices */
tpixelRatio = ParamConfig.BOOLEAN(0);
/** @param higher pixelRatio improves render sharpness but reduces performance */
pixelRatio = ParamConfig.INTEGER(2, {
visibleIf: {tpixelRatio: true},
range: [1, 4],
rangeLocked: [true, false],
});
/** @param toggle on to have shadow maps */
tshadowMap = ParamConfig.BOOLEAN(1);
/** @param toggle on to recompute the shadow maps on every frame. If all objects are static, you may want to turn this off */
shadowMapAutoUpdate = ParamConfig.BOOLEAN(1, {visibleIf: {tshadowMap: 1}});
/** @param toggle on to trigger shadows update */
shadowMapNeedsUpdate = ParamConfig.BOOLEAN(0, {visibleIf: {tshadowMap: 1}});
/** @param shadows type */
shadowMapType = ParamConfig.INTEGER(DEFAULT_SHADOW_MAP_TYPE, {
visibleIf: {tshadowMap: 1},
menu: {
entries: SHADOW_MAP_TYPE_NAMES.map((name, i) => {
return {
name: name,
value: SHADOW_MAP_TYPE_VALUES[i],
};
}),
},
});
// preserve_drawing_buffer = ParamConfig.BOOLEAN(0);
}
const ParamsConfig = new WebGLRendererRopParamsConfig();
export class WebGLRendererRopNode extends TypedRopNode<WebGLRendererRopParamsConfig> {
paramsConfig = ParamsConfig;
static type(): Readonly<RopType.WEBGL> {
return RopType.WEBGL;
}
private _renderers_by_canvas_id: PolyDictionary<WebGLRenderer> = {};
createRenderer(canvas: HTMLCanvasElement, gl: WebGLRenderingContext): WebGLRenderer {
const params: WebGLRendererParameters = {};
const keys: Array<keyof WebGLRendererParameters> = Object.keys(DEFAULT_PARAMS) as Array<
keyof WebGLRendererParameters
>;
let k: keyof WebGLRendererParameters;
for (k of keys) {
(params[k] as any) = DEFAULT_PARAMS[k];
}
if (isBooleanTrue(this.pv.tprecision)) {
const precision = RENDERER_PRECISIONS[this.pv.precision];
params.precision = precision;
}
if (isBooleanTrue(this.pv.tpowerPreference)) {
const powerPreference = POWER_PREFERENCES[this.pv.powerPreference];
params.powerPreference = powerPreference;
}
params.antialias = isBooleanTrue(this.pv.antialias);
params.antialias = isBooleanTrue(this.pv.antialias);
params.alpha = isBooleanTrue(this.pv.alpha);
params.premultipliedAlpha = isBooleanTrue(this.pv.premultipliedAlpha);
params.depth = isBooleanTrue(this.pv.depth);
params.stencil = isBooleanTrue(this.pv.stencil);
params.logarithmicDepthBuffer = isBooleanTrue(this.pv.logarithmicDepthBuffer);
params.canvas = canvas;
params.context = gl;
// (params as WebGLRendererParameters).preserveDrawingBuffer = this.pv.preserve_drawing_buffer;
const renderer = Poly.renderersController.createWebGLRenderer(params);
if (Poly.renderersController.printDebug()) {
Poly.renderersController.printDebugMessage(`create renderer from node '${this.path()}'`);
Poly.renderersController.printDebugMessage({
params: params,
});
}
this._update_renderer(renderer);
this._renderers_by_canvas_id[canvas.id] = renderer;
return renderer;
}
cook() {
const ids = Object.keys(this._renderers_by_canvas_id);
for (let id of ids) {
const renderer = this._renderers_by_canvas_id[id];
this._update_renderer(renderer);
}
this._traverse_scene_and_update_materials();
this.cookController.endCook();
}
_update_renderer(renderer: WebGLRenderer) {
// this._renderer.setClearAlpha(this.pv.alpha);
renderer.physicallyCorrectLights = this.pv.physicallyCorrectLights;
renderer.outputEncoding = this.pv.outputEncoding;
renderer.toneMapping = this.pv.toneMapping;
renderer.toneMappingExposure = this.pv.toneMappingExposure;
// shadows
renderer.shadowMap.enabled = this.pv.tshadowMap;
renderer.shadowMap.autoUpdate = this.pv.shadowMapAutoUpdate;
renderer.shadowMap.needsUpdate = this.pv.shadowMapNeedsUpdate;
renderer.shadowMap.type = this.pv.shadowMapType;
renderer.sortObjects = this.pv.sortObjects;
const pixelRatio = this.pv.tpixelRatio ? this.pv.pixelRatio : RenderController.defaultPixelRatio();
if (Poly.renderersController.printDebug()) {
Poly.renderersController.printDebugMessage(`set renderer pixelRatio from '${this.path()}'`);
Poly.renderersController.printDebugMessage({
pixelRatio: pixelRatio,
});
}
renderer.setPixelRatio(pixelRatio);
}
private _traverse_scene_and_update_materials() {
this.scene()
.threejsScene()
.traverse((object) => {
const material = (object as Mesh).material;
if (material) {
if (CoreType.isArray(material)) {
for (let mat of material) {
mat.needsUpdate = true;
}
} else {
material.needsUpdate = true;
}
}
});
}
} | the_stack |
import env from '../core/env';
import {applyTransform} from '../core/vector';
import BoundingRect from '../core/BoundingRect';
import * as colorTool from '../tool/color';
import * as textContain from '../graphic/text/parse';
import Displayable from '../graphic/Displayable';
import ZRImage from '../graphic/Image';
import Text from '../graphic/TSpan';
import Path from '../graphic/Path';
import PathProxy from '../core/PathProxy';
import Gradient from '../graphic/Gradient';
import * as vmlCore from './core';
var CMD = PathProxy.CMD;
var round = Math.round;
var sqrt = Math.sqrt;
var abs = Math.abs;
var cos = Math.cos;
var sin = Math.sin;
var mathMax = Math.max;
if (!env.canvasSupported) {
var comma = ',';
var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
var Z = 21600;
var Z2 = Z / 2;
var ZLEVEL_BASE = 100000;
var Z_BASE = 1000;
var initRootElStyle = function (el) {
el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
el.coordsize = Z + ',' + Z;
el.coordorigin = '0,0';
};
var encodeHtmlAttribute = function (s) {
return String(s).replace(/&/g, '&').replace(/"/g, '"');
};
var rgb2Str = function (r, g, b) {
return 'rgb(' + [r, g, b].join(',') + ')';
};
var append = function (parent, child) {
if (child && parent && child.parentNode !== parent) {
parent.appendChild(child);
}
};
var remove = function (parent, child) {
if (child && parent && child.parentNode === parent) {
parent.removeChild(child);
}
};
var getZIndex = function (zlevel, z, z2) {
// z 的取值范围为 [0, 1000]
return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE + z2;
};
var parsePercent = textHelper.parsePercent;
/***************************************************
* PATH
**************************************************/
var setColorAndOpacity = function (el, color, opacity) {
var colorArr = colorTool.parse(color);
opacity = +opacity;
if (isNaN(opacity)) {
opacity = 1;
}
if (colorArr) {
el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
el.opacity = opacity * colorArr[3];
}
};
var getColorAndAlpha = function (color) {
var colorArr = colorTool.parse(color);
return [
rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
colorArr[3]
];
};
var updateFillNode = function (el, style, zrEl) {
// TODO pattern
var fill = style.fill;
if (fill != null) {
// Modified from excanvas
if (fill instanceof Gradient) {
var gradientType;
var angle = 0;
var focus = [0, 0];
// additional offset
var shift = 0;
// scale factor for offset
var expansion = 1;
var rect = zrEl.getBoundingRect();
var rectWidth = rect.width;
var rectHeight = rect.height;
if (fill.type === 'linear') {
gradientType = 'gradient';
var transform = zrEl.transform;
var p0 = [fill.x * rectWidth, fill.y * rectHeight];
var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
if (transform) {
applyTransform(p0, p0, transform);
applyTransform(p1, p1, transform);
}
var dx = p1[0] - p0[0];
var dy = p1[1] - p0[1];
angle = Math.atan2(dx, dy) * 180 / Math.PI;
// The angle should be a non-negative number.
if (angle < 0) {
angle += 360;
}
// Very small angles produce an unexpected result because they are
// converted to a scientific notation string.
if (angle < 1e-6) {
angle = 0;
}
}
else {
gradientType = 'gradientradial';
var p0 = [fill.x * rectWidth, fill.y * rectHeight];
var transform = zrEl.transform;
var scale = zrEl.scale;
var width = rectWidth;
var height = rectHeight;
focus = [
// Percent in bounding rect
(p0[0] - rect.x) / width,
(p0[1] - rect.y) / height
];
if (transform) {
applyTransform(p0, p0, transform);
}
width /= scale[0] * Z;
height /= scale[1] * Z;
var dimension = mathMax(width, height);
shift = 2 * 0 / dimension;
expansion = 2 * fill.r / dimension - shift;
}
// We need to sort the color stops in ascending order by offset,
// otherwise IE won't interpret it correctly.
var stops = fill.colorStops.slice();
stops.sort(function (cs1, cs2) {
return cs1.offset - cs2.offset;
});
var length = stops.length;
// Color and alpha list of first and last stop
var colorAndAlphaList = [];
var colors = [];
for (var i = 0; i < length; i++) {
var stop = stops[i];
var colorAndAlpha = getColorAndAlpha(stop.color);
colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
if (i === 0 || i === length - 1) {
colorAndAlphaList.push(colorAndAlpha);
}
}
if (length >= 2) {
var color1 = colorAndAlphaList[0][0];
var color2 = colorAndAlphaList[1][0];
var opacity1 = colorAndAlphaList[0][1] * style.opacity;
var opacity2 = colorAndAlphaList[1][1] * style.opacity;
el.type = gradientType;
el.method = 'none';
el.focus = '100%';
el.angle = angle;
el.color = color1;
el.color2 = color2;
el.colors = colors.join(',');
// When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
el.opacity = opacity2;
// FIXME g_o_:opacity ?
el.opacity2 = opacity1;
}
if (gradientType === 'radial') {
el.focusposition = focus.join(',');
}
}
else {
// FIXME Change from Gradient fill to color fill
setColorAndOpacity(el, fill, style.opacity);
}
}
};
var updateStrokeNode = function (el, style) {
// if (style.lineJoin != null) {
// el.joinstyle = style.lineJoin;
// }
// if (style.miterLimit != null) {
// el.miterlimit = style.miterLimit * Z;
// }
// if (style.lineCap != null) {
// el.endcap = style.lineCap;
// }
if (style.lineDash) {
el.dashstyle = style.lineDash.join(' ');
}
if (style.stroke != null && !(style.stroke instanceof Gradient)) {
setColorAndOpacity(el, style.stroke, style.opacity);
}
};
var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
var isFill = type === 'fill';
var el = vmlEl.getElementsByTagName(type)[0];
// Stroke must have lineWidth
if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
// FIXME Remove before updating, or set `colors` will throw error
if (style[type] instanceof Gradient) {
remove(vmlEl, el);
}
if (!el) {
el = vmlCore.createNode(type);
}
isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
append(vmlEl, el);
}
else {
vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
remove(vmlEl, el);
}
};
var points = [[], [], []];
var pathDataToString = function (path, m) {
var M = CMD.M;
var C = CMD.C;
var L = CMD.L;
var A = CMD.A;
var Q = CMD.Q;
var str = [];
var nPoint;
var cmdStr;
var cmd;
var i;
var xi;
var yi;
var data = path.data;
var dataLength = path.len();
for (i = 0; i < dataLength;) {
cmd = data[i++];
cmdStr = '';
nPoint = 0;
switch (cmd) {
case M:
cmdStr = ' m ';
nPoint = 1;
xi = data[i++];
yi = data[i++];
points[0][0] = xi;
points[0][1] = yi;
break;
case L:
cmdStr = ' l ';
nPoint = 1;
xi = data[i++];
yi = data[i++];
points[0][0] = xi;
points[0][1] = yi;
break;
case Q:
case C:
cmdStr = ' c ';
nPoint = 3;
var x1 = data[i++];
var y1 = data[i++];
var x2 = data[i++];
var y2 = data[i++];
var x3;
var y3;
if (cmd === Q) {
// Convert quadratic to cubic using degree elevation
x3 = x2;
y3 = y2;
x2 = (x2 + 2 * x1) / 3;
y2 = (y2 + 2 * y1) / 3;
x1 = (xi + 2 * x1) / 3;
y1 = (yi + 2 * y1) / 3;
}
else {
x3 = data[i++];
y3 = data[i++];
}
points[0][0] = x1;
points[0][1] = y1;
points[1][0] = x2;
points[1][1] = y2;
points[2][0] = x3;
points[2][1] = y3;
xi = x3;
yi = y3;
break;
case A:
var x = 0;
var y = 0;
var sx = 1;
var sy = 1;
var angle = 0;
if (m) {
// Extract SRT from matrix
x = m[4];
y = m[5];
sx = sqrt(m[0] * m[0] + m[1] * m[1]);
sy = sqrt(m[2] * m[2] + m[3] * m[3]);
angle = Math.atan2(-m[1] / sy, m[0] / sx);
}
var cx = data[i++];
var cy = data[i++];
var rx = data[i++];
var ry = data[i++];
var startAngle = data[i++] + angle;
var endAngle = data[i++] + startAngle + angle;
// FIXME
// var psi = data[i++];
i++;
var clockwise = data[i++];
var x0 = cx + cos(startAngle) * rx;
var y0 = cy + sin(startAngle) * ry;
var x1 = cx + cos(endAngle) * rx;
var y1 = cy + sin(endAngle) * ry;
var type = clockwise ? ' wa ' : ' at ';
if (Math.abs(x0 - x1) < 1e-4) {
// IE won't render arches drawn counter clockwise if x0 == x1.
if (Math.abs(endAngle - startAngle) > 1e-2) {
// Offset x0 by 1/80 of a pixel. Use something
// that can be represented in binary
if (clockwise) {
x0 += 270 / Z;
}
}
else {
// Avoid case draw full circle
if (Math.abs(y0 - cy) < 1e-4) {
if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
y1 -= 270 / Z;
}
else {
y1 += 270 / Z;
}
}
else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
x1 += 270 / Z;
}
else {
x1 -= 270 / Z;
}
}
}
str.push(
type,
round(((cx - rx) * sx + x) * Z - Z2), comma,
round(((cy - ry) * sy + y) * Z - Z2), comma,
round(((cx + rx) * sx + x) * Z - Z2), comma,
round(((cy + ry) * sy + y) * Z - Z2), comma,
round((x0 * sx + x) * Z - Z2), comma,
round((y0 * sy + y) * Z - Z2), comma,
round((x1 * sx + x) * Z - Z2), comma,
round((y1 * sy + y) * Z - Z2)
);
xi = x1;
yi = y1;
break;
case CMD.R:
var p0 = points[0];
var p1 = points[1];
// x0, y0
p0[0] = data[i++];
p0[1] = data[i++];
// x1, y1
p1[0] = p0[0] + data[i++];
p1[1] = p0[1] + data[i++];
if (m) {
applyTransform(p0, p0, m);
applyTransform(p1, p1, m);
}
p0[0] = round(p0[0] * Z - Z2);
p1[0] = round(p1[0] * Z - Z2);
p0[1] = round(p0[1] * Z - Z2);
p1[1] = round(p1[1] * Z - Z2);
str.push(
// x0, y0
' m ', p0[0], comma, p0[1],
// x1, y0
' l ', p1[0], comma, p0[1],
// x1, y1
' l ', p1[0], comma, p1[1],
// x0, y1
' l ', p0[0], comma, p1[1]
);
break;
case CMD.Z:
// FIXME Update xi, yi
str.push(' x ');
}
if (nPoint > 0) {
str.push(cmdStr);
for (var k = 0; k < nPoint; k++) {
var p = points[k];
m && applyTransform(p, p, m);
// 不 round 会非常慢
str.push(
round(p[0] * Z - Z2), comma, round(p[1] * Z - Z2),
k < nPoint - 1 ? comma : ''
);
}
}
}
return str.join('');
};
// Rewrite the original path method
Path.prototype.brushVML = function (vmlRoot) {
var style = this.style;
var vmlEl = this._vmlEl;
if (!vmlEl) {
vmlEl = vmlCore.createNode('shape');
initRootElStyle(vmlEl);
this._vmlEl = vmlEl;
}
updateFillAndStroke(vmlEl, 'fill', style, this);
updateFillAndStroke(vmlEl, 'stroke', style, this);
var m = this.transform;
var needTransform = m != null;
var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
if (strokeEl) {
var lineWidth = style.lineWidth;
// Get the line scale.
// Determinant of this.m_ means how much the area is enlarged by the
// transformation. So its square root can be used as a scale factor
// for width.
if (needTransform && !style.strokeNoScale) {
var det = m[0] * m[3] - m[1] * m[2];
lineWidth *= sqrt(abs(det));
}
strokeEl.weight = lineWidth + 'px';
}
var path = this.path || (this.path = new PathProxy());
if (this.__dirtyPath) {
path.beginPath();
path.subPixelOptimize = false;
this.buildPath(path, this.shape);
path.toStatic();
this.__dirtyPath = false;
}
vmlEl.path = pathDataToString(path, this.transform);
vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
// Append to root
append(vmlRoot, vmlEl);
// Text
if (style.text != null) {
this.drawRectText(vmlRoot, this.getBoundingRect());
}
else {
this.removeRectText(vmlRoot);
}
};
Path.prototype.onRemove = function (vmlRoot) {
remove(vmlRoot, this._vmlEl);
this.removeRectText(vmlRoot);
};
Path.prototype.onAdd = function (vmlRoot) {
append(vmlRoot, this._vmlEl);
this.appendRectText(vmlRoot);
};
/***************************************************
* IMAGE
**************************************************/
var isImage = function (img) {
// FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
// return img instanceof Image;
};
// Rewrite the original path method
ZRImage.prototype.brushVML = function (vmlRoot) {
var style = this.style;
var image = style.image;
// Image original width, height
var ow;
var oh;
if (isImage(image)) {
var src = image.src;
if (src === this._imageSrc) {
ow = this._imageWidth;
oh = this._imageHeight;
}
else {
var imageRuntimeStyle = image.runtimeStyle;
var oldRuntimeWidth = imageRuntimeStyle.width;
var oldRuntimeHeight = imageRuntimeStyle.height;
imageRuntimeStyle.width = 'auto';
imageRuntimeStyle.height = 'auto';
// get the original size
ow = image.width;
oh = image.height;
// and remove overides
imageRuntimeStyle.width = oldRuntimeWidth;
imageRuntimeStyle.height = oldRuntimeHeight;
// Caching image original width, height and src
this._imageSrc = src;
this._imageWidth = ow;
this._imageHeight = oh;
}
image = src;
}
else {
if (image === this._imageSrc) {
ow = this._imageWidth;
oh = this._imageHeight;
}
}
if (!image) {
return;
}
var x = style.x || 0;
var y = style.y || 0;
var dw = style.width;
var dh = style.height;
var sw = style.sWidth;
var sh = style.sHeight;
var sx = style.sx || 0;
var sy = style.sy || 0;
var hasCrop = sw && sh;
var vmlEl = this._vmlEl;
if (!vmlEl) {
// FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
// vmlEl = vmlCore.createNode('group');
vmlEl = vmlCore.doc.createElement('div');
initRootElStyle(vmlEl);
this._vmlEl = vmlEl;
}
var vmlElStyle = vmlEl.style;
var hasRotation = false;
var m;
var scaleX = 1;
var scaleY = 1;
if (this.transform) {
m = this.transform;
scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
hasRotation = m[1] || m[2];
}
if (hasRotation) {
// If filters are necessary (rotation exists), create them
// filters are bog-slow, so only create them if abbsolutely necessary
// The following check doesn't account for skews (which don't exist
// in the canvas spec (yet) anyway.
// From excanvas
var p0 = [x, y];
var p1 = [x + dw, y];
var p2 = [x, y + dh];
var p3 = [x + dw, y + dh];
applyTransform(p0, p0, m);
applyTransform(p1, p1, m);
applyTransform(p2, p2, m);
applyTransform(p3, p3, m);
var maxX = mathMax(p0[0], p1[0], p2[0], p3[0]);
var maxY = mathMax(p0[1], p1[1], p2[1], p3[1]);
var transformFilter = [];
transformFilter.push('M11=', m[0] / scaleX, comma,
'M12=', m[2] / scaleY, comma,
'M21=', m[1] / scaleX, comma,
'M22=', m[3] / scaleY, comma,
'Dx=', round(x * scaleX + m[4]), comma,
'Dy=', round(y * scaleY + m[5]));
vmlElStyle.padding = '0 ' + round(maxX) + 'px ' + round(maxY) + 'px 0';
// FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
vmlElStyle.filter = imageTransformPrefix + '.Matrix('
+ transformFilter.join('') + ', SizingMethod=clip)';
}
else {
if (m) {
x = x * scaleX + m[4];
y = y * scaleY + m[5];
}
vmlElStyle.filter = '';
vmlElStyle.left = round(x) + 'px';
vmlElStyle.top = round(y) + 'px';
}
var imageEl = this._imageEl;
var cropEl = this._cropEl;
if (!imageEl) {
imageEl = vmlCore.doc.createElement('div');
this._imageEl = imageEl;
}
var imageELStyle = imageEl.style;
if (hasCrop) {
// Needs know image original width and height
if (!(ow && oh)) {
var tmpImage = new Image();
var self = this;
tmpImage.onload = function () {
tmpImage.onload = null;
ow = tmpImage.width;
oh = tmpImage.height;
// Adjust image width and height to fit the ratio destinationSize / sourceSize
imageELStyle.width = round(scaleX * ow * dw / sw) + 'px';
imageELStyle.height = round(scaleY * oh * dh / sh) + 'px';
// Caching image original width, height and src
self._imageWidth = ow;
self._imageHeight = oh;
self._imageSrc = image;
};
tmpImage.src = image;
}
else {
imageELStyle.width = round(scaleX * ow * dw / sw) + 'px';
imageELStyle.height = round(scaleY * oh * dh / sh) + 'px';
}
if (!cropEl) {
cropEl = vmlCore.doc.createElement('div');
cropEl.style.overflow = 'hidden';
this._cropEl = cropEl;
}
var cropElStyle = cropEl.style;
cropElStyle.width = round((dw + sx * dw / sw) * scaleX);
cropElStyle.height = round((dh + sy * dh / sh) * scaleY);
cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
+ (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
if (!cropEl.parentNode) {
vmlEl.appendChild(cropEl);
}
if (imageEl.parentNode !== cropEl) {
cropEl.appendChild(imageEl);
}
}
else {
imageELStyle.width = round(scaleX * dw) + 'px';
imageELStyle.height = round(scaleY * dh) + 'px';
vmlEl.appendChild(imageEl);
if (cropEl && cropEl.parentNode) {
vmlEl.removeChild(cropEl);
this._cropEl = null;
}
}
var filterStr = '';
var alpha = style.opacity;
if (alpha < 1) {
filterStr += '.Alpha(opacity=' + round(alpha * 100) + ') ';
}
filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
imageELStyle.filter = filterStr;
vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
// Append to root
append(vmlRoot, vmlEl);
// Text
if (style.text != null) {
this.drawRectText(vmlRoot, this.getBoundingRect());
}
};
ZRImage.prototype.onRemove = function (vmlRoot) {
remove(vmlRoot, this._vmlEl);
this._vmlEl = null;
this._cropEl = null;
this._imageEl = null;
this.removeRectText(vmlRoot);
};
ZRImage.prototype.onAdd = function (vmlRoot) {
append(vmlRoot, this._vmlEl);
this.appendRectText(vmlRoot);
};
/***************************************************
* TEXT
**************************************************/
var DEFAULT_STYLE_NORMAL = 'normal';
var fontStyleCache = {};
var fontStyleCacheCount = 0;
var MAX_FONT_CACHE_SIZE = 100;
var fontEl = document.createElement('div');
var getFontStyle = function (fontString) {
var fontStyle = fontStyleCache[fontString];
if (!fontStyle) {
// Clear cache
if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
fontStyleCacheCount = 0;
fontStyleCache = {};
}
var style = fontEl.style;
var fontFamily;
try {
style.font = fontString;
fontFamily = style.fontFamily.split(',')[0];
}
catch (e) {
}
fontStyle = {
style: style.fontStyle || DEFAULT_STYLE_NORMAL,
variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
size: parseFloat(style.fontSize || 12) | 0,
family: fontFamily || 'Microsoft YaHei'
};
fontStyleCache[fontString] = fontStyle;
fontStyleCacheCount++;
}
return fontStyle;
};
var textMeasureEl;
// Overwrite measure text method
textContain.$override('measureText', function (text, textFont) {
var doc = vmlCore.doc;
if (!textMeasureEl) {
textMeasureEl = doc.createElement('div');
textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
+ 'padding:0;margin:0;border:none;white-space:pre;';
vmlCore.doc.body.appendChild(textMeasureEl);
}
try {
textMeasureEl.style.font = textFont;
}
catch (ex) {
// Ignore failures to set to invalid font.
}
textMeasureEl.innerHTML = '';
// Don't use innerHTML or innerText because they allow markup/whitespace.
textMeasureEl.appendChild(doc.createTextNode(text));
return {
width: textMeasureEl.offsetWidth
};
});
var tmpRect = new BoundingRect(0, 0, 0, 0);
var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
var style = this.style;
// Optimize, avoid normalize every time.
this.__dirty && textHelper.normalizeTextStyle(style, true);
var text = style.text;
// Convert to string
text != null && (text += '');
if (!text) {
return;
}
// Convert rich text to plain text. Rich text is not supported in
// IE8-, but tags in rich text template will be removed.
if (style.rich) {
var contentBlock = textContain.parseRichText(text, style);
text = [];
for (var i = 0; i < contentBlock.lines.length; i++) {
var tokens = contentBlock.lines[i].tokens;
var textLine = [];
for (var j = 0; j < tokens.length; j++) {
textLine.push(tokens[j].text);
}
text.push(textLine.join(''));
}
text = text.join('\n');
}
var x;
var y;
var align = style.textAlign;
var verticalAlign = style.textVerticalAlign;
var fontStyle = getFontStyle(style.font);
// FIXME encodeHtmlAttribute ?
var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
+ fontStyle.size + 'px "' + fontStyle.family + '"';
textRect = textRect || textContain.getBoundingRect(
text, font, align, verticalAlign, style.textPadding, style.textLineHeight
);
// Transform rect to view space
var m = this.transform;
// Ignore transform for text in other element
if (m && !fromTextEl) {
tmpRect.copy(rect);
tmpRect.applyTransform(m);
rect = tmpRect;
}
if (!fromTextEl) {
var textPosition = style.textPosition;
// Text position represented by coord
if (textPosition instanceof Array) {
x = rect.x + parsePercent(textPosition[0], rect.width);
y = rect.y + parsePercent(textPosition[1], rect.height);
align = align || 'left';
}
else {
var res = this.calculateTextPosition
? this.calculateTextPosition({}, style, rect)
: textContain.calculateTextPosition({}, style, rect);
x = res.x;
y = res.y;
// Default align and baseline when has textPosition
align = align || res.align;
verticalAlign = verticalAlign || res.verticalAlign;
}
}
else {
x = rect.x;
y = rect.y;
}
x = textContain.adjustTextX(x, textRect.width, align);
y = textContain.adjustTextY(y, textRect.height, verticalAlign);
// Force baseline 'middle'
y += textRect.height / 2;
// var fontSize = fontStyle.size;
// 1.75 is an arbitrary number, as there is no info about the text baseline
// switch (baseline) {
// case 'hanging':
// case 'top':
// y += fontSize / 1.75;
// break;
// case 'middle':
// break;
// default:
// // case null:
// // case 'alphabetic':
// // case 'ideographic':
// // case 'bottom':
// y -= fontSize / 2.25;
// break;
// }
// switch (align) {
// case 'left':
// break;
// case 'center':
// x -= textRect.width / 2;
// break;
// case 'right':
// x -= textRect.width;
// break;
// case 'end':
// align = elementStyle.direction == 'ltr' ? 'right' : 'left';
// break;
// case 'start':
// align = elementStyle.direction == 'rtl' ? 'right' : 'left';
// break;
// default:
// align = 'left';
// }
var createNode = vmlCore.createNode;
var textVmlEl = this._textVmlEl;
var pathEl;
var textPathEl;
var skewEl;
if (!textVmlEl) {
textVmlEl = createNode('line');
pathEl = createNode('path');
textPathEl = createNode('textpath');
skewEl = createNode('skew');
// FIXME Why here is not cammel case
// Align 'center' seems wrong
textPathEl.style['v-text-align'] = 'left';
initRootElStyle(textVmlEl);
pathEl.textpathok = true;
textPathEl.on = true;
textVmlEl.from = '0 0';
textVmlEl.to = '1000 0.05';
append(textVmlEl, skewEl);
append(textVmlEl, pathEl);
append(textVmlEl, textPathEl);
this._textVmlEl = textVmlEl;
}
else {
// 这里是在前面 appendChild 保证顺序的前提下
skewEl = textVmlEl.firstChild;
pathEl = skewEl.nextSibling;
textPathEl = pathEl.nextSibling;
}
var coords = [x, y];
var textVmlElStyle = textVmlEl.style;
// Ignore transform for text in other element
if (m && fromTextEl) {
applyTransform(coords, coords, m);
skewEl.on = true;
skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma
+ m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
// Text position
skewEl.offset = (round(coords[0]) || 0) + ',' + (round(coords[1]) || 0);
// Left top point as origin
skewEl.origin = '0 0';
textVmlElStyle.left = '0px';
textVmlElStyle.top = '0px';
}
else {
skewEl.on = false;
textVmlElStyle.left = round(x) + 'px';
textVmlElStyle.top = round(y) + 'px';
}
textPathEl.string = encodeHtmlAttribute(text);
// TODO
try {
textPathEl.style.font = font;
}
// Error font format
catch (e) {}
updateFillAndStroke(textVmlEl, 'fill', {
fill: style.textFill,
opacity: style.opacity
}, this);
updateFillAndStroke(textVmlEl, 'stroke', {
stroke: style.textStroke,
opacity: style.opacity,
lineDash: style.lineDash || null // style.lineDash can be `false`.
}, this);
textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
// Attached to root
append(vmlRoot, textVmlEl);
};
var removeRectText = function (vmlRoot) {
remove(vmlRoot, this._textVmlEl);
this._textVmlEl = null;
};
var appendRectText = function (vmlRoot) {
append(vmlRoot, this._textVmlEl);
};
var list = [RectText, Displayable, ZRImage, Path, Text];
// In case Displayable has been mixed in RectText
for (var i = 0; i < list.length; i++) {
var proto = list[i].prototype;
proto.drawRectText = drawRectText;
proto.removeRectText = removeRectText;
proto.appendRectText = appendRectText;
}
Text.prototype.brushVML = function (vmlRoot) {
var style = this.style;
if (style.text != null) {
this.drawRectText(vmlRoot, {
x: style.x || 0, y: style.y || 0,
width: 0, height: 0
}, this.getBoundingRect(), true);
}
else {
this.removeRectText(vmlRoot);
}
};
Text.prototype.onRemove = function (vmlRoot) {
this.removeRectText(vmlRoot);
};
Text.prototype.onAdd = function (vmlRoot) {
this.appendRectText(vmlRoot);
};
} | the_stack |
import { stringify, parse } from "@brillout/json-s";
import { autoLoadEndpointFiles } from "./autoLoadEndpointFiles";
import {
assert,
assertUsage,
getUsageError,
UsageError,
setProjectInfo,
} from "@brillout/assert";
// @ts-ignore
import getUrlProps = require("@brillout/url-props");
export { WildcardServer };
loadTimeStuff();
// Endpoints
type EndpointName = string;
type EndpointArgs = any[];
type EndpointFunction = (...args: EndpointArgs) => EndpointResult;
type Endpoints = Record<EndpointName, EndpointFunction>;
type EndpointResult = any;
type EndpointError = Error | UsageError;
// Context
type ContextObject = Record<string, any>;
export type Context = ContextObject | undefined;
type ContextGetter = () => Promise<Context> | Context;
/** Wildcard Server Configuration */
type Config = {
/** Serve Wildcard API HTTP requests at `/${baseUrl}/*`. Default: `_wildcard_api`. */
baseUrl: string;
/** Whether Wildcard generates HTTP ETag headers. */
disableCache: boolean;
};
type ConfigName = keyof Config;
// Usage Error
type MalformedRequest = {
httpBodyErrorText: string & { _brand?: "HttpBodyErrorText" };
endpointDoesNotExist?: boolean & { _brand?: "endpointDoesNotExist" };
};
type MalformedIntegration = UsageError;
type WrongApiUsage = UsageError;
type ContextError = UsageError | Error;
// HTTP Request
type HttpRequestUrl = string & { _brand?: "HttpRequestUrl" };
const HttpRequestMethod = ["POST", "GET", "post", "get"];
type HttpRequestMethod = "POST" | "GET" | "post" | "get";
type HttpRequestBody = string & { _brand?: "HttpRequestBody" };
export type UniversalAdapterName = "express" | "koa" | "hapi" | undefined;
export type HttpRequestProps = {
url: HttpRequestUrl;
method: HttpRequestMethod;
body?: HttpRequestBody;
};
// HTTP Response
type HttpResponseBody = string & { _brand?: "HttpResponseBody" };
type HttpResponseContentType = string & { _brand?: "HttpResponseContentType" };
type HttpResponseStatusCode = number & { _brand?: "HttpResponseStatusCode" };
type HttpResponseEtag = string & { _brand?: "HttpResponseEtag" };
export type HttpResponseProps = {
body: HttpResponseBody;
contentType: HttpResponseContentType;
statusCode: HttpResponseStatusCode;
etag?: HttpResponseEtag;
};
type MinusContext<EndpointFunction, Context> = EndpointFunction extends (
this: Context,
...rest: infer EndpointArguments
) => infer EndpointReturnType
? (...rest: EndpointArguments) => EndpointReturnType
: never;
export type FrontendType<Endpoints, Context> = {
[EndpointName in keyof Endpoints]: MinusContext<
Endpoints[EndpointName],
Context
>;
};
// Whether to call the endpoint:
// 1. over HTTP (browser-side <-> Node.js communication) or
// 2. directly (communication whithin a single Node.js process, e.g. when doing SSR).
type IsDirectCall = boolean & { _brand?: "IsDirectCall" };
// Parsing & (de-)serialization
type ArgsInUrl = string & { _brand?: "ArgsInUrl" };
type ArgsInHttpBody = string & { _brand?: "ArgsInHttpBody" };
type EndpointArgsSerialized = ArgsInUrl | ArgsInHttpBody;
type IsHumanMode = boolean & { _brand?: "IsHumanMode" };
type RequestInfo = {
endpointName?: EndpointName;
endpointArgs?: EndpointArgs;
isHumanMode: IsHumanMode;
malformedRequest?: MalformedRequest;
malformedIntegration?: MalformedIntegration;
isNotWildcardRequest?: boolean & { _brand?: "IsNotWildcardRequest" };
};
const configDefault: Config = {
disableCache: false,
baseUrl: "/_wildcard_api/",
};
class WildcardServer {
endpoints: Endpoints = getEndpointsProxy();
config: Config = getConfigProxy(configDefault);
/**
* Get the HTTP response of API HTTP requests. Use this if you cannot use the express/koa/hapi middleware.
* @param requestProps.url HTTP request URL
* @param requestProps.method HTTP request method
* @param requestProps.body HTTP request body
* @param context The context object - the endpoint functions' `this`.
* @returns HTTP response
*/
async getApiHttpResponse(
requestProps: HttpRequestProps,
context?: Context | ContextGetter,
/** @ignore */
{
__INTERNAL_universalAdapter,
}: { __INTERNAL_universalAdapter?: UniversalAdapterName } = {}
): Promise<HttpResponseProps | null> {
try {
return await _getApiHttpResponse(
requestProps,
context,
this.endpoints,
this.config,
__INTERNAL_universalAdapter
);
} catch (internalError) {
// There is a bug in the Wildcard source code
return handleInternalError(internalError);
}
}
/** @private */
async __directCall(
endpointName: EndpointName,
endpointArgs: EndpointArgs,
context: Context
) {
return await directCall(
endpointName,
endpointArgs,
context,
this.endpoints
);
}
}
async function _getApiHttpResponse(
requestProps: HttpRequestProps,
context: Context | ContextGetter | undefined,
endpoints: Endpoints,
config: Config,
universalAdapterName: UniversalAdapterName
): Promise<HttpResponseProps | null> {
try {
context = await getContext(context);
} catch (contextError) {
return handleContextError(contextError);
}
assert(context === undefined || context instanceof Object);
const wrongApiUsage = validateApiUsage(requestProps, universalAdapterName);
if (wrongApiUsage) {
return handleWrongApiUsage(wrongApiUsage);
}
const {
endpointName,
endpointArgs,
malformedRequest,
malformedIntegration,
isNotWildcardRequest,
isHumanMode,
}: RequestInfo = parseRequestInfo(
requestProps,
endpoints,
config,
universalAdapterName
);
if (isNotWildcardRequest) {
return null;
}
if (malformedRequest) {
return handleMalformedRequest(malformedRequest);
}
if (malformedIntegration) {
return handleMalformedIntegration(malformedIntegration);
}
if (!endpointName || !endpointArgs) {
assert(false);
// Make TS happy
throw new Error();
}
const { endpointResult, endpointError } = await runEndpoint(
endpointName,
endpointArgs,
context,
false,
endpoints,
universalAdapterName
);
return handleEndpointOutcome(
endpointResult,
endpointError,
isHumanMode,
endpointName,
config
);
}
async function directCall(
endpointName: EndpointName,
endpointArgs: EndpointArgs,
context: Context,
endpoints: Endpoints
) {
assert(endpointName);
assert(endpointArgs.constructor === Array);
if (noEndpoints(endpoints)) {
autoLoadEndpointFiles();
}
assertUsage(
doesEndpointExist(endpointName, endpoints),
getEndpointMissingText(endpointName, endpoints).join(" ")
);
const resultObject = await runEndpoint(
endpointName,
endpointArgs,
context,
true,
endpoints,
undefined
);
const { endpointResult, endpointError } = resultObject;
if (endpointError) {
throw endpointError;
} else {
return endpointResult;
}
}
async function runEndpoint(
endpointName: EndpointName,
endpointArgs: EndpointArgs,
context: Context,
isDirectCall: IsDirectCall,
endpoints: Endpoints,
universalAdapterName: UniversalAdapterName
): Promise<{
endpointResult?: EndpointResult;
endpointError?: EndpointError;
}> {
assert(endpointName);
assert(endpointArgs.constructor === Array);
assert([true, false].includes(isDirectCall));
const endpoint: EndpointFunction = endpoints[endpointName];
assert(endpoint);
assert(endpointIsValid(endpoint));
const contextProxy: ContextObject = createContextProxy(
context,
endpointName,
isDirectCall,
universalAdapterName
);
assert(contextProxy !== undefined);
assert(contextProxy instanceof Object);
let endpointResult: EndpointResult | undefined;
let endpointError: EndpointError | undefined;
try {
endpointResult = await endpoint.apply(contextProxy, endpointArgs);
} catch (err) {
endpointError = err;
}
return { endpointResult, endpointError };
}
function endpointIsValid(endpoint: EndpointFunction) {
return isCallable(endpoint) && !isArrowFunction(endpoint);
}
function validateEndpoint(
obj: Endpoints,
prop: EndpointName,
value: EndpointFunction
) {
const endpointName = prop;
const endpointFunction = value;
assertUsage(
isCallable(endpointFunction),
[
"An endpoint must be a function,",
`but the endpoint \`${endpointName}\` is`,
endpointFunction && endpointFunction.constructor
? `a \`${endpointFunction.constructor.name}\``
: "`" + endpointFunction + "`",
].join(" ")
);
assertUsage(
!isArrowFunction(endpointFunction),
[
"The endpoint function `" + endpointName + "` is an arrow function.",
"Endpoints cannot be defined with arrow functions (`() => {}`),",
"use a plain function (`function(){}`) instead.",
].join(" ")
);
assert(endpointIsValid(endpointFunction));
obj[prop] = value;
return true;
}
function isCallable(thing: unknown) {
return thing instanceof Function || typeof thing === "function";
}
function isArrowFunction(fn: () => unknown) {
// https://stackoverflow.com/questions/28222228/javascript-es6-test-for-arrow-function-built-in-function-regular-function
// https://gist.github.com/brillout/51da4cb90a5034e503bc2617070cfbde
assert(!yes(function () {}));
assert(yes(() => {}));
assert(!yes(async function () {}));
assert(yes(async () => {}));
return yes(fn);
function yes(fn: () => unknown) {
// This (unfortunately...) seems to be the most reliable way.
return typeof fn === "function" && /^[^{]+?=>/.test(fn.toString());
}
}
function isHumanReadableMode(method: HttpRequestMethod) {
const DEBUG_CACHE =
/*/
true
/*/
false;
//*/
assert(method && method.toUpperCase() === method);
if (DEBUG_CACHE) {
return false;
}
if (method === "GET") {
return true;
} else {
return false;
}
}
function makeHumanReadable(
responseProps: HttpResponseProps,
endpointResult: EndpointResult
) {
const text =
responseProps.contentType === "application/json"
? JSON.stringify(
endpointResult && endpointResult instanceof Object
? endpointResult
: JSON.parse(responseProps.body),
null,
2
)
: responseProps.body;
return get_html_response(
`<h1>API Response</h1>
<pre>
${text}
</pre>
<br/>
<br/>
Status code: <b>${responseProps.statusCode}</b>
`
);
}
function get_html_response(htmlBody: HttpResponseBody): HttpResponseProps {
const note =
"Showing HTML because the request's method is <code>GET</code>. Make a <code>POST</code> request to get JSON.";
let body = `<html><body>
<style>
code {
display: inline-block;
padding: 0px 2px 1px 3px;
font-size: 0.98em;
border: 1px solid #d8d8d8;
border-radius: 3px;
background: #f5f5f5;
}
small {
color: #777;
}
</style>
${htmlBody}
`;
body += `
<br/>
<br/>
<small>
${note.split("\n").join("<br/>\n")}
</small>
`;
body += `
</body></html>
`;
const responseProps = {
body,
contentType: "text/html",
statusCode: 200,
};
return responseProps;
}
function getEndpointsProxy(): Endpoints {
const Endpoints: Endpoints = {};
return new Proxy(Endpoints, { set: validateEndpoint });
}
function getConfigProxy(configDefaults: Config): Config {
const configObject: Config = { ...configDefaults };
const configProxy: Config = new Proxy(configObject, { set: validateConfig });
return configProxy;
function validateConfig(
_: Config,
configName: ConfigName,
configValue: unknown
) {
assertUsage(
configName in configDefaults,
[
`Unknown config \`${configName}\`.`,
"Make sure that the config is a `@wildcard-api/server` config",
"and not a `@wildcard-api/client` one.",
].join(" ")
);
configObject[configName] = configValue as never;
return true;
}
}
function createContextProxy(
context: Context,
endpointName: EndpointName,
isDirectCall: IsDirectCall,
universalAdapterName: UniversalAdapterName
): ContextObject {
let contextObject: ContextObject = context || {};
const contextProxy: ContextObject = new Proxy(context || {}, { get, set });
return contextProxy;
function set() {
assertUsage(false, "The context object cannot be modified.");
// Make TS happy
return false;
}
function get(_: ContextObject, contextProp: string) {
assertUsage(
context,
getContextUsageNote(
endpointName,
contextProp,
isDirectCall,
universalAdapterName
)
);
return contextObject[contextProp];
}
}
function getContextUsageNote(
endpointName: EndpointName,
prop: string,
isDirectCall: IsDirectCall,
universalAdapterName: UniversalAdapterName
) {
const common = [
`Your endpoint function \`${endpointName}\` is trying to get \`this.${prop}\`,`,
"but you didn't define any context and",
"as a result `this` is `undefined`.",
`Make sure to provide a context`,
].join(" ");
if (!isDirectCall) {
const contextSource = universalAdapterName
? `with the \`setContext\` function when using the \`wildcard(setContext)\` ${universalAdapterName} middleware.`
: "when using `getApiHttpResponse(requestProps, context)`.";
return [common, contextSource].join(" ");
}
assert(isDirectCall);
assert(universalAdapterName === undefined);
return [
"Wrong usage of the Wildcard client in Node.js.",
common,
`by using \`bind({${prop}})\` when calling your \`${endpointName}\` endpoint in Node.js.`,
"More infos at https://github.com/reframejs/wildcard-api/blob/master/docs/ssr-auth.md",
].join(" ");
}
function parseRequestInfo(
requestProps: HttpRequestProps,
endpoints: Endpoints,
config: Config,
universalAdapterName: UniversalAdapterName
): RequestInfo {
assert(requestProps.url && requestProps.method);
const method: HttpRequestMethod = requestProps.method.toUpperCase() as HttpRequestMethod;
const urlProps = getUrlProps(requestProps.url);
assert(urlProps.pathname.startsWith("/"));
const { pathname } = urlProps;
const { body: requestBody } = requestProps;
const isHumanMode = isHumanReadableMode(method);
if (
!["GET", "POST"].includes(method) ||
!pathname.startsWith(config.baseUrl)
) {
return { isNotWildcardRequest: true, isHumanMode };
}
const {
malformedRequest: malformationError__pathname,
endpointName,
argsInUrl,
} = parsePathname(pathname, config);
if (malformationError__pathname) {
return {
malformedRequest: malformationError__pathname,
endpointName,
isHumanMode,
};
}
if (!doesEndpointExist(endpointName, endpoints)) {
const endpointMissingText = getEndpointMissingText(endpointName, endpoints);
return {
malformedRequest: {
endpointDoesNotExist: true,
httpBodyErrorText: endpointMissingText.join("\n\n"),
},
endpointName,
isHumanMode,
};
}
const {
endpointArgs,
malformedRequest,
malformedIntegration,
} = getEndpointArgs(
argsInUrl,
requestBody,
requestProps,
universalAdapterName
);
if (malformedRequest || malformedIntegration) {
assert(!malformedIntegration || !malformedRequest);
return {
malformedRequest,
malformedIntegration,
endpointName,
isHumanMode,
};
}
assert(endpointArgs && endpointArgs.constructor === Array);
return {
endpointArgs,
endpointName,
isHumanMode,
};
}
function getEndpointArgs(
argsInUrl: ArgsInUrl,
requestBody: HttpRequestBody | undefined,
requestProps: HttpRequestProps,
universalAdapterName: UniversalAdapterName
): {
endpointArgs?: EndpointArgs;
malformedRequest?: MalformedRequest;
malformedIntegration?: MalformedIntegration;
} {
const ARGS_IN_BODY = "args-in-body";
const args_are_in_body = argsInUrl === ARGS_IN_BODY;
let endpointArgs__string: EndpointArgsSerialized;
if (args_are_in_body) {
if (!requestBody) {
const malformedIntegration = getUsageError(
[
universalAdapterName
? `Your ${universalAdapterName} server is not providing the HTTP request body.`
: "Argument `body` missing when calling `getApiHttpResponse()`.",
"You need to provide the HTTP request body when calling an endpoint with arguments serialized to >=2000 characters.",
getBodyUsageNote(requestProps, universalAdapterName),
].join(" ")
);
return {
malformedIntegration,
};
}
const argsInHttpBody: ArgsInHttpBody =
requestBody.constructor === Array
? // Server framework already parsed HTTP Request body with JSON
JSON.stringify(requestBody)
: // Server framework didn't parse HTTP Request body
requestBody;
endpointArgs__string = argsInHttpBody;
} else {
if (!argsInUrl) {
return {
endpointArgs: [],
};
}
endpointArgs__string = argsInUrl;
}
assert(endpointArgs__string);
let endpointArgs: EndpointArgs;
try {
endpointArgs = parse(endpointArgs__string);
} catch (err_) {
const httpBodyErrorText = [
"Malformatted API request.",
"Cannot parse `" + endpointArgs__string + "`.",
].join(" ");
return {
malformedRequest: { httpBodyErrorText },
};
}
if (!endpointArgs || endpointArgs.constructor !== Array) {
const httpBodyErrorText =
"Malformatted API request. The parsed serialized endpoint arguments should be an array.";
return {
malformedRequest: { httpBodyErrorText },
};
}
return { endpointArgs };
}
function parsePathname(pathname: string, config: Config) {
assert(pathname.startsWith(config.baseUrl));
const urlParts = pathname.slice(config.baseUrl.length).split("/");
const isMalformatted =
urlParts.length < 1 || urlParts.length > 2 || !urlParts[0];
const endpointName = urlParts[0];
const argsInUrl: ArgsInUrl = urlParts[1] && decodeURIComponent(urlParts[1]);
/*
const pathname__prettified = isMalformatted
? pathname
: config.baseUrl + endpointName + "/" + argsInUrl;
*/
let malformedRequest: MalformedRequest | undefined;
if (isMalformatted) {
malformedRequest = {
httpBodyErrorText: "Malformatted API URL",
};
}
return {
malformedRequest,
endpointName,
argsInUrl,
};
}
function handleEndpointOutcome(
endpointResult: EndpointResult | undefined,
endpointError: EndpointError | undefined,
isHumanMode: IsHumanMode,
endpointName: EndpointName,
config: Config
): HttpResponseProps {
let responseProps: HttpResponseProps;
if (endpointError) {
responseProps = handleEndpointError(endpointError);
} else {
responseProps = handleEndpointResult(
endpointResult as EndpointResult,
isHumanMode,
endpointName
);
}
assert(responseProps.body.constructor === String);
if (!config.disableCache) {
const computeEtag = require("./computeEtag");
const etag = computeEtag(responseProps.body);
assert(etag);
responseProps.etag = etag;
}
return responseProps;
}
function getEndpointNames(endpoints: Endpoints): EndpointName[] {
return Object.keys(endpoints);
}
function handleInternalError(internalError: Error): HttpResponseProps {
const msg =
"[Wildcard API][Internal Error] Something unexpected happened. Please open a new issue at https://github.com/reframejs/wildcard-api/issues/new and include this error stack. ";
internalError = addMessage(internalError, msg);
console.error(internalError);
return HttpResponse_serverSideError();
}
function addMessage(err: Error, msg: string): Error {
if (!err) {
err = new Error();
}
if (!err.message || err.message.constructor !== String) {
err.message = "";
}
const prefix = "Error: ";
if (err.message.startsWith(prefix)) {
err.message = prefix + msg + err.message.slice(prefix.length);
} else {
err.message = msg + err.message;
}
return err;
}
function handleEndpointError(endpointError: EndpointError): HttpResponseProps {
console.error(endpointError);
return HttpResponse_serverSideError();
}
function handleContextError(contextError: ContextError): HttpResponseProps {
console.error(contextError);
return HttpResponse_serverSideError();
}
function handleWrongApiUsage(wrongApiUsage: WrongApiUsage): HttpResponseProps {
console.error(wrongApiUsage);
return HttpResponse_serverSideError();
}
function handleMalformedIntegration(
malformedIntegration: MalformedIntegration
): HttpResponseProps {
console.error(malformedIntegration);
return HttpResponse_serverSideError();
}
function HttpResponse_serverSideError(): HttpResponseProps {
return {
body: "Internal Server Error",
statusCode: 500,
contentType: "text/plain",
};
}
function handleMalformedRequest(
malformedRequest: MalformedRequest
): HttpResponseProps {
// We do NOT print any error on the server-side
// We only print the malformation error on the browser-side
// Because it's not a server-side bug but a browser-side bug
const statusCode = malformedRequest.endpointDoesNotExist ? 404 : 400;
const { httpBodyErrorText } = malformedRequest;
return HttpResponse_browserSideError(statusCode, httpBodyErrorText);
}
function HttpResponse_browserSideError(
errorCode: number,
httpBodyErrorText: string
): HttpResponseProps {
return {
statusCode: errorCode,
body: httpBodyErrorText,
contentType: "text/plain",
};
}
function handleEndpointResult(
endpointResult: EndpointResult,
isHumanMode: IsHumanMode,
endpointName: EndpointName
): HttpResponseProps {
let body: HttpResponseBody | undefined;
let endpointError: EndpointError | undefined;
try {
const ret: string = stringify(endpointResult);
body = ret;
} catch (stringifyError) {
endpointError = getUsageError(
[
`Couldn't serialize value returned by endpoint \`${endpointName}\`.`,
"Make sure the returned values",
"are only of the following types:",
"`Object`, `string`, `number`, `Date`, `null`, `undefined`, `Inifinity`, `NaN`, `RegExp`.",
].join(" ")
);
}
if (endpointError) {
return handleEndpointError(endpointError);
}
if (body === undefined) {
assert(false);
// Make TS happy
throw new Error();
}
assert(body.constructor === String);
const responseProps: HttpResponseProps = {
statusCode: 200,
contentType: "application/json",
body,
};
if (isHumanMode) {
return makeHumanReadable(responseProps, endpointResult);
} else {
return responseProps;
}
}
function validateApiUsage(
requestProps: HttpRequestProps,
universalAdapterName: UniversalAdapterName
) {
try {
validate();
} catch (wrongApiUsage) {
return wrongApiUsage;
}
return;
function validate() {
assert(
(requestProps && requestProps.url && requestProps.method) ||
!universalAdapterName
);
const missArg = (args: string[]) =>
`Missing argument${args.length === 1 ? "" : "s"} ${args
.map((s) => "`" + s + "`")
.join(" and ")} while calling \`getApiHttpResponse()\`.`;
const missingArguments = [];
if (!requestProps?.url) missingArguments.push("url");
if (!requestProps?.method) missingArguments.push("method");
assertUsage(missingArguments.length === 0, missArg(missingArguments));
}
}
function getBodyUsageNote(
requestProps: HttpRequestProps,
universalAdapterName: UniversalAdapterName
) {
const expressNote =
"make sure to parse the body, for Express v4.16 and above: `app.use(express.json())`.";
const koaNote =
"make sure to parse the body, for example: `app.use(require('koa-bodyparser')())`.";
if (universalAdapterName === "express") {
return "You seem to be using Express; " + expressNote;
}
if (universalAdapterName === "koa") {
return "You seem to be using Koa; " + expressNote;
}
if (universalAdapterName === "hapi") {
assert("body" in requestProps);
}
return [
"If you are using Express: " + expressNote,
"If you are using Hapi: the HTTP request body is available at `request.payload`.",
"If you are using Koa: " + koaNote,
].join(" ");
}
function doesEndpointExist(endpointName: EndpointName, endpoints: Endpoints) {
const endpoint: EndpointFunction | undefined = endpoints[endpointName];
return !!endpoint;
}
function noEndpoints(endpoints: Endpoints) {
const endpointNames = getEndpointNames(endpoints);
return endpointNames.length === 0;
}
function getEndpointMissingText(
endpointName: EndpointName,
endpoints: Endpoints
): string[] {
const endpointMissingText = [
"Endpoint `" + endpointName + "` doesn't exist.",
];
if (noEndpoints(endpoints)) {
endpointMissingText.push("You didn't define any endpoints.");
}
endpointMissingText.push(
"Make sure that the file that defines `" +
endpointName +
"` is named `endpoints.js` or `*.endpoints.js`: Wildcard automatically loads any file with such a name.",
"Alternatively, you can manually load your endpoint files: `require('./path/to/file-that-defines-" +
endpointName +
".js')`."
);
return endpointMissingText;
}
function assertNodejs() {
const isNodejs =
typeof "process" !== "undefined" &&
process &&
process.versions &&
process.versions.node;
assertUsage(
isNodejs,
[
"You are loading the module `@wildcard-api/server` in the browser.",
"The module `@wildcard-api/server` is meant for your Node.js server. Load `@wildcard-api/client` instead.",
].join(" ")
);
}
async function getContext(context: Context | ContextGetter): Promise<Context> {
if (context === undefined) {
return undefined;
}
const isContextFunction = isCallable(context);
const contextFunctionName = isContextFunction
? getFunctionName(context as ContextGetter)
: null;
if (isContextFunction) {
context = await (context as ContextGetter)();
}
assertContext(context, isContextFunction, contextFunctionName);
assert(context && context instanceof Object);
return context as Context;
}
function assertContext(
context: Context,
isContextFunction: boolean,
contextFunctionName: string | null
) {
if (isContextFunction) {
const errorMessageBegin = [
"Your context function",
...(!contextFunctionName ? [] : ["`" + contextFunctionName + "`"]),
"should",
].join(" ");
assertUsage(
context !== undefined && context !== null,
[
errorMessageBegin,
"not return `" + context + "`.",
"If there is no context, then return the empty object `{}`.",
].join(" ")
);
assertUsage(
context instanceof Object,
[errorMessageBegin, "return a `instanceof Object`."].join(" ")
);
}
assertUsage(
context && context instanceof Object,
[
"The context cannot be `" + context + "`.",
"The context should be a `instanceof Object`.",
"If there is no context then use the empty object `{}`.",
].join(" ")
);
}
function getFunctionName(fn: () => unknown): string {
let { name } = fn;
if (!name) {
return name;
}
const PREFIX = "bound ";
if (name.startsWith(PREFIX)) {
return name.slice(PREFIX.length);
}
return name;
}
function loadTimeStuff() {
// Some infos for `assertUsage` and `assert`
setProjectInfo({
projectName: "Wildcard API",
projectGithub: "https://github.com/reframejs/wildcard-api",
});
// The Wildcard server only works with Node.js
assertNodejs();
} | the_stack |
import {
dispatch,
getCodeRunnerService,
getVmControllerService,
getZ80CompilerService,
} from "@core/service-registry";
import {
executeCommand,
registerCommand,
} from "@abstractions/command-registry";
import {
sendFromIdeToEmu, sendFromMainToEmu,
} from "@core/messaging/message-sending";
import {
CompileFileResponse,
SupportsCodeInjectionResponse,
} from "@core/messaging/message-types";
import {
emuShowFrameInfoAction,
emuShowKeyboardAction,
emuShowStatusbarAction as emuShowStatusBarAction,
emuShowToolbarAction,
} from "@state/emu-view-options-reducer";
import { ideShowAction } from "@state/show-ide-reducer";
import {
IKliveCommand,
KliveCommandContext,
} from "@abstractions/command-definitions";
/**
* Names of core Klive commands
*/
type CoreKliveCommand =
| "showToolbar"
| "hideToolbar"
| "showStatusBar"
| "hideStatusBar"
| "showFrameInfo"
| "hideFrameInfo"
| "showKeyboard"
| "hideKeyboard"
| "showIde"
| "hideIde"
| "startVm"
| "pauseVm"
| "stopVm"
| "debugVm"
| "stepIntoVm"
| "stepOverVm"
| "stepOutVm"
| "compileCode"
| "injectCodeIntoVm"
| "injectAndStartVm"
| "injectAndDebugVm";
/**
* Registers common Klive commands that can be executed from any processes
*/
export function registerCommonCommands(): void {
registerCommand(showToolbarCommand);
registerCommand(hideToolbarCommand);
registerCommand(showStatusBarCommand);
registerCommand(hideStatusBarCommand);
registerCommand(showFrameInfoCommand);
registerCommand(hideFrameInfoCommand);
registerCommand(showKeyboardCommand);
registerCommand(hideKeyboardCommand);
registerCommand(showIdeCommand);
registerCommand(hideIdeCommand);
registerCommand(startVmCommand);
registerCommand(pauseVmCommand);
registerCommand(stopVmCommand);
registerCommand(debugVmCommand);
registerCommand(stepIntoVmCommand);
registerCommand(stepOverVmCommand);
registerCommand(stepOutVmCommand);
registerCommand(compileCodeCommand);
registerCommand(injectCodeIntoVmCommand);
registerCommand(injectAndStartVmCommand);
registerCommand(injectAndDebugVmCommand);
}
/**
* Executes the specified core Klive command
* @param id Klive command to execute
*/
export async function executeKliveCommand(
id: CoreKliveCommand,
additionalContext?: any
): Promise<void> {
await executeCommand(`klive.${id}`, additionalContext);
}
/**
* This command shows the Emulator toolbar
*/
const showToolbarCommand: IKliveCommand = {
commandId: "klive.showToolbar",
execute: async () => {
dispatch(emuShowToolbarAction(true));
},
queryState: async (context) => {
context.commandInfo.enabled = !(
context.appState?.emuViewOptions?.showStatusBar ?? false
);
},
};
/**
* This command shows the Emulator toolbar
*/
const hideToolbarCommand: IKliveCommand = {
commandId: "klive.hideToolbar",
execute: async () => {
dispatch(emuShowToolbarAction(false));
},
queryState: async (context) => {
context.commandInfo.enabled =
context.appState?.emuViewOptions?.showStatusBar ?? false;
},
};
/**
* This command shows the application status bar
*/
const showStatusBarCommand: IKliveCommand = {
commandId: "klive.showStatusBar",
execute: async () => {
dispatch(emuShowStatusBarAction(true));
},
};
/**
* This command hides the application status bar
*/
const hideStatusBarCommand: IKliveCommand = {
commandId: "klive.hideStatusBar",
execute: async () => {
dispatch(emuShowStatusBarAction(false));
},
};
/**
* This command shows the frame information in the Emu status bar
*/
const showFrameInfoCommand: IKliveCommand = {
commandId: "klive.showFrameInfo",
execute: async () => {
dispatch(emuShowFrameInfoAction(true));
},
};
/**
* This command hides the frame information in the Emu status bar
*/
const hideFrameInfoCommand: IKliveCommand = {
commandId: "klive.hideFrameInfo",
execute: async () => {
dispatch(emuShowFrameInfoAction(false));
},
};
/**
* This command shows the keyboard
*/
const showKeyboardCommand: IKliveCommand = {
commandId: "klive.showKeyboard",
execute: async () => {
dispatch(emuShowKeyboardAction(true));
},
};
/**
* This command hides the keyboard
*/
const hideKeyboardCommand: IKliveCommand = {
commandId: "klive.hideKeyboard",
execute: async () => {
dispatch(emuShowKeyboardAction(false));
},
};
/**
* This command shows the Ide window
*/
const showIdeCommand: IKliveCommand = {
commandId: "klive.showIde",
execute: async () => {
dispatch(ideShowAction(true));
},
};
/**
* This command hides the Ide window
*/
const hideIdeCommand: IKliveCommand = {
commandId: "klive.hideIde",
execute: async () => {
dispatch(ideShowAction(false));
},
};
/**
* This command starts the virtual machine
*/
const startVmCommand: IKliveCommand = {
commandId: "klive.startVm",
title: "Start",
icon: "play",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "StartVm" });
break;
case "emu":
await getVmControllerService().start();
break;
case "ide":
await sendFromIdeToEmu({ type: "StartVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState !== "running";
},
};
/**
* This command pauses the virtual machine
*/
const pauseVmCommand: IKliveCommand = {
commandId: "klive.pauseVm",
title: "Pause",
icon: "pause",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "PauseVm" });
break;
case "emu":
await getVmControllerService().pause();
break;
case "ide":
await sendFromIdeToEmu({ type: "PauseVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState === "running";
},
};
/**
* This command stops the virtual machine
*/
const stopVmCommand: IKliveCommand = {
commandId: "klive.stopVm",
title: "Stop",
icon: "stop",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "StopVm" });
break;
case "emu":
await getVmControllerService().stop();
break;
case "ide":
await sendFromIdeToEmu({ type: "StopVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled =
context.executionState === "running" ||
context.executionState === "paused";
},
};
/**
* This command stops the virtual machine
*/
const debugVmCommand: IKliveCommand = {
commandId: "klive.debugVm",
title: "Start with debugging",
icon: "debug",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "DebugVm" });
break;
case "emu":
await getVmControllerService().startDebug();
break;
case "ide":
await sendFromIdeToEmu({ type: "DebugVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState !== "running";
},
};
/**
* This command executes a step-into operation
*/
const stepIntoVmCommand: IKliveCommand = {
commandId: "klive.stepIntoVm",
title: "Step into code",
icon: "step-into",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "StepIntoVm" });
break;
case "emu":
await getVmControllerService().stepInto();
break;
case "ide":
await sendFromIdeToEmu({ type: "StepIntoVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState === "paused";
},
};
/**
* This command executes a step-over operation
*/
const stepOverVmCommand: IKliveCommand = {
commandId: "klive.stepOverVm",
title: "Step over code",
icon: "step-over",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "StepOverVm" });
break;
case "emu":
await getVmControllerService().stepOver();
break;
case "ide":
await sendFromIdeToEmu({ type: "StepOverVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState === "paused";
},
};
/**
* This command executes a step-out operation
*/
const stepOutVmCommand: IKliveCommand = {
commandId: "klive.stepOutVm",
title: "Step out code",
icon: "step-out",
execute: async (context) => {
switch (context.process) {
case "main":
await sendFromMainToEmu({ type: "StepOutVm" });
break;
case "emu":
await getVmControllerService().stepOut();
break;
case "ide":
await sendFromIdeToEmu({ type: "StepOutVm" });
break;
}
},
queryState: async (context) => {
context.commandInfo.enabled = context.executionState === "paused";
},
};
/**
* This command injects code into the virtual machine
*/
const compileCodeCommand: IKliveCommand = {
commandId: "klive.compileCode",
title: "Compiles the code",
icon: "combine",
execute: async (context) => {
if (!context.resource) {
return;
}
switch (context.process) {
case "main":
await getZ80CompilerService().compileFile(context.resource);
break;
case "emu":
signInvalidContext(context);
break;
case "ide":
await sendFromIdeToEmu<CompileFileResponse>({
type: "CompileFile",
filename: context.resource,
});
break;
}
},
};
/**
* This command injects code into the virtual machine
*/
const injectCodeIntoVmCommand: IKliveCommand = {
commandId: "klive.injectCodeIntoVm",
title: "Injects code into the virtual machine",
icon: "inject",
execute: async (context) => {
switch (context.process) {
case "main":
case "emu":
signInvalidContext(context);
break;
case "ide":
await getCodeRunnerService().manageCodeInjection(
context.resource,
"inject"
);
}
},
queryState: async (context) => await queryInjectionCommandState(context),
};
/**
* This command injects code into the virtual machine and starts it
*/
const injectAndStartVmCommand: IKliveCommand = {
commandId: "klive.injectAndStartVm",
title: "Injects code and starts",
icon: "play",
execute: async (context) => {
switch (context.process) {
case "main":
case "emu":
signInvalidContext(context);
break;
case "ide":
await getCodeRunnerService().manageCodeInjection(
context.resource,
"run"
);
}
},
queryState: async (context) => await queryInjectionCommandState(context),
};
/**
* This command injects code into the virtual machine and starts it
*/
const injectAndDebugVmCommand: IKliveCommand = {
commandId: "klive.injectAndDebugVm",
title: "Injects code and starts with debugging",
icon: "debug",
execute: async (context) => {
switch (context.process) {
case "main":
case "emu":
signInvalidContext(context);
break;
case "ide":
await getCodeRunnerService().manageCodeInjection(
context.resource,
"debug"
);
}
},
queryState: async (context) => await queryInjectionCommandState(context),
};
/**
* Signs the specified context as invalid for executing a command
* @param context Invalid context
*/
function signInvalidContext(context: KliveCommandContext) {
throw new Error(
`'${context.commandInfo.commandId}' cannot be executed it the ${context.process} process`
);
}
/**
* Queries the state of a code injection related command
* @param context
*/
async function queryInjectionCommandState(
context: KliveCommandContext
): Promise<void> {
let enabled = false;
if (context.process === "ide") {
const response = await sendFromIdeToEmu<SupportsCodeInjectionResponse>({
type: "SupportsCodeInjection",
});
enabled = response.supports;
}
context.commandInfo.enabled = enabled;
} | the_stack |
import * as assert from "assert";
import { testContext, disposeTestDocumentStore } from "../Utils/TestUtil";
import {
IDocumentStore,
} from "../../src";
import { User } from "../Assets/Entities";
describe("WhatChangedTest", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("whatChangedNewField", async () => {
{
const newSession = store.openSession();
const basicName = new BasicName();
basicName.name = "Toli";
await newSession.store(basicName, "users/1");
assert.strictEqual(Object.keys(newSession.advanced.whatChanged()).length, 1);
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const user = await newSession.load<User>("users/1");
user.age = 5;
const changes = await newSession.advanced.whatChanged();
assert.strictEqual(changes["users/1"].length, 1);
assert.strictEqual(changes["users/1"][0].change, "NewField");
await newSession.saveChanges();
}
});
it("whatChangedRemovedField", async () => {
{
const newSession = store.openSession();
const nameAndAge = new NameAndAge();
nameAndAge.age = 5;
nameAndAge.name = "Toli";
await newSession.store(nameAndAge, "users/1");
const whatChanged = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(whatChanged).length, 1);
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const ageOnly = await newSession.load<BasicAge>("users/1", BasicAge);
// since in JS we do Object.assign() on an empty object when loading
// 'name' prop is still there
//
// to actually remove a field we can use delete though
delete ageOnly["name"];
const changes = newSession.advanced.whatChanged()["users/1"];
assert.strictEqual(changes.length, 1);
assert.strictEqual(changes[0].change, "RemovedField");
await newSession.saveChanges();
}
});
it("whatChangedChangeField", async () => {
{
const newSession = store.openSession();
const basicAge = new BasicAge();
basicAge.age = 5;
await newSession.store(basicAge, "users/1");
assert.strictEqual(Object.keys(newSession.advanced.whatChanged()).length, 1);
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const user = await newSession.load<Int>("users/1", Int);
// JS won't know how to load User into Int class,
// we can do that manually though
user.number = user["age"];
delete user["age"];
const changes = newSession.advanced.whatChanged();
assert.strictEqual(changes["users/1"].length, 2);
assert.strictEqual(changes["users/1"][0].change, "RemovedField");
assert.strictEqual(changes["users/1"][1].change, "NewField");
await newSession.saveChanges();
}
});
it("whatChangedArrayValueChanged", async () => {
{
const newSession = store.openSession();
const arr = new Arr();
arr.array = ["a", 1, "b"];
await newSession.store(arr, "users/1");
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 1);
assert.strictEqual(changes["users/1"].length, 1);
assert.strictEqual(changes["users/1"][0].change, "DocumentAdded");
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const arr = await newSession.load<Arr>("users/1");
arr.array = ["a", 2, "c"];
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 1);
assert.strictEqual(changes["users/1"].length, 2);
assert.strictEqual(changes["users/1"][0].change, "ArrayValueChanged");
assert.strictEqual(changes["users/1"][0].fieldOldValue.toString(), "1");
assert.strictEqual(changes["users/1"][0].fieldNewValue, 2);
assert.strictEqual(changes["users/1"][1].change, "ArrayValueChanged");
assert.strictEqual(changes["users/1"][1].fieldOldValue, "b");
assert.strictEqual(changes["users/1"][1].fieldNewValue, "c");
}
});
it("whatChangedArrayValueAdded", async () => {
{
const newSession = store.openSession();
const arr = new Arr();
arr.array = ["a", 1, "b"];
await newSession.store(arr, "arr/1");
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const arr = await newSession.load<Arr>("arr/1", Arr);
arr.array = ["a", 1, "b", "c", 2];
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 1);
assert.strictEqual(changes["arr/1"].length, 2);
assert.strictEqual(changes["arr/1"][0].change, "ArrayValueAdded");
assert.strictEqual(changes["arr/1"][0].fieldNewValue, "c");
assert.ok(!changes["arr/1"][0].fieldOldValue);
assert.strictEqual(changes["arr/1"][1].change, "ArrayValueAdded");
assert.strictEqual(changes["arr/1"][1].fieldNewValue, 2);
assert.ok(!changes["arr/1"][1].fieldOldValue);
}
});
it("whatChangedArrayValueRemoved", async () => {
{
const newSession = store.openSession();
const arr = new Arr();
arr.array = ["a", 1, "b"];
await newSession.store(arr, "arr/1");
await newSession.saveChanges();
}
{
const newSession = store.openSession();
const arr = await newSession.load<Arr>("arr/1", Arr);
arr.array = ["a"];
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 1);
assert.strictEqual(changes["arr/1"].length, 2);
assert.strictEqual(changes["arr/1"][0].change, "ArrayValueRemoved");
assert.strictEqual(changes["arr/1"][0].fieldOldValue, 1);
assert.ok(!changes["arr/1"][0].fieldNewValue);
assert.strictEqual(changes["arr/1"][1].change, "ArrayValueRemoved");
assert.strictEqual(changes["arr/1"][1].fieldOldValue, "b");
assert.ok(!changes["arr/1"][1].fieldNewValue);
}
});
it("RavenDB-8169", async () => {
//Test that when old and new values are of different type
//but have the same value, we consider them unchanged
{
const newSession = store.openSession();
const anInt = new Int();
anInt.number = 1;
await newSession.store(anInt, "num/1");
await newSession.saveChanges();
const aDouble = new Double();
aDouble.number = 2.0;
await newSession.store(aDouble, "num/2");
await newSession.saveChanges();
}
{
const newSession = store.openSession();
await newSession.load<Double>("num/1", Double);
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 0);
}
{
const newSession = store.openSession();
await newSession.load<Int>("num/2", Int);
const changes = newSession.advanced.whatChanged();
assert.strictEqual(Object.keys(changes).length, 0);
}
});
it("whatChangedShouldBeIdempotentOperation", async () => {
//RavenDB-9150
{
const session = store.openSession();
let user1 = new User();
user1.name = "user1";
let user2 = new User();
user2.name = "user2";
user2.age = 1;
const user3 = new User();
user3.name = "user3";
user3.age = 1;
await session.store(user1, "users/1");
await session.store(user2, "users/2");
await session.store(user3, "users/3");
assert.strictEqual(Object.keys(session.advanced.whatChanged()).length, 3);
await session.saveChanges();
user1 = await session.load<User>("users/1", User);
user2 = await session.load<User>("users/2", User);
user1.age = 10;
await session.delete(user2);
assert.strictEqual(Object.keys(session.advanced.whatChanged()).length, 2);
assert.strictEqual(Object.keys(session.advanced.whatChanged()).length, 2);
}
});
it("has changes", async () => {
{
const session = store.openSession();
const user1 = new User();
user1.name = "user1";
const user2 = new User();
user2.name = "user2";
user2.age = 1;
await session.store(user1, "users/1");
await session.store(user2, "users/2");
await session.saveChanges();
}
{
const session = store.openSession();
assert.ok(!session.advanced.hasChanges());
const u1 = await session.load<User>("users/1", User);
const u2 = await session.load<User>("users/2", User);
assert.ok(!session.advanced.hasChanged(u1));
assert.ok(!session.advanced.hasChanged(u2));
u1.name = "new name";
assert.ok(session.advanced.hasChanged(u1));
assert.ok(!session.advanced.hasChanged(u2));
assert.ok(session.advanced.hasChanges());
}
});
});
class BasicName {
public name: string;
}
class NameAndAge {
public name: string;
public age: number;
}
class BasicAge {
public age: number;
}
class Int {
public number: number;
}
class Double {
public number: number;
}
class Arr {
public array: any[];
} | the_stack |
import {
InputNode,
InputRelation,
OutputNode,
OutputRelation,
NodeId,
InternalUpGradeNode,
InternalUpGradeLink,
DAGAIUConfig,
} from './types';
import BaseDAG from './BaseDAG';
import { maxBy } from '../../Utils/utils';
import { Point } from '../../Utils/graph';
const defaultDAGAIUConfig: DAGAIUConfig = {
isTransverse: false,
defaultNodeWidth: 180,
defaultNodeHeight: 50,
nodeAndNodeSpace: 40,
paddingLineSpace: 30,
levelSpace: 80,
margin: {
left: 180,
right: 180,
top: 50,
bottom: 50
},
padding: 200,
linkType: 'polyline',
DiyLine: () => { },
_isLinkMerge: true,
};
const emptyDAG = {
nodes: [] as any,
links: [] as any,
pos: {
width: 0,
height: 0
}
};
class DAGAIU<Node extends InputNode<Relation>, Relation extends InputRelation> {
/** 默认配置项 */
private config: DAGAIUConfig = defaultDAGAIUConfig;
constructor(DAGConfig: DAGAIUConfig = {}) {
this.config = {
...this.config,
// 横向布局时要尽量减小虚拟节点的高度
defaultVirtualNodeWidth: DAGConfig.isTransverse ? 0.1 : 180,
...DAGConfig,
};
}
// 数据预处理,将节点与边信息提取出来,
_preprocess(data: Node[]) {
// 节点去重
const nodeMap = new Map<NodeId, InternalUpGradeNode<Node, Relation>>();
// 边去重
const linkMap = new Map<NodeId, InternalUpGradeLink<Node, Relation>>();
// 去重节点列表
const nodes: InternalUpGradeNode<Node, Relation>[] = [];
// 去重边列表,不带自环
const links: InternalUpGradeLink<Node, Relation>[] = [];
// 自环边
const selfLinks: InternalUpGradeLink<Node, Relation>[] = [];
data.forEach(node => {
// 去除重复节点
if (node && node.id && !nodeMap.has(node.id)) {
const newNode: InternalUpGradeNode<Node, Relation> = {
id: node.id,
sourceLinks: [],
targetLinks: [],
type: 'real',
nodeWidth: this.config.isTransverse
? node.nodeHeight || this.config.defaultNodeHeight
: node.nodeWidth || this.config.defaultNodeWidth,
nodeHeight: this.config.isTransverse
? node.nodeWidth || this.config.defaultNodeWidth
: node.nodeHeight || this.config.defaultNodeHeight,
originInfo: node
};
const key = this.config.getNodeKey ? this.config.getNodeKey(node) : node.id;
nodeMap.set(key, newNode);
nodes.push(newNode);
}
});
data.forEach(node => {
if (node && node.id) {
[...node.downRelations, ...node.upRelations].forEach(relation => {
const { sourceId, targetId } = relation;
const key = this.config.getLinkKey ? this.config.getLinkKey(relation) : `${sourceId}-${targetId}`;
const sourceNode = nodeMap.get(sourceId);
const targetNode = nodeMap.get(targetId);
// 先确保节点均存在,连线不重复
if (sourceNode && targetNode && !linkMap.has(key)) {
const newRelation: InternalUpGradeLink<Node, Relation> = {
source: sourceNode,
target: targetNode,
originInfo: relation,
isReverse: false,
};
// 处理自环
if (sourceId === targetId) {
linkMap.set(key, newRelation);
selfLinks.push(newRelation);
} else {
linkMap.set(key, newRelation);
links.push(newRelation);
sourceNode.sourceLinks.push(newRelation);
targetNode.targetLinks.push(newRelation);
}
}
});
}
});
return {
nodes,
links,
selfLinks
};
}
_getDAG(data: Node[]): BaseDAG<Node, Relation> {
const { nodes, links, selfLinks } = this._preprocess(data);
const {
defaultVirtualNodeWidth,
nodeAndNodeSpace,
paddingLineSpace,
levelSpace,
linkType,
DiyLine,
_isLinkMerge,
} = this.config;
const dag = new BaseDAG<Node, Relation>({
nodes,
links,
selfLinks,
config: {
defaultVirtualNodeWidth,
nodeAndNodeSpace,
paddingLineSpace,
levelSpace,
linkType,
DiyLine,
_isLinkMerge,
}
});
return dag;
}
/**
* 单个 DAG
* @param data
*/
getSingleDAG(
data: Node[]
): {
nodes: OutputNode<Node>[];
links: OutputRelation<Relation>[];
pos: { width: number; height: number };
} {
if (!data || !data.length) {
return emptyDAG;
}
// 单图横向布局,本质为逆转竖向布局
if (this.config.isTransverse) {
const ans = this._getDAG(data)
.run()
.getOutput(this.config.margin.bottom, this.config.margin.left);
const width = ans.pos.width + this.config.margin.top + this.config.margin.bottom;
const height = ans.pos.height + this.config.margin.left + this.config.margin.right;
return {
nodes: ans.nodes.map((node) => {
return {
...node,
nodeWidth: node.nodeHeight,
nodeHeight: node.nodeWidth,
view: {
x: node.view.y,
y: node.view.x,
}
};
}),
links: ans.links.map(link => {
return {
...link,
pathPoint: link.path,
path: `${link.path
.map((point, index) => {
if (index === 0) return `M${point.y},${point.x}`;
return `L${point.y},${point.x}`;
})
.join(' ')}`
};
}),
pos: {
width: height,
height: width,
}
};
}
const ans = this._getDAG(data)
.run()
.getOutput(this.config.margin.left, this.config.margin.top);
return {
...ans,
links: ans.links.map(link => {
return {
...link,
pathPoint: link.path,
path: `${link.path
.map((point, index) => {
if (index === 0) return `M${point.x},${point.y}`;
return `L${point.x},${point.y}`;
})
.join(' ')}`
};
}),
pos: {
width:
ans.pos.width + this.config.margin.left + this.config.margin.right,
height:
ans.pos.height + this.config.margin.top + this.config.margin.bottom
}
};
}
/**
* 多个DAG,可兼容单个 DAG
* @param data
*/
getMultiDAG(
data: Node[]
): {
nodes: OutputNode<Node>[];
links: OutputRelation<Relation>[];
pos: { width: number; height: number };
} {
if (!data || !data.length) {
return emptyDAG;
}
const nodesList = this._separateNodes(data);
// 单个 DAG
if (nodesList.length === 1) {
return this.getSingleDAG(nodesList[0]);
} else {
const widthList: number[] = [];
const heightList: number[] = [];
const dagInstanceList = nodesList.map(nodes => {
const dag = this._getDAG(nodes).run();
const { width, height } = dag.getSize();
widthList.push(width);
heightList.push(height);
return dag;
});
if (this.config.isTransverse) {
const height = maxBy(heightList, width => {
return width;
}) + this.config.margin.left + this.config.margin.right;
const width = widthList.reduce((pre, width, index) => {
if (index === 0) {
return pre + width;
}
return pre + width + this.config.padding;
}, 0) +
this.config.margin.top +
this.config.margin.bottom;
const result = dagInstanceList.reduce(
(pre, dag) => {
const { addWidth } = pre;
const { height: curheight } = dag.getSize();
const ans = dag.getOutput(addWidth, (height - curheight) / 2);
return {
nodes: [...pre.nodes, ...ans.nodes],
links: [...pre.links, ...ans.links],
addWidth: addWidth + this.config.padding + ans.pos.width
};
},
{
nodes: [],
links: [],
addWidth: this.config.margin.top
});
return {
nodes: result.nodes.map((node) => {
return {
...node,
nodeWidth: node.nodeHeight,
nodeHeight: node.nodeWidth,
view: {
x: node.view.y,
y: node.view.x,
}
};
}),
links: result.links.map(link => {
return {
...link,
pathPoint: link.path,
path: `${link.path
.map((point: Point, index: number) => {
if (index === 0) return `M${point.y},${point.x}`;
return `L${point.y},${point.x}`;
})
.join(' ')}`
};
}),
pos: {
width: height,
height: width
}
};
}
const height =
maxBy(heightList, height => {
return height;
}) +
this.config.margin.top +
this.config.margin.bottom;
const width =
widthList.reduce((pre, width, index) => {
if (index === 0) {
return pre + width;
}
return pre + width + this.config.padding;
}, 0) +
this.config.margin.left +
this.config.margin.right;
const result = dagInstanceList.reduce(
(pre, dag, index) => {
const { addWidth } = pre;
const { height: curheight } = dag.getSize();
const ans = dag.getOutput(addWidth, (height - curheight) / 2);
return {
nodes: [...pre.nodes, ...ans.nodes],
links: [...pre.links, ...ans.links],
addWidth: addWidth + this.config.padding + ans.pos.width
};
},
{
nodes: [],
links: [],
addWidth: this.config.margin.left
}
);
return {
nodes: result.nodes,
links: result.links.map(link => {
return {
...link,
pathPoint: link.path,
path: `${link.path
.map((point: Point, index: number) => {
if (index === 0) return `M${point.x},${point.y}`;
return `L${point.x},${point.y}`;
})
.join(' ')}`
};
}),
pos: {
width,
height
}
};
}
}
dfs(
node: Node,
result: Node[],
queueId: number,
nodeMarkMap: Map<NodeId, { node: Node; queueId: number }>
) {
/** 下游节点 */
[...node.upRelations, ...node.downRelations].forEach(link => {
const nodeId = link.targetId !== node.id ? link.targetId : link.sourceId;
if (nodeMarkMap.has(nodeId)) {
if (nodeMarkMap.get(nodeId).queueId === -1) {
const targetNode = nodeMarkMap.get(nodeId).node;
nodeMarkMap.set(nodeId, {
node: targetNode,
queueId
});
result.push(targetNode);
this.dfs(targetNode, result, queueId, nodeMarkMap);
} else {
/** 表示重复遍历 */
// if (nodeMarkMap.get(nodeId).queueId === queueId) { }
if (nodeMarkMap.get(nodeId).queueId !== queueId) {
throw new Error(`图数据异常, ${nodeId},${node.id}`);
}
}
}
});
}
/**
* 将 nodes 进行分离
* @param data
*/
_separateNodes(data: Node[]): Node[][] {
const nodeMarkMap = new Map<
NodeId,
{
node: Node;
queueId: number;
}
>();
// 初始化 nodeMarkMap
data.forEach(node => {
if (!nodeMarkMap.has(node.id)) {
nodeMarkMap.set(node.id, {
node,
queueId: -1
});
}
});
const result = [] as Node[][];
let index = 0;
data.forEach(node => {
if (nodeMarkMap.get(node.id).queueId === -1) {
result[index] = [];
result[index].push(node);
const targetNode = nodeMarkMap.get(node.id).node;
nodeMarkMap.set(node.id, {
node: targetNode,
queueId: index
});
this.dfs(node, result[index], index, nodeMarkMap);
index++;
}
});
return result;
}
}
export default DAGAIU; | the_stack |
import { StateIndex } from "./state-index";
import { Grammar } from "../../grammar/grammar";
import { State, isCompleted, isActive, getActiveCategory } from "./state";
import { NonTerminal, Terminal, isNonTerminal } from "../../grammar/category";
import { Semiring } from "semiring";
import { getOrCreateSet, getOrCreateMap } from "../../util";
import { isUnitProduction, Rule, invalidDotPosition } from "../../grammar/rule";
import { ViterbiScore } from "./viterbi-score";
import { StateToObjectMap } from "./state-to-object-map";
export class Chart<T, S> {
readonly grammar: Grammar<T, S>;
private states = new StateIndex<S, T>();
private byIndex = new Map<number, Set<State<S, T>>>();
/**
* The forward probability <code>α_i</code> of a chart is
* the sum of the probabilities of
* all constrained paths of length i that end in that chart, do all
* paths from start to position i. So this includes multiple
* instances of the same history, which may happen because of recursion.
*/
private forwardScores = new StateToObjectMap<T, S>();
/**
* The inner probability <code>γ_{i}</code> of a chart
* is the sum of the probabilities of all
* paths of length (i - k) that start at position k (the rule's start position),
* and end at the current chart and generate the input the input symbols up to k.
* Note that this is conditional on the chart happening at position k with
* a certain non-terminal X
*/
private innerScores = new StateToObjectMap<T, S>();
private viterbiScores = new StateToObjectMap<T, ViterbiScore<S, T>>();
completedStates = new Map<number, Set<State<S, T>>>();
completedStatesFor = new Map<number, Map<NonTerminal, Set<State<S, T>>>>();
completedStatesThatAreNotUnitProductions = new Map<number, Set<State<S, T>>>();
statesActiveOnNonTerminals = new Map<number, Set<State<S, T>>>();
nonTerminalActiveAtIWithNonZeroUnitStarToY = new Map<number, Map<NonTerminal, Set<State<S, T>>>>();
statesActiveOnTerminals = new Map<number, Map<Terminal<T>, Set<State<S, T>>>>();
statesActiveOnNonTerminal = new Map<NonTerminal, Map<number, Set<State<S, T>>>>();
private EMPTY_SET: Set<State<S, T>> = new Set<State<S, T>>();
constructor(grammar: Grammar<T, S>) {
this.grammar = grammar;
}
// getCompletedStates(int i, NonTerminal s):Set<State<SemiringType, T>> {
// Multimap<NonTerminal, State> m = this.completedStatesFor.get(i);
// if (m != null && m.containsKey(s)) return m.get(s);
// return Collections.emptySet();
// }
//
// public Set<State> getCompletedStates(int index) {
// return getCompletedStates(index, true);
// }
//
// public Set<State> getCompletedStatesThatAreNotUnitProductions(int index) {
// return getCompletedStates(index, false);
// }
//
// public Set<State> getCompletedStates(int index, boolean allowUnitProductions) {
// if (allowUnitProductions) {
// if (!completedStates.containsKey(index))
// completedStates.put(index, new HashSet<>());
// return completedStates.get(index);
// } else {
// if (!completedStatesThatAreNotUnitProductions.containsKey(index))
// completedStatesThatAreNotUnitProductions.put(index, new HashSet<>());
// return completedStatesThatAreNotUnitProductions.get(index);
// }
// }
//
getStatesActiveOnNonTerminalWithNonZeroUnitStarScoreToY(index: number, Y: NonTerminal): Set<State<S, T>> {
return getOrCreateSet(getOrCreateMap(this.nonTerminalActiveAtIWithNonZeroUnitStarToY, index), Y);
}
getStatesActiveOnNonTerminal(y: NonTerminal, position: number, beforeOrOnPosition: number): Set<State<S, T>> {
if (position <= beforeOrOnPosition)
return getOrCreateSet(getOrCreateMap(this.statesActiveOnNonTerminal, y), position);
else
throw new Error("Querying position after what we're on?");
}
/**
* Default zero
*
* @param s chart
* @return forward score so far
*/
public getForwardScore(s: State<S, T>): S {
return this.forwardScores.getByStateOrDefault(s, this.grammar.probabilityMapping.ZERO);
}
addForwardScore(state: State<S, T>, increment: S, semiring: Semiring<S>): S {
const fw = semiring.plus(this.getForwardScore(state)/*default zero*/, increment);
this.setForwardScore(
state,
fw
);
return fw;
}
setForwardScore(s: State<S, T>, probability: S) {
return this.forwardScores.putByState(s, probability);
}
//noinspection JSUnusedLocalSymbols
private hasForwardScore(s: State<S, T>): boolean {
return this.forwardScores.hasByState(s);
}
public getState(rule: Rule<T>,
positionInInput: number,
ruleStartPosition: number,
ruleDotPosition: number): State<S, T> {
return this.states.getState(rule, positionInInput, ruleStartPosition, ruleDotPosition);
}
/**
* Adds chart if it does not exist yet
*
* @param positionInInput State position
* @param ruleStartPosition Rule start position
* @param ruleDotPosition Rule dot position
* @param rule State rule
* @param scannedToken The token that was scanned to create this chart
* @return State specified by parameter. May or may not be in the chart table. If not, it is added.
*/
public getOrCreate(positionInInput: number,
ruleStartPosition: number,
ruleDotPosition: number,
rule: Rule<T>,
scannedToken?: T): State<S, T> {
if (this.states.has(rule, positionInInput, ruleStartPosition, ruleDotPosition)) {
return this.states.getState(rule, positionInInput, ruleStartPosition, ruleDotPosition);
} else {
// Add chart if it does not exist yet
const scannedCategory: Terminal<T> = scannedToken
? <Terminal<T>>rule.right[ruleDotPosition - 1]
: undefined;
const state: State<S, T> = {
rule,
position: positionInInput,
ruleStartPosition,
ruleDotPosition,
scannedToken: scannedToken,
scannedCategory
};
this.addState(state);
return state;
}
}
hasState(state: State<S, T>): boolean {
return this.states.has(state.rule, state.position, state.ruleStartPosition, state.ruleDotPosition);
}
has(rule: Rule<T>, index: number, ruleStart: number, ruleDot: number): boolean {
return this.states.has(rule, index, ruleStart, ruleDot);
}
addState(state: State<S, T>): void {
if (state.ruleDotPosition < 0 || state.ruleDotPosition > state.rule.right.length)
invalidDotPosition(state.ruleDotPosition, state);
this.states.addState(state);
const position = state.position;
getOrCreateSet(this.byIndex, position).add(state);
if (isCompleted(state)) {
getOrCreateSet(this.completedStates, position).add(state);
if (!isUnitProduction(state.rule))
getOrCreateSet(this.completedStatesThatAreNotUnitProductions, position).add(state);
getOrCreateSet(getOrCreateMap(this.completedStatesFor,
state.position), state.rule.left)
.add(state);
}
if (isActive(state)) {
const activeCategory = getActiveCategory(state);
if (isNonTerminal(activeCategory)) {
getOrCreateSet(getOrCreateMap(this.statesActiveOnNonTerminal,
activeCategory), state.position)
.add(state);
getOrCreateSet(this.statesActiveOnNonTerminals,
state.position)
.add(state);
this.grammar.unitStarScores
.getNonZeroScoresToNonTerminals(activeCategory)
.forEach((FromNonTerminal: NonTerminal) => {
getOrCreateSet(getOrCreateMap(
this.nonTerminalActiveAtIWithNonZeroUnitStarToY,
position), FromNonTerminal).add(state);
});
} else {
// activeCategory MUST be terminal
getOrCreateSet(getOrCreateMap(this.statesActiveOnTerminals, position), activeCategory).add(state);
}
}
}
setInnerScore(s: State<S, T>, probability: S) {
this.innerScores.putByState(s, probability);
}
/**
* @param v viterbi score
*/
setViterbiScore(v: ViterbiScore<S, T>) {
this.viterbiScores.putByState(v.resultingState, v);
}
getViterbiScore(s: State<S, T>): ViterbiScore<S, T> {
/*if (!this.hasViterbiScore(s))
throw new Error(
"Viterbi not available for chart ("
+ s.position + ", " + s.ruleStartPosition + ", " + s.ruleDotPosition
+ ") " + s.rule.left + " -> " + s.rule.right.map(f => f.toString()));
else */
return this.viterbiScores.getByState(s);
}
hasViterbiScore(s: State<S, T>): boolean {
return this.viterbiScores.hasByState(s);
}
/**
* Default zero
*
* @param s chart
* @return inner score so far
*/
public getInnerScore(s: State<S, T>): S {
return this.innerScores.getByStateOrDefault(s, this.grammar.probabilityMapping.ZERO);
}
public getCompletedStatesThatAreNotUnitProductions(position: number) {
return this.completedStatesThatAreNotUnitProductions.get(position);
}
public getCompletedStates(position: number) {
if (this.completedStates.has(position))
return this.completedStates.get(position);
else return this.EMPTY_SET;
}
public getStatesActiveOnNonTerminals(index: number) {
return this.statesActiveOnNonTerminals.get(index);
}
public getStatesActiveOnTerminals(index: number, terminal: Terminal<T>) {
if (this.statesActiveOnTerminals.has(index))
return this.statesActiveOnTerminals.get(index).get(terminal);
else
return undefined;
}
// public hasInnerScore(s: State<S, T>): boolean {
// let ruleMap = getOrCreateMap(this.innerScores, s.rule);
// let posMap = getOrCreateMap(ruleMap, s.position);
// let dotMAp = getOrCreateMap(posMap, s.ruleStartPosition);
// return dotMAp.has(s.ruleDotPosition);
// }
// public Set<State> getStatesByIndex(int index) {
// return byIndex.get(index);
// }
//
//
// public void plus(State chart) {
// Rule rule = chart.getRule();
// int ruleStart = chart.getRuleStartPosition();
// int index = chart.getPosition();
//
// TIntObjectMap<TIntObjectMap<State>> forRuleStart = states.getRuleStartToDotToState(rule, index);
// if (!forRuleStart.containsKey(ruleStart)) forRuleStart.put(ruleStart, new TIntObjectHashMap<>(50));
// TIntObjectMap<State> dotToState = forRuleStart.get(ruleStart);
//
// addState(dotToState, chart);
// }
//
// public synchronized State getSynchronized(int index, int ruleStart, int ruleDot, Rule rule) {
// return states.getState(rule, index, ruleStart, ruleDot);
// }
//
// public State get(int index, int ruleStart, int ruleDot, Rule rule) {
// return states.getState(rule, index, ruleStart, ruleDot);
// }
//
// public countStates():number {
// return this.states.count();
// }
} | the_stack |
import log from "../../../log";
import Manifest, {
Adaptation,
Period,
Representation,
} from "../../../manifest";
import { IBufferedChunk } from "../../segment_buffers";
import { IBufferDiscontinuity } from "../types";
/**
* Check if there is a soon-to-be-encountered discontinuity in the buffer that
* won't be filled by any future segment.
* This function will only check discontinuities for the given `checkedRange`.
*
* @param {Object} content - The content we are currently loading.
* @param {Object} checkedRange - The time range that will be checked for
* discontinuities.
* Both `nextSegmentStart` and `bufferedSegments` arguments can only refer to
* that range.
* @param {number|null} nextSegmentStart - The start time in seconds of the next
* not-yet-pushed segment that can be pushed, in the limits of `checkedRange`.
* This includes segments which have not been loaded or pushed yet, but also
* segments which might be re-downloaded because currently incomplete in the
* buffer, the point being to know what is the earliest time in the buffer where
* a segment might be pushed in the future.
* `null` if no segment in `checkedRange` will be pushed under current buffer's
* conditions.
* @param {boolean} hasFinishedLoading - if `true`, all segments for the current
* Period have been loaded and none will be loaded in the future under the
* current buffer's state.
* @param {Array.<Object>} bufferedSegments - Information about every segments
* currently in the buffer, in chronological order.
* Only segments overlapping with the given `checkedRange` will be looked at,
* though the array given can be larger.
*/
export default function checkForDiscontinuity(
content : { adaptation : Adaptation;
manifest : Manifest;
period : Period;
representation : Representation; },
checkedRange : { start : number; end : number },
nextSegmentStart : number | null,
hasFinishedLoading : boolean,
bufferedSegments : IBufferedChunk[]
) : IBufferDiscontinuity | null {
const { period, adaptation, representation } = content;
// `bufferedSegments` might also contains segments which are before
// `checkedRange`.
// Here we want the first one that goes over `checkedRange.start`, to see
// if there's a discontinuity at the beginning in the buffer
const nextBufferedInRangeIdx = getIndexOfFirstChunkInRange(bufferedSegments,
checkedRange);
if (nextBufferedInRangeIdx === null) {
// There's no segment currently buffered for the current range.
if (nextSegmentStart === null) { // No segment to load in that range
// Check if we are in a discontinuity at the end of the current Period
if (hasFinishedLoading &&
period.end !== undefined &&
checkedRange.end >= period.end)
{
return { start: undefined, end: null }; // discontinuity to Period's end
}
// Check that there is a discontinuity announced in the Manifest there
const discontinuityEnd = representation.index
.checkDiscontinuity(checkedRange.start);
if (discontinuityEnd !== null) {
return { start: undefined,
end: discontinuityEnd };
}
}
return null;
}
const nextBufferedSegment = bufferedSegments[nextBufferedInRangeIdx];
// Check if there is a hole that won't be filled before `nextSegmentStart`
if (
// Next buffered segment starts after the start of the current range
nextBufferedSegment.bufferedStart !== undefined &&
nextBufferedSegment.bufferedStart > checkedRange.start &&
// and no segment will fill in that hole
(nextSegmentStart === null ||
nextBufferedSegment.infos.segment.end <= nextSegmentStart)
) {
log.debug("RS: current discontinuity encountered",
adaptation.type, nextBufferedSegment.bufferedStart);
return { start: undefined,
end: nextBufferedSegment.bufferedStart };
}
// Check if there's a discontinuity BETWEEN segments of the current range
const nextHoleIdx =
getIndexOfFirstDiscontinuityBetweenChunks(bufferedSegments,
checkedRange,
nextBufferedInRangeIdx + 1);
// If there was a hole between two consecutives segments, and if this hole
// comes before the next segment to load, there is a discontinuity (that hole!)
if (nextHoleIdx !== null &&
(nextSegmentStart === null ||
bufferedSegments[nextHoleIdx].infos.segment.end <= nextSegmentStart))
{
const start = bufferedSegments[nextHoleIdx - 1].bufferedEnd as number;
const end = bufferedSegments[nextHoleIdx].bufferedStart as number;
log.debug("RS: future discontinuity encountered", adaptation.type, start, end);
return { start, end };
} else if (nextSegmentStart === null) {
// If no hole between segments and no segment to load, check for a
// discontinuity at the end of the Period
if (hasFinishedLoading && period.end !== undefined) { // Period is finished
if (checkedRange.end < period.end) { // We've not reached the Period's end yet
return null;
}
// Check if the last buffered segment ends before this Period's end
// In which case there is a discontinuity between those
const lastBufferedInPeriodIdx = getIndexOfLastChunkInPeriod(bufferedSegments,
period.end);
if (lastBufferedInPeriodIdx !== null) {
const lastSegment = bufferedSegments[lastBufferedInPeriodIdx];
if (lastSegment.bufferedEnd !== undefined &&
lastSegment.bufferedEnd < period.end)
{
log.debug("RS: discontinuity encountered at the end of the current period",
adaptation.type, lastSegment.bufferedEnd, period.end);
return { start: lastSegment.bufferedEnd,
end: null };
}
}
}
// At last, check if we don't have a discontinuity at the end of the current
// range, announced in the Manifest, that is too big to be detected through
// the previous checks.
if (period.end !== undefined && checkedRange.end >= period.end) {
return null; // The previous checks should have taken care of those
}
for (let bufIdx = bufferedSegments.length - 1; bufIdx >= 0; bufIdx--) {
const bufSeg = bufferedSegments[bufIdx];
if (bufSeg.bufferedStart === undefined) {
break;
}
if (bufSeg.bufferedStart < checkedRange.end) {
if (bufSeg.bufferedEnd !== undefined && bufSeg.bufferedEnd < checkedRange.end) {
const discontinuityEnd = representation.index
.checkDiscontinuity(checkedRange.end);
if (discontinuityEnd !== null) {
return { start: bufSeg.bufferedEnd,
end: discontinuityEnd };
}
}
return null;
}
}
}
return null;
}
/**
* Returns the index of the first element in `bufferedChunks` that is part of
* `range` (starts before it ends and ends after it starts).
*
* Returns `null` if no element is found in that range or if we cannot know the
* index of the first element in it.
* @param {Array.<Object>} bufferedChunks
* @param {Object} range
* @returns {number|null}
*/
function getIndexOfFirstChunkInRange(
bufferedChunks : IBufferedChunk[],
range : { start : number; end : number }
) : number | null {
for (let bufIdx = 0; bufIdx < bufferedChunks.length; bufIdx++) {
const bufSeg = bufferedChunks[bufIdx];
if (bufSeg.bufferedStart === undefined ||
bufSeg.bufferedEnd === undefined ||
bufSeg.bufferedStart >= range.end)
{
return null;
}
if (bufSeg.bufferedEnd > range.start) {
return bufIdx;
}
}
return null;
}
/**
* Returns the index of the first element in `bufferedChunks` which is not
* immediately consecutive to the one before it.
*
* `startFromIndex` is the index of the first segment that will be checked with
* the element coming before it. As such, it has to be superior to 0.
*
* If the element at `startFromIndex` comes immediately after the one before it,
* the element at `startFromIndex + 1` will be checked instead and so on until a
* segment completely out of `checkedRange` (which starts after it) is detected.
*
* If no hole between elements is found, `null` is returned.
* @param {Array.<Object>} bufferedChunks
* @param {Object} range
* @param {number} startFromIndex
* @returns {number|null}
*/
function getIndexOfFirstDiscontinuityBetweenChunks(
bufferedChunks : IBufferedChunk[],
range : { start : number; end : number },
startFromIndex : number
) : number | null {
if (startFromIndex <= 0) {
log.error("RS: Asked to check a discontinuity before the first chunk.");
return null;
}
for (
let bufIdx = startFromIndex;
bufIdx < bufferedChunks.length;
bufIdx++
) {
const currSegment = bufferedChunks[bufIdx];
const prevSegment = bufferedChunks[bufIdx - 1];
// Exit as soon we miss information or when we go further than `checkedRange`
if (currSegment.bufferedStart === undefined ||
prevSegment.bufferedEnd === undefined ||
currSegment.bufferedStart >= range.end)
{
return null;
}
// If there is a hole between two consecutive buffered segment
if (currSegment.bufferedStart - prevSegment.bufferedEnd > 0) {
return bufIdx;
}
}
return null;
}
/**
* Returns the index of the last element in `bufferedChunks` that is part of
* `range` (starts before it ends and ends after it starts).
*
* Returns `null` if no element is found in that range or if we cannot know the
* index of the last element in it.
* @param {Array.<Object>} bufferedChunks
* @param {number} periodEnd
* @returns {number|null}
*/
function getIndexOfLastChunkInPeriod(
bufferedChunks : IBufferedChunk[],
periodEnd : number
) : number | null {
for (let bufIdx = bufferedChunks.length - 1; bufIdx >= 0; bufIdx--) {
const bufSeg = bufferedChunks[bufIdx];
if (bufSeg.bufferedStart === undefined) {
return null;
}
if (bufSeg.bufferedStart < periodEnd) {
return bufIdx;
}
}
return null;
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The object that describes the operation.
*/
export interface OperationDisplay {
/**
* The description of the operation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
/**
* The action that users can perform, based on their permission level.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operation?: string;
/**
* Service provider: Microsoft Support.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provider?: string;
/**
* Resource on which the operation is performed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resource?: string;
}
/**
* The operation supported by Microsoft Support resource provider.
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The object that describes the operation.
*/
display?: OperationDisplay;
}
/**
* Object that represents a Service resource.
*/
export interface Service {
/**
* Id of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Type of the resource 'Microsoft.Support/services'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Localized name of the Azure service.
*/
displayName?: string;
/**
* ARM Resource types.
*/
resourceTypes?: string[];
}
/**
* ProblemClassification resource object.
*/
export interface ProblemClassification {
/**
* Id of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Type of the resource 'Microsoft.Support/problemClassification'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Localized name of problem classification.
*/
displayName?: string;
}
/**
* Input of CheckNameAvailability API.
*/
export interface CheckNameAvailabilityInput {
/**
* The resource name to validate.
*/
name: string;
/**
* The type of resource. Possible values include: 'Microsoft.Support/supportTickets',
* 'Microsoft.Support/communications'
*/
type: Type;
}
/**
* Output of check name availability API.
*/
export interface CheckNameAvailabilityOutput {
/**
* Indicates whether the name is available.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nameAvailable?: boolean;
/**
* The reason why the name is not available.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reason?: string;
/**
* The detailed error message describing why the name is not available.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
}
/**
* Contact information associated with the support ticket.
*/
export interface ContactProfile {
/**
* First name.
*/
firstName: string;
/**
* Last name.
*/
lastName: string;
/**
* Preferred contact method. Possible values include: 'email', 'phone'
*/
preferredContactMethod: PreferredContactMethod;
/**
* Primary email address.
*/
primaryEmailAddress: string;
/**
* Additional email addresses listed will be copied on any correspondence about the support
* ticket.
*/
additionalEmailAddresses?: string[];
/**
* Phone number. This is required if preferred contact method is phone.
*/
phoneNumber?: string;
/**
* Time zone of the user. This is the name of the time zone from [Microsoft Time Zone Index
* Values](https://support.microsoft.com/help/973627/microsoft-time-zone-index-values).
*/
preferredTimeZone: string;
/**
* Country of the user. This is the ISO 3166-1 alpha-3 code.
*/
country: string;
/**
* Preferred language of support from Azure. Support languages vary based on the severity you
* choose for your support ticket. Learn more at [Azure Severity and
* responsiveness](https://azure.microsoft.com/support/plans/response). Use the standard
* language-country code. Valid values are 'en-us' for English, 'zh-hans' for Chinese, 'es-es'
* for Spanish, 'fr-fr' for French, 'ja-jp' for Japanese, 'ko-kr' for Korean, 'ru-ru' for
* Russian, 'pt-br' for Portuguese, 'it-it' for Italian, 'zh-tw' for Chinese and 'de-de' for
* German.
*/
preferredSupportLanguage: string;
}
/**
* Service Level Agreement details for a support ticket.
*/
export interface ServiceLevelAgreement {
/**
* Time in UTC (ISO 8601 format) when the service level agreement starts.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly startTime?: Date;
/**
* Time in UTC (ISO 8601 format) when the service level agreement expires.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly expirationTime?: Date;
/**
* Service Level Agreement in minutes.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly slaMinutes?: number;
}
/**
* Support engineer information.
*/
export interface SupportEngineer {
/**
* Email address of the Azure Support engineer assigned to the support ticket.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly emailAddress?: string;
}
/**
* Additional information for technical support ticket.
*/
export interface TechnicalTicketDetails {
/**
* This is the resource Id of the Azure service resource (For example: A virtual machine resource
* or an HDInsight resource) for which the support ticket is created.
*/
resourceId?: string;
}
/**
* This property is required for providing the region and new quota limits.
*/
export interface QuotaChangeRequest {
/**
* Region for which the quota increase request is being made.
*/
region?: string;
/**
* Payload of the quota increase request.
*/
payload?: string;
}
/**
* Additional set of information required for quota increase support ticket for certain quota
* types, e.g.: Virtual machine cores. Get complete details about Quota payload support request
* along with examples at [Support quota request](https://aka.ms/supportrpquotarequestpayload).
*/
export interface QuotaTicketDetails {
/**
* Required for certain quota types when there is a sub type, such as Batch, for which you are
* requesting a quota increase.
*/
quotaChangeRequestSubType?: string;
/**
* Quota change request version.
*/
quotaChangeRequestVersion?: string;
/**
* This property is required for providing the region and new quota limits.
*/
quotaChangeRequests?: QuotaChangeRequest[];
}
/**
* Object that represents SupportTicketDetails resource.
*/
export interface SupportTicketDetails extends BaseResource {
/**
* Id of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Type of the resource 'Microsoft.Support/supportTickets'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* System generated support ticket Id that is unique.
*/
supportTicketId?: string;
/**
* Detailed description of the question or issue.
*/
description: string;
/**
* Each Azure service has its own set of issue categories, also known as problem classification.
* This parameter is the unique Id for the type of problem you are experiencing.
*/
problemClassificationId: string;
/**
* Localized name of problem classification.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly problemClassificationDisplayName?: string;
/**
* A value that indicates the urgency of the case, which in turn determines the response time
* according to the service level agreement of the technical support plan you have with Azure.
* Note: 'Highest critical impact' severity is reserved only for our Premium customers. Possible
* values include: 'minimal', 'moderate', 'critical', 'highestcriticalimpact'
*/
severity: SeverityLevel;
/**
* Enrollment Id associated with the support ticket.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly enrollmentId?: string;
/**
* Indicates if this requires a 24x7 response from Azure.
*/
require24X7Response?: boolean;
/**
* Contact information of the user requesting to create a support ticket.
*/
contactDetails: ContactProfile;
/**
* Service Level Agreement information for this support ticket.
*/
serviceLevelAgreement?: ServiceLevelAgreement;
/**
* Information about the support engineer working on this support ticket.
*/
supportEngineer?: SupportEngineer;
/**
* Support plan type associated with the support ticket.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportPlanType?: string;
/**
* Title of the support ticket.
*/
title: string;
/**
* Time in UTC (ISO 8601 format) when the problem started.
*/
problemStartTime?: Date;
/**
* This is the resource Id of the Azure service resource associated with the support ticket.
*/
serviceId: string;
/**
* Localized name of the Azure service.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceDisplayName?: string;
/**
* Status of the support ticket.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: string;
/**
* Time in UTC (ISO 8601 format) when the support ticket was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdDate?: Date;
/**
* Time in UTC (ISO 8601 format) when the support ticket was last modified.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly modifiedDate?: Date;
/**
* Additional ticket details associated with a technical support ticket request.
*/
technicalTicketDetails?: TechnicalTicketDetails;
/**
* Additional ticket details associated with a quota support ticket request.
*/
quotaTicketDetails?: QuotaTicketDetails;
}
/**
* Object that represents a Communication resource.
*/
export interface CommunicationDetails extends BaseResource {
/**
* Id of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Name of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Type of the resource 'Microsoft.Support/communications'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Communication type. Possible values include: 'web', 'phone'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly communicationType?: CommunicationType;
/**
* Direction of communication. Possible values include: 'inbound', 'outbound'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly communicationDirection?: CommunicationDirection;
/**
* Email address of the sender. This property is required if called by a service principal.
*/
sender?: string;
/**
* Subject of the communication.
*/
subject: string;
/**
* Body of the communication.
*/
body: string;
/**
* Time in UTC (ISO 8601 format) when the communication was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly createdDate?: Date;
}
/**
* The error details.
*/
export interface ServiceErrorDetail {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The target of the error.
*/
target?: string;
}
/**
* The API error details.
*/
export interface ServiceError {
/**
* The error code.
*/
code?: string;
/**
* The error message.
*/
message?: string;
/**
* The target of the error.
*/
target?: string;
/**
* The list of error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ServiceErrorDetail[];
}
/**
* The API error.
*/
export interface ExceptionResponse {
/**
* The API error details.
*/
error?: ServiceError;
}
/**
* Contact information associated with the support ticket.
*/
export interface UpdateContactProfile {
/**
* First name.
*/
firstName?: string;
/**
* Last name.
*/
lastName?: string;
/**
* Preferred contact method. Possible values include: 'email', 'phone'
*/
preferredContactMethod?: PreferredContactMethod;
/**
* Primary email address.
*/
primaryEmailAddress?: string;
/**
* Email addresses listed will be copied on any correspondence about the support ticket.
*/
additionalEmailAddresses?: string[];
/**
* Phone number. This is required if preferred contact method is phone.
*/
phoneNumber?: string;
/**
* Time zone of the user. This is the name of the time zone from [Microsoft Time Zone Index
* Values](https://support.microsoft.com/help/973627/microsoft-time-zone-index-values).
*/
preferredTimeZone?: string;
/**
* Country of the user. This is the ISO 3166-1 alpha-3 code.
*/
country?: string;
/**
* Preferred language of support from Azure. Support languages vary based on the severity you
* choose for your support ticket. Learn more at [Azure Severity and
* responsiveness](https://azure.microsoft.com/support/plans/response/). Use the standard
* language-country code. Valid values are 'en-us' for English, 'zh-hans' for Chinese, 'es-es'
* for Spanish, 'fr-fr' for French, 'ja-jp' for Japanese, 'ko-kr' for Korean, 'ru-ru' for
* Russian, 'pt-br' for Portuguese, 'it-it' for Italian, 'zh-tw' for Chinese and 'de-de' for
* German.
*/
preferredSupportLanguage?: string;
}
/**
* Updates severity, ticket status, and contact details in the support ticket.
*/
export interface UpdateSupportTicket {
/**
* Severity level. Possible values include: 'minimal', 'moderate', 'critical',
* 'highestcriticalimpact'
*/
severity?: SeverityLevel;
/**
* Status to be updated on the ticket. Possible values include: 'open', 'closed'
*/
status?: Status;
/**
* Contact details to be updated on the support ticket.
*/
contactDetails?: UpdateContactProfile;
}
/**
* Optional Parameters.
*/
export interface SupportTicketsListOptionalParams extends msRest.RequestOptionsBase {
/**
* The number of values to return in the collection. Default is 25 and max is 100.
*/
top?: number;
/**
* The filter to apply on the operation. We support 'odata v4.0' filter semantics. [Learn
* more](https://docs.microsoft.com/odata/concepts/queryoptions-overview). _Status_ filter can
* only be used with Equals ('eq') operator. For _CreatedDate_ filter, the supported operators
* are Greater Than ('gt') and Greater Than or Equals ('ge'). When using both filters, combine
* them using the logical 'AND'.
*/
filter?: string;
}
/**
* Optional Parameters.
*/
export interface CommunicationsListOptionalParams extends msRest.RequestOptionsBase {
/**
* The number of values to return in the collection. Default is 10 and max is 10.
*/
top?: number;
/**
* The filter to apply on the operation. You can filter by communicationType and createdDate
* properties. CommunicationType supports Equals ('eq') operator and createdDate supports Greater
* Than ('gt') and Greater Than or Equals ('ge') operators. You may combine the CommunicationType
* and CreatedDate filters by Logical And ('and') operator.
*/
filter?: string;
}
/**
* An interface representing MicrosoftSupportOptions.
*/
export interface MicrosoftSupportOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* The list of operations supported by Microsoft Support resource provider.
* @extends Array<Operation>
*/
export interface OperationsListResult extends Array<Operation> {
}
/**
* @interface
* Collection of Service resources.
* @extends Array<Service>
*/
export interface ServicesListResult extends Array<Service> {
}
/**
* @interface
* Collection of ProblemClassification resources.
* @extends Array<ProblemClassification>
*/
export interface ProblemClassificationsListResult extends Array<ProblemClassification> {
}
/**
* @interface
* Object that represents a collection of SupportTicket resources.
* @extends Array<SupportTicketDetails>
*/
export interface SupportTicketsListResult extends Array<SupportTicketDetails> {
/**
* The URI to fetch the next page of SupportTicket resources.
*/
nextLink?: string;
}
/**
* @interface
* Collection of Communication resources.
* @extends Array<CommunicationDetails>
*/
export interface CommunicationsListResult extends Array<CommunicationDetails> {
/**
* The URI to fetch the next page of Communication resources.
*/
nextLink?: string;
}
/**
* Defines values for Type.
* Possible values include: 'Microsoft.Support/supportTickets', 'Microsoft.Support/communications'
* @readonly
* @enum {string}
*/
export type Type = 'Microsoft.Support/supportTickets' | 'Microsoft.Support/communications';
/**
* Defines values for SeverityLevel.
* Possible values include: 'minimal', 'moderate', 'critical', 'highestcriticalimpact'
* @readonly
* @enum {string}
*/
export type SeverityLevel = 'minimal' | 'moderate' | 'critical' | 'highestcriticalimpact';
/**
* Defines values for PreferredContactMethod.
* Possible values include: 'email', 'phone'
* @readonly
* @enum {string}
*/
export type PreferredContactMethod = 'email' | 'phone';
/**
* Defines values for CommunicationType.
* Possible values include: 'web', 'phone'
* @readonly
* @enum {string}
*/
export type CommunicationType = 'web' | 'phone';
/**
* Defines values for CommunicationDirection.
* Possible values include: 'inbound', 'outbound'
* @readonly
* @enum {string}
*/
export type CommunicationDirection = 'inbound' | 'outbound';
/**
* Defines values for Status.
* Possible values include: 'open', 'closed'
* @readonly
* @enum {string}
*/
export type Status = 'open' | 'closed';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationsListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type ServicesListResponse = ServicesListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ServicesListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ServicesGetResponse = Service & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Service;
};
};
/**
* Contains response data for the list operation.
*/
export type ProblemClassificationsListResponse = ProblemClassificationsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ProblemClassificationsListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ProblemClassificationsGetResponse = ProblemClassification & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ProblemClassification;
};
};
/**
* Contains response data for the checkNameAvailability operation.
*/
export type SupportTicketsCheckNameAvailabilityResponse = CheckNameAvailabilityOutput & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CheckNameAvailabilityOutput;
};
};
/**
* Contains response data for the list operation.
*/
export type SupportTicketsListResponse = SupportTicketsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketsListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type SupportTicketsGetResponse = SupportTicketDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketDetails;
};
};
/**
* Contains response data for the update operation.
*/
export type SupportTicketsUpdateResponse = SupportTicketDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketDetails;
};
};
/**
* Contains response data for the create operation.
*/
export type SupportTicketsCreateResponse = SupportTicketDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketDetails;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type SupportTicketsBeginCreateResponse = SupportTicketDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketDetails;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SupportTicketsListNextResponse = SupportTicketsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SupportTicketsListResult;
};
};
/**
* Contains response data for the checkNameAvailability operation.
*/
export type CommunicationsCheckNameAvailabilityResponse = CheckNameAvailabilityOutput & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CheckNameAvailabilityOutput;
};
};
/**
* Contains response data for the list operation.
*/
export type CommunicationsListResponse = CommunicationsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CommunicationsListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type CommunicationsGetResponse = CommunicationDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CommunicationDetails;
};
};
/**
* Contains response data for the create operation.
*/
export type CommunicationsCreateResponse = CommunicationDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CommunicationDetails;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type CommunicationsBeginCreateResponse = CommunicationDetails & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CommunicationDetails;
};
};
/**
* Contains response data for the listNext operation.
*/
export type CommunicationsListNextResponse = CommunicationsListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CommunicationsListResult;
};
}; | the_stack |
import * as React from 'react'
import styled from 'styled-components'
import { connect } from 'react-redux'
import { Dispatch } from 'redux'
import { usernameToAddress, validRecipientAccount } from 'helpers/account'
import { stroopsToLumens, lumensToStroops } from 'helpers/lumens'
import { BtnSubmit } from 'pages/shared/Button'
import { Heading } from 'pages/shared/Heading'
import { Icon } from 'pages/shared/Icon'
import { Hint, Input, Label, HelpBlock } from 'pages/shared/Input'
import { HorizontalLine } from 'pages/shared/HorizontalLine'
import { Total } from 'pages/shared/Total'
import { TransactionFee } from 'pages/shared/TransactionFee'
import { Unit, UnitContainer } from 'pages/shared/Unit'
import { RADICALRED, SEAFOAM } from 'pages/shared/Colors'
import { wallet } from 'state/wallet'
import { ApplicationState, ChannelsState } from 'types/schema'
import {
channelPay,
getCounterpartyAccounts,
getMyBalance,
getTheirAccount,
} from 'state/channels'
import { ChannelState } from 'types/schema'
const View = styled.div`
padding: 25px;
`
const Form = styled.form`
margin-top: 45px;
`
interface State {
amount: string
formErrors: {
amount: boolean
recipient: boolean
}
loading: boolean
recipient: string
showError: boolean
}
interface Props {
availableBalance: number
channels: ChannelsState
initialRecipient?: string
walletPay: (recipient: string, amount: number) => Promise<boolean>
channelPay: (id: string, amount: number) => Promise<boolean>
closeModal: () => void
counterpartyAccounts: { [id: string]: string }
username: string
}
export class SendPayment extends React.Component<Props, State> {
public constructor(props: Props) {
super(props)
this.state = {
amount: '',
formErrors: {
amount: false,
recipient: false,
},
loading: false,
recipient: props.initialRecipient || '',
showError: false,
}
this.handleSubmit = this.handleSubmit.bind(this)
}
public render() {
const validAmount = this.amount() !== undefined
const hasChannel = this.destinationChannel() !== undefined
const hasChannelWithSufficientBalance =
validAmount && hasChannel && this.channelHasSufficientBalance()
const submittable =
validAmount &&
(hasChannelWithSufficientBalance ||
(this.recipientIsValid() && this.walletHasSufficientBalance()))
const amount = this.amount()
let total = amount
if (total !== undefined && !hasChannelWithSufficientBalance) {
total += 100
}
const focusOnRecipient = this.props.initialRecipient === undefined
const channelBalance = this.channelBalance()
const displayChannelBtn =
(hasChannel && !validAmount) || this.channelHasSufficientBalance()
return (
<View>
<Heading>Send payment</Heading>
<Form onSubmit={this.handleSubmit}>
<Label htmlFor="recipient">Recipient</Label>
<Input
value={this.state.recipient}
onBlur={() => {
this.setState({
formErrors: {
amount: this.state.formErrors.amount,
recipient: !!this.state.recipient && !this.recipientIsValid(),
},
})
}}
onChange={e => {
this.setState({ recipient: e.target.value })
}}
type="text"
name="recipient"
autoComplete="off"
autoFocus={focusOnRecipient}
error={this.state.formErrors.recipient}
/>
{/* TODO: validate this is a Stellar account ID */}
<div>
<Label htmlFor="amount">Amount</Label>
<Hint>
{hasChannel && (
<span>
<strong>
{stroopsToLumens(this.channelBalance() as number)} XLM
</strong>{' '}
available in channel;{' '}
</span>
)}
<strong>
{stroopsToLumens(this.props.availableBalance)} XLM
</strong>{' '}
available in account
</Hint>
</div>
<UnitContainer>
<Input
value={this.state.amount}
onBlur={() => {
this.setState({
formErrors: {
amount:
!!this.state.amount &&
(parseFloat(this.state.amount) <= 0 ||
!validAmount ||
!this.walletHasSufficientBalance()),
recipient: this.state.formErrors.recipient,
},
})
}}
onChange={e => {
this.setState({ amount: e.target.value })
}}
type="number"
name="amount"
autoComplete="off"
autoFocus={!focusOnRecipient}
error={this.state.formErrors.amount}
/>
{/* TODO: validate this is a number, and not more than the wallet balance */}
<Unit>XLM</Unit>
</UnitContainer>
<HelpBlock
isShowing={
this.state.recipient === usernameToAddress(this.props.username)
}
>
You cannot send payments to yourself.
</HelpBlock>
<HelpBlock isShowing={!hasChannel && this.recipientIsValid()}>
You do not have a channel open with this recipient. Open a channel
or proceed to send this payment from your account on the Stellar
network.
</HelpBlock>
<HelpBlock
isShowing={
hasChannel &&
!hasChannelWithSufficientBalance &&
this.walletHasSufficientBalance()
}
>
You only have {stroopsToLumens(this.channelBalance() || 0)} XLM
available in this channel. The entire payment will occur on the
Stellar network from your account instead.
</HelpBlock>
<HelpBlock
isShowing={
this.recipientIsValid() &&
validAmount &&
!hasChannelWithSufficientBalance &&
!this.walletHasSufficientBalance()
}
>
{channelBalance === undefined ||
this.props.availableBalance > channelBalance
? `You only have ${stroopsToLumens(
this.props.availableBalance
)} XLM available in your wallet.`
: `You only have ${stroopsToLumens(
channelBalance
)} XLM available in this channel.`}
</HelpBlock>
<Label>Transaction Fee</Label>
{(!validAmount && hasChannel) ||
this.channelHasSufficientBalance() ? (
<TransactionFee>—</TransactionFee>
) : (
<TransactionFee>0.00001 XLM</TransactionFee>
)}
<HorizontalLine />
<Label>Total</Label>
{total && stroopsToLumens(total) !== 'NaN' ? (
<Total>{stroopsToLumens(total)} XLM</Total>
) : (
<Total>—</Total>
)}
{this.formatSubmitButton(displayChannelBtn, submittable)}
</Form>
</View>
)
}
private recipientIsValid() {
return (
this.destinationChannel() ||
validRecipientAccount(this.props.username, this.state.recipient)
)
}
private destinationChannel(): ChannelState | undefined {
const recipient = this.state.recipient
const channels = this.props.channels
if (channels[recipient] && channels[recipient].State !== 'Closed') {
return channels[recipient]
} else {
return this.lookupChannelByAccountId(recipient, channels)
}
}
private lookupChannelByAccountId(accountId: string, channels: ChannelsState) {
const counterpartyAccounts = this.props.counterpartyAccounts
const chanId = counterpartyAccounts[accountId]
if (chanId !== undefined) {
const channel = channels[chanId]
if (channel.State !== 'Closed') {
return channel
}
}
}
private channelBalance() {
const destinationChannel = this.destinationChannel()
return destinationChannel && getMyBalance(destinationChannel)
}
private amount() {
const lumensAmount = parseFloat(this.state.amount)
if (isNaN(lumensAmount) || lumensAmount < 0) {
return undefined
}
return lumensToStroops(lumensAmount)
}
private formatSubmitButton(displayChannelBtn: boolean, submittable: boolean) {
if (this.state.loading) {
return (
<BtnSubmit disabled>
Sending <Icon className="fa-pulse" name="spinner" />
</BtnSubmit>
)
} else if (this.state.showError) {
return (
<BtnSubmit color={RADICALRED} disabled>
Payment not sent
</BtnSubmit>
)
} else {
if (displayChannelBtn) {
return <BtnSubmit disabled={!submittable}>Send via channel</BtnSubmit>
} else {
return (
<BtnSubmit disabled={!submittable} color={SEAFOAM}>
Send on Stellar
</BtnSubmit>
)
}
}
}
private async handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
this.setState({ loading: true })
const amount = this.amount()
if (amount === undefined) {
throw new Error('invalid amount: ' + this.state.amount)
}
let ok
const channel = this.destinationChannel()
if (channel && this.channelHasSufficientBalance()) {
ok = await this.props.channelPay(channel.ID, amount)
} else {
if (!this.walletHasSufficientBalance()) {
throw new Error('wallet has insufficient balance')
}
if (channel) {
ok = await this.props.walletPay(getTheirAccount(channel), amount)
} else {
ok = await this.props.walletPay(this.state.recipient, amount)
}
}
if (ok) {
this.props.closeModal()
// TODO: drop you into channel view when successful
} else {
this.setState({ loading: false, showError: true })
window.setTimeout(() => {
this.setState({ showError: false })
}, 3000)
}
}
private channelHasSufficientBalance() {
const balance = this.channelBalance()
if (balance === undefined) {
return false
}
const amount = this.amount()
if (amount === undefined) {
return false
}
return balance >= amount
}
private walletHasSufficientBalance() {
const amount = this.amount()
if (amount === undefined) {
return false
}
return this.props.availableBalance >= amount
}
}
const mapStateToProps = (state: ApplicationState) => {
return {
availableBalance: state.wallet.Balance,
channels: state.channels,
counterpartyAccounts: getCounterpartyAccounts(state),
username: state.config.Username,
}
}
const mapDispatchToProps = (dispatch: Dispatch) => {
return {
walletPay: (recipient: string, amount: number) => {
return wallet.send(dispatch, recipient, amount)
},
channelPay: (id: string, amount: number) => {
return channelPay(dispatch, id, amount)
},
}
}
export const ConnectedSendPayment = connect<
{},
{},
{ closeModal: () => void; initialRecipient?: string }
>(
mapStateToProps,
mapDispatchToProps
)(SendPayment) | the_stack |
import {
Agile,
Observer,
ProxyWeakMapType,
SelectorWeakMapType,
SubscriptionContainer,
} from '../../../../../src';
import * as Utils from '@agile-ts/utils';
import { LogMock } from '../../../../helper/logMock';
describe('SubscriptionContainer Tests', () => {
let dummyAgile: Agile;
let dummyObserver1: Observer;
let dummyObserver2: Observer;
let dummySelectorWeakMap: SelectorWeakMapType;
let dummyProxyWeakMap: ProxyWeakMapType;
beforeEach(() => {
LogMock.mockLogs();
dummyAgile = new Agile();
dummyObserver1 = new Observer(dummyAgile, { key: 'dummyObserver1' });
dummyObserver2 = new Observer(dummyAgile, { key: 'dummyObserver2' });
dummySelectorWeakMap = new WeakMap();
dummyProxyWeakMap = new WeakMap();
jest.clearAllMocks();
});
it('should create SubscriptionContainer with passed subs array (default config)', () => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedId');
jest
.spyOn(SubscriptionContainer.prototype, 'addSubscription')
.mockReturnValueOnce()
.mockReturnValueOnce();
const subscriptionContainer = new SubscriptionContainer([
dummyObserver1,
dummyObserver2,
]);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledTimes(2);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver1,
{
proxyPaths: undefined,
selectorMethods: undefined,
key: undefined,
}
);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver2,
{
proxyPaths: undefined,
selectorMethods: undefined,
key: undefined,
}
);
expect(subscriptionContainer.key).toBe('generatedId');
expect(subscriptionContainer.ready).toBeFalsy();
expect(subscriptionContainer.componentId).toBeUndefined();
expect(Array.from(subscriptionContainer.subscribers)).toStrictEqual([]); // because of mocking addSubscription
expect(Array.from(subscriptionContainer.updatedSubscribers)).toStrictEqual(
[]
);
expect(subscriptionContainer.isObjectBased).toBeFalsy();
expect(subscriptionContainer.subscriberKeysWeakMap).toStrictEqual(
expect.any(WeakMap)
);
expect(subscriptionContainer.selectorsWeakMap).toStrictEqual(
expect.any(WeakMap)
);
});
it('should create SubscriptionContainer with passed subs object (default config)', () => {
jest.spyOn(Utils, 'generateId').mockReturnValueOnce('generatedId');
jest
.spyOn(SubscriptionContainer.prototype, 'addSubscription')
.mockReturnValueOnce()
.mockReturnValueOnce();
const subscriptionContainer = new SubscriptionContainer({
dummyObserver1: dummyObserver1,
dummyObserver2: dummyObserver2,
});
expect(subscriptionContainer.addSubscription).toHaveBeenCalledTimes(2);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver1,
{
proxyPaths: undefined,
selectorMethods: undefined,
key: 'dummyObserver1',
}
);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver2,
{
proxyPaths: undefined,
selectorMethods: undefined,
key: 'dummyObserver2',
}
);
expect(subscriptionContainer.key).toBe('generatedId');
expect(subscriptionContainer.ready).toBeFalsy();
expect(subscriptionContainer.componentId).toBeUndefined();
expect(Array.from(subscriptionContainer.subscribers)).toStrictEqual([]); // because of mocking addSubscription
expect(Array.from(subscriptionContainer.updatedSubscribers)).toStrictEqual(
[]
);
expect(subscriptionContainer.isObjectBased).toBeTruthy();
expect(subscriptionContainer.subscriberKeysWeakMap).toStrictEqual(
expect.any(WeakMap)
);
expect(subscriptionContainer.selectorsWeakMap).toStrictEqual(
expect.any(WeakMap)
);
});
it('should create SubscriptionContainer with passed subs array (specific config)', () => {
jest
.spyOn(SubscriptionContainer.prototype, 'addSubscription')
.mockReturnValueOnce()
.mockReturnValueOnce();
dummyProxyWeakMap.set(dummyObserver1, {
paths: 'dummyObserver1_paths' as any,
});
dummyProxyWeakMap.set(dummyObserver2, {
paths: 'dummyObserver2_paths' as any,
});
dummySelectorWeakMap.set(dummyObserver2, {
methods: 'dummyObserver2_selectors' as any,
});
const subscriptionContainer = new SubscriptionContainer(
[dummyObserver1, dummyObserver2],
{
key: 'dummyKey',
proxyWeakMap: dummyProxyWeakMap,
selectorWeakMap: dummySelectorWeakMap,
componentId: 'testID',
}
);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledTimes(2);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver1,
{
proxyPaths: 'dummyObserver1_paths',
selectorMethods: undefined,
key: undefined,
}
);
expect(subscriptionContainer.addSubscription).toHaveBeenCalledWith(
dummyObserver2,
{
proxyPaths: 'dummyObserver2_paths',
selectorMethods: 'dummyObserver2_selectors',
key: undefined,
}
);
expect(subscriptionContainer.key).toBe('dummyKey');
expect(subscriptionContainer.ready).toBeFalsy();
expect(subscriptionContainer.componentId).toBe('testID');
expect(Array.from(subscriptionContainer.subscribers)).toStrictEqual([]); // because of mocking addSubscription
expect(Array.from(subscriptionContainer.updatedSubscribers)).toStrictEqual(
[]
);
expect(subscriptionContainer.isObjectBased).toBeFalsy();
expect(subscriptionContainer.subscriberKeysWeakMap).toStrictEqual(
expect.any(WeakMap)
);
expect(subscriptionContainer.selectorsWeakMap).toStrictEqual(
expect.any(WeakMap)
);
expect(subscriptionContainer.selectorsWeakMap).not.toBe(
dummySelectorWeakMap
);
});
describe('Subscription Container Function Tests', () => {
let subscriptionContainer: SubscriptionContainer;
beforeEach(() => {
subscriptionContainer = new SubscriptionContainer([]);
});
describe('addSubscription function tests', () => {
it(
'should create selector methods based on the specified proxy paths, ' +
"assign newly created and provided selector methods to the 'selectorsWeakMap' " +
'and subscribe the specified Observer to the Subscription Container',
() => {
dummyObserver1.value = {
das: { haus: { vom: 'nikolaus' } },
alle: { meine: 'entchien' },
test1: 'test1Value',
test2: 'test2Value',
test3: 'test3Value',
};
subscriptionContainer.selectorsWeakMap.set(dummyObserver1, {
methods: [(value) => value.test3],
});
subscriptionContainer.selectorsWeakMap.set(dummyObserver2, {
methods: [(value) => 'doesNotMatter'],
});
subscriptionContainer.subscriberKeysWeakMap.set(
dummyObserver2,
'dummyObserver2'
);
subscriptionContainer.addSubscription(dummyObserver1, {
key: 'dummyObserver1',
proxyPaths: [['das', 'haus', 'vom'], ['test1']],
selectorMethods: [
(value) => value.alle.meine,
(value) => value.test2,
],
});
expect(Array.from(subscriptionContainer.subscribers)).toStrictEqual([
dummyObserver1,
]);
expect(Array.from(dummyObserver1.subscribedTo)).toStrictEqual([
subscriptionContainer,
]);
// should assign specified selectors/(and selectors created from proxy paths) to the 'selectorsWeakMap'
const observer1Selector = subscriptionContainer.selectorsWeakMap.get(
dummyObserver1
) as any;
expect(observer1Selector.methods.length).toBe(5);
expect(observer1Selector.methods[0](dummyObserver1.value)).toBe(
'test3Value'
);
expect(observer1Selector.methods[1](dummyObserver1.value)).toBe(
'entchien'
);
expect(observer1Selector.methods[2](dummyObserver1.value)).toBe(
'test2Value'
);
expect(observer1Selector.methods[3](dummyObserver1.value)).toBe(
'nikolaus'
);
expect(observer1Selector.methods[4](dummyObserver1.value)).toBe(
'test1Value'
);
// shouldn't overwrite already set values in 'selectorsWeakMap' (Observer2)
const observer2Selector = subscriptionContainer.selectorsWeakMap.get(
dummyObserver2
) as any;
expect(observer2Selector.methods.length).toBe(1);
expect(observer2Selector.methods[0](null)).toBe('doesNotMatter');
// should assign specified key to the 'subscriberKeysWeakMap'
const observer1Key =
subscriptionContainer.subscriberKeysWeakMap.get(dummyObserver1);
expect(observer1Key).toBe('dummyObserver1');
// shouldn't overwrite already set values in 'subscriberKeysWeakMap' (Observer2)
const observer2Key =
subscriptionContainer.subscriberKeysWeakMap.get(dummyObserver2);
expect(observer2Key).toBe('dummyObserver2');
}
);
});
describe('removeSubscription function tests', () => {
let subscriptionContainer: SubscriptionContainer;
beforeEach(() => {
subscriptionContainer = new SubscriptionContainer([]);
subscriptionContainer.subscribers = new Set([
dummyObserver1,
dummyObserver2,
]);
dummyObserver1.subscribedTo = new Set([subscriptionContainer]);
dummyObserver2.subscribedTo = new Set([subscriptionContainer]);
subscriptionContainer.selectorsWeakMap.set(dummyObserver1, {
methods: [],
});
subscriptionContainer.selectorsWeakMap.set(dummyObserver2, {
methods: [],
});
subscriptionContainer.subscriberKeysWeakMap.set(
dummyObserver1,
'dummyObserver1'
);
subscriptionContainer.subscriberKeysWeakMap.set(
dummyObserver2,
'dummyObserver2'
);
});
it('should remove subscribed Observer from Subscription Container', () => {
subscriptionContainer.removeSubscription(dummyObserver1);
expect(Array.from(subscriptionContainer.subscribers)).toStrictEqual([
dummyObserver2,
]);
expect(
subscriptionContainer.selectorsWeakMap.get(dummyObserver1)
).toBeUndefined();
expect(
subscriptionContainer.selectorsWeakMap.get(dummyObserver2)
).not.toBeUndefined();
expect(
subscriptionContainer.subscriberKeysWeakMap.get(dummyObserver1)
).toBeUndefined();
expect(
subscriptionContainer.subscriberKeysWeakMap.get(dummyObserver2)
).toBe('dummyObserver2');
expect(Array.from(dummyObserver1.subscribedTo)).toStrictEqual([]);
expect(Array.from(dummyObserver2.subscribedTo)).toStrictEqual([
subscriptionContainer,
]);
});
});
});
}); | the_stack |
type Callback0 = () => any;
type Callback1<T1> = (arg1: T1) => any;
type Callback2<T1, T2> = (arg1: T1, arg2: T2) => any;
type Callback3<T1, T2, T3> = (arg1: T1, arg2: T2, arg3: T3) => any;
type Callback4<T1, T2, T3, T4> = (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => any;
type Callback5<T1, T2, T3, T4, T5> = (arg1: T1, arg2: T2, arg3: T3,
arg4: T4, arg5: T5) => any;
type Callback6Rest<T1, T2, T3, T4, T5, T6> = (arg1: T1, arg2: T2, arg3: T3,
arg4: T4, arg5: T5, arg6: T6,
...rest: any[]) => any;
type ErrorHandler<T> = (error: Error, arg: T) => any
type ErrorHandler2<T1, T2> = (error: Error, arg1: T1, arg2: T2) => any
type ErrorHandler3<T1, T2, T3> = (error: Error, arg1: T1, arg2: T2, arg3: T3) => any
type ErrorHandler4<T1, T2, T3, T4> = (error: Error, arg1: T1, arg2: T2, arg3: T3,
arg4: T4) => any
type ErrorHandler5<T1, T2, T3, T4, T5> = (error: Error, arg1: T1, arg2: T2, arg3: T3,
arg4: T4, arg5: T5) => any
type ErrorHandler6Rest<T1, T2, T3, T4, T5, T6> = (error: Error, arg1: T1, arg2: T2, arg3: T3,
arg4: T4, arg5: T5, arg6: T6, ...rest: any[]) => any
export class EventProxy {
/**
* Create a new EventProxy
* Examples:
* ```js
* var ep = EventProxy.create();
* ep.assign('user', 'articles', function(user, articles) {
* // do something...
* });
* // or one line ways: Create EventProxy and Assign
* var ep = EventProxy.create('user', 'articles', function(user, articles) {
* // do something...
* });
* ```
* @return {EventProxy} EventProxy instance
*/
static create(): EventProxy
static create<T1>(ev1: string, callback: Callback1<T1>,
errorHandler?: ErrorHandler<T1>): EventProxy
static create<T1, T2>(ev1: string, ev2: string, callback: Callback2<T1, T2>,
errorHandler?: ErrorHandler<T1 | T2>): EventProxy
static create<T1, T2, T3>(ev1: string, ev2: string, ev3: string,
callback: Callback3<T1, T2, T3>, errorHandler?: ErrorHandler<T1 | T2 | T3>): EventProxy
static create<T1, T2, T3, T4>(ev1: string, ev2: string, ev3: string, ev4: string,
callback: Callback4<T1, T2, T3, T4>, errorHandler?: ErrorHandler<T1 | T2 | T3 | T4>): EventProxy
static create<T1, T2, T3, T4, T5>(ev1: string, ev2: string, ev3: string, ev4: string, ev5: string,
callback: Callback5<T1, T2, T3, T4, T5>, errorHandler?: ErrorHandler<T1 | T2 | T3 | T4 | T5>): EventProxy
static create<T1, T2, T3, T4, T5, T6>(ev1: string, ev2: string, ev3: string, ev4: string, ev5: string, ev6: string,
...rest: (string | ErrorHandler<any> | Callback6Rest<T1, T2, T3, T4, T5, T6>)[]): EventProxy
/**
* Bind an event, specified by a string name, `ev`, to a `callback` function.
* Passing __ALL_EVENT__ will bind the callback to all events fired.
* Examples:
* ```js
* var proxy = new EventProxy();
* proxy.addListener("template", function (event) {
* // TODO
* });
* ```
* @param {string} eventname Event name.
* @param {Function} callback Callback.
*/
addListener<T>(event: string, callback: Callback1<T>): this
addListener<T1, T2>(event: string, callback: Callback2<T1, T2>): this
addListener<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
addListener<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
addListener<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
addListener<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* `addListener` alias, `bind`
*/
bind<T>(event: string, callback: Callback1<T>): this
bind<T1, T2>(event: string, callback: Callback2<T1, T2>): this
bind<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
bind<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
bind<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
bind<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* `addListener` alias, `on`
*/
on<T>(event: string, callback: Callback1<T>): this
on<T1, T2>(event: string, callback: Callback2<T1, T2>): this
on<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
on<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
on<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
on<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* `addListener` alias, `subscribe`
*/
subscribe<T>(event: string, callback: Callback1<T>): this
subscribe<T1, T2>(event: string, callback: Callback2<T1, T2>): this
subscribe<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
subscribe<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
subscribe<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
subscribe<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* Bind an event, but put the callback into head of all callbacks.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
headbind<T>(event: string, callback: Callback1<T>): this
headbind<T1, T2>(event: string, callback: Callback2<T1, T2>): this
headbind<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
headbind<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
headbind<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
headbind<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* Remove one or many callbacks.
*
* - If `callback` is null, removes all callbacks for the event.
* - If `eventname` is null, removes all bound callbacks for all events.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
removeEventListener(event?: string, callback?: Function): this
/**
* `removeListener` alias, unbind
*/
unbind(event?: string, callback?: Function): this
/**
* Remove all listeners. It equals unbind()
* Just add this API for as same as Event.Emitter.
* @param {String} event Event name.
*/
removeAllListeners(event: string)
/**
* Bind the ALL_EVENT event
*/
bindForAll(callback: Function)
/**
* Unbind the ALL_EVENT event
*/
unbindForAll(callback: Function)
/**
* Trigger an event, firing all bound callbacks. Callbacks are passed the
* same arguments as `trigger` is, apart from the event name.
* Listening for `"all"` passes the true event name as the first argument.
* @param {String} eventname Event name
* @param {Mix} data Pass in data
*/
trigger(event: string)
trigger<T1>(event: string, arg: T1)
trigger<T1, T2>(event: string, arg1: T1, arg2: T2)
trigger<T1, T2, T3>(event: string, arg1: T1, arg2: T2, arg3: T3)
trigger<T1, T2, T3, T4>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4)
trigger<T1, T2, T3, T4, T5>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5)
trigger<T1, T2, T3, T4, T5, T6>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5,
arg6: T6, ...rest: any[])
/**
* `trigger` alias, `emit`
*/
emit(event: string)
emit<T1>(event: string, arg: T1)
emit<T1, T2>(event: string, arg1: T1, arg2: T2)
emit<T1, T2, T3>(event: string, arg1: T1, arg2: T2, arg3: T3)
emit<T1, T2, T3, T4>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4)
emit<T1, T2, T3, T4, T5>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5)
emit<T1, T2, T3, T4, T5, T6>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5,
arg6: T6, ...rest: any[])
/**
* `trigger` alias, `fire`
*/
fire(event: string)
fire<T1>(event: string, arg: T1)
fire<T1, T2>(event: string, arg1: T1, arg2: T2)
fire<T1, T2, T3>(event: string, arg1: T1, arg2: T2, arg3: T3)
fire<T1, T2, T3, T4>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4)
fire<T1, T2, T3, T4, T5>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5)
fire<T1, T2, T3, T4, T5, T6>(event: string, arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5,
arg6: T6, ...rest: any[])
/**
* Bind an event like the bind method, but will remove the listener after it was fired.
* @param {String} ev Event name
* @param {Function} callback Callback
*/
once<T>(event: string, callback: Callback1<T>): this
once<T1, T2>(event: string, callback: Callback2<T1, T2>): this
once<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): this
once<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): this
once<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): this
once<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* emitLater
* make emit async
*/
emitLater<T>(event: string, callback: Callback1<T>): void
emitLater<T1, T2>(event: string, callback: Callback2<T1, T2>): void
emitLater<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): void
emitLater<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): void
emitLater<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): void
emitLater<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): void
/**
* Bind an event, and trigger it immediately.
* @param {String} ev Event name.
* @param {Function} callback Callback.
* @param {Mix} data The data that will be passed to calback as arguments.
*/
immediate<T>(event: string, callback: Callback1<T>, data: T): this
/**
* `immediate` alias, `asap`
*/
asap<T>(event: string, callback: Callback1<T>, data: T): this
/**
* Assign some events, after all events were fired, the callback will be executed once.
*
* Examples:
* ```js
* proxy.all(ev1, ev2, callback);
* proxy.all([ev1, ev2], callback);
* proxy.all(ev1, [ev2, ev3], callback);
* ```
* @param {String} eventname1 First event name.
* @param {String} eventname2 Second event name.
* @param {Function} callback Callback, that will be called after predefined events were fired.
*/
all(event1: string | string[], event2: string | string[], callback: Function)
all(event: string[] | string, callback: Function)
/**
* `all` alias
*/
assign(event1: string | string[], event2: string | string[], callback: Function)
assign(event: string[] | string, callback: Function)
/**
* Assign the only one 'error' event handler.
* @param {Function(err)} callback
*/
fail<T>(callback: ErrorHandler<T>)
fail<T1, T2>(callback: ErrorHandler2<T1, T2>)
fail<T1, T2, T3>(callback: ErrorHandler3<T1, T2, T3>)
fail<T1, T2, T3, T4>(callback: ErrorHandler4<T1, T2, T3, T4>)
fail<T1, T2, T3, T4, T5>(callback: ErrorHandler5<T1, T2, T3, T4, T5>)
fail<T1, T2, T3, T4, T5, T6>(callback: ErrorHandler6Rest<T1, T2, T3, T4, T5, T6>)
/**
* A shortcut of ep#emit('error', err)
*/
throw(...args: any[])
/**
* Assign some events, after all events were fired, the callback will be executed first time.
* Then any event that predefined be fired again, the callback will executed with the newest data.
* Examples:
* ```js
* proxy.tail(ev1, ev2, callback);
* proxy.tail([ev1, ev2], callback);
* proxy.tail(ev1, [ev2, ev3], callback);
* ```
* @param {String} eventname1 First event name.
* @param {String} eventname2 Second event name.
* @param {Function} callback Callback, that will be called after predefined events were fired.
*/
tail(event1: string | string[], event2: string | string[], callback: Function)
tail(event: string[] | string, callback: Function)
/**
* `tail` alias, assignAll
*/
assignAll(event1: string | string[], event2: string | string[], callback: Function)
assignAll(event: string[] | string, callback: Function)
/**
* `tail` alias, assignAlways
*/
assignAlways(event1: string | string[], event2: string | string[], callback: Function)
assignAlways(event: string[] | string, callback: Function)
/**
* The callback will be executed after the event be fired N times.
* @param {String} eventname Event name.
* @param {Number} times N times.
* @param {Function} callback Callback, that will be called after event was fired N times.
*/
after<T>(event: string, times: number, callback: Callback1<T>): this
after<T1, T2>(event: string, times: number, callback: Callback2<T1, T2>): this
after<T1, T2, T3>(event: string, times: number, callback: Callback3<T1, T2, T3>): this
after<T1, T2, T3, T4>(event: string, times: number, callback: Callback4<T1, T2, T3, T4>): this
after<T1, T2, T3, T4, T5>(event: string, times: number, callback: Callback5<T1, T2, T3, T4, T5>): this
after<T1, T2, T3, T4, T5, T6>(event: string, times: number, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>): this
/**
* The `after` method's helper. Use it will return ordered results.
* If you need manipulate result, you need callback
* Examples:
* ```js
* var ep = new EventProxy();
* ep.after('file', files.length, function (list) {
* // Ordered results
* });
* for (var i = 0; i < files.length; i++) {
* fs.readFile(files[i], 'utf-8', ep.group('file'));
* }
* ```
* @param {String} eventname Event name, shoule keep consistent with `after`.
* @param {Function} callback Callback function, should return the final result.
*/
group(event: string)
group<T1>(event: string, callback: Callback1<T1>): ErrorHandler<T1>
group<T1, T2>(event: string, callback: Callback2<T1, T2>): ErrorHandler2<T1, T2>
group<T1, T2, T3>(event: string, callback: Callback3<T1, T2, T3>): ErrorHandler3<T1, T2, T3>
group<T1, T2, T3, T4>(event: string, callback: Callback4<T1, T2, T3, T4>): ErrorHandler4<T1, T2, T3, T4>
group<T1, T2, T3, T4, T5>(event: string, callback: Callback5<T1, T2, T3, T4, T5>): ErrorHandler5<T1, T2, T3, T4, T5>
group<T1, T2, T3, T4, T5, T6>(event: string, callback: Callback6Rest<T1, T2, T3, T4, T5, T6>)
: ErrorHandler6Rest<T1, T2, T3, T4, T5, T6>
/**
* The callback will be executed after any registered event was fired. It only executed once.
* @param {String} eventname1 Event name.
* @param {String} eventname2 Event name.
* @param {Function} callback The callback will get a map that has data and eventname attributes.
*/
any<T1>(ev1: string, callback: Callback1<T1>)
any<T1, T2>(ev1: string, ev2: string, callback: Callback2<T1, T2>)
any<T1, T2, T3>(ev1: string, ev2: string, ev3: string, callback: Callback3<T1, T2, T3>)
any<T1, T2, T3, T4>(ev1: string, ev2: string, ev3: string, ev4: string, callback: Callback4<T1, T2, T3, T4>)
any<T1, T2, T3, T4, T5>(ev1: string, ev2: string, ev3: string, ev4: string, ev5: string,
callback: Callback5<T1, T2, T3, T4, T5>)
any<T1, T2, T3, T4, T5, T6>(ev1: string, ev2: string, ev3: string, ev4: string, ev5: string, ev6: string,
...rest: (string | Callback6Rest<T1, T2, T3, T4, T5, T6>)[])
/**
* The callback will be executed when the event name not equals with assigned event.
* @param {String} eventname Event name.
* @param {Function} callback Callback.
*/
not(event: string, callback: Function)
/**
* Success callback wrapper, will handler err for you.
*
* ```js
* fs.readFile('foo.txt', ep.done('content'));
*
* // equal to =>
*
* fs.readFile('foo.txt', function (err, content) {
* if (err) {
* return ep.emit('error', err);
* }
* ep.emit('content', content);
* });
* ```
*
* ```js
* fs.readFile('foo.txt', ep.done('content', function (content) {
* return content.trim();
* }));
*
* // equal to =>
*
* fs.readFile('foo.txt', function (err, content) {
* if (err) {
* return ep.emit('error', err);
* }
* ep.emit('content', content.trim());
* });
* ```
* @param {Function|String} handler, success callback or event name will be emit after callback.
* @return {Function}
*/
done(handler: Function | string, callback?: Function)
/**
* make done async
* @return {Function} delay done
*/
doneLater(handler: Function | string, callback?: Function)
}
export default EventProxy | the_stack |
* @file Viewer for a group of layers.
*/
import './layer_group_viewer.css';
import debounce from 'lodash/debounce';
import {DataPanelLayoutContainer, InputEventBindings as DataPanelInputEventBindings} from 'neuroglancer/data_panel_layout';
import {DisplayContext} from 'neuroglancer/display_context';
import {LayerListSpecification, LayerSubsetSpecification, MouseSelectionState, SelectedLayerState} from 'neuroglancer/layer';
import {DisplayPose, LinkedDepthRange, LinkedDisplayDimensions, LinkedOrientationState, LinkedPosition, LinkedRelativeDisplayScales, linkedStateLegacyJsonView, LinkedZoomState, NavigationState, TrackableCrossSectionZoom, TrackableNavigationLink, TrackableProjectionZoom, WatchableDisplayDimensionRenderInfo} from 'neuroglancer/navigation_state';
import {RenderLayerRole} from 'neuroglancer/renderlayer';
import {TrackableBoolean} from 'neuroglancer/trackable_boolean';
import {WatchableSet, WatchableValueInterface} from 'neuroglancer/trackable_value';
import {ContextMenu} from 'neuroglancer/ui/context_menu';
import {popDragStatus, pushDragStatus} from 'neuroglancer/ui/drag_and_drop';
import {LayerBar} from 'neuroglancer/ui/layer_bar';
import {endLayerDrag, getDropEffectFromModifiers, startLayerDrag} from 'neuroglancer/ui/layer_drag_and_drop';
import {setupPositionDropHandlers} from 'neuroglancer/ui/position_drag_and_drop';
import {AutomaticallyFocusedElement} from 'neuroglancer/util/automatic_focus';
import {TrackableRGB} from 'neuroglancer/util/color';
import {Borrowed, Owned, RefCounted} from 'neuroglancer/util/disposable';
import {removeChildren} from 'neuroglancer/util/dom';
import {dispatchEventAction, registerActionListener} from 'neuroglancer/util/event_action_map';
import {CompoundTrackable, optionallyRestoreFromJsonMember} from 'neuroglancer/util/trackable';
import {WatchableVisibilityPriority} from 'neuroglancer/visibility_priority/frontend';
import {EnumSelectWidget} from 'neuroglancer/widget/enum_widget';
import {TrackableScaleBarOptions} from 'neuroglancer/widget/scale_bar';
declare var NEUROGLANCER_SHOW_LAYER_BAR_EXTRA_BUTTONS: boolean|undefined;
export interface LayerGroupViewerState {
display: Borrowed<DisplayContext>;
navigationState: Owned<NavigationState>;
perspectiveNavigationState: Owned<NavigationState>;
mouseState: MouseSelectionState;
showAxisLines: TrackableBoolean;
wireFrame: TrackableBoolean;
showScaleBar: TrackableBoolean;
scaleBarOptions: TrackableScaleBarOptions;
showPerspectiveSliceViews: TrackableBoolean;
layerSpecification: Owned<LayerListSpecification>;
inputEventBindings: DataPanelInputEventBindings;
visibility: WatchableVisibilityPriority;
selectedLayer: SelectedLayerState;
visibleLayerRoles: WatchableSet<RenderLayerRole>;
crossSectionBackgroundColor: TrackableRGB;
perspectiveViewBackgroundColor: TrackableRGB;
}
export interface LayerGroupViewerOptions {
showLayerPanel: WatchableValueInterface<boolean>;
showViewerMenu: boolean;
showLayerHoverValues: WatchableValueInterface<boolean>;
}
export const viewerDragType = 'neuroglancer-layer-group-viewer';
export function hasViewerDrag(event: DragEvent) {
return event.dataTransfer!.types.indexOf(viewerDragType) !== -1;
}
let dragSource: {viewer: LayerGroupViewer, disposer: () => void}|undefined;
export function getCompatibleViewerDragSource(manager: Borrowed<LayerListSpecification>):
LayerGroupViewer|undefined {
if (dragSource && dragSource.viewer.layerSpecification.rootLayers === manager.rootLayers) {
return dragSource.viewer;
} else {
return undefined;
}
}
export function getViewerDropEffect(event: DragEvent, manager: Borrowed<LayerListSpecification>):
{dropEffect: 'move'|'copy', dropEffectMessage: string} {
const source = getCompatibleViewerDragSource(manager);
let defaultDropEffect: 'move'|'copy';
let moveAllowed = false;
if (source === undefined || source.layerSpecification === source.layerSpecification.root) {
// Either drag source is from another window, or there is only a single layer group. If the
// drag source is from another window, move is not supported because we cannot reliably
// communicate the drop effect back to the source window anyway. If there is only a single
// layer group, move is not supported since it would be a no-op.
defaultDropEffect = 'copy';
} else {
moveAllowed = true;
defaultDropEffect = 'move';
}
return getDropEffectFromModifiers(event, defaultDropEffect, moveAllowed);
}
export class LinkedViewerNavigationState extends RefCounted {
position: LinkedPosition;
relativeDisplayScales: LinkedRelativeDisplayScales;
displayDimensions: LinkedDisplayDimensions;
displayDimensionRenderInfo: WatchableDisplayDimensionRenderInfo;
crossSectionOrientation: LinkedOrientationState;
crossSectionScale: LinkedZoomState<TrackableCrossSectionZoom>;
projectionOrientation: LinkedOrientationState;
projectionScale: LinkedZoomState<TrackableProjectionZoom>;
crossSectionDepthRange: LinkedDepthRange;
projectionDepthRange: LinkedDepthRange;
navigationState: NavigationState;
projectionNavigationState: NavigationState;
constructor(parent: {
navigationState: Borrowed<NavigationState>,
perspectiveNavigationState: Borrowed<NavigationState>
}) {
super();
this.relativeDisplayScales =
new LinkedRelativeDisplayScales(parent.navigationState.pose.relativeDisplayScales.addRef());
this.displayDimensions =
new LinkedDisplayDimensions(parent.navigationState.pose.displayDimensions.addRef());
this.position = new LinkedPosition(parent.navigationState.position.addRef());
this.crossSectionOrientation =
new LinkedOrientationState(parent.navigationState.pose.orientation.addRef());
this.displayDimensionRenderInfo = this.registerDisposer(new WatchableDisplayDimensionRenderInfo(
this.relativeDisplayScales.value, this.displayDimensions.value));
this.crossSectionScale = new LinkedZoomState(
parent.navigationState.zoomFactor.addRef() as TrackableCrossSectionZoom,
this.displayDimensionRenderInfo.addRef());
this.crossSectionDepthRange = new LinkedDepthRange(
parent.navigationState.depthRange.addRef(), this.displayDimensionRenderInfo);
this.projectionDepthRange = new LinkedDepthRange(
parent.perspectiveNavigationState.depthRange.addRef(), this.displayDimensionRenderInfo);
this.navigationState = this.registerDisposer(new NavigationState(
new DisplayPose(
this.position.value, this.displayDimensionRenderInfo.addRef(),
this.crossSectionOrientation.value),
this.crossSectionScale.value, this.crossSectionDepthRange.value));
this.projectionOrientation =
new LinkedOrientationState(parent.perspectiveNavigationState.pose.orientation.addRef());
this.projectionScale = new LinkedZoomState(
parent.perspectiveNavigationState.zoomFactor.addRef() as TrackableProjectionZoom,
this.displayDimensionRenderInfo.addRef());
this.projectionNavigationState = this.registerDisposer(new NavigationState(
new DisplayPose(
this.position.value.addRef(), this.displayDimensionRenderInfo.addRef(),
this.projectionOrientation.value),
this.projectionScale.value, this.projectionDepthRange.value));
}
copyToParent() {
for (const x
of [this.relativeDisplayScales,
this.displayDimensions,
this.position,
this.crossSectionOrientation,
this.crossSectionScale,
this.projectionOrientation,
this.projectionScale,
]) {
x.copyToPeer();
}
}
register(state: CompoundTrackable) {
state.add('dimensionRenderScales', this.relativeDisplayScales);
state.add('displayDimensions', this.displayDimensions);
state.add('position', linkedStateLegacyJsonView(this.position));
state.add('crossSectionOrientation', this.crossSectionOrientation);
state.add('crossSectionScale', this.crossSectionScale);
state.add('crossSectionDepth', this.crossSectionDepthRange);
state.add('projectionOrientation', this.projectionOrientation);
state.add('projectionScale', this.projectionScale);
state.add('projectionDepth', this.projectionDepthRange);
}
}
function makeViewerMenu(parent: HTMLElement, viewer: LayerGroupViewer) {
const contextMenu = new ContextMenu(parent);
const menu = contextMenu.element;
menu.classList.add('neuroglancer-layer-group-viewer-context-menu');
const closeButton = document.createElement('button');
closeButton.textContent = 'Remove layer group';
menu.appendChild(closeButton);
contextMenu.registerEventListener(closeButton, 'click', () => {
viewer.layerSpecification.layerManager.clear();
});
const {viewerNavigationState} = viewer;
for (const [name, model] of <[string, TrackableNavigationLink][]>[
['Render scale factors', viewerNavigationState.relativeDisplayScales.link],
['Render dimensions', viewerNavigationState.displayDimensions.link],
['Position', viewerNavigationState.position.link],
['Cross-section orientation', viewerNavigationState.crossSectionOrientation.link],
['Cross-section zoom', viewerNavigationState.crossSectionScale.link],
['Cross-section depth range', viewerNavigationState.crossSectionDepthRange.link],
['3-D projection orientation', viewerNavigationState.projectionOrientation.link],
['3-D projection zoom', viewerNavigationState.projectionScale.link],
['3-D projection depth range', viewerNavigationState.projectionDepthRange.link],
]) {
const widget = contextMenu.registerDisposer(new EnumSelectWidget(model));
const label = document.createElement('label');
label.style.display = 'flex';
label.style.flexDirection = 'row';
label.style.whiteSpace = 'nowrap';
label.textContent = name;
label.appendChild(widget.element);
menu.appendChild(label);
}
return contextMenu;
}
export class LayerGroupViewer extends RefCounted {
layerSpecification: LayerListSpecification;
viewerNavigationState: LinkedViewerNavigationState;
get perspectiveNavigationState() {
return this.viewerNavigationState.projectionNavigationState;
}
get navigationState() {
return this.viewerNavigationState.navigationState;
}
get selectionDetailsState() {
return this.layerSpecification.root.selectionState;
}
// FIXME: don't make viewerState a property, just make these things properties directly
get display() {
return this.viewerState.display;
}
get selectedLayer() {
return this.viewerState.selectedLayer;
}
get layerManager() {
return this.layerSpecification.layerManager;
}
get chunkManager() {
return this.layerSpecification.chunkManager;
}
get mouseState() {
return this.viewerState.mouseState;
}
get showAxisLines() {
return this.viewerState.showAxisLines;
}
get wireFrame() {
return this.viewerState.wireFrame;
}
get showScaleBar() {
return this.viewerState.showScaleBar;
}
get showPerspectiveSliceViews() {
return this.viewerState.showPerspectiveSliceViews;
}
get inputEventBindings() {
return this.viewerState.inputEventBindings;
}
get visibility() {
return this.viewerState.visibility;
}
get visibleLayerRoles() {
return this.viewerState.visibleLayerRoles;
}
get crossSectionBackgroundColor() {
return this.viewerState.crossSectionBackgroundColor;
}
get perspectiveViewBackgroundColor() {
return this.viewerState.perspectiveViewBackgroundColor;
}
get scaleBarOptions() {
return this.viewerState.scaleBarOptions;
}
layerPanel: LayerBar|undefined;
layout: DataPanelLayoutContainer;
options: LayerGroupViewerOptions;
state = new CompoundTrackable();
get changed() {
return this.state.changed;
}
constructor(
public element: HTMLElement, public viewerState: LayerGroupViewerState,
options: Partial<LayerGroupViewerOptions> = {}) {
super();
this.options = {
showLayerPanel: new TrackableBoolean(true),
showViewerMenu: false,
showLayerHoverValues: new TrackableBoolean(true),
...options
};
this.layerSpecification = this.registerDisposer(viewerState.layerSpecification);
this.viewerNavigationState =
this.registerDisposer(new LinkedViewerNavigationState(viewerState));
this.viewerNavigationState.register(this.state);
if (!(this.layerSpecification instanceof LayerSubsetSpecification)) {
this.state.add('layers', {
changed: this.layerSpecification.changed,
toJSON: () => this.layerSpecification.layerManager.managedLayers.map(x => x.name),
reset: () => {
throw new Error('not implemented');
},
restoreState: () => {
throw new Error('not implemented');
}
});
} else {
this.state.add('layers', this.layerSpecification);
}
element.classList.add('neuroglancer-layer-group-viewer');
this.registerDisposer(new AutomaticallyFocusedElement(element));
this.layout = this.registerDisposer(new DataPanelLayoutContainer(this, 'xy'));
this.state.add('layout', this.layout);
this.registerActionBindings();
this.registerDisposer(this.layerManager.useDirectly());
this.registerDisposer(setupPositionDropHandlers(element, this.navigationState.position));
this.registerDisposer(this.options.showLayerPanel.changed.add(
this.registerCancellable(debounce(() => this.updateUI(), 0))));
this.makeUI();
}
bindAction(action: string, handler: () => void) {
this.registerDisposer(registerActionListener(this.element, action, handler));
}
private registerActionBindings() {
this.bindAction('add-layer', () => {
if (this.layerPanel) {
this.layerPanel.addLayerMenu();
}
});
this.bindAction('t-', () => {
this.navigationState.pose.translateNonDisplayDimension(0, -1);
});
this.bindAction('t+', () => {
this.navigationState.pose.translateNonDisplayDimension(0, +1);
});
}
toJSON(): any {
return {'type': 'viewer', ...this.state.toJSON()};
}
reset() {
this.state.reset();
}
restoreState(obj: unknown) {
this.state.restoreState(obj);
// Handle legacy properties
optionallyRestoreFromJsonMember(
obj, 'crossSectionZoom',
linkedStateLegacyJsonView(this.viewerNavigationState.crossSectionScale));
optionallyRestoreFromJsonMember(
obj, 'perspectiveZoom',
linkedStateLegacyJsonView(this.viewerNavigationState.projectionScale));
optionallyRestoreFromJsonMember(
obj, 'perspectiveOrientation', this.viewerNavigationState.projectionOrientation);
}
private makeUI() {
this.element.style.flex = '1';
this.element.style.display = 'flex';
this.element.style.flexDirection = 'column';
this.element.appendChild(this.layout.element);
this.updateUI();
}
private updateUI() {
const {options} = this;
const showLayerPanel = options.showLayerPanel.value;
if (this.layerPanel !== undefined && !showLayerPanel) {
this.layerPanel.dispose();
this.layerPanel = undefined;
return;
}
if (showLayerPanel && this.layerPanel === undefined) {
const layerPanel = this.layerPanel = new LayerBar(
this.display, this.layerSpecification, this.viewerNavigationState,
this.viewerState.selectedLayer.addRef(), () => this.layout.toJSON(),
this.options.showLayerHoverValues);
if (options.showViewerMenu) {
layerPanel.registerDisposer(makeViewerMenu(layerPanel.element, this));
layerPanel.element.title = 'Right click for options, drag to move/copy layer group.';
} else {
layerPanel.element.title = 'Drag to move/copy layer group.';
}
if (typeof NEUROGLANCER_SHOW_LAYER_BAR_EXTRA_BUTTONS !== 'undefined' &&
NEUROGLANCER_SHOW_LAYER_BAR_EXTRA_BUTTONS === true) {
{
const button = document.createElement('button');
button.textContent = 'Clear segments';
button.title = `De-select all objects ("x")`;
button.addEventListener('click', (event: MouseEvent) => {
dispatchEventAction(event, event, {action: 'clear-segments'});
});
layerPanel.element.appendChild(button);
}
for (const layout of ['3d', 'xy', 'xz', 'yz']) {
const button = document.createElement('button');
button.textContent = layout;
button.title = `Switch to ${layout} layout`;
button.addEventListener('click', () => {
let newLayout: string;
if (this.layout.name === layout) {
if (layout !== '3d') {
newLayout = `${layout}-3d`;
} else {
newLayout = '4panel';
}
} else {
newLayout = layout;
}
this.layout.name = newLayout;
});
layerPanel.element.appendChild(button);
}
}
layerPanel.element.draggable = true;
const layerPanelElement = layerPanel.element;
layerPanelElement.addEventListener('dragstart', (event: DragEvent) => {
pushDragStatus(
layerPanel.element, 'drag',
'Drag layer group to the left/top/right/bottom edge of a layer group, or to another layer bar/panel (including in another Neuroglancer window)');
startLayerDrag(event, {
manager: this.layerSpecification,
layers: this.layerManager.managedLayers,
layoutSpec: this.layout.toJSON(),
});
const disposer = () => {
if (dragSource && dragSource.viewer === this) {
dragSource = undefined;
}
this.unregisterDisposer(disposer);
};
dragSource = {viewer: this, disposer};
this.registerDisposer(disposer);
const dragData = this.toJSON();
delete dragData['layers'];
event.dataTransfer!.setData(viewerDragType, JSON.stringify(dragData));
layerPanel.element.style.backgroundColor = 'black';
setTimeout(() => {
layerPanel.element.style.backgroundColor = '';
}, 0);
});
layerPanel.element.addEventListener('dragend', () => {
popDragStatus(layerPanelElement, 'drag');
endLayerDrag();
if (dragSource !== undefined && dragSource.viewer === this) {
dragSource.disposer();
}
});
this.element.insertBefore(layerPanelElement, this.element.firstChild);
}
}
disposed() {
removeChildren(this.element);
const {layerPanel} = this;
if (layerPanel !== undefined) {
layerPanel.dispose();
this.layerPanel = undefined;
}
super.disposed();
}
} | the_stack |
import Observable, { ZenObservable } from 'zen-observable-ts';
import { GraphQLError } from 'graphql';
import * as url from 'url';
import { v4 as uuid } from 'uuid';
import { Buffer } from 'buffer';
import { ProviderOptions } from '../../types';
import {
Logger,
Credentials,
Signer,
Hub,
Constants,
USER_AGENT_HEADER,
jitteredExponentialRetry,
NonRetryableError,
ICredentials,
} from '@aws-amplify/core';
import Cache from '@aws-amplify/cache';
import Auth, { GRAPHQL_AUTH_MODE } from '@aws-amplify/auth';
import { AbstractPubSubProvider } from '../PubSubProvider';
import { CONTROL_MSG } from '../../index';
import {
AMPLIFY_SYMBOL,
AWS_APPSYNC_REALTIME_HEADERS,
CONNECTION_INIT_TIMEOUT,
DEFAULT_KEEP_ALIVE_TIMEOUT,
MAX_DELAY_MS,
MESSAGE_TYPES,
NON_RETRYABLE_CODES,
SOCKET_STATUS,
START_ACK_TIMEOUT,
SUBSCRIPTION_STATUS,
} from './constants';
const logger = new Logger('AWSAppSyncRealTimeProvider');
const dispatchApiEvent = (event: string, data: any, message: string) => {
Hub.dispatch('api', { event, data, message }, 'PubSub', AMPLIFY_SYMBOL);
};
export type ObserverQuery = {
observer: ZenObservable.SubscriptionObserver<any>;
query: string;
variables: object;
subscriptionState: SUBSCRIPTION_STATUS;
subscriptionReadyCallback?: Function;
subscriptionFailedCallback?: Function;
startAckTimeoutId?: ReturnType<typeof setTimeout>;
};
const standardDomainPattern =
/^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com\/graphql$/i;
const customDomainPath = '/realtime';
type GraphqlAuthModes = keyof typeof GRAPHQL_AUTH_MODE;
export interface AWSAppSyncRealTimeProviderOptions extends ProviderOptions {
appSyncGraphqlEndpoint?: string;
authenticationType?: GraphqlAuthModes;
query?: string;
variables?: object;
apiKey?: string;
region?: string;
graphql_headers?: () => {} | (() => Promise<{}>);
additionalHeaders?: { [key: string]: string };
}
type AWSAppSyncRealTimeAuthInput =
Partial<AWSAppSyncRealTimeProviderOptions> & {
canonicalUri: string;
payload: string;
};
export class AWSAppSyncRealTimeProvider extends AbstractPubSubProvider {
private awsRealTimeSocket?: WebSocket;
private socketStatus: SOCKET_STATUS = SOCKET_STATUS.CLOSED;
private keepAliveTimeoutId?: ReturnType<typeof setTimeout>;
private keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
private subscriptionObserverMap: Map<string, ObserverQuery> = new Map();
private promiseArray: Array<{ res: Function; rej: Function }> = [];
getNewWebSocket(url, protocol) {
return new WebSocket(url, protocol);
}
getProviderName() {
return 'AWSAppSyncRealTimeProvider';
}
newClient(): Promise<any> {
throw new Error('Not used here');
}
public async publish(_topics: string[] | string, _msg: any, _options?: any) {
throw new Error('Operation not supported');
}
// Check if url matches standard domain pattern
private isCustomDomain(url: string): boolean {
return url.match(standardDomainPattern) === null;
}
subscribe(
_topics: string[] | string,
options?: AWSAppSyncRealTimeProviderOptions
): Observable<any> {
const appSyncGraphqlEndpoint = options?.appSyncGraphqlEndpoint;
return new Observable(observer => {
if (!options || !appSyncGraphqlEndpoint) {
observer.error({
errors: [
{
...new GraphQLError(
`Subscribe only available for AWS AppSync endpoint`
),
},
],
});
observer.complete();
} else {
const subscriptionId = uuid();
this._startSubscriptionWithAWSAppSyncRealTime({
options,
observer,
subscriptionId,
}).catch<any>(err => {
observer.error({
errors: [
{
...new GraphQLError(
`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`
),
},
],
});
observer.complete();
});
return async () => {
// Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
try {
// Waiting that subscription has been connected before trying to unsubscribe
await this._waitForSubscriptionToBeConnected(subscriptionId);
const { subscriptionState } =
this.subscriptionObserverMap.get(subscriptionId) || {};
if (!subscriptionState) {
// subscription already unsubscribed
return;
}
if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
this._sendUnsubscriptionMessage(subscriptionId);
} else {
throw new Error('Subscription never connected');
}
} catch (err) {
logger.debug(`Error while unsubscribing ${err}`);
} finally {
this._removeSubscriptionObserver(subscriptionId);
}
};
}
});
}
protected get isSSLEnabled() {
return !this.options
.aws_appsync_dangerously_connect_to_http_endpoint_for_testing;
}
private async _startSubscriptionWithAWSAppSyncRealTime({
options,
observer,
subscriptionId,
}: {
options: AWSAppSyncRealTimeProviderOptions;
observer: ZenObservable.SubscriptionObserver<any>;
subscriptionId: string;
}) {
const {
appSyncGraphqlEndpoint,
authenticationType,
query,
variables,
apiKey,
region,
graphql_headers = () => ({}),
additionalHeaders = {},
} = options;
const subscriptionState: SUBSCRIPTION_STATUS = SUBSCRIPTION_STATUS.PENDING;
const data = {
query,
variables,
};
// Having a subscription id map will make it simple to forward messages received
this.subscriptionObserverMap.set(subscriptionId, {
observer,
query: query ?? '',
variables: variables ?? {},
subscriptionState,
startAckTimeoutId: undefined,
});
// Preparing payload for subscription message
const dataString = JSON.stringify(data);
const headerObj = {
...(await this._awsRealTimeHeaderBasedAuth({
apiKey,
appSyncGraphqlEndpoint,
authenticationType,
payload: dataString,
canonicalUri: '',
region,
additionalHeaders,
})),
...(await graphql_headers()),
...additionalHeaders,
[USER_AGENT_HEADER]: Constants.userAgent,
};
const subscriptionMessage = {
id: subscriptionId,
payload: {
data: dataString,
extensions: {
authorization: {
...headerObj,
},
},
},
type: MESSAGE_TYPES.GQL_START,
};
const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
try {
await this._initializeWebSocketConnection({
apiKey,
appSyncGraphqlEndpoint,
authenticationType,
region,
additionalHeaders,
});
} catch (err) {
logger.debug({ err });
const message = err['message'] ?? '';
observer.error({
errors: [
{
...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
},
],
});
observer.complete();
const { subscriptionFailedCallback } =
this.subscriptionObserverMap.get(subscriptionId) || {};
// Notify concurrent unsubscription
if (typeof subscriptionFailedCallback === 'function') {
subscriptionFailedCallback();
}
return;
}
// Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
// E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
// Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
const { subscriptionFailedCallback, subscriptionReadyCallback } =
this.subscriptionObserverMap.get(subscriptionId) ?? {};
// This must be done before sending the message in order to be listening immediately
this.subscriptionObserverMap.set(subscriptionId, {
observer,
subscriptionState,
query: query ?? '',
variables: variables ?? {},
subscriptionReadyCallback,
subscriptionFailedCallback,
startAckTimeoutId: setTimeout(() => {
this._timeoutStartSubscriptionAck.call(this, subscriptionId);
}, START_ACK_TIMEOUT),
});
if (this.awsRealTimeSocket) {
this.awsRealTimeSocket.send(stringToAWSRealTime);
}
}
// Waiting that subscription has been connected before trying to unsubscribe
private async _waitForSubscriptionToBeConnected(subscriptionId: string) {
const subscriptionObserver =
this.subscriptionObserverMap.get(subscriptionId);
if (subscriptionObserver) {
const { subscriptionState } = subscriptionObserver;
// This in case unsubscribe is invoked before sending start subscription message
if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
return new Promise((res, rej) => {
const { observer, subscriptionState, variables, query } =
subscriptionObserver;
this.subscriptionObserverMap.set(subscriptionId, {
observer,
subscriptionState,
variables,
query,
subscriptionReadyCallback: res,
subscriptionFailedCallback: rej,
});
});
}
}
}
private _sendUnsubscriptionMessage(subscriptionId: string) {
try {
if (
this.awsRealTimeSocket &&
this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
this.socketStatus === SOCKET_STATUS.READY
) {
// Preparing unsubscribe message to stop receiving messages for that subscription
const unsubscribeMessage = {
id: subscriptionId,
type: MESSAGE_TYPES.GQL_STOP,
};
const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
this.awsRealTimeSocket.send(stringToAWSRealTime);
}
} catch (err) {
// If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
logger.debug({ err });
}
}
private _removeSubscriptionObserver(subscriptionId: string) {
this.subscriptionObserverMap.delete(subscriptionId);
// Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
}
private _closeSocketIfRequired() {
if (this.subscriptionObserverMap.size > 0) {
// Active subscriptions on the WebSocket
return;
}
if (!this.awsRealTimeSocket) {
this.socketStatus = SOCKET_STATUS.CLOSED;
return;
}
if (this.awsRealTimeSocket.bufferedAmount > 0) {
// Still data on the WebSocket
setTimeout(this._closeSocketIfRequired.bind(this), 1000);
} else {
logger.debug('closing WebSocket...');
if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
const tempSocket = this.awsRealTimeSocket;
// Cleaning callbacks to avoid race condition, socket still exists
tempSocket.onclose = null;
tempSocket.onerror = null;
tempSocket.close(1000);
this.awsRealTimeSocket = undefined;
this.socketStatus = SOCKET_STATUS.CLOSED;
}
}
private _handleIncomingSubscriptionMessage(message: MessageEvent) {
logger.debug(
`subscription message from AWS AppSync RealTime: ${message.data}`
);
const { id = '', payload, type } = JSON.parse(message.data);
const {
observer = null,
query = '',
variables = {},
startAckTimeoutId,
subscriptionReadyCallback,
subscriptionFailedCallback,
} = this.subscriptionObserverMap.get(id) || {};
logger.debug({ id, observer, query, variables });
if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
if (observer) {
observer.next(payload);
} else {
logger.debug(`observer not found for id: ${id}`);
}
return;
}
if (type === MESSAGE_TYPES.GQL_START_ACK) {
logger.debug(
`subscription ready for ${JSON.stringify({ query, variables })}`
);
if (typeof subscriptionReadyCallback === 'function') {
subscriptionReadyCallback();
}
if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
dispatchApiEvent(
CONTROL_MSG.SUBSCRIPTION_ACK,
{ query, variables },
'Connection established for subscription'
);
const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
if (observer) {
this.subscriptionObserverMap.set(id, {
observer,
query,
variables,
startAckTimeoutId: undefined,
subscriptionState,
subscriptionReadyCallback,
subscriptionFailedCallback,
});
}
// TODO: emit event on hub but it requires to store the id first
return;
}
if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
if (this.keepAliveTimeoutId) clearTimeout(this.keepAliveTimeoutId);
this.keepAliveTimeoutId = setTimeout(
this._errorDisconnect.bind(this, CONTROL_MSG.TIMEOUT_DISCONNECT),
this.keepAliveTimeout
);
return;
}
if (type === MESSAGE_TYPES.GQL_ERROR) {
const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
if (observer) {
this.subscriptionObserverMap.set(id, {
observer,
query,
variables,
startAckTimeoutId,
subscriptionReadyCallback,
subscriptionFailedCallback,
subscriptionState,
});
observer.error({
errors: [
{
...new GraphQLError(
`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`
),
},
],
});
if (startAckTimeoutId) clearTimeout(startAckTimeoutId);
observer.complete();
if (typeof subscriptionFailedCallback === 'function') {
subscriptionFailedCallback();
}
}
}
}
private _errorDisconnect(msg: string) {
logger.debug(`Disconnect error: ${msg}`);
this.subscriptionObserverMap.forEach(({ observer }) => {
if (observer && !observer.closed) {
observer.error({
errors: [{ ...new GraphQLError(msg) }],
});
}
});
this.subscriptionObserverMap.clear();
if (this.awsRealTimeSocket) {
this.awsRealTimeSocket.close();
}
this.socketStatus = SOCKET_STATUS.CLOSED;
}
private _timeoutStartSubscriptionAck(subscriptionId: string) {
const subscriptionObserver =
this.subscriptionObserverMap.get(subscriptionId);
if (subscriptionObserver) {
const { observer, query, variables } = subscriptionObserver;
if (!observer) {
return;
}
this.subscriptionObserverMap.set(subscriptionId, {
observer,
query,
variables,
subscriptionState: SUBSCRIPTION_STATUS.FAILED,
});
if (observer && !observer.closed) {
observer.error({
errors: [
{
...new GraphQLError(
`Subscription timeout ${JSON.stringify({
query,
variables,
})}`
),
},
],
});
// Cleanup will be automatically executed
observer.complete();
}
logger.debug(
'timeoutStartSubscription',
JSON.stringify({ query, variables })
);
}
}
private _initializeWebSocketConnection({
appSyncGraphqlEndpoint,
authenticationType,
apiKey,
region,
additionalHeaders,
}: AWSAppSyncRealTimeProviderOptions) {
if (this.socketStatus === SOCKET_STATUS.READY) {
return;
}
return new Promise(async (res, rej) => {
this.promiseArray.push({ res, rej });
if (this.socketStatus === SOCKET_STATUS.CLOSED) {
try {
this.socketStatus = SOCKET_STATUS.CONNECTING;
const payloadString = '{}';
const headerString = JSON.stringify(
await this._awsRealTimeHeaderBasedAuth({
authenticationType,
payload: payloadString,
canonicalUri: '/connect',
apiKey,
appSyncGraphqlEndpoint,
region,
additionalHeaders,
})
);
const headerQs = Buffer.from(headerString).toString('base64');
const payloadQs = Buffer.from(payloadString).toString('base64');
let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
if (this.isCustomDomain(discoverableEndpoint)) {
discoverableEndpoint =
discoverableEndpoint.concat(customDomainPath);
} else {
discoverableEndpoint = discoverableEndpoint
.replace('appsync-api', 'appsync-realtime-api')
.replace('gogi-beta', 'grt-beta');
}
// Creating websocket url with required query strings
const protocol = this.isSSLEnabled ? 'wss://' : 'ws://';
discoverableEndpoint = discoverableEndpoint
.replace('https://', protocol)
.replace('http://', protocol);
const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
await this._initializeRetryableHandshake(awsRealTimeUrl);
this.promiseArray.forEach(({ res }) => {
logger.debug('Notifying connection successful');
res();
});
this.socketStatus = SOCKET_STATUS.READY;
this.promiseArray = [];
} catch (err) {
this.promiseArray.forEach(({ rej }) => rej(err));
this.promiseArray = [];
if (
this.awsRealTimeSocket &&
this.awsRealTimeSocket.readyState === WebSocket.OPEN
) {
this.awsRealTimeSocket.close(3001);
}
this.awsRealTimeSocket = undefined;
this.socketStatus = SOCKET_STATUS.CLOSED;
}
}
});
}
private async _initializeRetryableHandshake(awsRealTimeUrl: string) {
logger.debug(`Initializaling retryable Handshake`);
await jitteredExponentialRetry(
this._initializeHandshake.bind(this),
[awsRealTimeUrl],
MAX_DELAY_MS
);
}
private async _initializeHandshake(awsRealTimeUrl: string) {
logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
// Because connecting the socket is async, is waiting until connection is open
// Step 1: connect websocket
try {
await (() => {
return new Promise<void>((res, rej) => {
const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
newSocket.onerror = () => {
logger.debug(`WebSocket connection error`);
};
newSocket.onclose = () => {
rej(new Error('Connection handshake error'));
};
newSocket.onopen = () => {
this.awsRealTimeSocket = newSocket;
return res();
};
});
})();
// Step 2: wait for ack from AWS AppSyncReaTime after sending init
await (() => {
return new Promise((res, rej) => {
if (this.awsRealTimeSocket) {
let ackOk = false;
this.awsRealTimeSocket.onerror = error => {
logger.debug(`WebSocket error ${JSON.stringify(error)}`);
};
this.awsRealTimeSocket.onclose = event => {
logger.debug(`WebSocket closed ${event.reason}`);
rej(new Error(JSON.stringify(event)));
};
this.awsRealTimeSocket.onmessage = (message: MessageEvent) => {
logger.debug(
`subscription message from AWS AppSyncRealTime: ${message.data} `
);
const data = JSON.parse(message.data);
const {
type,
payload: {
connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT,
} = {},
} = data;
if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
ackOk = true;
if (this.awsRealTimeSocket) {
this.keepAliveTimeout = connectionTimeoutMs;
this.awsRealTimeSocket.onmessage =
this._handleIncomingSubscriptionMessage.bind(this);
this.awsRealTimeSocket.onerror = err => {
logger.debug(err);
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
};
this.awsRealTimeSocket.onclose = event => {
logger.debug(`WebSocket closed ${event.reason}`);
this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
};
}
res('Cool, connected to AWS AppSyncRealTime');
return;
}
if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
const {
payload: {
errors: [{ errorType = '', errorCode = 0 } = {}] = [],
} = {},
} = data;
rej({ errorType, errorCode });
}
};
const gqlInit = {
type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
};
this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
setTimeout(checkAckOk.bind(this, ackOk), CONNECTION_INIT_TIMEOUT);
}
function checkAckOk(ackOk: boolean) {
if (!ackOk) {
rej(
new Error(
`Connection timeout: ack from AWSRealTime was not received on ${CONNECTION_INIT_TIMEOUT} ms`
)
);
}
}
});
})();
} catch (err) {
const { errorType, errorCode } = err as {
errorType: string;
errorCode: number;
};
if (NON_RETRYABLE_CODES.includes(errorCode)) {
throw new NonRetryableError(errorType);
} else if (errorType) {
throw new Error(errorType);
} else {
throw err;
}
}
}
private async _awsRealTimeHeaderBasedAuth({
authenticationType,
payload,
canonicalUri,
appSyncGraphqlEndpoint,
apiKey,
region,
additionalHeaders,
}: AWSAppSyncRealTimeProviderOptions): Promise<any> {
const headerHandler: {
[key in GraphqlAuthModes]: (AWSAppSyncRealTimeAuthInput) => {};
} = {
API_KEY: this._awsRealTimeApiKeyHeader.bind(this),
AWS_IAM: this._awsRealTimeIAMHeader.bind(this),
OPENID_CONNECT: this._awsRealTimeOPENIDHeader.bind(this),
AMAZON_COGNITO_USER_POOLS: this._awsRealTimeCUPHeader.bind(this),
AWS_LAMBDA: this._customAuthHeader,
};
if (!authenticationType || !headerHandler[authenticationType]) {
logger.debug(`Authentication type ${authenticationType} not supported`);
return '';
} else {
const handler = headerHandler[authenticationType];
const { host } = url.parse(appSyncGraphqlEndpoint ?? '');
logger.debug(`Authenticating with ${authenticationType}`);
const result = await handler({
payload,
canonicalUri,
appSyncGraphqlEndpoint,
apiKey,
region,
host,
additionalHeaders,
});
return result;
}
}
private async _awsRealTimeCUPHeader({ host }: AWSAppSyncRealTimeAuthInput) {
const session = await Auth.currentSession();
return {
Authorization: session.getAccessToken().getJwtToken(),
host,
};
}
private async _awsRealTimeOPENIDHeader({
host,
}: AWSAppSyncRealTimeAuthInput) {
let token;
// backwards compatibility
const federatedInfo = await Cache.getItem('federatedInfo');
if (federatedInfo) {
token = federatedInfo.token;
} else {
const currentUser = await Auth.currentAuthenticatedUser();
if (currentUser) {
token = currentUser.token;
}
}
if (!token) {
throw new Error('No federated jwt');
}
return {
Authorization: token,
host,
};
}
private async _awsRealTimeApiKeyHeader({
apiKey,
host,
}: AWSAppSyncRealTimeAuthInput) {
const dt = new Date();
const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
return {
host,
'x-amz-date': dtStr,
'x-api-key': apiKey,
};
}
private async _awsRealTimeIAMHeader({
payload,
canonicalUri,
appSyncGraphqlEndpoint,
region,
}: AWSAppSyncRealTimeAuthInput) {
const endpointInfo = {
region,
service: 'appsync',
};
const credentialsOK = await this._ensureCredentials();
if (!credentialsOK) {
throw new Error('No credentials');
}
const creds = await Credentials.get().then((credentials: any) => {
const { secretAccessKey, accessKeyId, sessionToken } =
credentials as ICredentials;
return {
secret_key: secretAccessKey,
access_key: accessKeyId,
session_token: sessionToken,
};
});
const request = {
url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
data: payload,
method: 'POST',
headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
};
const signed_params = Signer.sign(request, creds, endpointInfo);
return signed_params.headers;
}
private _customAuthHeader({
host,
additionalHeaders,
}: AWSAppSyncRealTimeAuthInput) {
if (!additionalHeaders || !additionalHeaders['Authorization']) {
throw new Error('No auth token specified');
}
return {
Authorization: additionalHeaders.Authorization,
host,
};
}
/**
* @private
*/
_ensureCredentials() {
return Credentials.get()
.then((credentials: any) => {
if (!credentials) return false;
const cred = Credentials.shear(credentials);
logger.debug('set credentials for AWSAppSyncRealTimeProvider', cred);
return true;
})
.catch((err: any) => {
logger.warn('ensure credentials error', err);
return false;
});
}
} | the_stack |
* 图片段信息
*/
export interface ImageSegments {
/**
* 截帧时间。
点播文件:该值为相对于视频偏移时间,单位为秒,例如:0,5,10
直播流:该值为时间戳,例如:1594650717
*/
OffsetTime: string
/**
* 画面截帧结果详情
*/
Result: ImageResult
}
/**
* 图片输出结果的子结果
*/
export interface ImageResultResult {
/**
* 场景
Porn 色情
Sexy 性感
Polity 政治
Illegal 违法
Abuse 谩骂
Terror 暴恐
Ad 广告
注意:此字段可能返回 null,表示取不到有效值。
*/
Scene: string
/**
* 是否命中
0 未命中
1 命中
注意:此字段可能返回 null,表示取不到有效值。
*/
HitFlag: number
/**
* 审核建议,可选值:
Pass 通过,
Review 建议人审,
Block 确认违规
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 子标签
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabel: string
/**
* 分数
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 如果命中场景为涉政,则该数据为人物姓名列表,否则null
注意:此字段可能返回 null,表示取不到有效值。
*/
Names: Array<string>
/**
* 图片OCR文本
注意:此字段可能返回 null,表示取不到有效值。
*/
Text: string
/**
* 其他详情
注意:此字段可能返回 null,表示取不到有效值。
*/
Details: Array<ImageResultsResultDetail>
}
/**
* 数据存储信息
*/
export interface StorageInfo {
/**
* 类型 可选:
URL 资源链接类型
COS 腾讯云对象存储类型
*/
Type?: string
/**
* 资源链接
*/
Url?: string
/**
* 腾讯云存储桶信息
*/
BucketInfo?: BucketInfo
}
/**
* 文件桶信息
参考腾讯云存储相关说明 https://cloud.tencent.com/document/product/436/44352
*/
export interface BucketInfo {
/**
* 腾讯云对象存储,存储桶名称
*/
Bucket: string
/**
* 地域
*/
Region: string
/**
* 对象Key
*/
Object: string
}
/**
* CreateVideoModerationTask返回参数结构体
*/
export interface CreateVideoModerationTaskResponse {
/**
* 任务创建结果
注意:此字段可能返回 null,表示取不到有效值。
*/
Results?: Array<TaskResult>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 创建任务时的返回结果
*/
export interface TaskResult {
/**
* 请求时传入的DataId
注意:此字段可能返回 null,表示取不到有效值。
*/
DataId: string
/**
* TaskId,任务ID
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId: string
/**
* 错误码。如果code为OK,则表示创建成功,其他则参考公共错误码
注意:此字段可能返回 null,表示取不到有效值。
*/
Code: string
/**
* 如果错误,该字段表示错误详情
注意:此字段可能返回 null,表示取不到有效值。
*/
Message: string
}
/**
* CancelTask请求参数结构体
*/
export interface CancelTaskRequest {
/**
* 任务ID
*/
TaskId: string
}
/**
* DescribeTaskDetail返回参数结构体
*/
export interface DescribeTaskDetailResponse {
/**
* 任务Id
注意:此字段可能返回 null,表示取不到有效值。
*/
TaskId?: string
/**
* 审核时传入的数据Id
注意:此字段可能返回 null,表示取不到有效值。
*/
DataId?: string
/**
* 业务类型
注意:此字段可能返回 null,表示取不到有效值。
*/
BizType?: string
/**
* 任务名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Name?: string
/**
* 状态,可选值:
FINISH 已完成
PENDING 等待中
RUNNING 进行中
ERROR 出错
CANCELLED 已取消
注意:此字段可能返回 null,表示取不到有效值。
*/
Status?: string
/**
* 类型
注意:此字段可能返回 null,表示取不到有效值。
*/
Type?: string
/**
* 审核建议
可选:
Pass 通过
Reveiw 建议复审
Block 确认违规
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion?: string
/**
* 审核结果
注意:此字段可能返回 null,表示取不到有效值。
*/
Labels?: Array<TaskLabel>
/**
* 媒体解码信息
注意:此字段可能返回 null,表示取不到有效值。
*/
MediaInfo?: MediaInfo
/**
* 任务信息
注意:此字段可能返回 null,表示取不到有效值。
*/
InputInfo?: InputInfo
/**
* 创建时间
注意:此字段可能返回 null,表示取不到有效值。
*/
CreatedAt?: string
/**
* 更新时间
注意:此字段可能返回 null,表示取不到有效值。
*/
UpdatedAt?: string
/**
* 在秒后重试
注意:此字段可能返回 null,表示取不到有效值。
*/
TryInSeconds?: number
/**
* 图片结果
注意:此字段可能返回 null,表示取不到有效值。
*/
ImageSegments?: Array<ImageSegments>
/**
* 音频结果
注意:此字段可能返回 null,表示取不到有效值。
*/
AudioSegments?: Array<AudioSegments>
/**
* 如果返回的状态为ERROR,该字段会标记错误类型。
可选值::
DECODE_ERROR: 解码失败。(输入资源中可能包含无法解码的视频)
URL_ERROR:下载地址验证失败。
TIMEOUT_ERROR:处理超时。
注意:此字段可能返回 null,表示取不到有效值。
*/
ErrorType?: string
/**
* 审核任务错误日志。当Error不为空时,会展示该字段
注意:此字段可能返回 null,表示取不到有效值。
*/
ErrorDescription?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeVideoStat返回参数结构体
*/
export interface DescribeVideoStatResponse {
/**
* 识别结果统计
*/
Overview?: Overview
/**
* 识别量统计
*/
TrendCount?: Array<TrendCount>
/**
* 违规数据分布
*/
EvilCount?: Array<EvilCount>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateBizConfig返回参数结构体
*/
export interface CreateBizConfigResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 音视频任务结构
*/
export interface TaskInput {
/**
* 数据ID
*/
DataId?: string
/**
* 任务名
*/
Name?: string
/**
* 任务输入
*/
Input?: StorageInfo
}
/**
* DescribeTaskDetail请求参数结构体
*/
export interface DescribeTaskDetailRequest {
/**
* 任务ID,创建任务后返回的TaskId字段
*/
TaskId: string
/**
* 是否展示所有分片,默认只展示命中规则的分片
*/
ShowAllSegments?: boolean
}
/**
* 任务输出标签
*/
export interface TaskLabel {
/**
* 命中的标签
Porn 色情
Sexy 性感
Polity 政治
Illegal 违法
Abuse 谩骂
Terror 暴恐
Ad 广告
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 审核建议,可选值:
Pass 通过,
Review 建议人审,
Block 确认违规
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 得分,分数是 0 ~ 100
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
}
/**
* 具体场景下的图片识别结果
*/
export interface ImageResultsResultDetail {
/**
* 任务名称
注意:此字段可能返回 null,表示取不到有效值。
*/
Name: string
/**
* OCR识别文本
注意:此字段可能返回 null,表示取不到有效值。
*/
Text: string
/**
* 位置信息
注意:此字段可能返回 null,表示取不到有效值。
*/
Location: ImageResultsResultDetailLocation
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 库ID
注意:此字段可能返回 null,表示取不到有效值。
*/
LibId: string
/**
* 库名称
注意:此字段可能返回 null,表示取不到有效值。
*/
LibName: string
/**
* 命中的关键词
注意:此字段可能返回 null,表示取不到有效值。
*/
Keywords: Array<string>
/**
* 建议
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 得分
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 子标签码
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabelCode: string
}
/**
* DescribeVideoStat请求参数结构体
*/
export interface DescribeVideoStatRequest {
/**
* 审核类型 1: 机器审核; 2: 人工审核
*/
AuditType: number
/**
* 查询条件
*/
Filters: Array<Filters>
}
/**
* 输入信息详情
*/
export interface InputInfo {
/**
* 传入的类型可选:URL,COS
注意:此字段可能返回 null,表示取不到有效值。
*/
Type: string
/**
* Url地址
注意:此字段可能返回 null,表示取不到有效值。
*/
Url: string
/**
* 桶信息。当输入当时COS时,该字段不为空
注意:此字段可能返回 null,表示取不到有效值。
*/
BucketInfo: string
}
/**
* 违规数据分布
*/
export interface EvilCount {
/**
* 违规类型:
Terror 24001
Porn 20002
Polity 20001
Ad 20105
Abuse 20007
Illegal 20006
Spam 25001
Moan 26001
*/
EvilType: string
/**
* 分布类型总量
*/
Count: number
}
/**
* CreateVideoModerationTask请求参数结构体
*/
export interface CreateVideoModerationTaskRequest {
/**
* 业务类型, 定义 模版策略,输出存储配置。如果没有BizType,可以先参考 【创建业务配置】接口进行创建
*/
BizType: string
/**
* 任务类型:可选VIDEO(点播视频),LIVE_VIDEO(直播视频)
*/
Type: string
/**
* 输入的任务信息,最多可以同时创建10个任务
*/
Tasks: Array<TaskInput>
/**
* 回调签名key,具体可以查看签名文档。
*/
Seed?: string
/**
* 接收审核信息回调地址,如果设置,则审核过程中产生的违规音频片段和画面截帧发送此接口
*/
CallbackUrl?: string
/**
* 审核排队优先级。当您有多个视频审核任务排队时,可以根据这个参数控制排队优先级。用于处理插队等逻辑。默认该参数为0
*/
Priority?: number
}
/**
* 音频小语种检测结果
*/
export interface AudioResultDetailLanguageResult {
/**
* 语种
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 得分
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 开始时间
注意:此字段可能返回 null,表示取不到有效值。
*/
StartTime: number
/**
* 结束时间
注意:此字段可能返回 null,表示取不到有效值。
*/
EndTime: number
/**
* 子标签码
注意:此字段可能返回 null,表示取不到有效值。
*/
SubLabelCode: string
}
/**
* Cos FileOutput
*/
export interface FileOutput {
/**
* 存储的Bucket
*/
Bucket: string
/**
* Cos Region
*/
Region: string
/**
* 对象前缀
*/
ObjectPrefix: string
}
/**
* CancelTask返回参数结构体
*/
export interface CancelTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* 识别量统计
*/
export interface TrendCount {
/**
* 总调用量
*/
TotalCount: number
/**
* 总调用时长
*/
TotalHour: number
/**
* 通过量
*/
PassCount: number
/**
* 通过时长
*/
PassHour: number
/**
* 违规量
*/
EvilCount: number
/**
* 违规时长
*/
EvilHour: number
/**
* 疑似违规量
*/
SuspectCount: number
/**
* 疑似违规时长
*/
SuspectHour: number
/**
* 日期
*/
Date: string
}
/**
* 音频ASR文本审核结果
*/
export interface AudioResultDetailTextResult {
/**
* 标签
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 命中的关键词
注意:此字段可能返回 null,表示取不到有效值。
*/
Keywords: Array<string>
/**
* 命中的LibId
注意:此字段可能返回 null,表示取不到有效值。
*/
LibId: string
/**
* 命中的LibName
注意:此字段可能返回 null,表示取不到有效值。
*/
LibName: string
/**
* 得分
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 词库类型 1 黑白库 2 自定义库
注意:此字段可能返回 null,表示取不到有效值。
*/
LibType: number
/**
* 审核建议
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
}
/**
* 识别结果统计
*/
export interface Overview {
/**
* 总调用量
*/
TotalCount: number
/**
* 总调用时长
*/
TotalHour: number
/**
* 通过量
*/
PassCount: number
/**
* 通过时长
*/
PassHour: number
/**
* 违规量
*/
EvilCount: number
/**
* 违规时长
*/
EvilHour: number
/**
* 疑似违规量
*/
SuspectCount: number
/**
* 疑似违规时长
*/
SuspectHour: number
}
/**
* 音频输出参数
*/
export interface AudioResult {
/**
* 是否命中
0 未命中
1 命中
注意:此字段可能返回 null,表示取不到有效值。
*/
HitFlag: number
/**
* 命中的标签
Porn 色情
Polity 政治
Illegal 违法
Abuse 谩骂
Terror 暴恐
Ad 广告
Moan 呻吟
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 审核建议,可选值:
Pass 通过,
Review 建议人审,
Block 确认违规
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 得分,0-100
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 音频ASR文本
注意:此字段可能返回 null,表示取不到有效值。
*/
Text: string
/**
* 音频片段存储URL,有效期为1天
注意:此字段可能返回 null,表示取不到有效值。
*/
Url: string
/**
* 音频时长
注意:此字段可能返回 null,表示取不到有效值。
*/
Duration: string
/**
* 拓展字段
注意:此字段可能返回 null,表示取不到有效值。
*/
Extra: string
/**
* 文本审核结果
注意:此字段可能返回 null,表示取不到有效值。
*/
TextResults: Array<AudioResultDetailTextResult>
/**
* 音频呻吟审核结果
注意:此字段可能返回 null,表示取不到有效值。
*/
MoanResults: Array<AudioResultDetailMoanResult>
/**
* 音频语种检测结果
注意:此字段可能返回 null,表示取不到有效值。
*/
LanguageResults: Array<AudioResultDetailLanguageResult>
}
/**
* 音频呻吟审核结果
*/
export interface AudioResultDetailMoanResult {
/**
* 固定为Moan
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 分数
*/
Score: number
/**
* 开始时间
*/
StartTime: number
/**
* 结束时间
*/
EndTime: number
/**
* 子标签码
*/
SubLabelCode: string
}
/**
* CreateBizConfig请求参数结构体
*/
export interface CreateBizConfigRequest {
/**
* 业务ID,仅限英文字母、数字和下划线(_)组成,长度不超过8位
*/
BizType: string
/**
* 审核分类信息
*/
MediaModeration: MediaModerationConfig
/**
* 业务名称,用于标识业务场景,长度不超过32位
*/
BizName?: string
/**
* 审核内容,可选:Polity (政治); Porn (色情); Illegal(违法);Abuse (谩骂); Terror (暴恐); Ad (广告); Custom (自定义);
*/
ModerationCategories?: Array<string>
}
/**
* 媒体类型
*/
export interface MediaInfo {
/**
* 编码格式
*/
Codecs: string
/**
* 流检测时分片时长
注意:此字段可能返回 0,表示取不到有效值。
*/
Duration: number
/**
* 宽,单位为像素
*/
Width: number
/**
* 高,单位为像素
*/
Height: number
}
/**
* 媒体审核配置
*/
export interface MediaModerationConfig {
/**
* 是否使用OCR,默认为true
*/
UseOCR: boolean
/**
* 是否使用音频,默认为true。视频场景下,默认为 false
*/
UseAudio: boolean
/**
* 图片取帧频率, 单位(秒/帧),默认 5, 可选 1 ~ 300
*/
ImageFrequency?: number
/**
* 音频片段长度。单位为:秒
*/
AudioFrequency?: number
/**
* 临时文件存储位置
*/
SegmentOutput?: FileOutput
/**
* 回调地址
*/
CallbackUrl?: string
}
/**
* 声音段信息
*/
export interface AudioSegments {
/**
* 截帧时间。
点播文件:该值为相对于视频偏移时间,单位为秒,例如:0,5,10
直播流:该值为时间戳,例如:1594650717
注意:此字段可能返回 null,表示取不到有效值。
*/
OffsetTime: string
/**
* 结果集
注意:此字段可能返回 null,表示取不到有效值。
*/
Result: AudioResult
}
/**
* 视频过滤条件
*/
export interface Filters {
/**
* 查询字段:
策略BizType
子账号SubUin
日期区间DateRange
*/
Name: string
/**
* 查询值
*/
Values: Array<string>
}
/**
* 图片详情位置信息
*/
export interface ImageResultsResultDetailLocation {
/**
* x坐标
注意:此字段可能返回 null,表示取不到有效值。
*/
X: number
/**
* y坐标
注意:此字段可能返回 null,表示取不到有效值。
*/
Y: number
/**
* 宽度
注意:此字段可能返回 null,表示取不到有效值。
*/
Width: number
/**
* 高度
注意:此字段可能返回 null,表示取不到有效值。
*/
Height: number
/**
* 旋转角度
注意:此字段可能返回 null,表示取不到有效值。
*/
Rotate: number
}
/**
* Result结果详情
*/
export interface ImageResult {
/**
* 违规标志
0 未命中
1 命中
注意:此字段可能返回 null,表示取不到有效值。
*/
HitFlag: number
/**
* 命中的标签
Porn 色情
Sexy 性感
Polity 政治
Illegal 违法
Abuse 谩骂
Terror 暴恐
Ad 广告
注意:此字段可能返回 null,表示取不到有效值。
*/
Label: string
/**
* 审核建议,可选值:
Pass 通过,
Review 建议人审,
Block 确认违规
注意:此字段可能返回 null,表示取不到有效值。
*/
Suggestion: string
/**
* 得分
注意:此字段可能返回 null,表示取不到有效值。
*/
Score: number
/**
* 画面截帧图片结果集
注意:此字段可能返回 null,表示取不到有效值。
*/
Results: Array<ImageResultResult>
/**
* 图片URL地址
注意:此字段可能返回 null,表示取不到有效值。
*/
Url: string
/**
* 附加字段
注意:此字段可能返回 null,表示取不到有效值。
*/
Extra: string
} | the_stack |
import { jsx } from '@emotion/core';
import React, { useState, Fragment, useEffect } from 'react';
import formatMessage from 'format-message';
import {
Link,
PrimaryButton,
DefaultButton,
Pivot,
PivotItem,
Dialog,
DialogType,
Dropdown,
MessageBar,
MessageBarType,
MessageBarButton,
ScrollablePane,
ScrollbarVisibility,
Stack,
SearchBox,
IContextualMenuProps,
IDropdownOption,
} from 'office-ui-fabric-react';
import {
render,
useHttpClient,
useProjectApi,
useApplicationApi,
useTelemetryClient,
TelemetryClient,
} from '@bfc/extension-client';
import { Toolbar, IToolbarItem, LoadingSpinner, DisplayMarkdownDialog } from '@bfc/ui-shared';
import ReactMarkdown from 'react-markdown';
import {
ContentHeaderStyle,
HeaderText,
packageScrollContainerStyle,
tabAndSearchBarStyles,
} from '../components/styles';
import { ImportDialog } from '../components/ImportDialog';
import { LibraryRef, LibraryList, LetterIcon } from '../components/LibraryList';
import { WorkingModal } from '../components/WorkingModal';
import { FeedModal } from '../components/FeedModal';
import { ProjectList } from '../components/projectList/ProjectList';
const docsUrl = `https://aka.ms/composer-package-manager-readme`;
export interface PackageSourceFeed extends IDropdownOption {
name: string;
key: string;
url: string;
type: string;
defaultQuery?: {
prerelease: boolean;
semVerLevel: string;
query: string;
};
readonly?: boolean;
}
const Library: React.FC = () => {
const [items, setItems] = useState<LibraryRef[]>([]);
const { projectId, reloadProject, projectCollection: allProjectCollection, stopBot } = useProjectApi();
const { setApplicationLevelError, navigateTo, confirm } = useApplicationApi();
const telemetryClient: TelemetryClient = useTelemetryClient();
const projectCollection = allProjectCollection.filter((proj) => !proj.isRemote);
const startingProjectId = allProjectCollection.find((proj) => proj.projectId === projectId).isRemote
? projectCollection[0].projectId // this should always exist, because there's always at least a root bot
: projectId;
const [ejectedRuntime, setEjectedRuntime] = useState<boolean>(false);
const [availableLibraries, updateAvailableLibraries] = useState<LibraryRef[] | undefined>(undefined);
const [installedComponents, updateInstalledComponents] = useState<LibraryRef[]>([]);
const [isLoadingInstalled, setIsLoadingInstalled] = useState<boolean>(false);
const [recentlyUsed, setRecentlyUsed] = useState<LibraryRef[]>([]);
const [runtimeLanguage, setRuntimeLanguage] = useState<string>('c#');
const [feeds, updateFeeds] = useState<PackageSourceFeed[]>([]);
const [feed, setFeed] = useState<string | undefined>(undefined);
const [searchTerm, setSearchTerm] = useState<string>('');
const [loading, setLoading] = useState(false);
const [selectedItem, setSelectedItem] = useState<LibraryRef>();
const [selectedItemVersions, setSelectedItemVersions] = useState<string[]>([]);
const [selectedVersion, setSelectedVersion] = useState<string>('');
const [currentProjectId, setCurrentProjectId] = useState<string>(startingProjectId);
const [working, setWorking] = useState<string>('');
const [addDialogHidden, setAddDialogHidden] = useState(true);
const [isModalVisible, setModalVisible] = useState<boolean>(false);
const [readmeContent, setReadmeContent] = useState<string>('');
const [versionOptions, setVersionOptions] = useState<IContextualMenuProps | undefined>(undefined);
const [isUpdate, setIsUpdate] = useState<boolean>(false);
const [readmeHidden, setReadmeHidden] = useState<boolean>(true);
const httpClient = useHttpClient();
const API_ROOT = '';
const TABS = {
INSTALL: 'INSTALL',
BROWSE: 'BROWSE",',
};
const [currentTab, setCurrentTab] = useState<string>(TABS.BROWSE);
const strings = {
title: formatMessage('Package Manager'),
editFeeds: formatMessage('Edit feeds'),
description: formatMessage('Discover and use components that can be installed into your bot.'),
descriptionLink: formatMessage('Learn more'),
viewDocumentation: formatMessage('View documentation'),
installButton: formatMessage('Install'),
installToolbarButton: formatMessage('Add a package'),
updateButton: formatMessage('Update to'),
installed: formatMessage('installed'),
importDialogTitle: formatMessage('Add a package'),
installProgress: formatMessage('Installing package...'),
uninstallProgress: formatMessage('Removing package...'),
recentlyUsedCategory: formatMessage('Recently Used'),
installedCategory: formatMessage('Installed'),
updateConfirmationPrompt: formatMessage(
'Any changes you made to this package will be lost! Are you sure you want to continue?'
),
updateConfirmationTitle: formatMessage('Update Package'),
conflictConfirmationTitle: formatMessage('Conflicting changes detected'),
conflictConfirmationPrompt: formatMessage(
'This operation will overwrite changes made to previously imported files. Do you want to proceed?'
),
removeConfirmationTitle: formatMessage('Remove Package'),
removeConfirmationPrompt: formatMessage(
'Any changes you made to this package will be lost! In addition, this may leave your bot in a broken state. Are you sure you want to continue?'
),
requireEject: formatMessage(
'To install components, this project must have an ejected runtime. Please navigate to the project settings page, custom runtime section.'
),
ejectRuntime: formatMessage('Eject Runtime'),
noComponentsInstalled: formatMessage('No packages installed'),
noComponentsFound: formatMessage('No packages found'),
browseHeader: formatMessage('Browse'),
installHeader: formatMessage('Installed'),
libraryError: formatMessage('Package Manager Error'),
importError: formatMessage('Install Error'),
emptyPanel: formatMessage('Select an item from the list to view a detailed description.'),
};
const onChangeFeed = (ev, op, idx) => {
setFeed(op.key);
return true;
};
const installComponentAPI = (
projectId: string,
packageName: string,
version: string,
isUpdating: boolean,
source: string
) => {
return httpClient.post(`${API_ROOT}/projects/${projectId}/import`, {
package: packageName,
version: version,
source: source,
isUpdating,
});
};
const getLibraryAPI = () => {
const feedUrl = `${API_ROOT}/feed?key=${feed}`;
return httpClient.get(feedUrl);
};
const getSearchResults = () => {
const feedUrl = `${API_ROOT}/feed?key=${feed}&term=${encodeURIComponent(searchTerm)}`;
return httpClient.get(feedUrl);
};
const getFeeds = () => {
return httpClient.get(`${API_ROOT}/feeds`);
};
const getInstalledComponentsAPI = (projectId: string) => {
return httpClient.get(`${API_ROOT}/projects/${projectId}/installedComponents`);
};
const getReadmeAPI = (packageName: string) => {
return httpClient.get(`${API_ROOT}/readme/${packageName}`);
};
const uninstallComponentAPI = (projectId: string, packageName: string) => {
return httpClient.post(`${API_ROOT}/projects/${projectId}/unimport`, {
package: packageName,
});
};
const isCompatible = (component) => {
return component.language === runtimeLanguage;
};
useEffect(() => {
setCurrentProjectId(startingProjectId);
getFeeds().then((feeds) => updateFeeds(feeds.data));
}, []);
useEffect(() => {
getInstalledLibraries();
}, [currentProjectId]);
useEffect(() => {
if (!feed && feeds.length) {
if (runtimeLanguage === 'js') {
setFeed('npm');
} else {
setFeed('nuget');
}
}
}, [feeds, feeds, runtimeLanguage]);
useEffect(() => {
if (feed && feeds.length) {
getLibraries();
}
}, [feed, feeds, searchTerm]);
useEffect(() => {
const settings = projectCollection.find((b) => b.projectId === currentProjectId)?.setting;
if (settings?.runtime && settings.runtime.customRuntime === true && settings.runtime.path) {
setEjectedRuntime(true);
// detect programming language.
// should one day be a dynamic property of the runtime or at least stored in the settings?
if (settings.runtime.key === 'node-azurewebapp' || settings.runtime.key.startsWith('adaptive-runtime-js')) {
setRuntimeLanguage('js');
} else {
setRuntimeLanguage('c#');
}
} else {
setEjectedRuntime(false);
updateInstalledComponents([]);
}
}, [projectCollection, currentProjectId]);
useEffect(() => {
const items: any[] = [];
// find all categories listed in the available libraries
if (availableLibraries) {
const availableCompatibleLibraries = availableLibraries;
availableCompatibleLibraries.forEach((item) => {
item.isCompatible = isCompatible(item);
items.push(item);
});
}
setItems(items);
}, [installedComponents, availableLibraries, recentlyUsed]);
useEffect(() => {
if (selectedItem) {
if (selectedItem.language === 'js') {
// fetch the extended readme from npm
try {
getReadmeAPI(selectedItem.name).then((res) => {
// TODO: also process available versions, should be in payload
if (res.data.readme) {
setReadmeContent(res.data.readme);
} else {
setReadmeContent(selectedItem.description);
}
});
} catch (err) {
console.error(err);
setReadmeContent(selectedItem.description);
}
} else {
setReadmeContent(selectedItem.description);
let availversions;
let setversion;
if (selectedItem.versions && selectedItem.versions.length) {
availversions = selectedItem.versions;
} else {
availversions = [selectedItem.version];
}
setversion = availversions[0];
// default is that this not an update
setIsUpdate(false);
// is this item already installed? If so, set the selectedVersion to the INSTALLED version
if (isInstalled(selectedItem)) {
// Check if this is the newest, or if an update might be available
const indexOfVersion = availversions.indexOf(installedVersion(selectedItem));
if (indexOfVersion > 0) {
// there is an update!
setversion = availversions[0];
setIsUpdate(true);
} else {
// this is the latest version
setversion = installedVersion(selectedItem);
}
}
setSelectedItemVersions(availversions);
setSelectedVersion(setversion);
}
} else {
setReadmeContent('');
}
}, [selectedItem, installedComponents]);
useEffect(() => {
if (selectedItemVersions.length > 1) {
let installed = null;
if (isInstalled(selectedItem)) {
installed = installedVersion(selectedItem);
const indexOfInstalledVersion = selectedItemVersions.indexOf(installed);
const indexOfSelectedVersion = selectedItemVersions.indexOf(selectedVersion);
if (indexOfInstalledVersion > 0) {
if (indexOfInstalledVersion > indexOfSelectedVersion) {
setIsUpdate(true);
} else {
setIsUpdate(false);
}
}
}
setVersionOptions({
items: selectedItemVersions.map((v) => {
return {
key: v,
text: installed && installed === v ? `${v} (${strings.installed})` : v,
disabled: installed && installed === v,
iconProps: { iconName: v === selectedVersion ? 'Checkmark' : '' },
};
}),
onItemClick: (ev, item) => setSelectedVersion(item.key),
});
} else {
setVersionOptions(undefined);
}
}, [selectedItemVersions, selectedVersion, installedComponents]);
const toolbarItems: IToolbarItem[] = [
{
type: 'action',
text: strings.installToolbarButton,
buttonProps: {
iconProps: {
iconName: 'Add',
},
onClick: () => setAddDialogHidden(false),
},
align: 'left',
dataTestid: 'publishPage-ToolBar-Add',
disabled: !ejectedRuntime,
},
{
type: 'action',
text: strings.editFeeds,
buttonProps: {
iconProps: {
iconName: 'SingleColumnEdit',
},
onClick: () => setModalVisible(true),
},
align: 'left',
dataTestid: 'publishPage-ToolBar-EditFeeds',
},
];
const closeDialog = () => {
setAddDialogHidden(true);
};
const importFromWeb = async (packageName, version, isUpdating, source) => {
const existing = installedComponents?.find((l) => l.name === packageName);
let okToProceed = true;
if (existing) {
const title = strings.updateConfirmationTitle;
const msg = strings.updateConfirmationPrompt;
okToProceed = await confirm(title, msg);
}
if (okToProceed) {
closeDialog();
setWorking(strings.installProgress);
await importComponent(packageName, version, isUpdating || false, source);
setWorking('');
}
};
const importComponent = async (packageName, version, isUpdating, source) => {
try {
stopBot(currentProjectId);
const results = await installComponentAPI(currentProjectId, packageName, version, isUpdating, source);
// check to see if there was a conflict that requires confirmation
if (results.data.success === false) {
telemetryClient.track('PackageInstallConflictFound', {
package: packageName,
version: version,
isUpdate: isUpdating,
});
const title = strings.conflictConfirmationTitle;
const msg = strings.conflictConfirmationPrompt;
if (await confirm(title, msg)) {
telemetryClient.track('PackageInstallConflictResolved', {
package: packageName,
version: version,
isUpdate: isUpdating,
});
await installComponentAPI(currentProjectId, packageName, version, true, source);
}
} else {
telemetryClient.track('PackageInstalled', { package: packageName, version: version, isUpdate: isUpdating });
setWorking('');
updateInstalledComponents(results.data.components);
// find newly installed item
// and pop up the readme if one exists.
const newItem = results.data.components.find((i) => i.name === packageName);
if (newItem?.readme) {
setSelectedItem(newItem);
setReadmeHidden(false);
}
await reloadProject();
}
} catch (err) {
telemetryClient.track('PackageInstallFailed', { package: packageName, version: version, isUpdate: isUpdating });
console.error(err);
setApplicationLevelError({
status: err.response.status,
message: err.response && err.response.data.message ? err.response.data.message : err,
summary: strings.importError,
});
}
};
// return true if the name, description or any of the keywords match the search term
const applySearchTerm = (item: LibraryRef): boolean => {
// eslint-disable-next-line security/detect-non-literal-regexp
const term = new RegExp(searchTerm.trim().toLocaleLowerCase());
if (
item.name.toLowerCase().match(term) ||
item.description.toLowerCase().match(term) ||
item.keywords.filter((tag) => tag.toLowerCase().match(term)).length
)
return true;
return false;
};
const getLibraries = async () => {
try {
updateAvailableLibraries(undefined);
setLoading(true);
if (searchTerm) {
telemetryClient.track('PackageSearch', { term: searchTerm });
const response = await getSearchResults();
// if we are searching, apply a local filter
response.data.available = response.data.available.filter(applySearchTerm);
updateAvailableLibraries(response.data.available);
setRecentlyUsed(response.data.recentlyUsed);
} else {
const response = await getLibraryAPI();
updateAvailableLibraries(response.data.available);
setRecentlyUsed(response.data.recentlyUsed);
}
} catch (err) {
setApplicationLevelError({
status: err.response.status,
message: err.response && err.response.data.message ? err.response.data.message : err,
summary: strings.libraryError,
});
} finally {
setLoading(false);
}
};
const getInstalledLibraries = async () => {
if (!isLoadingInstalled) {
setIsLoadingInstalled(true);
try {
updateInstalledComponents([]);
const response = await getInstalledComponentsAPI(currentProjectId);
updateInstalledComponents(response.data.components);
} catch (err) {
setApplicationLevelError({
status: err.response.status,
message: err.response && err.response.data.message ? err.response.data.message : err,
summary: strings.libraryError,
});
}
setIsLoadingInstalled(false);
}
};
const install = async () => {
return importFromWeb(selectedItem?.name, selectedVersion, false, feeds.find((f) => f.key == feed).url);
};
const redownload = async () => {
return importFromWeb(selectedItem?.name, selectedVersion, true, feed);
};
const removeComponent = async () => {
if (selectedItem) {
const title = strings.removeConfirmationTitle;
const msg = strings.removeConfirmationPrompt;
const okToProceed = await confirm(title, msg);
if (okToProceed) {
closeDialog();
setWorking(strings.uninstallProgress);
try {
stopBot(currentProjectId);
const results = await uninstallComponentAPI(currentProjectId, selectedItem.name);
if (results.data.success) {
telemetryClient.track('PackageUninstalled', { package: selectedItem.name });
updateInstalledComponents(results.data.components);
} else {
throw new Error(results.data.message);
}
// reload modified content
await reloadProject();
} catch (err) {
telemetryClient.track('PackageUninstallFailed', { package: selectedItem.name });
if (err.response) {
setApplicationLevelError({
status: err.response.status,
message: err.response && err.response.data.message ? err.response.data.message : err,
summary: strings.importError,
});
} else {
setApplicationLevelError(err);
}
}
setWorking('');
}
}
};
const isInstalled = (item: LibraryRef): boolean => {
return installedComponents?.find((l) => l.name === item.name) != undefined;
};
const installedVersion = (item: LibraryRef): string => {
const installedItem = installedComponents?.find((l) => l.name === item.name);
return installedItem?.version ?? '';
};
const selectItem = (item: LibraryRef | null) => {
if (item) {
setSelectedItem(item);
} else {
setSelectedItem(undefined);
}
};
const navigateToEject = (evt: any): void => {
navigateTo(`/bot/${currentProjectId}/botProjectsSettings/#runtimeSettings`);
};
const updateFeed = async (feeds: PackageSourceFeed[]) => {
const response = await httpClient.post(`${API_ROOT}/feeds`, {
feeds,
});
// update the list of feeds in the component state
updateFeeds(response.data);
};
return (
<ScrollablePane scrollbarVisibility={ScrollbarVisibility.auto}>
<Dialog
dialogContentProps={{
title: strings.importDialogTitle,
type: DialogType.normal,
}}
hidden={addDialogHidden}
minWidth={450}
modalProps={{ isBlocking: true, isClickableOutsideFocusTrap: true }}
onDismiss={closeDialog}
>
<ImportDialog closeDialog={closeDialog} doImport={importFromWeb} />
</Dialog>
<WorkingModal hidden={working === ''} title={working} />
<FeedModal
closeDialog={() => setModalVisible(false)}
feeds={feeds}
hidden={!isModalVisible}
onUpdateFeed={updateFeed}
/>
{selectedItem && (
<DisplayMarkdownDialog
content={selectedItem?.readme}
hidden={readmeHidden}
title={'Project Readme'}
onDismiss={() => {
setReadmeHidden(true);
}}
/>
)}
<Toolbar toolbarItems={toolbarItems} />
<div css={ContentHeaderStyle}>
<h1 css={HeaderText}>{strings.title}</h1>
<p>
{strings.description}
<Link href={docsUrl} target="_new">
{strings.descriptionLink}
</Link>
</p>
</div>
<Stack horizontal verticalFill styles={packageScrollContainerStyle}>
{projectCollection && projectCollection.length > 1 && (
<Stack.Item styles={{ root: { width: '175px', borderRight: '1px solid #CCC' } }}>
<ProjectList
defaultSelected={projectId}
projectCollection={projectCollection}
onSelect={(link) => setCurrentProjectId(link.projectId)}
/>
</Stack.Item>
)}
<Stack.Item align="stretch" styles={{ root: { flexGrow: 1, overflowX: 'hidden', maxHeight: '100%' } }}>
{!ejectedRuntime && (
<MessageBar
actions={
<div>
<MessageBarButton onClick={navigateToEject}>{strings.ejectRuntime}</MessageBarButton>
</div>
}
isMultiline={false}
messageBarType={MessageBarType.warning}
>
{strings.requireEject}
</MessageBar>
)}
{/* ***************************************************************************
* This is the top nav that includes the tabs and search bar
****************************************************************************/}
<Stack horizontal styles={tabAndSearchBarStyles}>
<Stack.Item align="stretch">
<Pivot aria-label="Library Views" onLinkClick={(item: PivotItem) => setCurrentTab(item.props.itemKey)}>
<PivotItem headerText={strings.browseHeader} itemKey={TABS.BROWSE} />
<PivotItem headerText={strings.installHeader} itemKey={TABS.INSTALL} />
</Pivot>
</Stack.Item>
<Stack.Item align="end" grow={1}>
<Stack horizontal horizontalAlign="end" tokens={{ childrenGap: 10 }}>
<Stack.Item>
<Dropdown
ariaLabel={formatMessage('Feeds')}
hidden={currentTab !== TABS.BROWSE}
options={feeds}
placeholder="Format"
selectedKey={feed}
styles={{
root: { width: '200px' },
}}
onChange={onChangeFeed}
></Dropdown>
</Stack.Item>
<Stack.Item>
<SearchBox
disabled={!feeds || !feed || (!searchTerm && items.length === 0)}
placeholder="Search"
styles={{
root: { width: '200px' },
}}
onClear={() => setSearchTerm('')}
onSearch={setSearchTerm}
/>
</Stack.Item>
</Stack>
</Stack.Item>
</Stack>
{/* ***************************************************************************
* This is the browse tab
****************************************************************************/}
{currentTab === TABS.BROWSE && (
<Fragment>
{loading && <LoadingSpinner />}
{items?.length ? (
<LibraryList
disabled={!ejectedRuntime}
install={install}
isInstalled={isInstalled}
items={items}
redownload={redownload}
removeLibrary={removeComponent}
updateItems={setItems}
onItemClick={selectItem}
/>
) : null}
{items && !items.length && !loading && (
<div
style={{
marginLeft: '50px',
fontSize: 'smaller',
marginTop: '20px',
}}
>
{strings.noComponentsFound}
</div>
)}
</Fragment>
)}
{/* ***************************************************************************
* This is the installed tab
****************************************************************************/}
{currentTab === TABS.INSTALL && (
<Fragment>
<LibraryList
disabled={!ejectedRuntime}
install={install}
isInstalled={isInstalled}
items={installedComponents}
redownload={redownload}
removeLibrary={removeComponent}
updateItems={setItems}
onItemClick={selectItem}
/>
{(!installedComponents || installedComponents.length === 0) && (
<div
style={{
marginLeft: '50px',
fontSize: 'smaller',
marginTop: '20px',
}}
>
{strings.noComponentsInstalled}
</div>
)}
</Fragment>
)}
</Stack.Item>
{/* ***************************************************************************
* This is the details pane
****************************************************************************/}
<Stack.Item
disableShrink
grow={0}
shrink={0}
styles={{
root: {
width: '400px',
padding: '10px 20px',
borderLeft: '1px solid #CCC',
overflowX: 'auto',
maxHeight: '100%',
},
}}
>
{selectedItem ? (
<Fragment>
<Stack horizontal tokens={{ childrenGap: 10 }}>
<Stack.Item align="center" grow={0} styles={{ root: { width: 32 } }}>
{selectedItem.iconUrl ? (
<img alt="icon" height="32" src={selectedItem.iconUrl} width="32" />
) : (
<LetterIcon letter={selectedItem.name[0]} />
)}
</Stack.Item>
<Stack.Item align="center" grow={1} styles={{ root: { width: 140 } }}>
{selectedItem.authors}
</Stack.Item>
<Stack.Item align="center" grow={1} styles={{ root: { textAlign: 'right' } }}>
<PrimaryButton
disabled={!ejectedRuntime || !selectedItem.isCompatible}
menuProps={versionOptions}
split={versionOptions != undefined}
styles={{ root: { maxWidth: 180, textOverflow: 'ellipsis' } }}
onClick={install}
>
{/* display "v1.0 installed" if installed, or "install v1.1" if not" */}
{isInstalled(selectedItem) && selectedVersion === installedVersion(selectedItem) ? (
<span>
<span
css={{
maxWidth: 80,
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
display: 'inline-block',
}}
title={selectedVersion}
>
{selectedVersion}
</span>
<span css={{ display: 'inline-block', overflow: 'hidden' }}>{strings.installed}</span>
</span>
) : isUpdate ? (
<span>
<span css={{ display: 'inline-block', overflow: 'hidden' }}>{strings.updateButton}</span>
<span
css={{
maxWidth: 80,
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
display: 'inline-block',
}}
title={selectedVersion}
>
{selectedVersion}
</span>
</span>
) : (
<span>
<span css={{ display: 'inline-block', overflow: 'hidden' }}>{strings.installButton}</span>
<span
css={{
maxWidth: 80,
textOverflow: 'ellipsis',
overflow: 'hidden',
whiteSpace: 'nowrap',
display: 'inline-block',
}}
title={selectedVersion}
>
{selectedVersion}
</span>
</span>
)}
</PrimaryButton>
</Stack.Item>
</Stack>
<h3 css={{ marginBottom: 0 }}>{selectedItem.name}</h3>
{isInstalled(selectedItem) ? (
<p css={{ marginTop: 0 }}>
{formatMessage('Installed:')} {installedVersion(selectedItem)}
</p>
) : (
<p css={{ marginTop: 0 }}>
{formatMessage('Latest:')} {selectedItem.version}
</p>
)}
{readmeContent && <ReactMarkdown>{readmeContent}</ReactMarkdown>}
{selectedItem.repository && (
<p>
<Link href={selectedItem.repository} target="_docs">
{strings.viewDocumentation}
</Link>
</p>
)}
{selectedItem.readme && (
<DefaultButton
styles={{ root: { marginRight: 20 } }}
onClick={() => {
setReadmeHidden(false);
}}
>
{formatMessage('View readme')}
</DefaultButton>
)}
{isInstalled(selectedItem) && <DefaultButton onClick={removeComponent}>Uninstall</DefaultButton>}
</Fragment>
) : (
<Fragment>
<p>{strings.emptyPanel}</p>
</Fragment>
)}
</Stack.Item>
</Stack>
</ScrollablePane>
);
};
render(<Library />); | the_stack |
declare namespace ts {
function createDiagnosticForNodeInSourceFile(
sourceFile: SourceFile,
node: Node,
message: DiagnosticMessage,
arg0?: string | number,
arg1?: string | number,
arg2?: string | number,
arg3?: string | number): DiagnosticWithLocation;
}
let compilerOptions: ts.CompilerOptions = {
target: ts.ScriptTarget.ES2017,
downlevelIteration: true,
strict: true,
suppressOutputPathCheck: false,
extendedDiagnostics: true,
jsx: ts.JsxEmit.React,
jsxFactory: "jsx",
noImplicitAny: false,
};
let languageServiceHost;
let languageService;
let id = 0;
let ttcontext: any = {};
Object.setPrototypeOf(ttcontext, window);
(Object as any).prototype.__constructor = (...args) => { };
ttcontext.TTObject = class TTObject {
constructor(...args) {
(this as any).__constructor(...args);
}
};
ttcontext.nativeConstructor = (theInstance: any, theClass: any, ...args: any) => {
theClass.prototype.constructor.bind(theInstance)(...args);
};
function createClass(name: string) {
let fn = new Function(`
return function ${name}(...args) {
this.__constructor(...args);
};
`)();
id++;
Object.defineProperty(fn, "__id", { enumerable: false, value: id });
Object.defineProperty(fn.prototype, "__id", { enumerable: false, value: id });
return fn;
}
let TTClassImpl = ttcontext.TTClass = createClass("TTClass");
Object.setPrototypeOf(TTClassImpl, TTClassImpl.prototype);
let typetalk = ttcontext.TypeTalk = createClass("TypeTalk");
Object.setPrototypeOf(typetalk, TTClassImpl.prototype);
let classes = new Map<string, any>();
let projectVersion = 0;
TTClassImpl.prototype._typescript = "";
TTClassImpl.prototype._typescriptVersion = 0;
TTClassImpl.prototype._javascript = "";
TTClassImpl.prototype._javascriptDirty = true;
TTClassImpl.prototype._errors = [];
TTClassImpl.prototype.setSource = function (typescript) {
if (this._typescript != typescript) {
this._typescript = typescript;
this._typescriptVersion++;
this._javascriptDirty = true;
this._errors = [];
projectVersion++;
fireSubscribers();
}
}
TTClassImpl.prototype.getSource = function () {
return this._typescript;
}
TTClassImpl.prototype.getCommitted = function () {
return !this._javascriptDirty;
}
TTClassImpl.prototype.getErrors = function () {
return this._errors;
}
let subscribers = new Set<TTClassChangeListener>();
function fireSubscribers() {
for (let subscriber of subscribers)
setTimeout(() => subscriber.onClassesChanged(), 0);
subscribers.clear();
}
TTClassImpl.subscribe = function (subscriber) {
subscribers.add(subscriber);
}
TTClassImpl.addClass = function (name) {
let ttclass = classes.get(name);
if (!ttclass) {
ttclass = createClass(name);
Object.setPrototypeOf(ttclass, TTClassImpl.prototype);
classes.set(name, ttclass);
ttcontext[name] = ttclass;
fireSubscribers();
}
return ttclass;
}
TTClassImpl.getClass = function (name) {
return classes.get(name);
}
TTClassImpl.getAllClasses = function () {
return classes;
}
TTClassImpl.recompile = function () {
let errors = false;
/* Phase 1: clear pending diagnostics. */
for (let ttclass of classes.values())
ttclass._errors = [];
/* Phase 2: accumulate all diagnostics. */
let diagnostics: ts.DiagnosticWithLocation[] = [];
for (let ttclass of classes.values()) {
let filename = `${ttclass.name}.tsx`;
diagnostics = diagnostics.concat(
languageService
.getCompilerOptionsDiagnostics()
.concat(languageService.getSyntacticDiagnostics(filename))
.concat(languageService.getSemanticDiagnostics(filename))
.filter(d => d.file && d.start));
}
/* Phase 3: attach the diagnostics to the files. */
for (let d of diagnostics) {
let classname = d.file.fileName.replace(/\.tsx$/, "");
let ttclass = classes.get(classname);
console.log(`${d.file.fileName}:${d.start} ${ts.flattenDiagnosticMessageText(d.messageText, "\n")}`);
if (ttclass) {
ttclass._errors.push(d);
}
}
/* Phase 4: emit Javascript, even if we had diagnostics. This may add more diagnostics. */
for (let ttclass of classes.values()) {
if (!ttclass._javascriptDirty)
continue;
let filename = `${ttclass.name}.tsx`;
console.log(`compiling ${ttclass.name}`);
let output = languageService.getEmitOutput(filename);
if (!output.emitSkipped) {
for (let f of output.outputFiles) {
if (f.name !== `${ttclass.name}.js`)
throw `filename mismatch: got ${f.name}, expected ${filename}`;
ttclass._javascript = f.text;
}
}
}
/* Phase 5: check all classes for diagnostics. If found, stop now. */
let diagnostics_found = false;
for (let ttclass of classes.values()) {
if (ttclass._errors.length > 0) {
diagnostics_found = true;
break;
}
}
if (diagnostics_found) {
console.log("Compilation failed.");
return;
}
/* Phase 6: reload the Javascript. */
for (let ttclass of classes.values()) {
if (!ttclass._javascriptDirty)
continue;
console.log(`loading ${ttclass.name}`);
let ctx = Object.create(ttcontext);
let body = `with (this) {\n\n` +
`${ttclass._javascript}\n\n` +
`return __tt_exported_class; }\n` +
`//# sourceURL=${ttclass.name}.js`;
let fn = new Function(body).bind(ctx);
let classImpl = fn();
if (classImpl) {
Object.defineProperty(classImpl, 'name', { value: ttclass.name });
/* We have to leave existing properties because they may contain static
* class state. */
for (let methodName of Object.getOwnPropertyNames(classImpl)) {
if (methodName == "__id")
continue;
if ((methodName != "length") && (methodName != "name") && (methodName != "prototype"))
ttclass[methodName] = classImpl[methodName];
}
/* Delete existing methods before updating the prototype in case a stale
* method aliases one defined by a superclass. */
for (let key of Object.keys(ttclass.prototype))
delete ttclass.prototype[key];
for (let methodName of Object.getOwnPropertyNames(classImpl.prototype)) {
if (methodName == "__id")
continue;
ttclass.prototype[methodName] = classImpl.prototype[methodName];
}
/* The prototype of a `prototype` is always Object. The *actual* superclass
* is the prototype of newClass itself. */
let superclass = Object.getPrototypeOf(classImpl);
/* Construct the chain of prototypes (this is not how ES6 classes do it). */
Object.setPrototypeOf(ttclass.prototype, superclass.prototype);
}
ttclass._javascriptDirty = false;
}
};
languageServiceHost = new class implements ts.LanguageServiceHost {
private libraries = new Map<string, string>();
private classOfFile(path: string): any {
return TTClassImpl.getClass(path.replace(/\.tsx$/, ""));
}
addLibrary(path: string, contents: string) {
this.libraries.set(path, contents);
}
getScriptFileNames(): string[] {
return Array.from(classes.keys())
.map(name => `${name}.tsx`)
.concat(Array.from(this.libraries.keys()));
}
getScriptVersion(path: string): string {
if (this.libraries.has(path))
return "0";
return this.classOfFile(path)._typescriptVersion.toString();
}
getProjectVersion(): string {
return projectVersion.toString();
}
getScriptSnapshot(path: string) {
let text = this.libraries.get(path);
if (text == undefined)
text = this.classOfFile(path)._typescript;
return ts.ScriptSnapshot.fromString(text!);
}
getCurrentDirectory(): string {
return "";
}
getCompilationSettings(): any {
return compilerOptions;
}
getDefaultLibFileName(options: any): string {
return "lib.d.ts";
}
getCustomTransformers(): ts.CustomTransformers {
return new class implements ts.CustomTransformers {
before = [
(context) =>
(sourceFile) => sanityCheckTransformer(sourceFile).apply(),
(context) =>
(sourceFile) => constructorTransformer(context, sourceFile).apply()
];
after = [
(context) =>
(sourceFile) => deconstructorTransformer(context, sourceFile).apply()
];
}
}
trace = console.log;
};
languageService = ts.createLanguageService(
languageServiceHost,
ts.createDocumentRegistry()
);
function createDiagnostic(message: string) {
return {
key: message,
category: ts.DiagnosticCategory.Error,
code: 9999,
message: message
};
};
class TransformedFileWithDiagnostics {
constructor(
public result: ts.SourceFile,
public diagnostics: ReadonlyArray<ts.DiagnosticWithLocation>) { }
apply(): ts.SourceFile {
for (let d of this.diagnostics) {
let classname = d.file.fileName.replace(/\.tsx$/, "");
let ttclass = classes.get(classname);
if (ttclass)
ttclass._errors.push(d);
}
return this.result!;
}
}
function sanityCheckTransformer(node: ts.SourceFile): TransformedFileWithDiagnostics {
let diagnostics: ts.DiagnosticWithLocation[] = [];
let theClass: ts.ClassLikeDeclaration | null = null;
for (let statement of node.statements) {
if (ts.isClassDeclaration(statement) || ts.isInterfaceDeclaration(statement)) {
if (theClass)
diagnostics.push(ts.createDiagnosticForNodeInSourceFile(node, statement,
createDiagnostic("TypeTalk files must contain precisely one class")));
else
theClass = statement as ts.ClassLikeDeclaration;
} else if (ts.isEmptyStatement(statement)) {
/* Do nothing, these are legal */
} else
diagnostics.push(ts.createDiagnosticForNodeInSourceFile(node, statement,
createDiagnostic(`Illegal statement ${statement.kind}`)));
}
if (theClass) {
for (let member of theClass.members) {
if (ts.isPropertyDeclaration(member)) {
let theProperty = member as ts.PropertyDeclaration;
if (theProperty.modifiers && theProperty.initializer) {
for (let modifier of theProperty.modifiers) {
if (modifier.kind == ts.SyntaxKind.StaticKeyword) {
diagnostics.push(ts.createDiagnosticForNodeInSourceFile(node, member,
createDiagnostic(`Static properties in TypeTalk classes can't be initialised`)));
}
}
}
}
}
}
return new TransformedFileWithDiagnostics(node, diagnostics);
}
function constructorTransformer(context: ts.TransformationContext, node: ts.SourceFile): TransformedFileWithDiagnostics {
function visitor(node: ts.Node): ts.VisitResult<ts.Node> {
if (!ts.isClassDeclaration(node))
return node
let theClass = node as ts.ClassDeclaration;
let hasConstructor = false;
for (let member of theClass.members) {
hasConstructor = hasConstructor || ts.isConstructorDeclaration(member);
}
if (hasConstructor)
return node;
return ts.updateClassDeclaration(
theClass,
theClass.decorators,
theClass.modifiers,
theClass.name,
theClass.typeParameters,
theClass.heritageClauses,
theClass.members.concat(
ts.createConstructor(
undefined,
undefined,
[
ts.createParameter(
undefined,
undefined,
ts.createToken(ts.SyntaxKind.DotDotDotToken),
"args"
)
],
ts.createBlock(
[
ts.createStatement(
ts.createCall(
ts.createSuper(),
undefined,
[
ts.createSpread(
ts.createIdentifier("args")
)
]
)
)
]
)
)
)
);
}
return new TransformedFileWithDiagnostics(ts.visitEachChild(node, visitor, context), []);
}
function deconstructorTransformer(ctx: ts.TransformationContext, node: ts.SourceFile): TransformedFileWithDiagnostics {
let diagnostics: ts.DiagnosticWithLocation[] = [];
let seenClass = false;
for (let statement of node.statements) {
if (ts.isClassDeclaration(statement))
seenClass = true;
}
if (!seenClass) {
/* No class has been seen, which means this is an interface (which TypeScript compiles
* into no code). Add a dummy declaration to keep the rest of the runtime happy. */
return new TransformedFileWithDiagnostics(
ts.updateSourceFileNode(
node,
ts.createNodeArray([
ts.createExpressionStatement(
ts.createAssignment(
ts.createIdentifier("__tt_exported_class"),
ts.createNull()
)
)
])
),
diagnostics
);
}
function visitConstructorNodes(node: ts.Node): ts.VisitResult<ts.Node> {
/* Don't iterate into class expressions. */
if (ts.isClassLike(node))
return node;
if (node.kind == ts.SyntaxKind.SuperKeyword) {
/* Rewrite any calls to super to super.__constructor. */
return ts.createPropertyAccess(
ts.createSuper(),
"__constructor");
}
return ts.visitEachChild(node, visitConstructorNodes, ctx);
}
function visitMembers(node: ts.Node): ts.VisitResult<ts.Node> {
if (ts.isConstructorDeclaration(node)) {
return ts.createMethod(
node.decorators,
node.modifiers,
node.asteriskToken,
"__constructor",
node.questionToken,
node.typeParameters,
node.parameters,
node.type,
ts.visitEachChild((node as ts.ConstructorDeclaration).body,
visitConstructorNodes, ctx));
}
if (ts.isClassDeclaration(node)) {
let theClass = node as ts.ClassLikeDeclaration;
let hasExtension = false;
if (theClass.heritageClauses) {
for (let clause of theClass.heritageClauses)
hasExtension = hasExtension || (clause.token == ts.SyntaxKind.ExtendsKeyword);
}
let clauses = theClass.heritageClauses
if (!hasExtension && ts.isClassDeclaration(theClass)) {
if (!clauses)
clauses = ts.createNodeArray();
clauses = ts.createNodeArray(
clauses.concat(
ts.createHeritageClause(
ts.SyntaxKind.ExtendsKeyword,
[ts.createExpressionWithTypeArguments(
undefined,
ts.createIdentifier("TTObject")
)]
)
)
);
}
if (ts.isClassDeclaration(theClass))
node = ts.updateClassDeclaration(
theClass,
theClass.decorators,
theClass.modifiers,
ts.createIdentifier("__tt_exported_class"),
theClass.typeParameters,
clauses,
theClass.members
);
else if (ts.isInterfaceDeclaration(theClass))
node = ts.updateInterfaceDeclaration(
theClass,
theClass.decorators,
theClass.modifiers,
ts.createIdentifier("__tt_exported_class"),
theClass.typeParameters,
theClass.heritageClauses,
theClass.members
);
else
throw "object is not a class or interface";
return ts.visitEachChild(node, visitMembers, ctx);
}
if (ts.isMethodDeclaration(node) || ts.isPropertyDeclaration(node)) {
return node;
}
return ts.visitEachChild(node, visitMembers, ctx);
}
return new TransformedFileWithDiagnostics(
ts.visitEachChild(node, visitMembers, ctx),
diagnostics
);
}
ttcontext.globals = ttcontext;
(function () {
let scripts = document.getElementsByTagName("SCRIPT");
for (let i = 0; i < scripts.length; i++) {
let script: any = scripts[i];
switch (script.getAttribute("type")) {
case "typetalk-lib":
languageServiceHost.addLibrary(script.leafName, script.text);
break;
case "typetalk-src": {
let matches = /(?:class|interface) (\w+)(?: +extends (\w+))?/.exec(script.text);
if (!matches)
throw `script ${script.leafName} did not contain a parseable class`;
let className = matches[1];
let superclassName = matches[2] || null;
console.log(`loading ${className}`);
TTClassImpl.addClass(className).setSource(script.text);
}
}
}
})();
TTClassImpl.recompile();
let browser = new ttcontext.Browser();
browser.run();
//(async () => await browser.run())(); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.