text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
$Object,
} from '../types/object.js';
import {
$Null,
} from '../types/null.js';
import {
Realm,
ExecutionContext,
} from '../realm.js';
import {
$PropertyKey,
$AnyNonEmpty,
$AnyNonEmptyNonError,
$AnyObject,
CompletionType,
} from '../types/_shared.js';
import {
$Call,
$ToPropertyDescriptor,
$ValidateAndApplyPropertyDescriptor,
$FromPropertyDescriptor,
$CreateListFromArrayLike,
$Construct,
} from '../operations.js';
import {
$Boolean,
} from '../types/boolean.js';
import {
$PropertyDescriptor,
} from '../types/property-descriptor.js';
import {
$Undefined,
} from '../types/undefined.js';
import {
$String,
} from '../types/string.js';
import {
$Symbol,
} from '../types/symbol.js';
import {
$Function,
} from '../types/function.js';
import {
$CreateArrayFromList,
} from './array.js';
import {
$TypeError,
$Error,
} from '../types/error.js';
import {
$List,
} from '../types/list.js';
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots
export class $ProxyExoticObject extends $Object<'ProxyExoticObject'> {
public '[[ProxyHandler]]': $AnyObject | $Null;
public '[[ProxyTarget]]': $AnyObject | $Null;
public get isProxy(): true { return true; }
// http://www.ecma-international.org/ecma-262/#sec-proxycreate
// 9.5.14 ProxyCreate ( target , handler )
public constructor(
realm: Realm,
target: $AnyNonEmpty,
handler: $AnyNonEmpty,
) {
super(realm, 'ProxyExoticObject', realm['[[Intrinsics]]'].null, CompletionType.normal, realm['[[Intrinsics]]'].empty);
// 1. If Type(target) is not Object, throw a TypeError exception.
if (!target.isObject) {
return new $TypeError(realm) as any; // TODO: move to static method so we can return error completion
}
// 2. If target is a Proxy exotic object and target.[[ProxyHandler]] is null, throw a TypeError exception.
if (target.isProxy && (target as $ProxyExoticObject)['[[ProxyHandler]]'].isNull) {
return new $TypeError(realm) as any; // TODO: move to static method so we can return error completion
}
// 3. If Type(handler) is not Object, throw a TypeError exception.
if (!handler.isObject) {
return new $TypeError(realm) as any; // TODO: move to static method so we can return error completion
}
// 4. If handler is a Proxy exotic object and handler.[[ProxyHandler]] is null, throw a TypeError exception.
if (handler instanceof $ProxyExoticObject && handler['[[ProxyHandler]]'].isNull) {
return new $TypeError(realm) as any; // TODO: move to static method so we can return error completion
}
// 5. Let P be a newly created object.
// 6. Set P's essential internal methods (except for [[Call]] and [[Construct]]) to the definitions specified in 9.5.
// 7. If IsCallable(target) is true, then
// 7. a. Set P.[[Call]] as specified in 9.5.12.
// 7. b. If IsConstructor(target) is true, then
// 7. b. i. Set P.[[Construct]] as specified in 9.5.13.
// 8. Set P.[[ProxyTarget]] to target.
this['[[ProxyTarget]]'] = target;
// 9. Set P.[[ProxyHandler]] to handler.
this['[[ProxyHandler]]'] = handler;
// 10. Return P.
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-getprototypeof
// 9.5.1 [[GetPrototypeOf]] ( )
public '[[GetPrototypeOf]]'(
ctx: ExecutionContext,
): $AnyObject | $Null | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 5. Let trap be ? GetMethod(handler, "getPrototypeOf").
const trap = handler.GetMethod(ctx, intrinsics.$getPrototypeOf);
if (trap.isAbrupt) { return trap; }
// 6. If trap is undefined, then
if (trap.isUndefined) {
// 6. a. Return ? target.[[GetPrototypeOf]]().
return target['[[GetPrototypeOf]]'](ctx);
}
// 7. Let handlerProto be ? Call(trap, handler, « target »).
const handlerProto = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target));
if (handlerProto.isAbrupt) { return handlerProto; }
// 8. If Type(handlerProto) is neither Object nor Null, throw a TypeError exception.
if (!handlerProto.isNull && !handlerProto.isObject) {
return new $TypeError(realm, `Proxy handler prototype is ${handlerProto}, but expected Object or Null`);
}
// 9. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
// 10. If extensibleTarget is true, return handlerProto.
if (extensibleTarget.isTruthy) {
return handlerProto;
}
// 11. Let targetProto be ? target.[[GetPrototypeOf]]().
const targetProto = target['[[GetPrototypeOf]]'](ctx);
if (targetProto.isAbrupt) { return targetProto; }
// 12. If SameValue(handlerProto, targetProto) is false, throw a TypeError exception.
if (!handlerProto.is(targetProto)) {
return new $TypeError(realm, `Expected handler prototype ${handlerProto} to be the same value as target prototype ${targetProto}`);
}
// 13. Return handlerProto.
return handlerProto;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-setprototypeof-v
// 9.5.2 [[SetPrototypeOf]] ( V )
public '[[SetPrototypeOf]]'(
ctx: ExecutionContext,
V: $AnyObject | $Null,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: Either Type(V) is Object or Type(V) is Null.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "setPrototypeOf").
const trap = handler.GetMethod(ctx, intrinsics.$setPrototypeOf);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[SetPrototypeOf]](V).
return target['[[SetPrototypeOf]]'](ctx, V);
}
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, V »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, V)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 9. If booleanTrapResult is false, return false.
if (booleanTrapResult.isFalsey) {
return intrinsics.false;
}
// 10. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
if (extensibleTarget.isTruthy) {
// 11. If extensibleTarget is true, return true.
return intrinsics.true;
}
// 12. Let targetProto be ? target.[[GetPrototypeOf]]().
const targetProto = target['[[GetPrototypeOf]]'](ctx);
if (targetProto.isAbrupt) { return targetProto; }
// 13. If SameValue(V, targetProto) is false, throw a TypeError exception.
if (!V.is(targetProto)) {
return new $TypeError(realm, `Expected value ${V} to be the same value as target prototype ${targetProto}`);
}
// 14. Return true.
return intrinsics.true;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-isextensible
// 9.5.3 [[IsExtensible]] ( )
public '[[IsExtensible]]'(
ctx: ExecutionContext,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 5. Let trap be ? GetMethod(handler, "isExtensible").
const trap = handler.GetMethod(ctx, intrinsics.$isExtensible);
if (trap.isAbrupt) { return trap; }
// 6. If trap is undefined, then
if (trap.isUndefined) {
// 6. a. Return ? target.[[IsExtensible]]().
return target['[[IsExtensible]]'](ctx);
}
// 7. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target)).ToBoolean(ctx);
// 8. Let targetResult be ? target.[[IsExtensible]]().
const targetResult = target['[[IsExtensible]]'](ctx);
if (targetResult.isAbrupt) { return targetResult; }
// 9. If SameValue(booleanTrapResult, targetResult) is false, throw a TypeError exception.
if (!booleanTrapResult.is(targetResult)) {
return new $TypeError(realm, `Expected booleanTrapResult ${booleanTrapResult} to be the same value as targetResult ${targetResult}`);
}
// 10. Return booleanTrapResult.
return booleanTrapResult;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-preventextensions
// 9.5.4 [[PreventExtensions]] ( )
public '[[PreventExtensions]]'(
ctx: ExecutionContext,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 5. Let trap be ? GetMethod(handler, "preventExtensions").
const trap = handler.GetMethod(ctx, intrinsics.$preventExtensions);
if (trap.isAbrupt) { return trap; }
// 6. If trap is undefined, then
if (trap.isUndefined) {
// 6. a. Return ? target.[[PreventExtensions]]().
return target['[[PreventExtensions]]'](ctx);
}
// 7. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 8. If booleanTrapResult is true, then
if (booleanTrapResult.isTruthy) {
// 8. a. Let targetIsExtensible be ? target.[[IsExtensible]]().
const targetIsExtensible = target['[[IsExtensible]]'](ctx);
if (targetIsExtensible.isAbrupt) { return targetIsExtensible; }
// 8. b. If targetIsExtensible is true, throw a TypeError exception.
if (targetIsExtensible.isTruthy) {
return new $TypeError(realm, `Target is still extensible`);
}
}
// 9. Return booleanTrapResult.
return booleanTrapResult;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-getownproperty-p
// 9.5.5 [[GetOwnProperty]] ( P )
public '[[GetOwnProperty]]'(
ctx: ExecutionContext,
P: $PropertyKey,
): $PropertyDescriptor | $Undefined | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "getOwnPropertyDescriptor").
const trap = handler.GetMethod(ctx, intrinsics.$getOwnPropertyDescriptor);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[GetOwnProperty]](P).
return target['[[GetOwnProperty]]'](ctx, P);
}
// 8. Let trapResultObj be ? Call(trap, handler, « target, P »).
const trapResultObj = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P));
if (trapResultObj.isAbrupt) { return trapResultObj; }
// 9. If Type(trapResultObj) is neither Object nor Undefined, throw a TypeError exception.
if (!trapResultObj.isObject && !trapResultObj.isUndefined) {
return new $TypeError(realm, `trapResultObj from GetOwnProperty(${P}) is ${trapResultObj}, but expected Object or Undefined`);
}
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 11. If trapResultObj is undefined, then
if (trapResultObj.isUndefined) {
// 11. a. If targetDesc is undefined, return undefined.
if (targetDesc.isUndefined) {
return intrinsics.undefined;
}
// 11. b. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
if (targetDesc['[[Configurable]]'].isFalsey) {
return new $TypeError(realm, `The proxy returned undefined for property descriptor ${P}, but there is a backing property descriptor which is not configurable`);
}
// 11. c. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
// 11. d. If extensibleTarget is false, throw a TypeError exception.
if (extensibleTarget.isFalsey) {
return new $TypeError(realm, `The proxy returned undefined for property descriptor ${P}, but there is a backing property descriptor and the backing object is not extensible`);
}
// 11. e. Return undefined.
return intrinsics.undefined;
}
// 12. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
// 13. Let resultDesc be ? ToPropertyDescriptor(trapResultObj).
const resultDesc = $ToPropertyDescriptor(ctx, trapResultObj, P);
if (resultDesc.isAbrupt) { return resultDesc; }
// 14. Call CompletePropertyDescriptor(resultDesc).
resultDesc.Complete(ctx);
// 15. Let valid be IsCompatiblePropertyDescriptor(extensibleTarget, resultDesc, targetDesc).
const valid = $ValidateAndApplyPropertyDescriptor(
ctx,
/* O */intrinsics.undefined,
/* P */intrinsics.undefined,
/* extensible */extensibleTarget,
/* Desc */resultDesc,
/* current */targetDesc,
);
// 16. If valid is false, throw a TypeError exception.
if (valid.isFalsey) {
return new $TypeError(realm, `Validation for property descriptor ${P} failed`);
}
// 17. If resultDesc.[[Configurable]] is false, then
if (resultDesc['[[Configurable]]'].isFalsey) {
// 17. a. If targetDesc is undefined or targetDesc.[[Configurable]] is true, then
if (targetDesc.isUndefined || targetDesc['[[Configurable]]'].isTruthy) {
// 17. a. i. Throw a TypeError exception.
return new $TypeError(realm, `The proxy returned a non-configurable property descriptor for ${P}, but the backing property descriptor is either undefined or configurable`);
}
}
// 18. Return resultDesc.
return resultDesc;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc
// 9.5.6 [[DefineOwnProperty]] ( P , Desc )
public '[[DefineOwnProperty]]'(
ctx: ExecutionContext,
P: $PropertyKey,
Desc: $PropertyDescriptor,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "defineProperty").
const trap = handler.GetMethod(ctx, intrinsics.$defineProperty);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[DefineOwnProperty]](P, Desc).
return target['[[DefineOwnProperty]]'](ctx, P, Desc);
}
// 8. Let descObj be FromPropertyDescriptor(Desc).
const descObj = $FromPropertyDescriptor(ctx, Desc);
if (descObj.isAbrupt) { return descObj; } // TODO: spec doesn't say this. maybe we need to fix the types somehow?
// 9. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P, descObj »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P, descObj)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 10. If booleanTrapResult is false, return false.
if (booleanTrapResult.isFalsey) {
return intrinsics.false;
}
// 11. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 12. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
let settingConfigFalse: boolean;
// 13. If Desc has a [[Configurable]] field and if Desc.[[Configurable]] is false, then
if (Desc['[[Configurable]]'].hasValue && Desc['[[Configurable]]'].isFalsey) {
// 13. a. Let settingConfigFalse be true.
settingConfigFalse = true;
}
// 14. Else, let settingConfigFalse be false.
else {
settingConfigFalse = false;
}
// 15. If targetDesc is undefined, then
if (targetDesc.isUndefined) {
// 15. a. If extensibleTarget is false, throw a TypeError exception.
if (extensibleTarget.isFalsey) {
return new $TypeError(realm, `Cannot define property ${P} on non-extensible target`);
}
// 15. b. If settingConfigFalse is true, throw a TypeError exception.
if (!settingConfigFalse) {
return new $TypeError(realm, `Cannot define non-configurable property ${P} on proxy`);
}
}
// 16. Else targetDesc is not undefined,
else {
// 16. a. If IsCompatiblePropertyDescriptor(extensibleTarget, Desc, targetDesc) is false, throw a TypeError exception.
if ($ValidateAndApplyPropertyDescriptor(
ctx,
/* O */intrinsics.undefined,
/* P */intrinsics.undefined,
/* extensible */extensibleTarget,
/* Desc */Desc,
/* current */targetDesc,
).isFalsey) {
return new $TypeError(realm, `The provided property descriptor for ${P} is not compatible with the proxy target's existing descriptor`);
}
// 16. b. If settingConfigFalse is true and targetDesc.[[Configurable]] is true, throw a TypeError exception.
if (settingConfigFalse && targetDesc['[[Configurable]]'].isTruthy) {
return new $TypeError(realm, `The provided property descriptor for ${P} is not configurable but the proxy target's existing descriptor is`);
}
}
// 17. Return true.
return intrinsics.true;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-hasproperty-p
// 9.5.7 [[HasProperty]] ( P )
public '[[HasProperty]]'(
ctx: ExecutionContext,
P: $PropertyKey,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "has").
const trap = handler.GetMethod(ctx, intrinsics.$has);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[HasProperty]](P).
return target['[[HasProperty]]'](ctx, P);
}
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 9. If booleanTrapResult is false, then
if (booleanTrapResult.isFalsey) {
// 9. a. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 9. b. If targetDesc is not undefined, then
if (!targetDesc.isUndefined) {
// 9. b. i. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
if (targetDesc['[[Configurable]]'].isFalsey) {
return new $TypeError(realm, `The proxy returned false for HasProperty for ${P}, but the backing object has a property with that name which is not configurable`);
}
// 9. b. ii. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
if (extensibleTarget.isFalsey) {
// 9. b. iii. If extensibleTarget is false, throw a TypeError exception.
return new $TypeError(realm, `The proxy returned false for HasProperty for ${P}, but the backing object has a property with that name and is not extensible`);
}
}
}
// 10. Return booleanTrapResult.
return booleanTrapResult;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
// 9.5.8 [[Get]] ( P , Receiver )
public '[[Get]]'(
ctx: ExecutionContext,
P: $PropertyKey,
Receiver: $AnyNonEmptyNonError,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "get").
const trap = handler.GetMethod(ctx, intrinsics.$get);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[Get]](P, Receiver).
return target['[[Get]]'](ctx, P, Receiver);
}
// 8. Let trapResult be ? Call(trap, handler, « target, P, Receiver »).
const trapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P, Receiver));
if (trapResult.isAbrupt) { return trapResult; }
// 9. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 10. If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
if (!targetDesc.isUndefined && targetDesc['[[Configurable]]'].isFalsey) {
// 10. a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
if (targetDesc.isDataDescriptor && targetDesc['[[Writable]]'].isFalsey) {
// 10. a. i. If SameValue(trapResult, targetDesc.[[Value]]) is false, throw a TypeError exception.
if (!trapResult.is(targetDesc['[[Value]]'])) {
return new $TypeError(realm, `The value returned by the proxy's getter for ${P} (${trapResult}) is different from the backing property's value (${targetDesc}), but the backing descriptor is neither configurable nor writable`);
}
}
// 10. b. If IsAccessorDescriptor(targetDesc) is true and targetDesc.[[Get]] is undefined, then
if (targetDesc.isAccessorDescriptor && targetDesc['[[Get]]'].isUndefined) {
// 10. b. i. If trapResult is not undefined, throw a TypeError exception.
if (!trapResult.isUndefined) {
return new $TypeError(realm, `The proxy's getter for ${P} returned (${trapResult}), but expected undefined because the backing property's accessor descriptor has no getter and is not configurable`);
}
}
}
// 11. Return trapResult.
return trapResult;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver
// 9.5.9 [[Set]] ( P , V , Receiver )
public '[[Set]]'(
ctx: ExecutionContext,
P: $PropertyKey,
V: $AnyNonEmpty ,
Receiver: $AnyObject,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "set").
const trap = handler.GetMethod(ctx, intrinsics.$set);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[Set]](P, V, Receiver).
return target['[[Set]]'](ctx, P, V, Receiver);
}
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P, V, Receiver »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P, V, Receiver)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 9. If booleanTrapResult is false, return false.
if (booleanTrapResult.isFalsey) {
return intrinsics.false;
}
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 11. If targetDesc is not undefined and targetDesc.[[Configurable]] is false, then
if (!targetDesc.isUndefined && targetDesc['[[Configurable]]'].isFalsey) {
// 11. a. If IsDataDescriptor(targetDesc) is true and targetDesc.[[Writable]] is false, then
if (targetDesc.isDataDescriptor && targetDesc['[[Writable]]'].isFalsey) {
// 11. a. i. If SameValue(V, targetDesc.[[Value]]) is false, throw a TypeError exception.
if (!V.is(targetDesc['[[Value]]'])) {
return new $TypeError(realm, `The value supplied to the proxy's setter for ${P} (${V}) is different from the backing property's value (${targetDesc}), but the backing descriptor is neither configurable nor writable`);
}
}
// 11. b. If IsAccessorDescriptor(targetDesc) is true, then
if (targetDesc.isAccessorDescriptor) {
// 11. b. i. If targetDesc.[[Set]] is undefined, throw a TypeError exception.
if (targetDesc['[[Set]]'].isUndefined) {
return new $TypeError(realm, `The proxy's setter for ${P} was invoked, but the backing property's accessor descriptor has no setter and is not configurable`);
}
}
}
// 12. Return true.
return intrinsics.true;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-delete-p
// 9.5.10 [[Delete]] ( P )
public '[[Delete]]'(
ctx: ExecutionContext,
P: $PropertyKey,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Assert: IsPropertyKey(P) is true.
// 2. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 3. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 4. Assert: Type(handler) is Object.
// 5. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 6. Let trap be ? GetMethod(handler, "deleteProperty").
const trap = handler.GetMethod(ctx, intrinsics.$deleteProperty);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? target.[[Delete]](P).
return target['[[Delete]]'](ctx, P);
}
// 8. Let booleanTrapResult be ToBoolean(? Call(trap, handler, « target, P »)).
const booleanTrapResult = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, P)).ToBoolean(ctx);
if (booleanTrapResult.isAbrupt) { return booleanTrapResult; }
// 9. If booleanTrapResult is false, return false.
if (booleanTrapResult.isFalsey) {
return intrinsics.false;
}
// 10. Let targetDesc be ? target.[[GetOwnProperty]](P).
const targetDesc = target['[[GetOwnProperty]]'](ctx, P);
if (targetDesc.isAbrupt) { return targetDesc; }
// 11. If targetDesc is undefined, return true.
if (targetDesc.isUndefined) {
return intrinsics.true;
}
// 12. If targetDesc.[[Configurable]] is false, throw a TypeError exception.
if (targetDesc['[[Configurable]]'].isFalsey) {
return new $TypeError(realm, `The [[Delete]] trap returned true for ${P}, but the backing descriptor is not configurable`);
}
// 13. Return true.
return intrinsics.true;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-ownpropertykeys
// 9.5.11 [[OwnPropertyKeys]] ( )
public '[[OwnPropertyKeys]]'(
ctx: ExecutionContext,
): $List<$PropertyKey> | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Object;
// 5. Let trap be ? GetMethod(handler, "ownKeys").
const trap = handler.GetMethod(ctx, intrinsics.$ownKeys);
if (trap.isAbrupt) { return trap; }
// 6. If trap is undefined, then
if (trap.isUndefined) {
// 6. a. Return ? target.[[OwnPropertyKeys]]().
return target['[[OwnPropertyKeys]]'](ctx);
}
// 7. Let trapResultArray be ? Call(trap, handler, « target »).
const trapResultArray = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target));
if (trapResultArray.isAbrupt) { return trapResultArray; }
// 8. Let trapResult be ? CreateListFromArrayLike(trapResultArray, « String, Symbol »).
const trapResult = $CreateListFromArrayLike(ctx, trapResultArray, ['String', 'Symbol']) as $List<$String | $Symbol>;
if (trapResult.isAbrupt) { return trapResult; }
// 9. If trapResult contains any duplicate entries, throw a TypeError exception.
if (trapResult.filter((x, i) => trapResult.findIndex(y => x.is(y)) === i).length !== trapResult.length) {
return new $TypeError(realm, `The [[OwnPropertyKeys]] trap returned more than one of the same property key: ${trapResult.map(x => x['[[Value]]'])}`);
}
// 10. Let extensibleTarget be ? IsExtensible(target).
const extensibleTarget = target['[[IsExtensible]]'](ctx);
if (extensibleTarget.isAbrupt) { return extensibleTarget; }
// 11. Let targetKeys be ? target.[[OwnPropertyKeys]]().
const targetKeys = target['[[OwnPropertyKeys]]'](ctx);
if (targetKeys.isAbrupt) { return targetKeys; }
// 12. Assert: targetKeys is a List containing only String and Symbol values.
// 13. Assert: targetKeys contains no duplicate entries.
// 14. Let targetConfigurableKeys be a new empty List.
const targetConfigurableKeys: $PropertyKey[] = [];
// 15. Let targetNonconfigurableKeys be a new empty List.
const targetNonconfigurableKeys: $PropertyKey[] = [];
// 16. For each element key of targetKeys, do
for (const key of targetKeys) {
// 16. a. Let desc be ? target.[[GetOwnProperty]](key).
const desc = target['[[GetOwnProperty]]'](ctx, key);
if (desc.isAbrupt) { return desc; }
// 16. b. If desc is not undefined and desc.[[Configurable]] is false, then
if (!desc.isUndefined && desc['[[Configurable]]'].isFalsey) {
// 16. b. i. Append key as an element of targetNonconfigurableKeys.
targetNonconfigurableKeys.push(key);
}
// 16. c. Else,
else {
// 16. c. i. Append key as an element of targetConfigurableKeys.
targetConfigurableKeys.push(key);
}
}
// 17. If extensibleTarget is true and targetNonconfigurableKeys is empty, then
if (extensibleTarget.isTruthy && targetConfigurableKeys.length === 0) {
// 17. a. Return trapResult.
return trapResult;
}
// 18. Let uncheckedResultKeys be a new List which is a copy of trapResult.
const uncheckedResultKeys = trapResult.slice();
// 19. For each key that is an element of targetNonconfigurableKeys, do
for (const key of targetNonconfigurableKeys) {
// 19. a. If key is not an element of uncheckedResultKeys, throw a TypeError exception.
const idx = uncheckedResultKeys.findIndex(x => x.is(key));
if (idx === -1) {
return new $TypeError(realm, `The [[OwnPropertyKeys]] trap did not return all non-configurable keys of the backing object: ${key}`);
}
// 19. b. Remove key from uncheckedResultKeys.
uncheckedResultKeys.splice(idx, 1);
}
// 20. If extensibleTarget is true, return trapResult.
if (extensibleTarget.isTruthy) {
return trapResult;
}
// 21. For each key that is an element of targetConfigurableKeys, do
for (const key of targetConfigurableKeys) {
// 21. a. If key is not an element of uncheckedResultKeys, throw a TypeError exception.
const idx = uncheckedResultKeys.findIndex(x => x.is(key));
if (idx === -1) {
return new $TypeError(realm, `The [[OwnPropertyKeys]] trap did not return all configurable keys of the backing object: ${key}`);
}
// 21. b. Remove key from uncheckedResultKeys.
uncheckedResultKeys.splice(idx, 1);
}
// 22. If uncheckedResultKeys is not empty, throw a TypeError exception.
if (uncheckedResultKeys.length > 0) {
return new $TypeError(realm, `The [[OwnPropertyKeys]] returned one or more keys that do not exist on the backing object: ${uncheckedResultKeys.map(x => x)}`);
}
// 23. Return trapResult.
return trapResult;
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-call-thisargument-argumentslist
// 9.5.12 [[Call]] ( thisArgument , argumentsList )
public '[[Call]]'(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Function;
// 5. Let trap be ? GetMethod(handler, "apply").
const trap = handler.GetMethod(ctx, intrinsics.$apply);
if (trap.isAbrupt) { return trap; }
// 6. If trap is undefined, then
if (trap.isUndefined) {
// 6. a. Return ? Call(target, thisArgument, argumentsList).
return $Call(ctx, target, thisArgument, argumentsList);
}
// 7. Let argArray be CreateArrayFromList(argumentsList).
const argArray = $CreateArrayFromList(ctx, argumentsList);
// 8. Return ? Call(trap, handler, « target, thisArgument, argArray »).
return $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, thisArgument, argArray));
}
// http://www.ecma-international.org/ecma-262/#sec-proxy-object-internal-methods-and-internal-slots-construct-argumentslist-newtarget
// 9.5.13 [[Construct]] ( argumentsList , newTarget )
public '[[Construct]]'(
ctx: ExecutionContext,
argumentsList: $List<$AnyNonEmpty>,
newTarget: $Function | $Undefined,
): $AnyObject | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let handler be O.[[ProxyHandler]].
const handler = this['[[ProxyHandler]]'];
if (handler.isNull) {
// 2. If handler is null, throw a TypeError exception.
return new $TypeError(realm, `ProxyHandler is null`);
}
// 3. Assert: Type(handler) is Object.
// 4. Let target be O.[[ProxyTarget]].
const target = this['[[ProxyTarget]]'] as $Function;
// 5. Assert: IsConstructor(target) is true.
// 6. Let trap be ? GetMethod(handler, "construct").
const trap = handler.GetMethod(ctx, intrinsics.$construct);
if (trap.isAbrupt) { return trap; }
// 7. If trap is undefined, then
if (trap.isUndefined) {
// 7. a. Return ? Construct(target, argumentsList, newTarget).
return $Construct(ctx, target, argumentsList, newTarget);
}
// 8. Let argArray be CreateArrayFromList(argumentsList).
const argArray = $CreateArrayFromList(ctx, argumentsList);
// 9. Let newObj be ? Call(trap, handler, « target, argArray, newTarget »).
const newObj = $Call(ctx, trap, handler, new $List<$AnyNonEmpty>(target, argArray, newTarget));
if (newObj.isAbrupt) { return newObj; }
// 10. If Type(newObj) is not Object, throw a TypeError exception.
if (!newObj.isObject) {
return new $TypeError(realm, `The [[Construct]] trap returned ${newObj}, but expected an object`);
}
// 11. Return newObj.
return newObj;
}
} | the_stack |
import { Controller, ValidationService, FieldErrors, ValidateError, TsoaRoute, HttpStatusCodeLiteral, TsoaResponse } from '@tsoa/runtime';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { CryptocurrenciesController } from './../routes/cryptocurrencies';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { GitHubController } from './../routes/github';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { TwitterController } from './../routes/twitter';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { UnsplashController } from './../routes/unsplash';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { WeatherController } from './../routes/weather';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
import { YoutubeController } from './../routes/youtube';
import * as express from 'express';
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
const models: TsoaRoute.Models = {
"CryptocurrencyPrice": {
"dataType": "refObject",
"properties": {
"currentPrice": {"dataType":"double","required":true},
"last24h": {"dataType":"nestedObjectLiteral","nestedProperties":{"changePercentage":{"dataType":"double","required":true},"change":{"dataType":"double","required":true}},"required":true},
"imageUrl": {"dataType":"string"},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"GitHubStats": {
"dataType": "refObject",
"properties": {
"name": {"dataType":"string"},
"followers": {"dataType":"double"},
"stars": {"dataType":"double"},
"subscribers": {"dataType":"double"},
"forks": {"dataType":"double"},
"open_issues": {"dataType":"double"},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"TwitterUser": {
"dataType": "refObject",
"properties": {
"name": {"dataType":"string"},
"followers": {"dataType":"double"},
"following": {"dataType":"double"},
"tweets": {"dataType":"double"},
"listed": {"dataType":"double"},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"UnsplashImage": {
"dataType": "refObject",
"properties": {
"imageUrl": {"dataType":"string"},
"authorName": {"dataType":"string"},
"authorUrl": {"dataType":"string"},
"altText": {"dataType":"string"},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"WeatherCondition": {
"dataType": "refObject",
"properties": {
"description": {"dataType":"string","required":true},
"icon": {"dataType":"union","subSchemas":[{"dataType":"enum","enums":["01d"]},{"dataType":"enum","enums":["02d"]},{"dataType":"enum","enums":["03d"]},{"dataType":"enum","enums":["04d"]},{"dataType":"enum","enums":["09d"]},{"dataType":"enum","enums":["10d"]},{"dataType":"enum","enums":["11d"]},{"dataType":"enum","enums":["13d"]},{"dataType":"enum","enums":["50d"]},{"dataType":"enum","enums":["01n"]},{"dataType":"enum","enums":["02n"]},{"dataType":"enum","enums":["03n"]},{"dataType":"enum","enums":["04n"]},{"dataType":"enum","enums":["09n"]},{"dataType":"enum","enums":["10n"]},{"dataType":"enum","enums":["11n"]},{"dataType":"enum","enums":["13n"]},{"dataType":"enum","enums":["50n"]}],"required":true},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"WeatherData": {
"dataType": "refObject",
"properties": {
"current": {"dataType":"nestedObjectLiteral","nestedProperties":{"condition":{"ref":"WeatherCondition","required":true},"temperature":{"dataType":"double","required":true}},"required":true},
"forecast": {"dataType":"array","array":{"dataType":"nestedObjectLiteral","nestedProperties":{"condition":{"ref":"WeatherCondition","required":true},"temperatureMax":{"dataType":"double","required":true},"temperatureMin":{"dataType":"double","required":true},"date":{"dataType":"double","required":true}}},"required":true},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
"YoutubeStats": {
"dataType": "refObject",
"properties": {
"channelTitle": {"dataType":"string"},
"subscriberCount": {"dataType":"double"},
"viewCount": {"dataType":"double"},
"videoCount": {"dataType":"double"},
},
"additionalProperties": true,
},
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
};
const validationService = new ValidationService(models);
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
export function RegisterRoutes(app: express.Router) {
// ###########################################################################################################
// NOTE: If you do not see routes for all of your controllers in this file, then you might not have informed tsoa of where to look
// Please look into the "controllerPathGlobs" config option described in the readme: https://github.com/lukeautry/tsoa
// ###########################################################################################################
app.get('/cryptocurrencies/price',
function CryptocurrenciesController_getCryptocurrencyPrice(request: any, response: any, next: any) {
const args = {
crypto: {"in":"query","name":"crypto","required":true,"dataType":"string"},
fiat: {"in":"query","name":"fiat","required":true,"dataType":"string"},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new CryptocurrenciesController();
const promise = controller.getCryptocurrencyPrice.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.get('/github/stats',
function GitHubController_getGitHubStats(request: any, response: any, next: any) {
const args = {
query: {"in":"query","name":"query","required":true,"dataType":"string"},
unprocessableEntity: {"in":"res","name":"422","required":true,"dataType":"nestedObjectLiteral","nestedProperties":{"reason":{"dataType":"string","required":true}}},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new GitHubController();
const promise = controller.getGitHubStats.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.get('/twitter/user',
function TwitterController_getTwitterStats(request: any, response: any, next: any) {
const args = {
username: {"in":"query","name":"username","required":true,"dataType":"string"},
notFound: {"in":"res","name":"404","required":true,"dataType":"nestedObjectLiteral","nestedProperties":{}},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new TwitterController();
const promise = controller.getTwitterStats.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.get('/unsplash/random',
function UnsplashController_getRandomImage(request: any, response: any, next: any) {
const args = {
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new UnsplashController();
const promise = controller.getRandomImage.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.get('/weather',
function WeatherController_getWeatherData(request: any, response: any, next: any) {
const args = {
lat: {"in":"query","name":"lat","required":true,"dataType":"string"},
lon: {"in":"query","name":"lon","required":true,"dataType":"string"},
unit: {"in":"query","name":"unit","required":true,"dataType":"union","subSchemas":[{"dataType":"enum","enums":["imperial"]},{"dataType":"enum","enums":["metric"]}]},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new WeatherController();
const promise = controller.getWeatherData.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
app.get('/youtube/stats',
function YoutubeController_getYoutubeStats(request: any, response: any, next: any) {
const args = {
query: {"in":"query","name":"query","required":true,"dataType":"string"},
notFound: {"in":"res","name":"404","required":true,"dataType":"nestedObjectLiteral","nestedProperties":{}},
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
let validatedArgs: any[] = [];
try {
validatedArgs = getValidatedArgs(args, request, response);
} catch (err) {
return next(err);
}
const controller = new YoutubeController();
const promise = controller.getYoutubeStats.apply(controller, validatedArgs as any);
promiseHandler(controller, promise, response, undefined, next);
});
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
function isController(object: any): object is Controller {
return 'getHeaders' in object && 'getStatus' in object && 'setStatus' in object;
}
function promiseHandler(controllerObj: any, promise: any, response: any, successStatus: any, next: any) {
return Promise.resolve(promise)
.then((data: any) => {
let statusCode = successStatus;
let headers;
if (isController(controllerObj)) {
headers = controllerObj.getHeaders();
statusCode = controllerObj.getStatus() || statusCode;
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
returnHandler(response, statusCode, data, headers)
})
.catch((error: any) => next(error));
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
function returnHandler(response: any, statusCode?: number, data?: any, headers: any = {}) {
if (response.headersSent) {
return;
}
Object.keys(headers).forEach((name: string) => {
response.set(name, headers[name]);
});
if (data && typeof data.pipe === 'function' && data.readable && typeof data._read === 'function') {
data.pipe(response);
} else if (data !== null && data !== undefined) {
response.status(statusCode || 200).json(data);
} else {
response.status(statusCode || 204).end();
}
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
function responder(response: any): TsoaResponse<HttpStatusCodeLiteral, unknown> {
return function(status, data, headers) {
returnHandler(response, status, data, headers);
};
};
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
function getValidatedArgs(args: any, request: any, response: any): any[] {
const fieldErrors: FieldErrors = {};
const values = Object.keys(args).map((key) => {
const name = args[key].name;
switch (args[key].in) {
case 'request':
return request;
case 'query':
return validationService.ValidateParam(args[key], request.query[name], name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
case 'path':
return validationService.ValidateParam(args[key], request.params[name], name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
case 'header':
return validationService.ValidateParam(args[key], request.header(name), name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
case 'body':
return validationService.ValidateParam(args[key], request.body, name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
case 'body-prop':
return validationService.ValidateParam(args[key], request.body[name], name, fieldErrors, 'body.', {"noImplicitAdditionalProperties":"ignore"});
case 'formData':
if (args[key].dataType === 'file') {
return validationService.ValidateParam(args[key], request.file, name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
} else if (args[key].dataType === 'array' && args[key].array.dataType === 'file') {
return validationService.ValidateParam(args[key], request.files, name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
} else {
return validationService.ValidateParam(args[key], request.body[name], name, fieldErrors, undefined, {"noImplicitAdditionalProperties":"ignore"});
}
case 'res':
return responder(response);
}
});
if (Object.keys(fieldErrors).length > 0) {
throw new ValidateError(fieldErrors, '');
}
return values;
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa
}
// WARNING: This file was auto-generated with tsoa. Please do not modify it. Re-run tsoa to re-generate this file: https://github.com/lukeautry/tsoa | the_stack |
import getDataValue from 'lodash.get';
import setDataValue from 'lodash.set';
import zip from 'lodash.zip';
import template from 'lodash.template';
import { FileUploadWidget } from './FileUploadWidget';
import { parse } from './tag-attributes';
type FieldElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
type FieldValue = string | Array<string | Object>;
type ErrorKey = keyof ValidityState;
const NON_FIELD_ERRORS = '__all__';
const MARKED_FOR_REMOVAL = '_marked_for_removal_';
function assert(condition: any) {
if (!condition)
throw new Error("Assertion failed");
}
class BoundValue {
public readonly value: FieldValue;
constructor(value: FieldValue) {
this.value = value;
}
equals(other: FieldValue) {
if (typeof this.value === 'string') {
return this.value === other;
} else {
return this.value.length === other.length && this.value.every((val, index) => val === other[index]);
}
}
}
class ErrorMessages extends Map<ErrorKey, string>{
constructor(fieldGroup: FieldGroup) {
super();
const element = fieldGroup.element.querySelector('django-error-messages');
if (!element)
throw new Error(`<django-field-group> for '${fieldGroup.name}' requires one <django-error-messages> tag.`);
for (const attr of element.getAttributeNames()) {
const clientKey = attr.replace(/([_][a-z])/g, (group) => group.toUpperCase().replace('_', ''));
const clientValue = element.getAttribute(attr);
if (clientValue) {
this.set(clientKey as ErrorKey, clientValue);
}
}
}
}
class FieldGroup {
public readonly form: DjangoForm;
public readonly name: string = '__undefined__';
public readonly element: HTMLElement;
private readonly pristineValue: BoundValue;
private readonly inputElements: Array<FieldElement>;
private readonly initialDisabled: Array<Boolean>;
public readonly errorPlaceholder: Element | null;
private readonly errorMessages: ErrorMessages;
private readonly fileUploader: FileUploadWidget | null = null;
private readonly updateVisibility: Function;
private readonly updateDisabled: Function;
constructor(form: DjangoForm, element: HTMLElement) {
this.form = form;
this.element = element;
this.errorPlaceholder = element.querySelector('.dj-errorlist > .dj-placeholder');
this.errorMessages = new ErrorMessages(this);
const requiredAny = element.classList.contains('dj-required-any');
const inputElements = (Array.from(element.getElementsByTagName('INPUT')) as Array<HTMLInputElement>).filter(e => e.name && e.type !== 'hidden');
for (const element of inputElements) {
switch (element.type) {
case 'checkbox':
case 'radio':
element.addEventListener('input', () => {
this.touch();
this.inputted()
});
element.addEventListener('change', () => {
requiredAny ? this.validateCheckboxSelectMultiple() : this.validate()
});
break;
case 'file':
this.fileUploader = new FileUploadWidget(this, element);
break;
default:
element.addEventListener('focus', () => this.touch());
element.addEventListener('input', () => this.inputted());
element.addEventListener('blur', () => this.validate());
break;
}
}
const selectElements = (Array.from(element.getElementsByTagName('SELECT')) as Array<HTMLSelectElement>).filter(e => e.name);
for (const element of selectElements) {
element.addEventListener('focus', () => this.touch());
element.addEventListener('change', () => {
this.setDirty();
this.resetCustomError();
this.validate()
});
}
const textAreaElements = Array.from(element.getElementsByTagName('TEXTAREA')) as Array<HTMLTextAreaElement>;
for (const element of textAreaElements) {
element.addEventListener('focus', () => this.touch());
element.addEventListener('input', () => this.inputted());
element.addEventListener('blur', () => this.validate());
}
this.inputElements = Array<FieldElement>(0).concat(inputElements, selectElements, textAreaElements);
for (const element of this.inputElements) {
if (this.name === '__undefined__') {
this.name = element.name;
} else {
if (this.name !== element.name)
throw new Error(`Name mismatch on multiple input fields on ${element.name}`);
}
}
this.initialDisabled = this.inputElements.map(element => element.disabled);
if (requiredAny) {
this.validateCheckboxSelectMultiple();
} else {
this.validateBoundField();
}
this.pristineValue = new BoundValue(this.aggregateValue());
this.updateVisibility = this.evalVisibility('show-if', true) ?? this.evalVisibility('hide-if', false) ?? function() {};
this.updateDisabled = this.evalDisable();
this.untouch();
this.setPristine();
}
public aggregateValue(): FieldValue {
if (this.inputElements.length === 1) {
const element = this.inputElements[0];
if (element.type === 'checkbox') {
return (element as HTMLInputElement).checked ? element.value : '';
}
if (element.type === 'select-multiple') {
const value = [];
const select = element as HTMLSelectElement;
for (const key in select.options) {
if (select.options[key].selected) {
value.push(select.options[key].value);
}
}
return value;
}
if (element.type === 'file') {
if (!this.fileUploader)
throw new Error("fileUploader expected");
return this.fileUploader.uploadedFiles;
}
// all other input types just return their value
return element.value;
} else {
const value = [];
for (let element of this.inputElements) {
if (element.type === 'checkbox') {
if ((element as HTMLInputElement).checked) {
value.push(element.value);
}
} else if (element.type === 'radio') {
if ((element as HTMLInputElement).checked)
return element.value;
}
}
return value;
}
}
public updateOperability() {
this.updateVisibility();
this.updateDisabled();
}
private evalVisibility(attribute: string, visible: boolean): Function | null {
const attrValue = this.inputElements[0].getAttribute(attribute);
if (typeof attrValue !== 'string')
return null;
try {
const evalExpression = new Function('return ' + parse(attrValue, {startRule: 'Expression'}));
if (visible) {
return () => this.element.toggleAttribute('hidden', !evalExpression.call(this));
} else {
return () => this.element.toggleAttribute('hidden', evalExpression.call(this));
}
} catch (error) {
throw new Error(`Error while parsing <... show-if/hide-if="${attrValue}">: ${error}.`);
}
}
private evalDisable(): Function {
const attrValue = this.inputElements[0].getAttribute('disable-if');
if (typeof attrValue !== 'string')
return () => {};
try {
const evalExpression = new Function('return ' + parse(attrValue, {startRule: 'Expression'}));
return () => {
const disable = evalExpression.call(this);
this.inputElements.forEach(elem => elem.disabled = disable);
}
} catch (error) {
throw new Error(`Error while parsing <... disable-if="${attrValue}">: ${error}.`);
}
}
getDataValue(path: Array<string>) {
return this.form.getDataValue(path);
}
public inputted() {
if (this.pristineValue.equals(this.aggregateValue())) {
this.setPristine();
} else {
this.setDirty();
}
this.resetCustomError();
}
private resetCustomError() {
this.form.resetCustomError();
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = '';
}
for (const element of this.inputElements) {
if (element.validity.customError)
element.setCustomValidity('');
}
}
public resetToInitial() {
if (this.fileUploader) {
this.fileUploader.resetToInitial();
}
this.untouch();
this.setPristine();
this.resetCustomError();
}
public disableAllFields() {
for (const element of this.inputElements) {
element.disabled = true;
}
}
public reenableAllFields() {
for (const [element, disabled] of zip(this.inputElements, this.initialDisabled)) {
if (element && typeof disabled === 'boolean') {
element.disabled = disabled;
}
}
}
public touch() {
this.element.classList.remove('dj-untouched');
this.element.classList.remove('dj-validated');
this.element.classList.add('dj-touched');
}
private untouch() {
this.element.classList.remove('dj-touched');
this.element.classList.add('dj-untouched');
}
private setDirty() {
this.element.classList.remove('dj-submitted');
this.element.classList.remove('dj-pristine');
this.element.classList.add('dj-dirty');
}
private setPristine() {
this.element.classList.remove('dj-dirty');
this.element.classList.add('dj-pristine');
}
public setSubmitted() {
this.element.classList.add('dj-submitted');
}
public validate() {
let element: FieldElement | null = null;
for (element of this.inputElements) {
if (!element.validity.valid)
break;
}
if (element && !element.validity.valid) {
for (const [key, message] of this.errorMessages) {
if (element.validity[key as keyof ValidityState]) {
if (this.form.formset.showFeedbackMessages && this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = message;
}
element = null;
break;
}
}
if (this.form.formset.showFeedbackMessages && element instanceof HTMLInputElement) {
this.validateInput(element);
}
}
this.form.validate();
}
private validateCheckboxSelectMultiple() {
let validity = false;
for (const inputElement of this.inputElements) {
if (inputElement.type !== 'checkbox')
throw new Error("Expected input element of type 'checkbox'.");
if ((inputElement as HTMLInputElement).checked) {
validity = true;
} else {
inputElement.setCustomValidity(this.errorMessages.get('customError') ?? '');
}
}
if (validity) {
for (const inputElement of this.inputElements) {
inputElement.setCustomValidity('');
}
} else if (this.pristineValue !== undefined && this.errorPlaceholder && this.form.formset.showFeedbackMessages) {
this.errorPlaceholder.innerHTML = this.errorMessages.get('customError') ?? '';
}
this.form.validate();
return validity;
}
private validateInput(inputElement: HTMLInputElement) {
// By default, HTML input fields do not validate their bound value regarding their
// min- and max-length. Therefore this validation must be performed by the client.
if (inputElement.type === 'text' && inputElement.value) {
if (inputElement.minLength > 0 && inputElement.value.length < inputElement.minLength) {
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = this.errorMessages.get('tooShort') ?? '';
}
return false;
}
if (inputElement.maxLength > 0 && inputElement.value.length > inputElement.maxLength) {
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = this.errorMessages.get('tooLong') ?? '';
}
return false;
}
}
if (inputElement.type === 'file' && this.fileUploader) {
if (this.fileUploader.inProgress()) {
// seems that file upload is still in progress => field shall not be valid
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = this.errorMessages.get('typeMismatch') ?? '';
}
return false;
}
}
return true;
}
private validateBoundField() {
// By default, HTML input fields do not validate their bound value regarding their min-
// and max-length. Therefore this validation must be performed separately.
if (this.inputElements.length !== 1 || !(this.inputElements[0] instanceof HTMLInputElement))
return;
const inputElement = this.inputElements[0];
if (!inputElement.value)
return;
if (inputElement.type === 'text') {
if (inputElement.minLength > 0 && inputElement.value.length < inputElement.minLength)
return inputElement.setCustomValidity(this.errorMessages.get('tooShort') ?? '');
if (inputElement.maxLength > 0 && inputElement.value.length > inputElement.maxLength)
return inputElement.setCustomValidity(this.errorMessages.get('tooLong') ?? '');
}
}
public setValidationError(): boolean {
let element: FieldElement | undefined;
for (element of this.inputElements) {
if (!element.validity.valid)
break;
}
for (const [key, message] of this.errorMessages) {
if (element && element.validity[key as ErrorKey]) {
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = message;
element.setCustomValidity(message);
}
return false;
}
}
if (element instanceof HTMLInputElement)
return this.validateInput(element);
return true;
}
public reportCustomError(message: string) {
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = message;
}
this.inputElements[0].setCustomValidity(message);
}
public reportFailedUpload() {
if (this.errorPlaceholder) {
this.errorPlaceholder.innerHTML = this.errorMessages.get('badInput') ?? "File upload failed";
}
}
}
class ButtonAction {
constructor(func: Function, args: Array<any>) {
this.func = func;
this.args = args;
}
public readonly func: Function;
public readonly args: Array<any>;
}
class DjangoButton {
private readonly formset: DjangoFormset;
private readonly element: HTMLButtonElement;
private readonly initialClass: string;
private readonly isAutoDisabled: boolean;
private readonly successActions = Array<ButtonAction>(0);
private readonly rejectActions = Array<ButtonAction>(0);
private timeoutHandler?: number;
constructor(formset: DjangoFormset, element: HTMLButtonElement) {
this.formset = formset;
this.element = element;
this.initialClass = element.getAttribute('class') ?? '';
this.isAutoDisabled = !!JSON.parse((element.getAttribute('auto-disable') ?? 'false').toLowerCase());
this.parseActionsQueue(element.getAttribute('click'));
element.addEventListener('click', () => this.clicked());
}
/**
* Event handler to be called when someone clicks on the button.
*/
// @ts-ignore
private clicked() {
let promise: Promise<Response> | undefined;
for (const [index, action] of this.successActions.entries()) {
if (!promise) {
promise = action.func.apply(this, action.args)();
} else {
promise = promise.then(action.func.apply(this, action.args));
}
}
if (promise) {
for (const [index, action] of this.rejectActions.entries()) {
if (index === 0) {
promise = promise.catch(action.func.apply(this, action.args));
} else {
promise = promise.then(action.func.apply(this, action.args));
}
}
promise.finally(this.restore.apply(this));
}
}
public autoDisable(formValidity: Boolean) {
if (this.isAutoDisabled) {
this.element.disabled = !formValidity;
}
}
/**
* Disable the button for further submission.
*/
// @ts-ignore
private disable() {
return (response: Response) => {
this.element.disabled = true;
return Promise.resolve(response);
};
}
/**
* Re-enable the button for further submission.
*/
// @ts-ignore
enable() {
return (response: Response) => {
this.element.disabled = false;
return Promise.resolve(response);
};
}
/**
* Validate form content and submit to the endpoint given in element `<django-formset>`.
*/
// @ts-ignore
submit(data: Object | undefined) {
return () => {
return new Promise((resolve, reject) => {
this.formset.submit(data).then(response =>
response instanceof Response && response.status === 200 ? resolve(response) : reject(response)
);
});
};
}
/**
* Reset form content to their initial values.
*/
// @ts-ignore
reset() {
return (response: Response) => {
this.formset.resetToInitial();
return Promise.resolve(response);
};
}
/**
* Proceed to a given URL, if the response object returns status code 200.
* If the response object contains an element `success_url`, proceed to that URL,
* otherwise proceed to the given fallback URL.
*
* @param fallbackUrl: The URL to proceed to, for valid response objects without
* given success URL.
*/
// @ts-ignore
private proceed(fallbackUrl: string | undefined) {
return (response: Response) => {
if (response instanceof Response && response.status === 200) {
response.json().then(body => {
if ('success_url' in body) {
window.location.href = body.success_url;
}
});
if (typeof fallbackUrl === 'string') {
window.location.href = fallbackUrl;
}
}
return Promise.resolve(response);
}
}
/**
* Delay execution of the next task.
*
* @param ms: Time to wait in milliseconds.
*/
// @ts-ignore
private delay(ms: number) {
return (response: Response) => new Promise(resolve => this.timeoutHandler = window.setTimeout(() => {
this.timeoutHandler = undefined;
resolve(response);
}, ms));
}
public abortAction() {
if (this.timeoutHandler) {
clearTimeout(this.timeoutHandler);
this.timeoutHandler = undefined;
}
}
/**
* Add a CSS class to the button element.
*
* @param cssClass: The CSS class.
*/
// @ts-ignore
private addClass(cssClass: string) {
return (response: Response) => {
this.element.classList.add(cssClass);
return Promise.resolve(response);
};
}
/**
* Remove a CSS class from the button element.
*
* @param cssClass: The CSS class.
*/
// @ts-ignore
private removeClass(cssClass: string) {
return (response: Response) => {
this.element.classList.remove(cssClass);
return Promise.resolve(response);
};
}
/**
* Add a CSS class to the button element or remove it if it is already set.
*
* @param cssClass: The CSS class.
*/
// @ts-ignore
private toggleClass(cssClass: string) {
return (response: Response) => {
this.element.classList.toggle(cssClass);
return Promise.resolve(response);
};
}
/**
* Emit an event to the DOM.
*
* @param event: The named event.
*/
// @ts-ignore
private emit(namedEvent: string, detail: Object | undefined) {
return (response: Response) => {
const options = {bubbles: true, cancelable: true};
if (detail !== undefined) {
Object.assign(options, {detail: detail});
this.element.dispatchEvent(new CustomEvent(namedEvent, options));
} else {
this.element.dispatchEvent(new Event(namedEvent, options));
}
return Promise.resolve(response);
};
}
/**
* For debugging purpose only: Intercept, log and forward the response object to the next handler.
*/
// @ts-ignore
private intercept() {
return (response: Response) => {
console.info(response);
return Promise.resolve(response);
}
}
/**
* Scroll to first element reporting an error.
*/
// @ts-ignore
private scrollToError() {
return (response: Response) => {
const errorReportElement = this.formset.findFirstErrorReport();
if (errorReportElement) {
errorReportElement.scrollIntoView({behavior: 'smooth'});
}
return Promise.resolve(response);
}
}
/**
* Dummy action to be called in case of empty actionsQueue.
*/
private noop() {
return (response: Response) => {
return Promise.resolve(response);
}
}
private restore() {
return () => {
this.element.setAttribute('class', this.initialClass);
this.element.disabled = false;
}
}
private parseActionsQueue(actionsQueue: string | null) {
if (!actionsQueue)
return;
let self = this;
function createActions(actions: Array<ButtonAction>, chain: Array<any>) {
for (let action of chain) {
const func = self[action.funcname as keyof DjangoButton];
if (typeof func !== 'function')
throw new Error(`Unknown function '${action.funcname}'.`);
actions.push(new ButtonAction(func, action.args));
}
if (actions.length === 0) {
// the actionsQueue must resolve at least once
actions.push(new ButtonAction(self.noop, []));
}
}
try {
const ast = parse(actionsQueue, {startRule: 'Actions'});
createActions(this.successActions, ast.successChain);
createActions(this.rejectActions, ast.rejectChain);
} catch (error) {
throw new Error(`Error while parsing <button click="${actionsQueue}">: ${error}.`);
}
}
}
class DjangoFieldset {
public readonly form: DjangoForm;
private readonly element: HTMLFieldSetElement;
private readonly updateVisibility: Function;
private readonly updateDisabled: Function;
constructor(form: DjangoForm, element: HTMLFieldSetElement) {
this.form = form;
this.element = element;
this.updateVisibility = this.evalVisibility('show-if', true) ?? this.evalVisibility('hide-if', false) ?? function() {};
this.updateDisabled = this.evalDisable();
}
private evalVisibility(attribute: string, visible: boolean): Function | null {
const attrValue = this.element.getAttribute(attribute);
if (typeof attrValue !== 'string')
return null;
try {
const evalExpression = new Function('return ' + parse(attrValue, {startRule: 'Expression'}));
if (visible) {
return () => this.element.toggleAttribute('hidden', !evalExpression.call(this));
} else {
return () => this.element.toggleAttribute('hidden', evalExpression.call(this));
}
} catch (error) {
throw new Error(`Error while parsing <fieldset show-if/hide-if="${attrValue}">: ${error}.`);
}
}
private evalDisable(): Function {
const attrValue = this.element.getAttribute('disable-if');
if (typeof attrValue !== 'string')
return () => {};
try {
const evalExpression = new Function('return ' + parse(attrValue, {startRule: 'Expression'}));
return () => this.element.disabled = evalExpression.call(this);
} catch (error) {
throw new Error(`Error while parsing <fieldset disable-if="${attrValue}">: ${error}.`);
}
}
private getDataValue(path: Array<string>) {
return this.form.getDataValue(path);
}
updateOperability() {
this.updateVisibility();
this.updateDisabled();
}
}
class DjangoForm {
public readonly formId: string | null;
public readonly name: string | null;
public readonly path: Array<string>;
public readonly formset: DjangoFormset;
public readonly element: HTMLFormElement;
public readonly fieldset: DjangoFieldset | null;
private readonly errorList: Element | null;
private readonly errorPlaceholder: Element | null;
public readonly fieldGroups = Array<FieldGroup>(0);
public readonly hiddenInputFields = Array<HTMLInputElement>(0);
public markedForRemoval = false;
constructor(formset: DjangoFormset, element: HTMLFormElement) {
this.formId = element.getAttribute('id');
this.name = element.getAttribute('name') ?? null;
this.path = this.name?.split('.') ?? [];
this.formset = formset;
this.element = element;
const fieldsetElement = element.querySelector('fieldset');
this.fieldset = fieldsetElement ? new DjangoFieldset(this, fieldsetElement) : null;
const formError = element.querySelector('.dj-form-errors');
const placeholder = formError ? formError.querySelector('.dj-errorlist > .dj-placeholder') : null;
if (placeholder) {
this.errorList = placeholder.parentElement;
this.errorPlaceholder = this.errorList ? this.errorList.removeChild(placeholder) : null;
} else {
this.errorList = this.errorPlaceholder = null;
}
}
aggregateValues(): Map<string, FieldValue> {
const data = new Map<string, FieldValue>();
for (const fieldGroup of this.fieldGroups) {
data.set(fieldGroup.name, fieldGroup.aggregateValue());
}
// hidden fields are not handled by a django-field-group
for (const element of this.hiddenInputFields.filter(e => e.type === 'hidden')) {
data.set(element.name, element.value);
}
return data;
}
getDataValue(path: Array<string>) {
const absPath = [];
if (path[0] === '') {
// path is relative, so concatenate it to the form's path
absPath.push(...this.path);
const relPath = path.filter(part => part !== '');
const delta = path.length - relPath.length;
absPath.splice(absPath.length - delta + 1);
absPath.push(...relPath);
} else {
absPath.push(...path);
}
return this.formset.getDataValue(absPath);
}
updateOperability() {
this.fieldset?.updateOperability();
for (const fieldGroup of this.fieldGroups) {
fieldGroup.updateOperability();
}
}
setSubmitted() {
for (const fieldGroup of this.fieldGroups) {
fieldGroup.setSubmitted();
}
}
validate() {
this.formset.validate();
}
isValid() {
let isValid = true;
for (const fieldGroup of this.fieldGroups) {
isValid = fieldGroup.setValidationError() && isValid;
}
return isValid;
}
checkValidity() {
return this.element.checkValidity();
}
reportValidity() {
this.element.reportValidity();
}
resetCustomError() {
while (this.errorList && this.errorList.lastChild) {
this.errorList.removeChild(this.errorList.lastChild);
}
}
resetToInitial() {
this.element.reset();
for (const fieldGroup of this.fieldGroups) {
fieldGroup.resetToInitial();
}
}
toggleForRemoval(remove: boolean) {
this.markedForRemoval = remove;
for (const fieldGroup of this.fieldGroups) {
if (remove) {
fieldGroup.resetToInitial();
fieldGroup.disableAllFields();
} else {
fieldGroup.reenableAllFields();
}
}
}
reportCustomErrors(errors: Map<string, Array<string>>) {
this.resetCustomError();
const nonFieldErrors = errors.get(NON_FIELD_ERRORS);
if (this.errorList && nonFieldErrors instanceof Array && this.errorPlaceholder) {
for (const message of nonFieldErrors) {
const item = this.errorPlaceholder.cloneNode() as Element;
item.innerHTML = message;
this.errorList.appendChild(item);
}
}
for (const fieldGroup of this.fieldGroups) {
const fieldErrors = errors.get(fieldGroup.name);
if (fieldErrors instanceof Array && fieldErrors.length > 0) {
fieldGroup.reportCustomError(fieldErrors[0]);
}
}
}
findFirstErrorReport() : Element | null {
if (this.errorList?.textContent)
return this.element; // report a non-field error
for (const fieldGroup of this.fieldGroups) {
if (fieldGroup.errorPlaceholder?.textContent)
return fieldGroup.element;
}
return null;
}
}
class DjangoFormCollection {
protected readonly formset: DjangoFormset;
protected readonly element: Element;
protected readonly parent?: DjangoFormCollection;
protected readonly removeButton: HTMLButtonElement | null = null;
protected forms = Array<DjangoForm>(0);
public formCollectionTemplate?: DjangoFormCollectionTemplate;
public readonly children = Array<DjangoFormCollection>(0);
public markedForRemoval = false;
constructor(formset: DjangoFormset, element: Element, parent?: DjangoFormCollection, justAdded?: boolean) {
this.formset = formset;
this.element = element;
this.parent = parent;
this.findFormCollections();
this.removeButton = element.querySelector(':scope > button.remove-collection');
}
private findFormCollections() {
// find all immediate elements <django-form-collection> of this DjangoFormCollection
for (const childElement of this.element.querySelectorAll(':scope > django-form-collection')) {
this.children.push(childElement.hasAttribute('sibling-position')
? new DjangoFormCollectionSibling(this.formset, childElement, this)
: new DjangoFormCollection(this.formset, childElement, this)
);
}
for (const sibling of this.children) {
sibling.updateRemoveButtonAttrs();
}
this.formCollectionTemplate = DjangoFormCollectionTemplate.findFormCollectionTemplate(this.formset, this.element, this);
}
public assignForms(forms: Array<DjangoForm>) {
this.forms = forms.filter(form => form.element.parentElement?.isEqualNode(this.element));
for (const formCollection of this.children) {
formCollection.assignForms(forms);
}
}
public updateRemoveButtonAttrs() {
assert(this.removeButton === null);
}
toggleForRemoval(remove: boolean) {
this.markedForRemoval = remove;
for (const form of this.forms) {
form.toggleForRemoval(remove);
}
for (const formCollection of this.children) {
formCollection.toggleForRemoval(remove);
}
if (this.formCollectionTemplate) {
this.formCollectionTemplate.markedForRemoval = remove;
this.formCollectionTemplate.updateAddButtonAttrs();
}
if (this.removeButton) {
this.removeButton.disabled = remove;
}
this.element.classList.toggle('dj-marked-for-removal', this.markedForRemoval);
}
}
class DjangoFormCollectionSibling extends DjangoFormCollection {
public readonly position: number;
private readonly minSiblings: number = 0;
public readonly maxSiblings: number | null = null;
private justAdded = false;
constructor(formset: DjangoFormset, element: Element, parent?: DjangoFormCollection, justAdded?: boolean) {
super(formset, element, parent);
this.justAdded = justAdded ?? false;
const position = element.getAttribute('sibling-position');
if (!position)
throw new Error("Missing argument 'sibling-position' in <django-form-collection>")
this.position = parseInt(position);
const minSiblings = element.getAttribute('min-siblings');
if (!minSiblings)
throw new Error("Missing argument 'min-siblings' in <django-form-collection>")
this.minSiblings = parseInt(minSiblings);
const maxSiblings = element.getAttribute('max-siblings');
if (maxSiblings)
this.maxSiblings = parseInt(maxSiblings);
this.removeButton?.addEventListener('click', () => this.removeCollection());
}
private removeCollection() {
if (this.justAdded) {
this.element.remove();
this.toggleForRemoval(true);
} else {
this.toggleForRemoval(!this.markedForRemoval);
}
const siblings = this.parent?.children ?? this.formset.formCollections;
for (const sibling of siblings) {
sibling.updateRemoveButtonAttrs();
}
const formCollectionTemplate = this.parent?.formCollectionTemplate ?? this.formset.formCollectionTemplate;
formCollectionTemplate?.updateAddButtonAttrs();
}
updateRemoveButtonAttrs() {
if (!this.removeButton)
return;
const siblings = this.parent?.children ?? this.formset.formCollections;
const numActiveSiblings = siblings.filter(s => !s.markedForRemoval).length;
if (this.markedForRemoval) {
if (this.maxSiblings) {
this.removeButton.disabled = numActiveSiblings >= this.maxSiblings;
} else {
this.removeButton.disabled = false;
}
} else {
this.removeButton.disabled = numActiveSiblings <= this.minSiblings;
}
}
}
class DjangoFormCollectionTemplate {
private readonly formset: DjangoFormset;
private readonly element: HTMLTemplateElement;
private readonly parent?: DjangoFormCollection;
private readonly renderEmptyCollection: Function;
private readonly addButton?: HTMLButtonElement;
private readonly baseContext = new Map<string, string>();
public markedForRemoval = false;
constructor(formset: DjangoFormset, element: HTMLTemplateElement, parent?: DjangoFormCollection) {
this.formset = formset;
this.element = element;
this.parent = parent;
const matches = element.innerHTML.matchAll(/\$\{([^} ]+)\}/g);
for (const match of matches) {
this.baseContext.set(match[1], match[0]);
}
this.renderEmptyCollection = template(element.innerHTML);
if (element.nextElementSibling?.matches('button.add-collection')) {
this.addButton = element.nextElementSibling as HTMLButtonElement;
this.addButton.addEventListener('click', event => this.appendFormCollectionSibling());
}
}
private appendFormCollectionSibling() {
const context = Object.fromEntries(this.baseContext);
context['position'] = (this.getHighestPosition() + 1).toString();
// this context rewriting is necessary to render nested templates properly.
// the hard-coded limit of 10 nested levels should be more than anybody ever will need
context['position_1'] = '${position}'
for (let k = 1; k < 10; ++k) {
context[`position_${k + 1}`] = `$\{position_${k}\}`;
}
const renderedHTML = this.renderEmptyCollection(context);
this.element.insertAdjacentHTML('beforebegin', renderedHTML);
const newCollectionElement = this.element.previousElementSibling;
if (!newCollectionElement)
throw new Error("Unable to insert empty <django-form-collection> element.");
const siblings = this.parent?.children ?? this.formset.formCollections;
siblings.push(new DjangoFormCollectionSibling(this.formset, newCollectionElement, this.parent, true));
this.formset.findForms(newCollectionElement);
this.formset.assignFieldsToForms(newCollectionElement);
this.formset.assignFormsToCollections();
this.formset.validate();
for (const sibling of siblings) {
sibling.updateRemoveButtonAttrs();
}
this.updateAddButtonAttrs();
}
private getHighestPosition() : number {
// look for the highest position number inside interconnected DjangoFormCollectionSiblings
let position = -1;
const children = this.parent ? this.parent.children : this.formset.formCollections;
for (const sibling of children.filter(s => s instanceof DjangoFormCollectionSibling)) {
position = Math.max(position, (sibling as DjangoFormCollectionSibling).position);
}
return position;
}
public updateAddButtonAttrs() {
if (!this.addButton)
return;
if (this.markedForRemoval) {
this.addButton.disabled = true;
return;
}
const siblings = this.parent?.children ?? this.formset.formCollections;
if (siblings.length === 0)
return;
assert(siblings[0] instanceof DjangoFormCollectionSibling);
const maxSiblings = (siblings[0] as DjangoFormCollectionSibling).maxSiblings;
const numActiveSiblings = siblings.filter(s => !s.markedForRemoval).length;
this.addButton.disabled = maxSiblings === null ? false : numActiveSiblings >= maxSiblings;
}
static findFormCollectionTemplate(formset: DjangoFormset, element: Element, formCollection?: DjangoFormCollection) : DjangoFormCollectionTemplate | undefined {
const templateElement = element.querySelector(':scope > template.empty-collection');
if (templateElement) {
const formCollectionTemplate = new DjangoFormCollectionTemplate(formset, templateElement as HTMLTemplateElement, formCollection);
formCollectionTemplate.updateAddButtonAttrs();
return formCollectionTemplate;
}
}
}
export class DjangoFormset {
private readonly element: DjangoFormsetElement;
private readonly buttons = Array<DjangoButton>(0);
private readonly forms = Array<DjangoForm>(0);
public readonly formCollections = Array<DjangoFormCollection>(0);
public formCollectionTemplate?: DjangoFormCollectionTemplate;
public readonly showFeedbackMessages: boolean;
private readonly abortController = new AbortController;
private data = {};
constructor(formset: DjangoFormsetElement) {
this.element = formset;
this.showFeedbackMessages = this.parseWithholdFeedback();
}
public get endpoint(): string {
return this.element.getAttribute('endpoint') ?? '';
}
public get forceSubmission(): Boolean {
return this.element.hasAttribute('force-submission');
}
private parseWithholdFeedback(): boolean {
let showFeedbackMessages = true;
const withholdFeedback = this.element.getAttribute('withhold-feedback')?.split(' ') ?? [];
const feedbackClasses = new Set(['dj-feedback-errors', 'dj-feedback-warnings', 'dj-feedback-success']);
for (const wf of withholdFeedback) {
switch (wf.toLowerCase()) {
case 'messages':
showFeedbackMessages = false;
break;
case 'errors':
feedbackClasses.delete('dj-feedback-errors');
break;
case 'warnings':
feedbackClasses.delete('dj-feedback-warnings');
break;
case 'success':
feedbackClasses.delete('dj-feedback-success');
break;
default:
throw new Error(`Unknown value in <django-formset withhold-feedback="${wf}">.`);
}
}
feedbackClasses.forEach(feedbackClass => this.element.classList.add(feedbackClass));
return showFeedbackMessages;
}
public assignFieldsToForms(parentElement?: Element) {
parentElement = parentElement ?? this.element;
for (const element of parentElement.querySelectorAll('INPUT, SELECT, TEXTAREA')) {
const formId = element.getAttribute('form');
let djangoForm: DjangoForm;
if (formId) {
const djangoForms = this.forms.filter(form => form.formId && form.formId === formId);
if (djangoForms.length > 1)
throw new Error(`More than one form has id="${formId}"`);
if (djangoForms.length !== 1)
continue;
djangoForm = djangoForms[0];
} else {
const formElement = element.closest('form');
if (!formElement)
continue;
const djangoForms = this.forms.filter(form => form.element === formElement);
if (djangoForms.length !== 1)
continue;
djangoForm = djangoForms[0];
}
const fieldGroupElement = element.closest('django-field-group');
if (fieldGroupElement) {
if (djangoForm.fieldGroups.filter(fg => fg.element === fieldGroupElement).length === 0) {
djangoForm.fieldGroups.push(new FieldGroup(djangoForm, fieldGroupElement as HTMLElement));
}
} else if (element.nodeName === 'INPUT' && (element as HTMLInputElement).type === 'hidden') {
const hiddenInputElement = element as HTMLInputElement;
if (!djangoForm.hiddenInputFields.includes(hiddenInputElement)) {
djangoForm.hiddenInputFields.push(hiddenInputElement);
}
}
}
}
public findForms(parentElement?: Element) {
parentElement = parentElement ?? this.element;
for (const element of parentElement.getElementsByTagName('FORM')) {
const form = new DjangoForm(this, element as HTMLFormElement);
this.forms.push(form);
}
this.checkForUniqueness();
}
private checkForUniqueness() {
const formNames = Array<string>(0);
if (this.forms.length > 1) {
for (const form of this.forms) {
if (!form.name)
throw new Error('Multiple <form>-elements in a <django-formset> require a unique name each.');
if (form.name in formNames)
throw new Error(`Detected more than one <form name="${form.name}"> in <django-formset>.`);
formNames.push(form.name);
}
}
}
public findFormCollections() {
// find all immediate elements <django-form-collection sibling-position="..."> belonging to the current <django-formset>
for (const element of this.element.querySelectorAll(':scope > django-form-collection')) {
this.formCollections.push(element.hasAttribute('sibling-position')
? new DjangoFormCollectionSibling(this, element)
: new DjangoFormCollection(this, element)
);
}
for (const sibling of this.formCollections) {
sibling.updateRemoveButtonAttrs();
}
this.formCollectionTemplate = DjangoFormCollectionTemplate.findFormCollectionTemplate(this, this.element);
}
public findButtons() {
this.buttons.length = 0;
for (const element of this.element.getElementsByTagName('BUTTON')) {
if (element.hasAttribute('click')) {
this.buttons.push(new DjangoButton(this, element as HTMLButtonElement));
}
}
}
public assignFormsToCollections() {
for (const sibling of this.formCollections) {
sibling.assignForms(this.forms);
}
}
public get CSRFToken(): string | undefined {
const value = `; ${document.cookie}`;
const parts = value.split('; csrftoken=');
if (parts.length === 2) {
return parts[1].split(';').shift();
}
}
private aggregateValues() {
this.data = {};
for (const form of this.forms) {
const path = ['formset_data']
if (form.name) {
path.push(...form.name.split('.'));
}
setDataValue(this.data, path, Object.fromEntries(form.aggregateValues()));
}
for (const form of this.forms) {
if (!form.markedForRemoval) {
form.updateOperability();
}
}
}
public validate() {
let isValid = true;
for (const form of this.forms) {
isValid = (form.markedForRemoval || form.checkValidity()) && isValid;
}
for (const button of this.buttons) {
button.autoDisable(isValid);
}
this.aggregateValues();
return isValid;
}
private buildBody(extraData?: Object) : Object {
let dataValue: any;
// Build `body`-Object recursively.
// deliberately ignore type-checking, because `body` must be build as POJO to be JSON serializable.
// If it would have been build as a `Map<string, Object>`, the `body` would additionally have to be
// converted to a POJO by a second recursive function.
function extendBody(entry: any, relPath: Array<string>) {
if (relPath.length === 1) {
// the leaf object
if (dataValue === MARKED_FOR_REMOVAL) {
entry[MARKED_FOR_REMOVAL] = MARKED_FOR_REMOVAL;
} else if (Array.isArray(entry)) {
entry.push(dataValue);
} else {
entry[relPath[0]] = dataValue;
}
return;
}
if (isNaN(parseInt(relPath[1]))) {
let innerObject;
if (Array.isArray(entry)) {
innerObject = {};
entry.push(innerObject)
} else {
innerObject = entry[relPath[0]] ?? {};
Object.isExtensible(innerObject);
entry[relPath[0]] = innerObject;
}
extendBody(innerObject, relPath.slice(1));
} else {
if (Array.isArray(entry))
throw new Error("Invalid form name: Contains nested arrays.");
const innerArray = entry[relPath[0]] ?? [];
entry[relPath[0]] = innerArray;
extendBody(innerArray, relPath.slice(1));
}
}
const body = {};
for (const form of this.forms) {
if (!form.name) // only a single form doesn't have a name
return Object.assign({}, this.data, {_extra: extraData});
const absPath = ['formset_data', ...form.path];
dataValue = form.markedForRemoval ? MARKED_FOR_REMOVAL : getDataValue(this.data, absPath);
extendBody(body, absPath);
}
return Object.assign({}, body, {_extra: extraData});
}
public async submit(extraData?: Object): Promise<Response | undefined> {
let formsAreValid = true;
this.setSubmitted();
if (!this.forceSubmission) {
for (const form of this.forms) {
formsAreValid = (form.markedForRemoval || form.isValid()) && formsAreValid;
}
}
if (formsAreValid) {
if (!this.endpoint)
throw new Error("<django-formset> requires attribute 'endpoint=\"server endpoint\"' for submission");
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
const csrfToken = this.CSRFToken;
if (csrfToken) {
headers.append('X-CSRFToken', csrfToken);
}
const response = await fetch(this.endpoint, {
method: 'POST',
headers: headers,
body: JSON.stringify(this.buildBody(extraData)),
signal: this.abortController.signal,
});
if (response.status === 422) {
const body = await response.json();
for (const form of this.forms) {
const errors = form.name ? getDataValue(body, form.name.split('.'), null) : body;
if (errors) {
form.reportCustomErrors(new Map(Object.entries(errors)));
form.reportValidity();
} else {
form.resetCustomError();
}
}
}
return response;
} else {
for (const form of this.forms) {
form.reportValidity();
}
}
}
public resetToInitial() {
for (const form of this.forms) {
form.resetToInitial();
}
}
/**
* Abort the current actions.
*/
public abort() {
for (const button of this.buttons) {
button.abortAction();
}
this.abortController.abort();
}
private setSubmitted() {
for (const form of this.forms) {
form.setSubmitted();
}
}
public getDataValue(path: Array<string>) : string | null {
const absPath = ['formset_data'];
absPath.push(...path);
return getDataValue(this.data, absPath, null);
}
findFirstErrorReport() : Element | null {
for (const form of this.forms) {
const errorReportElement = form.findFirstErrorReport();
if (errorReportElement)
return errorReportElement;
}
return null;
}
}
const FS = Symbol('DjangoFormset');
export class DjangoFormsetElement extends HTMLElement {
private readonly [FS]: DjangoFormset; // hides internal implementation
constructor() {
super();
this[FS] = new DjangoFormset(this);
}
private static get observedAttributes() {
return ['endpoint', 'withhold-messages', 'force-submission'];
}
private connectedCallback() {
this[FS].findButtons();
this[FS].findForms();
this[FS].findFormCollections();
this[FS].assignFieldsToForms();
this[FS].assignFormsToCollections();
window.setTimeout(() => this[FS].validate(), 0);
}
public async submit(data: Object | undefined): Promise<Response | undefined> {
return this[FS].submit(data);
}
public async abort() {
return this[FS].abort();
}
public async reset() {
return this[FS].resetToInitial();
}
} | the_stack |
// Query Compiler
// -------
import helpers from '../helpers.js';
import Raw from '../raw.js';
import QueryBuilder from './builder.js';
import JoinClause from './joinclause.js';
import debug from '../deps/debug@4.1.1/src/index.js';
import _ from '../deps/lodash@4.17.15/index.js';
const assign = _.assign;
const bind = _.bind;
const compact = _.compact;
const groupBy = _.groupBy;
const has = _.has;
const isEmpty = _.isEmpty;
const isString = _.isString;
const isUndefined = _.isUndefined;
const map = _.map;
const omitBy = _.omitBy;
const reduce = _.reduce;
import * as uuidlib from "../deps/uuid/mod.ts";
const uuid = {
v1: uuidlib.v1.generate
}
const debugBindings = debug('knex:bindings');
const components = [
'columns',
'join',
'where',
'union',
'group',
'having',
'order',
'limit',
'offset',
'lock',
'waitMode',
];
// The "QueryCompiler" takes all of the query statements which
// have been gathered in the "QueryBuilder" and turns them into a
// properly formatted / bound query string.
class QueryCompiler {
constructor(client, builder) {
this.client = client;
this.method = builder._method || 'select';
this.options = builder._options;
this.single = builder._single;
this.timeout = builder._timeout || false;
this.cancelOnTimeout = builder._cancelOnTimeout || false;
this.grouped = groupBy(builder._statements, 'grouping');
this.formatter = client.formatter(builder);
// Used when the insert call is empty.
this._emptyInsertValue = 'default values';
this.first = this.select;
}
// Collapse the builder into a single object
toSQL(method, tz) {
this._undefinedInWhereClause = false;
this.undefinedBindingsInfo = [];
method = method || this.method;
const val = this[method]() || '';
const query = {
method,
options: reduce(this.options, assign, {}),
timeout: this.timeout,
cancelOnTimeout: this.cancelOnTimeout,
bindings: this.formatter.bindings || [],
__knexQueryUid: uuid.v1(),
};
Object.defineProperties(query, {
toNative: {
value: () => {
return {
sql: this.client.positionBindings(query.sql),
bindings: this.client.prepBindings(query.bindings),
};
},
enumerable: false,
},
});
if (isString(val)) {
query.sql = val;
} else {
assign(query, val);
}
if (method === 'select' || method === 'first') {
if (this.single.as) {
query.as = this.single.as;
}
}
if (this._undefinedInWhereClause) {
debugBindings(query.bindings);
throw new Error(
`Undefined binding(s) detected when compiling ` +
`${method.toUpperCase()}. Undefined column(s): [${this.undefinedBindingsInfo.join(
', '
)}] query: ${query.sql}`
);
}
return query;
}
// Compiles the `select` statement, or nested sub-selects by calling each of
// the component compilers, trimming out the empties, and returning a
// generated query string.
select() {
let sql = this.with();
const statements = components.map((component) => this[component](this));
sql += compact(statements).join(' ');
return sql;
}
pluck() {
let toPluck = this.single.pluck;
if (toPluck.indexOf('.') !== -1) {
toPluck = toPluck.split('.').slice(-1)[0];
}
return {
sql: this.select(),
pluck: toPluck,
};
}
// Compiles an "insert" query, allowing for multiple
// inserts using a single query statement.
insert() {
const insertValues = this.single.insert || [];
let sql = this.with() + `insert into ${this.tableName} `;
if (Array.isArray(insertValues)) {
if (insertValues.length === 0) {
return '';
}
} else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
return sql + this._emptyInsertValue;
}
const insertData = this._prepInsert(insertValues);
if (typeof insertData === 'string') {
sql += insertData;
} else {
if (insertData.columns.length) {
sql += `(${this.formatter.columnize(insertData.columns)}`;
sql += ') values (';
let i = -1;
while (++i < insertData.values.length) {
if (i !== 0) sql += '), (';
sql += this.formatter.parameterize(
insertData.values[i],
this.client.valueForUndefined
);
}
sql += ')';
} else if (insertValues.length === 1 && insertValues[0]) {
sql += this._emptyInsertValue;
} else {
sql = '';
}
}
return sql;
}
// Compiles the "update" query.
update() {
// Make sure tableName is processed by the formatter first.
const withSQL = this.with();
const { tableName } = this;
const updateData = this._prepUpdate(this.single.update);
const wheres = this.where();
return (
withSQL +
`update ${this.single.only ? 'only ' : ''}${tableName}` +
' set ' +
updateData.join(', ') +
(wheres ? ` ${wheres}` : '')
);
}
// Compiles the columns in the query, specifying if an item was distinct.
columns() {
let distinctClause = '';
if (this.onlyUnions()) return '';
const columns = this.grouped.columns || [];
let i = -1,
sql = [];
if (columns) {
while (++i < columns.length) {
const stmt = columns[i];
if (stmt.distinct) distinctClause = 'distinct ';
if (stmt.distinctOn) {
distinctClause = this.distinctOn(stmt.value);
continue;
}
if (stmt.type === 'aggregate') {
sql.push(...this.aggregate(stmt));
} else if (stmt.type === 'aggregateRaw') {
sql.push(this.aggregateRaw(stmt));
} else if (stmt.value && stmt.value.length > 0) {
sql.push(this.formatter.columnize(stmt.value));
}
}
}
if (sql.length === 0) sql = ['*'];
return (
`select ${distinctClause}` +
sql.join(', ') +
(this.tableName
? ` from ${this.single.only ? 'only ' : ''}${this.tableName}`
: '')
);
}
_aggregate(stmt, { aliasSeparator = ' as ', distinctParentheses } = {}) {
const value = stmt.value;
const method = stmt.method;
const distinct = stmt.aggregateDistinct ? 'distinct ' : '';
const wrap = (identifier) => this.formatter.wrap(identifier);
const addAlias = (value, alias) => {
if (alias) {
return value + aliasSeparator + wrap(alias);
}
return value;
};
const aggregateArray = (value, alias) => {
let columns = value.map(wrap).join(', ');
if (distinct) {
const openParen = distinctParentheses ? '(' : ' ';
const closeParen = distinctParentheses ? ')' : '';
columns = distinct.trim() + openParen + columns + closeParen;
}
const aggregated = `${method}(${columns})`;
return addAlias(aggregated, alias);
};
const aggregateString = (value, alias) => {
const aggregated = `${method}(${distinct + wrap(value)})`;
return addAlias(aggregated, alias);
};
if (Array.isArray(value)) {
return [aggregateArray(value)];
}
if (typeof value === 'object') {
if (stmt.alias) {
throw new Error('When using an object explicit alias can not be used');
}
return Object.entries(value).map(([alias, column]) => {
if (Array.isArray(column)) {
return aggregateArray(column, alias);
}
return aggregateString(column, alias);
});
}
// Allows us to speciy an alias for the aggregate types.
const splitOn = value.toLowerCase().indexOf(' as ');
let column = value;
let { alias } = stmt;
if (splitOn !== -1) {
column = value.slice(0, splitOn);
if (alias) {
throw new Error(`Found multiple aliases for same column: ${column}`);
}
alias = value.slice(splitOn + 4);
}
return [aggregateString(column, alias)];
}
aggregate(stmt) {
return this._aggregate(stmt);
}
aggregateRaw(stmt) {
const distinct = stmt.aggregateDistinct ? 'distinct ' : '';
return `${stmt.method}(${distinct + this.formatter.unwrapRaw(stmt.value)})`;
}
// Compiles all each of the `join` clauses on the query,
// including any nested join queries.
join() {
let sql = '';
let i = -1;
const joins = this.grouped.join;
if (!joins) return '';
while (++i < joins.length) {
const join = joins[i];
const table = join.schema ? `${join.schema}.${join.table}` : join.table;
if (i > 0) sql += ' ';
if (join.joinType === 'raw') {
sql += this.formatter.unwrapRaw(join.table);
} else {
sql += join.joinType + ' join ' + this.formatter.wrap(table);
let ii = -1;
while (++ii < join.clauses.length) {
const clause = join.clauses[ii];
if (ii > 0) {
sql += ` ${clause.bool} `;
} else {
sql += ` ${clause.type === 'onUsing' ? 'using' : 'on'} `;
}
const val = this[clause.type].call(this, clause);
if (val) {
sql += val;
}
}
}
}
return sql;
}
onBetween(statement) {
return (
this.formatter.wrap(statement.column) +
' ' +
this._not(statement, 'between') +
' ' +
map(statement.value, bind(this.formatter.parameter, this.formatter)).join(
' and '
)
);
}
onNull(statement) {
return (
this.formatter.wrap(statement.column) +
' is ' +
this._not(statement, 'null')
);
}
onExists(statement) {
return (
this._not(statement, 'exists') +
' (' +
this.formatter.rawOrFn(statement.value) +
')'
);
}
onIn(statement) {
if (Array.isArray(statement.column)) return this.multiOnIn(statement);
return (
this.formatter.wrap(statement.column) +
' ' +
this._not(statement, 'in ') +
this.wrap(this.formatter.parameterize(statement.value))
);
}
multiOnIn(statement) {
let i = -1,
sql = `(${this.formatter.columnize(statement.column)}) `;
sql += this._not(statement, 'in ') + '((';
while (++i < statement.value.length) {
if (i !== 0) sql += '),(';
sql += this.formatter.parameterize(statement.value[i]);
}
return sql + '))';
}
// Compiles all `where` statements on the query.
where() {
const wheres = this.grouped.where;
if (!wheres) return;
const sql = [];
let i = -1;
while (++i < wheres.length) {
const stmt = wheres[i];
if (
Object.prototype.hasOwnProperty.call(stmt, 'value') &&
helpers.containsUndefined(stmt.value)
) {
this.undefinedBindingsInfo.push(stmt.column);
this._undefinedInWhereClause = true;
}
const val = this[stmt.type](stmt);
if (val) {
if (sql.length === 0) {
sql[0] = 'where';
} else {
sql.push(stmt.bool);
}
sql.push(val);
}
}
return sql.length > 1 ? sql.join(' ') : '';
}
group() {
return this._groupsOrders('group');
}
order() {
return this._groupsOrders('order');
}
// Compiles the `having` statements.
having() {
const havings = this.grouped.having;
if (!havings) return '';
const sql = ['having'];
for (let i = 0, l = havings.length; i < l; i++) {
const s = havings[i];
const val = this[s.type](s);
if (val) {
if (sql.length === 0) {
sql[0] = 'where';
}
if (sql.length > 1 || (sql.length === 1 && sql[0] !== 'having')) {
sql.push(s.bool);
}
sql.push(val);
}
}
return sql.length > 1 ? sql.join(' ') : '';
}
havingRaw(statement) {
return this._not(statement, '') + this.formatter.unwrapRaw(statement.value);
}
havingWrapped(statement) {
const val = this.formatter.rawOrFn(statement.value, 'where');
return (val && this._not(statement, '') + '(' + val.slice(6) + ')') || '';
}
havingBasic(statement) {
return (
this._not(statement, '') +
this.formatter.wrap(statement.column) +
' ' +
this.formatter.operator(statement.operator) +
' ' +
this.formatter.parameter(statement.value)
);
}
havingNull(statement) {
return (
this.formatter.wrap(statement.column) +
' is ' +
this._not(statement, 'null')
);
}
havingExists(statement) {
return (
this._not(statement, 'exists') +
' (' +
this.formatter.rawOrFn(statement.value) +
')'
);
}
havingBetween(statement) {
return (
this.formatter.wrap(statement.column) +
' ' +
this._not(statement, 'between') +
' ' +
map(statement.value, bind(this.formatter.parameter, this.formatter)).join(
' and '
)
);
}
havingIn(statement) {
if (Array.isArray(statement.column)) return this.multiHavingIn(statement);
return (
this.formatter.wrap(statement.column) +
' ' +
this._not(statement, 'in ') +
this.wrap(this.formatter.parameterize(statement.value))
);
}
multiHavingIn(statement) {
let i = -1,
sql = `(${this.formatter.columnize(statement.column)}) `;
sql += this._not(statement, 'in ') + '((';
while (++i < statement.value.length) {
if (i !== 0) sql += '),(';
sql += this.formatter.parameterize(statement.value[i]);
}
return sql + '))';
}
// Compile the "union" queries attached to the main query.
union() {
const onlyUnions = this.onlyUnions();
const unions = this.grouped.union;
if (!unions) return '';
let sql = '';
for (let i = 0, l = unions.length; i < l; i++) {
const union = unions[i];
if (i > 0) sql += ' ';
if (i > 0 || !onlyUnions) sql += union.clause + ' ';
const statement = this.formatter.rawOrFn(union.value);
if (statement) {
if (union.wrap) sql += '(';
sql += statement;
if (union.wrap) sql += ')';
}
}
return sql;
}
// If we haven't specified any columns or a `tableName`, we're assuming this
// is only being used for unions.
onlyUnions() {
return !this.grouped.columns && this.grouped.union && !this.tableName;
}
limit() {
const noLimit = !this.single.limit && this.single.limit !== 0;
if (noLimit) return '';
return `limit ${this.formatter.parameter(this.single.limit)}`;
}
offset() {
if (!this.single.offset) return '';
return `offset ${this.formatter.parameter(this.single.offset)}`;
}
// Compiles a `delete` query.
del() {
// Make sure tableName is processed by the formatter first.
const { tableName } = this;
const withSQL = this.with();
const wheres = this.where();
return (
withSQL +
`delete from ${this.single.only ? 'only ' : ''}${tableName}` +
(wheres ? ` ${wheres}` : '')
);
}
// Compiles a `truncate` query.
truncate() {
return `truncate ${this.tableName}`;
}
// Compiles the "locks".
lock() {
if (this.single.lock) {
return this[this.single.lock]();
}
}
// Compiles the wait mode on the locks.
waitMode() {
if (this.single.waitMode) {
return this[this.single.waitMode]();
}
}
// Fail on unsupported databases
skipLocked() {
throw new Error(
'.skipLocked() is currently only supported on MySQL 8.0+ and PostgreSQL 9.5+'
);
}
// Fail on unsupported databases
noWait() {
throw new Error(
'.noWait() is currently only supported on MySQL 8.0+, MariaDB 10.3.0+ and PostgreSQL 9.5+'
);
}
distinctOn(value) {
throw new Error('.distinctOn() is currently only supported on PostgreSQL');
}
// On Clause
// ------
onWrapped(clause) {
const self = this;
const wrapJoin = new JoinClause();
clause.value.call(wrapJoin, wrapJoin);
let sql = '';
wrapJoin.clauses.forEach(function (wrapClause, ii) {
if (ii > 0) {
sql += ` ${wrapClause.bool} `;
}
const val = self[wrapClause.type](wrapClause);
if (val) {
sql += val;
}
});
if (sql.length) {
return `(${sql})`;
}
return '';
}
onBasic(clause) {
return (
this.formatter.wrap(clause.column) +
' ' +
this.formatter.operator(clause.operator) +
' ' +
this.formatter.wrap(clause.value)
);
}
onVal(clause) {
return (
this.formatter.wrap(clause.column) +
' ' +
this.formatter.operator(clause.operator) +
' ' +
this.formatter.parameter(clause.value)
);
}
onRaw(clause) {
return this.formatter.unwrapRaw(clause.value);
}
onUsing(clause) {
return '(' + this.formatter.columnize(clause.column) + ')';
}
// Where Clause
// ------
whereIn(statement) {
let columns = null;
if (Array.isArray(statement.column)) {
columns = `(${this.formatter.columnize(statement.column)})`;
} else {
columns = this.formatter.wrap(statement.column);
}
const values = this.formatter.values(statement.value);
return `${columns} ${this._not(statement, 'in ')}${values}`;
}
whereNull(statement) {
return (
this.formatter.wrap(statement.column) +
' is ' +
this._not(statement, 'null')
);
}
// Compiles a basic "where" clause.
whereBasic(statement) {
return (
this._not(statement, '') +
this.formatter.wrap(statement.column) +
' ' +
this.formatter.operator(statement.operator) +
' ' +
(statement.asColumn
? this.formatter.wrap(statement.value)
: this.formatter.parameter(statement.value))
);
}
whereExists(statement) {
return (
this._not(statement, 'exists') +
' (' +
this.formatter.rawOrFn(statement.value) +
')'
);
}
whereWrapped(statement) {
const val = this.formatter.rawOrFn(statement.value, 'where');
return (val && this._not(statement, '') + '(' + val.slice(6) + ')') || '';
}
whereBetween(statement) {
return (
this.formatter.wrap(statement.column) +
' ' +
this._not(statement, 'between') +
' ' +
map(statement.value, bind(this.formatter.parameter, this.formatter)).join(
' and '
)
);
}
// Compiles a "whereRaw" query.
whereRaw(statement) {
return this._not(statement, '') + this.formatter.unwrapRaw(statement.value);
}
wrap(str) {
if (str.charAt(0) !== '(') return `(${str})`;
return str;
}
// Compiles all `with` statements on the query.
with() {
if (!this.grouped.with || !this.grouped.with.length) {
return '';
}
const withs = this.grouped.with;
if (!withs) return;
const sql = [];
let i = -1;
let isRecursive = false;
while (++i < withs.length) {
const stmt = withs[i];
if (stmt.recursive) {
isRecursive = true;
}
const val = this[stmt.type](stmt);
sql.push(val);
}
return `with ${isRecursive ? 'recursive ' : ''}${sql.join(', ')} `;
}
withWrapped(statement) {
const val = this.formatter.rawOrFn(statement.value);
return (
(val &&
this.formatter.columnize(statement.alias) + ' as (' + val + ')') ||
''
);
}
// Determines whether to add a "not" prefix to the where clause.
_not(statement, str) {
if (statement.not) return `not ${str}`;
return str;
}
_prepInsert(data) {
const isRaw = this.formatter.rawOrFn(data);
if (isRaw) return isRaw;
let columns = [];
const values = [];
if (!Array.isArray(data)) data = data ? [data] : [];
let i = -1;
while (++i < data.length) {
if (data[i] == null) break;
if (i === 0) columns = Object.keys(data[i]).sort();
const row = new Array(columns.length);
const keys = Object.keys(data[i]);
let j = -1;
while (++j < keys.length) {
const key = keys[j];
let idx = columns.indexOf(key);
if (idx === -1) {
columns = columns.concat(key).sort();
idx = columns.indexOf(key);
let k = -1;
while (++k < values.length) {
values[k].splice(idx, 0, undefined);
}
row.splice(idx, 0, undefined);
}
row[idx] = data[i][key];
}
values.push(row);
}
return {
columns,
values,
};
}
// "Preps" the update.
_prepUpdate(data = {}) {
const { counter = {} } = this.single;
for (const column of Object.keys(counter)) {
//Skip?
if (has(data, column)) {
//Needed?
this.client.logger.warn(
`increment/decrement called for a column that has already been specified in main .update() call. Ignoring increment/decrement and using value from .update() call.`
);
continue;
}
let value = counter[column];
const symbol = value < 0 ? '-' : '+';
if (symbol === '-') {
value = -value;
}
data[column] = this.client.raw(`?? ${symbol} ?`, [column, value]);
}
data = omitBy(data, isUndefined);
const vals = [];
const columns = Object.keys(data);
let i = -1;
while (++i < columns.length) {
vals.push(
this.formatter.wrap(columns[i]) +
' = ' +
this.formatter.parameter(data[columns[i]])
);
}
if (isEmpty(vals)) {
throw new Error(
[
'Empty .update() call detected!',
'Update data does not contain any values to update.',
'This will result in a faulty query.',
this.single.table ? `Table: ${this.single.table}.` : '',
this.single.update
? `Columns: ${Object.keys(this.single.update)}.`
: '',
].join(' ')
);
}
return vals;
}
_formatGroupsItemValue(value) {
const { formatter } = this;
if (value instanceof Raw) {
return formatter.unwrapRaw(value);
} else if (value instanceof QueryBuilder) {
return '(' + formatter.columnize(value) + ')';
} else {
return formatter.columnize(value);
}
}
// Compiles the `order by` statements.
_groupsOrders(type) {
const items = this.grouped[type];
if (!items) return '';
const { formatter } = this;
const sql = items.map((item) => {
const column = this._formatGroupsItemValue(item.value);
const direction =
type === 'order' && item.type !== 'orderByRaw'
? ` ${formatter.direction(item.direction)}`
: '';
return column + direction;
});
return sql.length ? type + ' by ' + sql.join(', ') : '';
}
// Get the table name, wrapping it if necessary.
// Implemented as a property to prevent ordering issues as described in #704.
get tableName() {
if (!this._tableName) {
// Only call this.formatter.wrap() the first time this property is accessed.
let tableName = this.single.table;
const schemaName = this.single.schema;
if (tableName && schemaName) tableName = `${schemaName}.${tableName}`;
this._tableName = tableName
? // Wrap subQuery with parenthesis, #3485
this.formatter.wrap(tableName, tableName instanceof QueryBuilder)
: '';
}
return this._tableName;
}
}
export default QueryCompiler; | the_stack |
import * as moment from "moment";
import * as Web3 from "web3";
import { ContractsAPI } from "../../src/apis";
import { SignerAPI, SignerAPIErrors } from "../../src/apis/signer_api";
import { BigNumber } from "../../utils/bignumber";
import { SignatureUtils } from "../../utils/signature_utils";
import * as Units from "../../utils/units";
import { Web3Utils } from "../../utils/web3_utils";
import { ACCOUNTS, NULL_ADDRESS } from "../accounts";
// Given that this is an integration test, we unmock the Dharma
// smart contracts artifacts package to pull the most recently
// deployed contracts on the current network.
jest.unmock("@dharmaprotocol/contracts");
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const web3 = new Web3(provider);
const contractsApi = new ContractsAPI(web3);
const orderSigner = new SignerAPI(web3, contractsApi);
// For the unit test's purposes, we use arbitrary
// addresses for all debt order fields that expect addresses.
const debtOrderData = {
kernelVersion: ACCOUNTS[0].address,
issuanceVersion: ACCOUNTS[1].address,
principalAmount: Units.ether(1),
principalToken: ACCOUNTS[2].address,
debtor: ACCOUNTS[3].address,
debtorFee: Units.ether(0.001),
creditor: ACCOUNTS[4].address,
creditorFee: Units.ether(0.001),
relayer: ACCOUNTS[5].address,
relayerFee: Units.ether(0.001),
underwriter: ACCOUNTS[6].address,
underwriterFee: Units.ether(0.001),
underwriterRiskRating: Units.percent(0.001),
termsContract: ACCOUNTS[7].address,
termsContractParameters: web3.sha3("bytes32proxy"),
expirationTimestampInSec: new BigNumber(moment().seconds()),
salt: new BigNumber(0),
};
// TODO: Add test coverage for the requirement that non-required debt order values
// be merged with defaults before signing.
describe("Order Signer (Unit Tests)", () => {
describe("Sign order as debtor", () => {
// TODO: Add tests for when debtor's account is locked. Problem I'm facing right now is
// that ganache-cli's implementation of personal_unlockAccount is broken:
// https://github.com/trufflesuite/ganache-cli/issues/405
//
// describe("...with debtor's private key unavailable or locked", () => {
// beforeAll(async () => {
// await promisify(web3.personal.lockAccount)(debtOrderData.debtor);
// });
//
// afterAll(async () => {
// await promisify(web3.personal.unlockAccount)(debtOrderData.debtor);
// });
//
// test("throws INVALID_SIGNING_KEY error", async () => {
// await expect(orderSigner.asDebtor(debtOrderData)).rejects
// .toThrow(SignerAPIErrors.INVALID_SIGNING_KEY(debtOrderData.debtor));
// });
// });
describe("...with required parameters missing or malformed", () => {
describe("missing debtor address", () => {
const debtOrderDataUndefinedDebtor = { ...debtOrderData };
debtOrderDataUndefinedDebtor.debtor = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataUndefinedDebtor, false),
).rejects.toThrow(/requires property "debtor"/);
});
});
describe("malformed debtor address", () => {
const debtOrderDataMalformedDebtor = { ...debtOrderData };
debtOrderDataMalformedDebtor.debtor = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMalformedDebtor, false),
).rejects.toThrow(/\.debtor does not match pattern/);
});
});
describe("missing principal amount", () => {
const debtOrderDataUndefinedPrincipal = { ...debtOrderData };
debtOrderDataUndefinedPrincipal.principalAmount = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataUndefinedPrincipal, false),
).rejects.toThrow(/requires property "principalAmount"/);
});
});
describe("malformed principal amount", () => {
const debtOrderDataMalformedPrincipal: any = { ...debtOrderData };
debtOrderDataMalformedPrincipal.principalAmount = 14;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMalformedPrincipal, false),
).rejects.toThrow(
/\.principalAmount does not conform to the "BigNumber" format/,
);
});
});
describe("missing principal token", () => {
const debtOrderDataMissingPrincipalToken = { ...debtOrderData };
debtOrderDataMissingPrincipalToken.principalToken = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMissingPrincipalToken, false),
).rejects.toThrow(/requires property "principalToken"/);
});
});
describe("malformed principal token", () => {
const debtOrderDataMalformedPrincipalToken: any = { ...debtOrderData };
debtOrderDataMalformedPrincipalToken.principalToken = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMalformedPrincipalToken, false),
).rejects.toThrow(/\.principalToken does not match pattern/);
});
});
describe("missing terms contract", () => {
const debtOrderDataUndefinedTermsContract: any = { ...debtOrderData };
debtOrderDataUndefinedTermsContract.termsContract = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataUndefinedTermsContract, false),
).rejects.toThrow(/requires property "termsContract"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContract: any = { ...debtOrderData };
debtOrderDataMalformedTermsContract.termsContract = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMalformedTermsContract, false),
).rejects.toThrow(/\.termsContract does not match pattern/);
});
});
describe("missing terms contract parameters", () => {
const debtOrderDataUndefinedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataUndefinedTermsContractParams.termsContractParameters = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataUndefinedTermsContractParams, false),
).rejects.toThrow(/requires property "termsContractParameters"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataMalformedTermsContractParams.termsContractParameters =
"0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataMalformedTermsContractParams, false),
).rejects.toThrow(/\.termsContractParameters does not match pattern/);
});
});
});
describe("...with debtor's address set to 0x", () => {
const debtOrderDataWithNullDebtor = { ...debtOrderData };
debtOrderDataWithNullDebtor.debtor = NULL_ADDRESS;
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataWithNullDebtor, false),
).rejects.toThrow(SignerAPIErrors.INVALID_SIGNING_KEY(NULL_ADDRESS));
});
});
describe("...with debtor's address not owned by user", () => {
const debtOrderDataWithExternalDebtor = { ...debtOrderData };
debtOrderDataWithExternalDebtor.debtor = "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe";
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asDebtor(debtOrderDataWithExternalDebtor, false),
).rejects.toThrow(
SignerAPIErrors.INVALID_SIGNING_KEY(debtOrderDataWithExternalDebtor.debtor),
);
});
});
describe("...with debtor's private key available and unlocked", () => {
let debtOrderDataHash: string;
beforeAll(() => {
debtOrderDataHash = Web3Utils.soliditySHA3(
debtOrderData.kernelVersion,
Web3Utils.soliditySHA3(
debtOrderData.issuanceVersion,
debtOrderData.debtor,
debtOrderData.underwriter,
debtOrderData.underwriterRiskRating,
debtOrderData.termsContract,
debtOrderData.termsContractParameters,
debtOrderData.salt,
),
debtOrderData.underwriterFee,
debtOrderData.principalAmount,
debtOrderData.principalToken,
debtOrderData.debtorFee,
debtOrderData.creditorFee,
debtOrderData.relayer,
debtOrderData.relayerFee,
debtOrderData.expirationTimestampInSec,
);
});
describe("on signing client that expects hashed message w/ personal message prefix", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asDebtor(debtOrderData, true);
// Given that our test environment (namely, Ganache) is a client that
// prepends the personal message prefix on the user's behalf, the correctly
// produced signature in this test environment will actually
// redundantly prepend a personal message prefix to the payload
// twice. Thus, to test for correctness as best we can, we redundantly prefix
// and hash the debtOrderDataHash -- once below, and again in the `isValidSignature`
// mtheod.
const prefixedDebtOrderHash = SignatureUtils.addPersonalMessagePrefix(
debtOrderDataHash,
);
expect(
SignatureUtils.isValidSignature(
prefixedDebtOrderHash,
ecdsaSignature,
debtOrderData.debtor,
true,
),
).toBeTruthy();
});
});
describe("on signing client that adds personal message prefix on user's behalf", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asDebtor(debtOrderData, false);
expect(
SignatureUtils.isValidSignature(
debtOrderDataHash,
ecdsaSignature,
debtOrderData.debtor,
true,
),
).toBeTruthy();
});
});
});
});
describe("Sign order as creditor", () => {
// TODO: Add tests for when creditor's account is locked. Problem I'm facing right now is
// that ganache-cli's implementation of personal_unlockAccount is broken:
// https://github.com/trufflesuite/ganache-cli/issues/405
describe("...with required parameters missing or malformed", () => {
describe("missing debtor address", () => {
const debtOrderDataUndefinedDebtor = { ...debtOrderData };
debtOrderDataUndefinedDebtor.debtor = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataUndefinedDebtor, false),
).rejects.toThrow(/requires property "debtor"/);
});
});
describe("malformed debtor address", () => {
const debtOrderDataMalformedDebtor = { ...debtOrderData };
debtOrderDataMalformedDebtor.debtor = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMalformedDebtor, false),
).rejects.toThrow(/\.debtor does not match pattern/);
});
});
describe("missing creditor address", () => {
const debtOrderDataUndefinedCreditor = { ...debtOrderData };
debtOrderDataUndefinedCreditor.creditor = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataUndefinedCreditor, false),
).rejects.toThrow(/requires property "creditor"/);
});
});
describe("malformed creditor address", () => {
const debtOrderDataMalformedCreditor = { ...debtOrderData };
debtOrderDataMalformedCreditor.creditor = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMalformedCreditor, false),
).rejects.toThrow(/\.creditor does not match pattern/);
});
});
describe("missing principal amount", () => {
const debtOrderDataUndefinedPrincipal = { ...debtOrderData };
debtOrderDataUndefinedPrincipal.principalAmount = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataUndefinedPrincipal, false),
).rejects.toThrow(/requires property "principalAmount"/);
});
});
// TODO: Check more precisely for numbers being of type BigNumber
// describe("malformed principal amount", () => {
// let debtOrderDataMalformedPrincipal: any = Object.assign({}, debtOrderData);
// debtOrderDataMalformedPrincipal.principalAmount = 14;
//
// test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
// await expect(orderSigner.asCreditor(debtOrderDataMalformedPrincipal)).rejects
// .toThrow(/\.principalAmount is not of type BigNumber/);
// });
// });
describe("missing principal token", () => {
const debtOrderDataMissingPrincipalToken = { ...debtOrderData };
debtOrderDataMissingPrincipalToken.principalToken = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMissingPrincipalToken, false),
).rejects.toThrow(/requires property "principalToken"/);
});
});
describe("malformed principal token", () => {
const debtOrderDataMalformedPrincipalToken: any = { ...debtOrderData };
debtOrderDataMalformedPrincipalToken.principalToken = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMalformedPrincipalToken, false),
).rejects.toThrow(/\.principalToken does not match pattern/);
});
});
describe("missing terms contract", () => {
const debtOrderDataUndefinedTermsContract: any = { ...debtOrderData };
debtOrderDataUndefinedTermsContract.termsContract = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataUndefinedTermsContract, false),
).rejects.toThrow(/requires property "termsContract"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContract: any = { ...debtOrderData };
debtOrderDataMalformedTermsContract.termsContract = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMalformedTermsContract, false),
).rejects.toThrow(/\.termsContract does not match pattern/);
});
});
describe("missing terms contract parameters", () => {
const debtOrderDataUndefinedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataUndefinedTermsContractParams.termsContractParameters = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataUndefinedTermsContractParams, false),
).rejects.toThrow(/requires property "termsContractParameters"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataMalformedTermsContractParams.termsContractParameters =
"0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataMalformedTermsContractParams, false),
).rejects.toThrow(/\.termsContractParameters does not match pattern/);
});
});
});
describe("...with creditor's address set to 0x", () => {
const debtOrderDataWithNullCreditor = { ...debtOrderData };
debtOrderDataWithNullCreditor.creditor = NULL_ADDRESS;
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataWithNullCreditor, false),
).rejects.toThrow(SignerAPIErrors.INVALID_SIGNING_KEY(NULL_ADDRESS));
});
});
describe("...with creditor's address not owned by user", () => {
const debtOrderDataWithExternalCreditor = { ...debtOrderData };
debtOrderDataWithExternalCreditor.creditor =
"0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe";
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asCreditor(debtOrderDataWithExternalCreditor, false),
).rejects.toThrow(
SignerAPIErrors.INVALID_SIGNING_KEY(debtOrderDataWithExternalCreditor.creditor),
);
});
});
describe("...with creditor's private key available and unlocked", () => {
let debtOrderDataHash: string;
beforeAll(() => {
debtOrderDataHash = Web3Utils.soliditySHA3(
debtOrderData.kernelVersion,
Web3Utils.soliditySHA3(
debtOrderData.issuanceVersion,
debtOrderData.debtor,
debtOrderData.underwriter,
debtOrderData.underwriterRiskRating,
debtOrderData.termsContract,
debtOrderData.termsContractParameters,
debtOrderData.salt,
),
debtOrderData.underwriterFee,
debtOrderData.principalAmount,
debtOrderData.principalToken,
debtOrderData.debtorFee,
debtOrderData.creditorFee,
debtOrderData.relayer,
debtOrderData.relayerFee,
debtOrderData.expirationTimestampInSec,
);
});
describe("on signing client that expects hashed message w/ personal message prefix", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asCreditor(debtOrderData, true);
// Given that our test environment (namely, Ganache) is a client that
// prepends the personal message prefix on the user's behalf, the correctly
// produced signature in this test environment will actually
// redundantly prepend a personal message prefix to the payload
// twice. Thus, to test for correctness as best we can, we redundantly prefix
// and hash the debtOrderDataHash -- once below, and again in the `isValidSignature`
// mtheod.
const prefixedDebtOrderHash = SignatureUtils.addPersonalMessagePrefix(
debtOrderDataHash,
);
expect(
SignatureUtils.isValidSignature(
prefixedDebtOrderHash,
ecdsaSignature,
debtOrderData.creditor,
true,
),
).toBeTruthy();
});
});
describe("on signing client that adds personal message prefix on user's behalf", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asCreditor(debtOrderData, false);
expect(
SignatureUtils.isValidSignature(
debtOrderDataHash,
ecdsaSignature,
debtOrderData.creditor,
true,
),
).toBeTruthy();
});
});
});
});
describe("Sign order as underwriter", () => {
// TODO: Add tests for when underwriter's account is locked. Problem I'm facing right now is
// that ganache-cli's implementation of personal_unlockAccount is broken:
// https://github.com/trufflesuite/ganache-cli/issues/405
describe("...with required parameters missing or malformed", () => {
describe("missing debtor address", () => {
const debtOrderDataUndefinedDebtor = { ...debtOrderData };
debtOrderDataUndefinedDebtor.debtor = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataUndefinedDebtor, false),
).rejects.toThrow(/requires property "debtor"/);
});
});
describe("malformed debtor address", () => {
const debtOrderDataMalformedDebtor = { ...debtOrderData };
debtOrderDataMalformedDebtor.debtor = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataMalformedDebtor, false),
).rejects.toThrow(/\.debtor does not match pattern/);
});
});
describe("missing principal amount", () => {
const debtOrderDataUndefinedPrincipal = { ...debtOrderData };
debtOrderDataUndefinedPrincipal.principalAmount = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataUndefinedPrincipal, false),
).rejects.toThrow(/requires property "principalAmount"/);
});
});
// TODO: Check more precisely for numbers being of type BigNumber
// describe("malformed principal amount", () => {
// let debtOrderDataMalformedPrincipal: any = Object.assign({}, debtOrderData);
// debtOrderDataMalformedPrincipal.principalAmount = 14;
//
// test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
// await expect(orderSigner.asUnderwriter(debtOrderDataMalformedPrincipal)).rejects
// .toThrow(/\.principalAmount is not of type BigNumber/);
// });
// });
describe("missing principal token", () => {
const debtOrderDataMissingPrincipalToken = { ...debtOrderData };
debtOrderDataMissingPrincipalToken.principalToken = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataMissingPrincipalToken, false),
).rejects.toThrow(/requires property "principalToken"/);
});
});
describe("malformed principal token", () => {
const debtOrderDataMalformedPrincipalToken: any = { ...debtOrderData };
debtOrderDataMalformedPrincipalToken.principalToken = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataMalformedPrincipalToken, false),
).rejects.toThrow(/\.principalToken does not match pattern/);
});
});
describe("missing terms contract", () => {
const debtOrderDataUndefinedTermsContract: any = { ...debtOrderData };
debtOrderDataUndefinedTermsContract.termsContract = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataUndefinedTermsContract, false),
).rejects.toThrow(/requires property "termsContract"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContract: any = { ...debtOrderData };
debtOrderDataMalformedTermsContract.termsContract = "0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataMalformedTermsContract, false),
).rejects.toThrow(/\.termsContract does not match pattern/);
});
});
describe("missing terms contract parameters", () => {
const debtOrderDataUndefinedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataUndefinedTermsContractParams.termsContractParameters = undefined;
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataUndefinedTermsContractParams, false),
).rejects.toThrow(/requires property "termsContractParameters"/);
});
});
describe("malformed terms contract", () => {
const debtOrderDataMalformedTermsContractParams: any = {
...debtOrderData,
};
debtOrderDataMalformedTermsContractParams.termsContractParameters =
"0x12345malformed";
test("throws DOES_NOT_CONFORM_TO_SCHEMA error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataMalformedTermsContractParams, false),
).rejects.toThrow(/\.termsContractParameters does not match pattern/);
});
});
});
describe("...with underwriter's address set to 0x", () => {
const debtOrderDataWithNullUnderwriter = { ...debtOrderData };
debtOrderDataWithNullUnderwriter.underwriter = NULL_ADDRESS;
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataWithNullUnderwriter, false),
).rejects.toThrow(SignerAPIErrors.INVALID_SIGNING_KEY(NULL_ADDRESS));
});
});
describe("...with underwriter's address not owned by user", () => {
const debtOrderDataWithExternalUnderwriter = { ...debtOrderData };
debtOrderDataWithExternalUnderwriter.underwriter =
"0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe";
test("throws INVALID_SIGNING_KEY error", async () => {
await expect(
orderSigner.asUnderwriter(debtOrderDataWithExternalUnderwriter, false),
).rejects.toThrow(
SignerAPIErrors.INVALID_SIGNING_KEY(
debtOrderDataWithExternalUnderwriter.underwriter,
),
);
});
});
describe("...with underwriter's private key available and unlocked", () => {
let underwriterCommitmentHash: string;
beforeAll(() => {
underwriterCommitmentHash = Web3Utils.soliditySHA3(
debtOrderData.kernelVersion,
Web3Utils.soliditySHA3(
debtOrderData.issuanceVersion,
debtOrderData.debtor,
debtOrderData.underwriter,
debtOrderData.underwriterRiskRating,
debtOrderData.termsContract,
debtOrderData.termsContractParameters,
debtOrderData.salt,
),
debtOrderData.underwriterFee,
debtOrderData.principalAmount,
debtOrderData.principalToken,
debtOrderData.expirationTimestampInSec,
);
});
describe("on signing client that expects hashed message w/ personal message prefix", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asUnderwriter(debtOrderData, true);
// Given that our test environment (namely, Ganache) is a client that
// prepends the personal message prefix on the user's behalf, the correctly
// produced signature in this test environment will actually
// redundantly prepend a personal message prefix to the payload
// twice. Thus, to test for correctness as best we can, we redundantly prefix
// and hash the debtOrderDataHash -- once below, and again in the `isValidSignature`
// mtheod.
const prefixedCommitmentHash = SignatureUtils.addPersonalMessagePrefix(
underwriterCommitmentHash,
);
expect(
SignatureUtils.isValidSignature(
prefixedCommitmentHash,
ecdsaSignature,
debtOrderData.underwriter,
true,
),
).toBeTruthy();
});
});
describe("on signing client that adds personal message prefix on user's behalf", () => {
test("returns valid signature", async () => {
const ecdsaSignature = await orderSigner.asUnderwriter(debtOrderData, false);
expect(
SignatureUtils.isValidSignature(
underwriterCommitmentHash,
ecdsaSignature,
debtOrderData.underwriter,
true,
),
).toBeTruthy();
});
});
});
});
}); | 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 { ok } from 'chord/base/common/assert';
import { assign } from 'chord/base/common/objects';
import { md5 } from 'chord/base/node/crypto';
import { getRandomInt } from 'chord/base/node/random';
import { Cookie, makeCookieJar, makeCookie, makeCookies } from 'chord/base/node/cookies';
import { querystringify } from 'chord/base/node/url';
import { request, IRequestOptions, htmlGet } from 'chord/base/node/_request';
import { ORIGIN } from 'chord/music/common/origin';
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 { IListOption, IOption } from 'chord/music/api/listOption';
import { TMusicItems } from 'chord/music/api/items';
import { IUserProfile, IAccount } from 'chord/music/api/user';
import { ESize, resizeImageUrl } from 'chord/music/common/size';
import {
makeAliSong,
makeAliLyric,
makeAliSongs,
makeAliAlbum,
makeAliAlbums,
makeAliArtist,
makeAliArtists,
makeAliCollection,
makeAliCollections,
makeUserProfile,
makeUserProfiles,
makeUserProfileMore,
makeAccount,
} from "chord/music/xiami/parser";
import { ARTIST_LIST_OPTIONS } from 'chord/music/xiami/common';
import { XiamiApi } from 'chord/music/xiami/webApi';
const DOMAIN = 'xiami.com';
const UIDXM = 'uidXM';
const CNA = 'cna';
/**
* Alibaba Music Api
*/
export class AliMusicApi {
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.xiami.com/collect_detail.html?id=422425970&f=&from=&ch=',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
};
// static readonly BASICURL = 'https://acs.m.xiami.com/h5/';
static readonly BASICURL = 'http://h5api.m.xiami.com/h5/';
static readonly PLATFORM_ID = 'h5';
static readonly VERSION = '1.0';
static readonly APPKEY = '23649156';
static readonly JSV = '2.4.0';
static readonly NODE_MAP = {
// No use this song node, it does not give audio url
song: 'mtop.alimusic.music.songservice.getsongdetail',
songs: 'mtop.alimusic.music.songservice.getsongs',
similarSongs: 'mtop.alimusic.recommend.songservice.getroamingsongs',
album: 'mtop.alimusic.music.albumservice.getalbumdetail',
albums: 'mtop.alimusic.music.albumservice.getalbums',
artist: 'mtop.alimusic.music.artistservice.getartistdetail',
artistAlbums: 'mtop.alimusic.music.albumservice.getartistalbums',
artistSongs: 'mtop.alimusic.music.songservice.getartistsongs',
similarArtists: 'mtop.alimusic.recommend.artistservice.getsimilarartists',
collection: 'mtop.alimusic.music.list.collectservice.getcollectdetail',
collections: 'mtop.alimusic.music.list.collectservice.getcollects',
// genre: 'mtop.alimusic.music.genreservice.getgenredetail', // no privilege
recommendTags: 'mtop.alimusic.music.list.collectservice.getrecommendtags',
hotTags: 'mtop.alimusic.music.list.collectservice.gethottags',
// searchSongs: XXX Cookies must include 'uidXM=${userId}'
searchSongs: 'mtop.alimusic.search.searchservice.searchsongs',
// searchAlbums: XXX Cookies must include 'uidXM=${userId}'
searchAlbums: 'mtop.alimusic.search.searchservice.searchalbums',
searchArtists: 'mtop.alimusic.search.searchservice.searchartists',
searchCollections: 'mtop.alimusic.search.searchservice.searchcollects',
// AI recommends songs
radioSongs: 'mtop.alimusic.music.radio.getradiosongs',
newSongs: '',
newAlbums: 'mtop.alimusic.recommend.albumservice.getmusiclist',
newCollections: '',
songList: 'mtop.alimusic.recommend.songservice.gethotsongs',
albumList: 'mtop.alimusic.recommend.albumservice.getmusiclist',
artistList: 'mtop.alimusic.music.artistservice.gethotartists',
login: 'mtop.alimusic.xuser.facade.xiamiuserservice.login',
userProfile: 'mtop.alimusic.xuser.facade.xiamiuserservice.getuserinfobyuserid',
userProfileMore: 'mtop.alimusic.xuser.facade.homepageservice.getuserhomeinfo',
userFavorites: 'mtop.alimusic.fav.favoriteservice.getfavorites',
userCreatedCollections: 'mtop.alimusic.music.list.collectservice.getcollectbyuser',
// userRecentPlay: 'mtop.alimusic.playlog.facade.playlogservice.getrecentplaylog',
userRecentPlay: 'mtop.alimusic.playlog.facade.playlogservice.getrecentsongplaylog',
userFollowings: 'mtop.alimusic.social.friendservice.getfollows',
// no privilege for some users
userFollowers: 'mtop.alimusic.social.friendservice.getfans',
userLikeSong: 'mtop.alimusic.fav.songfavoriteservice.favoritesong',
userLikeAlbum: 'mtop.alimusic.fav.albumfavoriteservice.favoritealbum',
userLikeArtist: 'mtop.alimusic.fav.artistfavoriteservice.favoriteartist',
userLikeCollection: 'mtop.alimusic.fav.collectfavoriteservice.favoritecollect',
userLikeUserProfile: 'mtop.alimusic.social.friendservice.addfollow',
userDislikeSong: 'mtop.alimusic.fav.songfavoriteservice.unfavoritesong',
userDislikeAlbum: 'mtop.alimusic.fav.albumfavoriteservice.unfavoritealbum',
userDislikeArtist: 'mtop.alimusic.fav.artistfavoriteservice.unfavoriteartist',
userDislikeCollection: 'mtop.alimusic.fav.collectfavoriteservice.unfavoritecollect',
userDislikeUserProfile: 'mtop.alimusic.social.friendservice.unfollow',
// recommend songs for user logined
recommendSongs: 'mtop.alimusic.recommend.songservice.getdailysongs',
recommendAlbums: 'mtop.alimusic.music.recommendservice.getrecommendalbums',
// Recommend collections by user's favorite collections
recommendCollections: 'mtop.alimusic.music.recommendservice.getrecommendcollects',
playLog: 'mtop.alimusic.playlog.facade.playlogservice.addplaylog',
}
// account
private account: IAccount;
private token: string;
private cookies: { [key: string]: Cookie; } = {};
// For user authority
private userId: string;
private accessToken: string;
private refreshToken: string;
private xiamiWebApi: XiamiApi;
constructor() {
this.userId = '1';
// Get cna
this.getEtag().then((etag) => {
this.setEtagCookie(etag);
});
this.xiamiWebApi = new XiamiApi();
}
public reset() {
this.token = null;
this.cookies = {};
}
public static makeCookie(key: string, value: string): Cookie {
let domain = DOMAIN;
return makeCookie(key, value, domain);
}
public makeQueryStr(params: object): string {
let header = {
platformId: AliMusicApi.PLATFORM_ID,
callId: Date.now(),
appVersion: 1000000,
resolution: '2560x1440',
appId: 200,
openId: 0,
};
if (this.accessToken) {
header = assign({}, header, { accessToken: this.accessToken });
}
return JSON.stringify(
{
requestStr: JSON.stringify(
{
header: header,
model: params,
})
}
);
}
public makeSign(queryStr: string, time: number): string {
let token = this.token || 'undefined';
let str = token + '&' + time + '&' + AliMusicApi.APPKEY + '&' + queryStr;
return md5(str);
}
public makeParamstr(time: number, sign: string, queryStr: string, node: string): string {
let paramstr = querystringify({
jsv: AliMusicApi.JSV,
appKey: AliMusicApi.APPKEY,
t: time,
sign: sign,
api: node,
v: AliMusicApi.VERSION,
type: 'originaljsonp',
timeout: '200000',
dataType: 'originaljsonp',
AntiCreep: 'true',
AntiFlood: 'true',
callback: 'mtopjsonp1',
data: queryStr,
});
return paramstr;
}
public async getToken(): Promise<any | null> {
if (this.token) {
return null;
}
// userId is needed to anti-creep
if (this.userId) {
this.setUserIdCookie();
}
let guess = getRandomInt(0, 4);
switch (guess) {
case 0:
return this.request(
AliMusicApi.NODE_MAP.song,
{ songId: '1' },
'http://h.xiami.com/song_detail.html?id=1&f=&from=&ch=',
true,
);
case 1:
return this.request(
AliMusicApi.NODE_MAP.album,
{ albumId: '1' },
'http://h.xiami.com/album_detail.html?id=1&f=&from=&ch=',
true,
);
case 2:
return this.request(
AliMusicApi.NODE_MAP.artist,
{ artistId: '1' },
'http://h.xiami.com/artist_detail.html?id=1&f=&from=&ch=',
true,
);
case 3:
return this.request(
AliMusicApi.NODE_MAP.collection,
{ collectId: '928111975' },
'http://h.xiami.com/collect_detail.html?id=1&f=&from=&ch=',
true,
);
case 4:
return this.request(
AliMusicApi.NODE_MAP.userProfile,
{ userId: 423815251 },
null,
true,
);
default:
break;
}
}
public setUserIdCookie(userId?: string): void {
userId = userId || this.userId;
ok(userId, 'no userId');
let key = 'uidXM';
let value = userId;
let cookie = AliMusicApi.makeCookie(key, value);
this.cookies['uidXM'] = cookie;
}
/**
* Etag for anti spider
*/
public async getEtag(): Promise<string> {
let url = 'http://log.mmstat.com/eg.js';
let options: IRequestOptions = {
method: 'GET',
url: url,
headers: { ...AliMusicApi.HEADERS },
gzip: true,
resolveWithFullResponse: true,
};
let result: any = await request(options);
return result.headers['etag'];
}
public setEtagCookie(etag: string): void {
let key = 'cna';
let value = etag;
let cookie = AliMusicApi.makeCookie(key, value);
this.cookies['cna'] = cookie;
}
/**
* If init is true, request returns response, NOT json
*/
public async request(node: string, apiParams: object, referer?: string, init: boolean = false, excludedCookies: Array<string> = []): Promise<any | null> {
if (!init) {
await this.getToken();
}
// set random use id for anti-spider
this.setUserIdCookie(getRandomInt(1, 30000000).toString());
let url = AliMusicApi.BASICURL + node + '/' + AliMusicApi.VERSION + '/';
let queryStr = this.makeQueryStr(apiParams);
let time = Date.now();
let sign = this.makeSign(queryStr, time);
let params = this.makeParamstr(time, sign, queryStr, node);
let headers = !!referer ? { ...AliMusicApi.HEADERS, Referer: referer } : { ...AliMusicApi.HEADERS };
// Make cookie jar
let cookieJar = makeCookieJar();
let cookies = { ...this.cookies };
excludedCookies.forEach(key => { delete cookies[key]; });
for (let key in cookies) {
cookieJar.setCookie(cookies[key], 'http://' + DOMAIN);
}
url = url + '?' + params;
let options: IRequestOptions = {
method: 'GET',
url: url,
// Cookies is excepted to get token
jar: !init ? cookieJar : null,
headers: headers,
gzip: true,
resolveWithFullResponse: init,
};
let result: any = await request(options);
if (init && result.headers.hasOwnProperty('set-cookie')) {
makeCookies(result.headers['set-cookie']).forEach(cookie => {
this.cookies[cookie.key] = cookie;
if (cookie.key == '_m_h5_tk') {
this.token = cookie.value.split('_')[0];
}
});
return null;
}
let json = JSON.parse(result.trim().slice(11, -1));
// TODO: Handle each errors
if (json.ret[0].search('SUCCESS') == -1) {
loggerWarning.warning('[AliMusicApi.request] [Error]: (params, response):', options, json);
}
// FAIL_SYS_TOKEN_EXOIRED::令牌过期
if (json.ret && json.ret[0].search('FAIL_SYS_TOKEN_EXOIRED') != -1) {
loggerWarning.warning('AliMusicApi: TOKEN_EXOIRED');
this.reset();
await this.getToken();
return this.request(node, apiParams, referer, init);
}
return json;
}
/**
* Get audio urls, the songId must be number string
*
* WARN: AliMusicApi.song could be easily blocked by server,
* We try XiamiApi.audios to get the audio urls
*/
public async audios(songId: string, supkbps?: number): Promise<Array<IAudio>> {
try {
let audios = await this.xiamiWebApi.audios(songId);
return audios;
} catch {
let song = await this.song(songId);
return song.audios;
}
}
/**
* Get many songs' audios
*/
public async songsAudios(songIds: Array<string>): Promise<Array<Array<IAudio>>> {
let songs = await this.songs(songIds);
return songs.map(song => song.audios);
}
/**
* Get a song, the songId must be number string
*/
public async song2(songId: string): Promise<ISong> {
let json = await this.request(
AliMusicApi.NODE_MAP.song,
{ songId },
`http://h.xiami.com/song.html?id=${songId}&f=&from=&ch=`,
);
let info = json.data.data.songDetail;
let song = makeAliSong(info);
return song;
}
/**
* Get a song, the songId must be number string
*/
public async song(songId: string): Promise<ISong> {
let json = await this.request(
AliMusicApi.NODE_MAP.songs,
{ songIds: [songId] },
`http://h.xiami.com/song.html?id=${songId}&f=&from=&ch=`,
);
let info = json.data.data.songs[0];
let song = makeAliSong(info);
return song;
}
/**
* Get songs, the songId must be number string
*/
public async songs(songIds: Array<string>): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.songs,
{ songIds },
`http://h.xiami.com/song.html?id=${songIds[0]}&f=&from=&ch=`,
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
public async lyric(songId: string, song?: ISong): Promise<ILyric> {
let lyricUrl;
if (!song || !song.lyricUrl) {
song = await this.song(songId);
}
lyricUrl = song.lyricUrl;
if (!lyricUrl) return null;
let cn: any = await htmlGet(lyricUrl);
return makeAliLyric(songId, cn);
}
/**
* Get similer songs, the songId must be number string
*/
public async similarSongs(songId: string, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.similarSongs,
{
limit: size,
quality: 'l',
context: '',
songId: parseInt(songId),
},
`http://h.xiami.com/song.html?id=${songId}&f=&from=&ch=`,
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* Get an album, the albumId must be number string
*/
public async album(albumId: string): Promise<IAlbum> {
try {
let json = await this.request(
AliMusicApi.NODE_MAP.album,
{ albumId },
`http://h.xiami.com/album_detail.html?id=${albumId}&f=&from=&ch=`,
false,
[UIDXM],
);
let info = json.data.data.albumDetail;
let album = makeAliAlbum(info);
return album;
} catch (err) {
return await this.xiamiWebApi.album(albumId);
}
}
public async albums(albumIds: Array<string>): Promise<Array<IAlbum>> {
let json = await this.request(
AliMusicApi.NODE_MAP.albums,
{ albumIds },
`http://h.xiami.com/album_detail.html?id=${albumIds[0]}&f=&from=&ch=`,
);
let info = json.data.data.albums;
let albums = makeAliAlbums(info);
return albums;
}
/**
* Get an artist, the artistId must be number string
*/
public async artist(artistId: string): Promise<IArtist> {
try {
let json = await this.request(
AliMusicApi.NODE_MAP.artist,
{ artistId },
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
let info = json.data.data['artistDetailVO'];
let artist = makeAliArtist(info);
return artist;
} catch (err) {
return await this.xiamiWebApi.artist(artistId);
}
}
/**
* 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>> {
try {
let json = await this.request(
AliMusicApi.NODE_MAP.artistAlbums,
{
artistId: artistId,
pagingVO: {
page: page,
pageSize: size,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
let info = json.data.data.albums;
let albums = makeAliAlbums(info);
return albums;
} catch (e) {
return this.xiamiWebApi.artistAlbums(artistId, page, size);
}
}
/**
* Get albums amount of an artist, the artistId must be number string
*/
public async artistAlbumCount(artistId: string): Promise<number> {
let json = await this.request(
AliMusicApi.NODE_MAP.artistAlbums,
{
artistId: artistId,
pagingVO: {
page: 1,
pageSize: 1,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
return json.data.data.total;
}
/**
* 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>> {
try {
let json = await this.request(
AliMusicApi.NODE_MAP.artistSongs,
{
artistId: artistId,
backwardOffSale: true,
pagingVO: {
page: page,
pageSize: size,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
} catch (e) {
return this.xiamiWebApi.artistSongs(artistId, page, size);
}
}
/**
* Get songs amount of an artist, the artistId must be number string
*/
public async artistSongCount(artistId: string): Promise<number> {
let json = await this.request(
AliMusicApi.NODE_MAP.artistSongs,
{
artistId: artistId,
backwardOffSale: true,
pagingVO: {
page: 1,
pageSize: 1,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
return json.data.data.total;
}
/**
* Get similar artists of the artist, the artistId must be number string
*/
public async similarArtists(artistId: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> {
let json = await this.request(
AliMusicApi.NODE_MAP.similarArtists,
{
artistId: artistId,
pagingVO: {
page: page,
pageSize: size,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
let info = json.data.data.artists;
let artists = makeAliArtists(info);
return artists;
}
/**
* How many similar artists has the artist, the artistId must be number string
*/
public async similarArtistCount(artistId: string): Promise<number> {
let json = await this.request(
AliMusicApi.NODE_MAP.similarArtists,
{
artistId: artistId,
pagingVO: {
page: 1,
pageSize: 1,
}
},
`http://h.xiami.com/artist_detail.html?id=${artistId}&f=&from=&ch=`,
);
return json.data.data.pagingVO.count;
}
/**
* Get a collection, the collectionId must be number string
*/
public async collection(collectionId: string, page: number = 1, size: number = 100): Promise<ICollection> {
try {
let json = await this.request(
AliMusicApi.NODE_MAP.collection,
{
listId: collectionId,
isFullTags: false,
pagingVO: {
page,
pageSize: size,
}
},
`http://h.xiami.com/collect_detail.html?id=${collectionId}&f=&from=&ch=`,
);
let info = json.data.data.collectDetail;
let collection = makeAliCollection(info);
return collection;
} catch (err) {
return await this.xiamiWebApi.collection(collectionId);
}
}
/**
* Search Songs
*
* XXX Cookies must include 'uidXM=${userId}'
*
* If we call this api frequently, the xiami server will blocked us,
* so we instead to use the web api.
*/
public async searchSongs(keyword: string, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json;
try {
json = await this.request(
AliMusicApi.NODE_MAP.searchSongs,
{
key: keyword.replace(/\s+/g, '+'),
pagingVO: {
page: page,
pageSize: size,
}
},
);
} catch (err) {
return await this.xiamiWebApi.searchSongs(keyword, page, size);
}
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* Search albums
*
* XXX Cookies must include 'uidXM=${userId}'
*/
public async searchAlbums(keyword: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> {
let json;
try {
json = await this.request(
AliMusicApi.NODE_MAP.searchAlbums,
{
// isRecommendCorrection: false,
// isTouFu: true,
key: keyword.replace(/\s+/g, '+'),
pagingVO: {
page: page,
pageSize: size,
}
},
);
} catch (err) {
return await this.xiamiWebApi.searchAlbums(keyword, page, size);
}
let info = json.data.data.albums;
let albums = makeAliAlbums(info);
return albums;
}
public async searchArtists(keyword: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> {
let json;
try {
json = await this.request(
AliMusicApi.NODE_MAP.searchArtists,
{
key: keyword.replace(/\s+/g, '+'),
pagingVO: {
page: page,
pageSize: size,
}
},
);
} catch (err) {
return await this.xiamiWebApi.searchArtists(keyword, page, size);
}
let info = json.data.data.artists;
let artists = makeAliArtists(info);
return artists;
}
public async searchCollections(keyword: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> {
let json;
try {
json = await this.request(
AliMusicApi.NODE_MAP.searchCollections,
{
key: keyword.replace(/\s+/g, '+'),
pagingVO: {
page: page,
pageSize: size,
}
},
);
} catch (err) {
return await this.xiamiWebApi.searchCollections(keyword, page, size);
}
let info = json.data.data.collects;
let collections = makeAliCollections(info);
return collections;
}
/**
* radioId:
* 1 - 猜你喜欢
* 0 - 听见不同
* 7 - 私人电台
*/
public async radioSongs(radioId: string, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.radioSongs,
{
extraId: 0,
limit: size,
radioType: radioId,
},
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* TODO, parser is need
*/
public async hotTags(): Promise<any> {
let json = await this.request(
AliMusicApi.NODE_MAP.hotTags,
{},
);
return json;
}
/**
* Get new songs
*
* languageId:
* 5: 推荐
* 10: 华语
* 12: 欧美
* 13: 韩国
* 14: 日本
*/
public async songList(languageId: number = 5, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.songList,
{
language: languageId.toString(),
pagingVO: {
page,
pageSize: size,
},
},
);
let info = json.data.data.songs;
return makeAliSongs(info);
}
public async albumListOptions(): Promise<Array<IListOption>> {
let json = await this.request(
AliMusicApi.NODE_MAP.newAlbums,
{
bizCode: 'album',
filter: '{}',
pagingVO: {
page: 1,
pageSize: 1,
},
},
);
let orders: IListOption = {
name: '排序',
type: 'order',
items: [
{ id: '0', name: '推荐' },
{ id: '1', name: '最新' },
{ id: '2', name: '最热' },
],
}
let options = json.data.data.label.map(
option => {
option.items.forEach(
item => item.id = item.id.toString());
return option;
});
return [...options, orders];
}
/**
* Select Albums
*
* order:
* 0 or undefined: 推荐
* 1: 最新
* 2: 最热
*
* language: 语种
* tag: 曲风
* century: 年代
* category: 分类
*/
public async albumList(
order: number = 0,
languageId: number = 0,
tagId: number = 0,
centuryId: number = 0,
categoryId: number = 0,
page: number = 1,
size: number = 10): Promise<Array<IAlbum>> {
let json = await this.request(
AliMusicApi.NODE_MAP.albumList,
{
bizCode: 'album',
filter: JSON.stringify({
order: order || undefined,
language: languageId || undefined,
tag: tagId || undefined,
century: centuryId || undefined,
category: categoryId || undefined,
}),
pagingVO: {
page,
pageSize: size,
},
},
);
let info = json.data.data.albums;
return makeAliAlbums(info);
}
public collectionListOrders(): Array<IOption> {
return [
{ id: 'system', name: '推荐' },
{ id: 'recommend', name: '精选' },
{ id: 'hot', name: '最热' },
{ id: 'new', name: '最新' },
];
}
/**
* Collection List Options
*/
public async collectionListOptions(): Promise<Array<IListOption>> {
let json = await this.request(
AliMusicApi.NODE_MAP.recommendTags,
{ from: 'web' },
);
let options = json.data.data.recommendTags
.map(tag => ({
type: null,
name: tag['title'],
items: tag['items'].map(item => ({
name: item['name'],
id: item['name'],
})),
}));
let option = {
type: null,
name: '全部歌单',
items: [{
name: '全部',
id: null,
}],
};
return [option, ...options];
}
/**
* Get collections by type
*
* types:
* 'system' - 推荐
* 'recommend' - 精选
* 'hot' - 最热
* 'new' - 最新
*/
public async collectionList(
keyword: string,
type: string = 'new',
page: number = 1,
size: number = 10): Promise<Array<ICollection>> {
let json = await this.request(
AliMusicApi.NODE_MAP.collections,
{
custom: 0,
dataType: type,
info: 1,
key: keyword ? keyword.replace(/\s+/g, '+') : undefined,
pagingVO: {
page: page,
pageSize: size,
}
},
);
let info = json.data.data.collects;
let collections = makeAliCollections(info);
return collections;
}
public async artistListOptions(): Promise<Array<IListOption>> {
return ARTIST_LIST_OPTIONS;
}
public async artistList(
language: string,
tag: string,
gender: string,
page: number = 1,
size: number = 10): Promise<any> {
let json = await this.request(
AliMusicApi.NODE_MAP.artistList,
{
language: Number.parseInt(language),
tag: Number.parseInt(tag),
gender: Number.parseInt(gender),
},
);
let info = json.data.data.artists;
let artists = makeAliArtists(info);
let pinyins = info.map(i => i.pinyin);
info = json.data.data.hotArtists;
let hotArtists = makeAliArtists(info);
let hotPinyins = info.map(i => i.pinyin);
return [[...hotArtists, null, ...artists], [...hotPinyins, null, ...pinyins]];
}
public async newSongs(page: number = 1, size: number = 10): Promise<Array<ISong>> {
return this.songList(5, page, size);
}
/**
* Get new albums
*
* The minimum return albums size are 5
*/
public async newAlbums(page: number = 1, size: number = 10): Promise<Array<IAlbum>> {
return this.albumList(0, 0, 0, 0, 0, page, size);
}
public async newCollections(page: number = 1, size: number = 10): Promise<Array<ICollection>> {
return this.collectionList(undefined, 'new', page, size);
}
public async login(accountName: string, password: string): Promise<IAccount> {
// Create a new AliMusicApi instance to handle login
let tmpApi = new AliMusicApi();
let json = await tmpApi.request(
AliMusicApi.NODE_MAP.login,
{
account: accountName,
password: md5(password),
},
`http://h.xiami.com/`,
);
/**
* accessToken: string
* expires: number
* nickName: string
* refreshExpires: number
* refreshToken: string
* schemeUrl: string
* userId: number
*/
if (json.ret[0].search('SUCCESS') == -1) {
let message = json.ret[0].split('::')[1];
throw new Error(message);
}
let info = json.data.data;
let account = makeAccount(info);
let userProfile = await this.userProfile(account.user.userOriginalId);
account.user.userAvatarUrl = userProfile.userAvatarUrl;
return account;
}
/**
* WARN !! This is only way of setting an account to an AliMusicApi instance
*/
public setAccount(account: IAccount): void {
ok(account.user.origin == ORIGIN.xiami, `[AliMusicApi.setAccount]: this account is not a xiami account`);
this.setAccessToken(account.accessToken, account.refreshToken);
this.setUserId(account.user.userOriginalId);
this.account = account;
}
public getAccount(): IAccount {
return this.account;
}
public setAccessToken(accessToken: string, refreshToken?: string): void {
this.accessToken = accessToken;
this.refreshToken = refreshToken;
}
/**
* here, the userId is IUserProfile.userOriginalId, as followings
*/
public setUserId(userId: string): void {
this.userId = userId;
}
public logined(): boolean {
return !!this.account && !!this.account.accessToken;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userProfile(userId: string): Promise<IUserProfile> {
let req = this.request(
AliMusicApi.NODE_MAP.userProfile,
{ userId: parseInt(userId) },
);
let [json, userProfileMore] = await Promise.all([req, this.userProfileMore(userId)]);
let userProfile = makeUserProfile(json.data.data);
let _up = { ...userProfile, ...userProfileMore };
_up.userId = userProfile.userId;
return _up;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userProfileMore(userId: string): Promise<IUserProfile> {
let json = await this.request(
AliMusicApi.NODE_MAP.userProfileMore,
{ userId: parseInt(userId) },
);
return makeUserProfileMore(json.data.data);
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
protected async userFavorites(userId: string, type: number, page: number = 1, size: number = 10): Promise<any> {
let json = await this.request(
AliMusicApi.NODE_MAP.userFavorites,
{
full: false,
type: type, // song: 1, album: 2, artist: 3, collection: 5
userId: parseInt(userId),
pagingVO: {
page: page,
pageSize: size,
},
},
);
return json;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFavoriteSongs(userId: string, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.userFavorites(userId, 1, page, size);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFavoriteAlbums(userId: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> {
let json = await this.userFavorites(userId, 2, page, size);
let info = json.data.data.albums;
let albums = makeAliAlbums(info);
return albums;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFavoriteArtists(userId: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> {
let json = await this.userFavorites(userId, 3, page, size);
let info = json.data.data.artists;
let artists = makeAliArtists(info);
return artists;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFavoriteCollections(userId: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> {
let json = await this.userFavorites(userId, 5, page, size);
let info = json.data.data.collects;
let collections = makeAliCollections(info);
return collections;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userCreatedCollections(userId: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> {
let json = await this.request(
AliMusicApi.NODE_MAP.userCreatedCollections,
{
userId,
hideSystemSonglistCover: 1,
includeSystemCreate: 1,
sort: 0,
pagingVO: {
page: page,
pageSize: size,
},
},
);
let info = json.data.data.collects;
let collections = makeAliCollections(info);
let userName = collections.length ? collections[0].userName : null;
if (!userName) {
let userProfile = await this.userProfile(userId);
userName = userProfile.userName;
}
collections.forEach(collection => collection.userName = userName);
return collections;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userRecentPlay(userId: string, page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.userRecentPlay,
// {
// objectType: 'song',
// },
{
userId,
fullView: 1,
pagingVO: {
page: page,
pageSize: size,
},
},
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFollowings(userId: string, page: number = 1, size: number = 10): Promise<Array<IUserProfile>> {
let json = await this.request(
AliMusicApi.NODE_MAP.userFollowings,
{
userId,
pagingVO: {
page: page,
pageSize: size,
},
},
);
let info = json.data.data.friendVOList;
return makeUserProfiles(info);
}
/**
* here, the userId is IUserProfile.userOriginalId
*/
public async userFollowers(userId: string, page: number = 1, size: number = 10): Promise<Array<IUserProfile>> {
let json = await this.request(
AliMusicApi.NODE_MAP.userFollowers,
{
userId,
pagingVO: {
page: page,
pageSize: size,
},
},
);
let info = json.data.data.friendVOList;
return makeUserProfiles(info);
}
/**
* songId is ISong.songOriginalId, as following
*/
public async userLikeSong(songId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userLikeSong,
{
songId,
},
);
return json.data.data.status;
}
public async userLikeAlbum(albumId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userLikeAlbum,
{
albumId,
},
);
return json.data.data.status;
}
public async userLikeArtist(artistId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userLikeArtist,
{
artistId,
},
);
return json.data.data.status;
}
public async userLikeCollection(collectionId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userLikeCollection,
{
collectId: collectionId,
},
);
return json.data.data.status;
}
public async userLikeUserProfile(userId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userLikeUserProfile,
{
toUserId: userId,
},
);
return json.data.data.toUserId == userId;
}
public async userDislikeSong(songId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userDislikeSong,
{
songId,
},
);
return json.data.data.status;
}
public async userDislikeAlbum(albumId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userDislikeAlbum,
{
albumId,
},
);
return json.data.data.status;
}
public async userDislikeArtist(artistId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userDislikeArtist,
{
artistId,
},
);
return json.data.data.status;
}
public async userDislikeCollection(collectionId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userDislikeCollection,
{
collectId: collectionId,
},
);
return json.data.data.status;
}
public async userDislikeUserProfile(userId: string): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.userDislikeUserProfile,
{
toUserId: userId,
},
);
return json.data.data.status;
}
public async recommendSongs(page: number = 1, size: number = 10): Promise<Array<ISong>> {
let json = await this.request(
AliMusicApi.NODE_MAP.recommendSongs,
{
// no params needed
},
);
let info = json.data.data.songs;
let songs = makeAliSongs(info);
return songs;
}
/**
* Recommend collections related through user's favorite collections
*/
public async recommendCollections(page: number = 1, size: number = 10): Promise<Array<ICollection>> {
let json = await this.request(
AliMusicApi.NODE_MAP.recommendCollections,
{
recommendType: 'favorite',
},
);
return makeAliCollections(json.data.data.list);
}
/**
* Record played song
*/
public async playLog(songId: string, seek: number): Promise<boolean> {
let json = await this.request(
AliMusicApi.NODE_MAP.playLog,
{
collectId: 0,
latitude: 0,
longitude: 0,
songId: parseInt(songId),
startPoint: seek,
time: Date.now(),
type: 8,
userId: 0,
},
);
return json.data.data.status;
}
public resizeImageUrl(url: string, size: ESize | number): string {
return resizeImageUrl(url, size, (url, size) => `${url}?x-oss-process=image/resize,m_fill,w_${size},h_${size}/format,webp`);
}
public async fromURL(input: string): Promise<Array<TMusicItems>> {
let chunks = input.split(' ');
let items = [];
for (let chunk of chunks) {
let m;
let url;
let type;
let matchList = [
// song
[/song\/(\w+)/, 'song'],
// artist
[/artist\/(\w+)/, 'artist'],
// album
[/album\/(\w+)/, 'album'],
// collection
[/collect\/(\w+)/, 'collect'],
// user
[/user\/(\w+)/, 'user'],
];
for (let [re, tp] of matchList) {
m = (re as RegExp).exec(chunk);
if (m) {
type = tp;
url = XiamiApi.BASICURL + type + '/' + m[1];
break;
}
}
if (url) {
let originId;
if (type == 'user' || type == 'collect') {
originId = m[1];
} else {
let cn = await this.xiamiWebApi.request('GET', url);
m = (new RegExp(`xiami\\.com/${type}/(\\d+)`)).exec(cn);
if (!m) break;
originId = m[1];
}
let item;
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;
case 'user':
item = await this.userProfile(originId);
items.push(item);
break;
default:
break;
}
}
}
return items;
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormSLAItem_Information {
interface Header extends DevKit.Controls.IHeader {
/** Unique identifier for SLA associated with SLA Item. */
SLAId: DevKit.Controls.Lookup;
}
interface tab_tabUC_Sections {
Actions: DevKit.Controls.Section;
ApplicableWhen: DevKit.Controls.Section;
PauseConfiguration: DevKit.Controls.Section;
SuccessConditions: DevKit.Controls.Section;
Warn_and_Fail_Duration: DevKit.Controls.Section;
}
interface tab_tabUC extends DevKit.Controls.ITab {
Section: tab_tabUC_Sections;
}
interface Tabs {
tabUC: tab_tabUC;
}
interface Body {
Tab: Tabs;
/** Action URL */
ActionURL: DevKit.Controls.String;
/** Select whether this SLA will allow pausing and resuming during the time calculation. */
AllowPauseResume: DevKit.Controls.Boolean;
ApplicableEntity: DevKit.Controls.String;
applicablewhencontrol: DevKit.Controls.ActionCards;
/** Choose the business hours for calculating SLA item timelines. */
BusinessHoursId: DevKit.Controls.Lookup;
/** Select how soon the success criteria must be met until the SLA item is considered failed and failure actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
FailureAfter: DevKit.Controls.Integer;
/** Select how soon the success criteria must be met until the SLA item is considered failed and failure actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
FailureAfter_1: DevKit.Controls.Integer;
msdyn_AdvancedPauseConfiguration: DevKit.Controls.Boolean;
msdyn_pauseconfigurationxml: DevKit.Controls.ActionCards;
/** Unique identifier for SLAKPI associated with SLA Item. */
msdyn_slakpiid: DevKit.Controls.Lookup;
/** Type a descriptive name of the service level agreement (SLA) item. */
Name: DevKit.Controls.String;
/** Type a descriptive name of the service level agreement (SLA) item. */
Name_1: DevKit.Controls.String;
successconditioncontrol: DevKit.Controls.ActionCards;
/** Select how soon the success criteria must be met before warning actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
WarnAfter: DevKit.Controls.Integer;
/** Select how soon the success criteria must be met before warning actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
WarnAfter_1: DevKit.Controls.Integer;
WebResource_preview: DevKit.Controls.WebResource;
WebResource_slaitem_applicablewhen_notification: DevKit.Controls.WebResource;
WebResource_slaitem_success_notification: DevKit.Controls.WebResource;
}
}
class FormSLAItem_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form SLAItem_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form SLAItem_Information */
Body: DevKit.FormSLAItem_Information.Body;
/** The Header section of form SLAItem_Information */
Header: DevKit.FormSLAItem_Information.Header;
}
class SLAItemApi {
/**
* DynamicsCrm.DevKit SLAItemApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
actionflowuniquename: DevKit.WebApi.StringValue;
/** Action URL */
ActionURL: DevKit.WebApi.StringValue;
/** Select whether this SLA will allow pausing and resuming during the time calculation. */
AllowPauseResume: DevKit.WebApi.BooleanValue;
ApplicableEntity: DevKit.WebApi.StringValue;
/** Condition for SLA item */
ApplicableWhenXml: DevKit.WebApi.StringValue;
/** Choose the business hours for calculating SLA item timelines. */
BusinessHoursId: DevKit.WebApi.LookupValue;
ChangedAttributeList: DevKit.WebApi.StringValue;
/** For internal use only. */
ComponentState: DevKit.WebApi.OptionSetValueReadonly;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Type additional information to describe the SLA Item */
Description: DevKit.WebApi.StringValue;
/** Exchange rate between the currency associated with the SLA Item record and the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Select how soon the success criteria must be met until the SLA item is considered failed and failure actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
FailureAfter: DevKit.WebApi.IntegerValue;
/** For internal use only. */
IsManaged: DevKit.WebApi.BooleanValueReadonly;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
msdyn_AdvancedPauseConfiguration: DevKit.WebApi.BooleanValue;
msdyn_PauseConfigurationXml: DevKit.WebApi.StringValue;
/** Unique identifier for SLAKPI associated with SLA Item. */
msdyn_slakpiid: DevKit.WebApi.LookupValue;
/** Type a descriptive name of the service level agreement (SLA) item. */
Name: DevKit.WebApi.StringValue;
/** For internal use only. */
OverwriteTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the SLA Item record. */
OwningUser: DevKit.WebApi.LookupValue;
/** Select the service level agreement (SLA) key performance indicator (KPI) that this SLA Item is created for. */
RelatedField: DevKit.WebApi.StringValue;
/** Select the time zone, or UTC offset, for this address so that other people can reference it when they contact someone at this address. */
SequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier for SLA associated with SLA Item. */
SLAId: DevKit.WebApi.LookupValue;
/** Unique identifier of the SLA Item. */
SLAItemId: DevKit.WebApi.GuidValue;
/** For internal use only. */
SLAItemIdUnique: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the associated solution. */
SolutionId: DevKit.WebApi.GuidValueReadonly;
/** Condition for SLA item */
SuccessConditionsXml: DevKit.WebApi.StringValue;
/** For internal use only. */
SupportingSolutionId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the currency associated with the SLA Item record. */
TransactionCurrencyId: DevKit.WebApi.LookupValueReadonly;
/** Version number of the SLA Item. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Select how soon the success criteria must be met before warning actions are initiated. The actual duration is based on the business hours as specified in the associated SLA record. */
WarnAfter: DevKit.WebApi.IntegerValue;
/** Workflow associated with the SLA Item. */
WorkflowId: DevKit.WebApi.LookupValue;
}
}
declare namespace OptionSet {
namespace SLAItem {
enum ComponentState {
/** 2 */
Deleted,
/** 3 */
Deleted_Unpublished,
/** 0 */
Published,
/** 1 */
Unpublished
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { stringify } from 'querystring'
import { DefaultClient, RequestConfig, ResourceResponse } from './client'
import { AxiosResponse } from 'axios'
import { uuidWeak } from './util'
import RelatedManager from './related'
import { BaseNormalizer, NormalizerDict, ValidNormalizer } from './helpers/normalization'
import * as exceptions from './exceptions'
import assert from 'assert'
const _ = require('lodash')
export default class Resource {
static endpoint: string = ''
static cacheMaxAge: number = 10
static client: DefaultClient = new DefaultClient('/')
static queued: Record<string, any> = {}
static uniqueKey: string = 'id'
static defaults: Record<string, any> = {}
static RelatedManagerClass: typeof RelatedManager = RelatedManager
static validation: ValidatorDictOrFunction = {}
static normalization: NormalizerDict = {}
static fields: string[] = []
static related: RelatedDictOrFunction = {}
static _cache: any = {}
static _uuid: string
_attributes: Record<string, any> = {}
uuid: string
attributes: Record<string, any> = {}
managers: Record<string, RelatedManager> = {}
changes: Record<string, any> = {}
constructor(attributes: any = {}, options: any = {}) {
const Ctor = this.getConstructor()
if (typeof Ctor.client !== 'object') {
throw new exceptions.ImproperlyConfiguredError("Resource can't be used without Client class instance")
}
this._attributes = {}
let _attrKeys = Object.keys(attributes)
let _defaults = Ctor.makeDefaultsObject()
// Set up Proxy to this._attributes
this.attributes = new Proxy(this._attributes, {
set: (receiver: any, key: string, value: any) => {
receiver[key] = this.toInternalValue(key, value)
return true
},
get: (receiver: any, key: string) => {
return receiver[key]
},
defineProperty: (target, prop, descriptor) => {
return Reflect.defineProperty(target, prop, descriptor)
},
})
// Default attributes, ignore any that will be overridden
for (let defaultsKey in _defaults) {
if (_attrKeys.includes(defaultsKey)) {
continue
}
this.attributes[defaultsKey] = _defaults[defaultsKey]
}
// Attributes parameters, will fire setter
for (let attrKey in attributes) {
this.attributes[attrKey] = attributes[attrKey]
}
// Set/Reset changes
this.changes = {}
// Create related managers
for (let relAttrKey in Ctor.getRelatedClasses()) {
this.managers[relAttrKey] = this.createManagerFor(relAttrKey)
}
if (this.id) {
Ctor.cacheResource(this)
}
}
/**
* Cache getter
*/
static get cache() {
let ParentClass = Object.getPrototypeOf(this)
// FooResource.cache === BarResource.cache should always return false where BarResource extends FooResource
if (!this._cache || this._cache === ParentClass._cache) {
this._cache = {}
}
return new Proxy(this._cache, {
set: (receiver: any, key: string, value: any) => {
receiver[key] = value
return true
},
get: (receiver: any, key: string) => {
return receiver[key]
},
defineProperty: (target, prop, descriptor) => {
return Reflect.defineProperty(target, prop, descriptor)
},
})
}
static get uuid() {
if (!this._uuid) {
this._uuid = uuidWeak()
return this._uuid
}
return this._uuid
}
/**
* Cache a resource onto this class' cache for cacheMaxAge seconds
* @param resource
* @param replace
*/
static cacheResource<T extends typeof Resource>(this: T, resource: InstanceType<T>, replace: boolean = false) {
if (!resource.id) {
throw new exceptions.CacheError(`Can't cache ${resource.toResourceName()} resource without ${resource.getConstructor().uniqueKey} field`)
} else if (replace) {
try {
return this.replaceCache<InstanceType<T>>(resource)
} catch (e) {}
}
this.cache[resource.id] = {
resource,
expires: this.cacheDeltaSeconds(),
}
}
/**
* Replace attributes on a cached resource onto this class' cache for cacheMaxAge seconds (useful for bubbling up changes to states that may be already rendered)
* @param resource
*/
static replaceCache<T extends Resource>(resource: T) {
if (!this.cache[resource.id]) {
throw new exceptions.CacheError("Can't replace cache: resource doesn't exist")
}
Object.assign(this.cache[resource.id].resource.attributes, resource.attributes)
this.cache[resource.id].expires = this.cacheDeltaSeconds()
}
static clearCache() {
this._cache = {}
}
/**
* Get time delta in seconds of cache expiry
*/
static cacheDeltaSeconds() {
return Date.now() + this.cacheMaxAge * 1000
}
/**
* Get a cached resource by ID
* @param id
*/
static getCached<T extends typeof Resource>(this: T, id: string | number): CachedResource<InstanceType<T>> | undefined {
const cached = this.cache[String(id)]
if (cached && cached.expires > Date.now()) {
return cached as CachedResource<InstanceType<T>>
}
return undefined
}
static getCachedAll<T extends typeof Resource>(this: T): CachedResource<InstanceType<T>>[] {
return Object.keys(this.cache)
.map((cacheKey) => this.getCached(cacheKey))
.filter((valid) => !!valid)
}
/**
* Backwards compatibility
* Remove in next major release @todo
*/
static get validators() {
return this.validation
}
/**
* Backwards compatibility
* Remove in next major release @todo
*/
static set validators(value: any) {
this.validation = value
}
/**
* Get list route path (eg. /users) to be used with HTTP requests and allow a querystring object
* @param query Querystring
*/
static getListRoutePath(query?: any): string {
if (query && Object.keys(query).length) {
let qs = stringify(query)
return `${this.endpoint}?${qs}`
}
return this.endpoint
}
/**
* Get detail route path (eg. /users/123) to be used with HTTP requests
* @param id
* @param query Querystring
*/
static getDetailRoutePath(id: string | number, query?: any): string {
let qs = stringify(query)
return `${this.endpoint}/${String(id)}${query && Object.keys(query).length ? '?' : ''}${qs}`
}
/**
* HTTP Get of resource's list route--returns a promise
* @param options Options object
* @returns Promise
*/
static list<T extends typeof Resource>(this: T, options: ListOpts = {}): ListResponse<T> {
return this.client.list<T>(this as T, options).then((result) => {
if (options.resolveRelated || options.resolveRelatedDeep) {
let deep = !!options.resolveRelatedDeep
const promises: Promise<void>[] = []
result.resources.forEach((resource) => {
promises.push(resource.resolveRelated({ deep }))
})
return Promise.all(promises).then(() => result)
}
return result
})
}
static detail<T extends typeof Resource>(this: T, id: string | number, options: DetailOpts = {}): Promise<InstanceType<T>> {
// Check cache first
const cached: CachedResource<InstanceType<T>> = this.getCached(String(id))
return new Promise((resolve, reject) => {
// Do we want to use cache?
if (!cached || options.useCache === false) {
// Set a hash key for the queue (keeps it organized by type+id)
const queueHashKey = this.getResourceHashKey(String(id))
// If we want to use cache and cache wasn't found...
if (!this.queued[queueHashKey]) {
// We want to use cached and a resource with this ID hasn't been requested yet
this.queued[queueHashKey] = []
this.client
.detail(this, String(id), options)
.then(async (result) => {
// Get detail route and get resource from response
const correctResource = <InstanceType<T>>result.resources.pop()
// Get related resources?
if (options.resolveRelated || options.resolveRelatedDeep) {
let deep = !!options.resolveRelatedDeep
await correctResource.resolveRelated({ deep })
}
// Resolve first-sent request
setTimeout(() => resolve(correctResource), 0)
// Then resolve any deferred requests if there are any
this.queued[queueHashKey].forEach((deferred: (resource: InstanceType<T>) => any) => {
deferred(correctResource)
})
})
.catch((e) => {
reject(e)
})
.finally(() => {
// Finally, remove the fact that we've queued any requests with this ID
delete this.queued[queueHashKey]
})
} else {
// We want to use cache, but a resource with this ID has already been queued--defer promise and resolve when queued resource actually completes
const deferredPromise: Promise<InstanceType<T>> = new Promise((resolveDeferred) => {
this.queued[queueHashKey].push(resolveDeferred)
})
// Resolve related call to detail() but deferredPromise doesn't run until the first queued resource is completed
resolve(deferredPromise)
}
} else {
// We want to use cache, and we found it!
const cachedResource = cached.resource
// Get related resources?
if (options.resolveRelated || options.resolveRelatedDeep) {
let deep = !!options.resolveRelatedDeep
cached.resource.resolveRelated({ deep }).then(() => resolve(cachedResource))
} else {
resolve(cachedResource)
}
}
})
}
static wrap(relativePath: string, query?: any) {
assert(relativePath && relativePath[0] === '/', `Relative path "${relativePath}" must start with a "/"`)
let relEndpoint = this.endpoint + relativePath
if (query && Object.keys(query).length) {
let qs = stringify(query)
relEndpoint = `${relEndpoint}?${qs}`
}
return this.client.bindMethodsToPath(relEndpoint)
}
static toResourceName(): string {
// In an ES5 config, Webpack will reassign class name as a function like
// function class_1() { } when transpiling, so to help out with this in
// debugging, replace the class_1 function name with something more descriptive
if (this.name.match(/^class_/)) {
return `ResourceClass(${this.endpoint})`
}
return this.name
}
static makeDefaultsObject(): any {
let defaults: any = {}
for (let key in this.defaults) {
let thisDefault = this.defaults[key]
if ('function' === typeof thisDefault) {
defaults[key] = thisDefault.call(null)
} else {
defaults[key] = thisDefault
}
}
return defaults
}
/**
* Unique resource hash key used for caching and organizing requests
* @param resourceId
*/
static getResourceHashKey(resourceId: string | number) {
assert(Boolean(resourceId), "Can't generate resource hash key with an empty Resource ID. Please ensure Resource is saved first.")
return Buffer.from(`${this.uuid}:${String(resourceId)}`).toString('base64')
}
private static getRelatedClasses(): RelatedDict {
if ('function' === typeof this.related) {
return this.related() as RelatedDict
}
return this.related as RelatedDict
}
private static getValidatorObject(): ValidatorDict {
if ('function' === typeof this.validation) {
return this.validation() as ValidatorDict
}
return this.validation as ValidatorDict
}
static extend<T, U>(this: U, classProps: T): U & T {
// @todo Figure out typings here -- this works perfectly but typings are not happy
// @ts-ignore
return Object.assign(class extends this {}, classProps)
}
/**
* Set an attribute of Resource instance and apply getters/setters
* Do not use Dot Notation here
* @param key
* @param value
*/
set(key: string, value: any) {
this.attributes[key] = value
return this
}
/**
* Get an attribute of Resource instance
* You can use dot notation here -- eg. `resource.get('user.username')`
* You can also get all properties by not providing any arguments
* @param? key
*/
get<T = any>(key?: string): T {
if (typeof key !== 'undefined') {
// Get a value
const pieces = key.split('.')
const thisKey = String(pieces.shift())
const thisValue = this.attributes[thisKey]
const manager: RelatedManager = this.rel(thisKey)
if (pieces.length > 0) {
// We need to go deeper...
if (!manager) {
throw new exceptions.ImproperlyConfiguredError(`No relation found on ${this.toResourceName()}[${thisKey}]. Did you define it on ${this.toResourceName()}.related?`)
}
if (!manager.hasValues()) {
return undefined
}
if (manager.many) {
return manager.resources.map((thisResource) => {
return thisResource.get(pieces.join('.'))
}) as any
}
return manager.resource.get(pieces.join('.'))
} else if (Boolean(thisValue) && manager) {
// If the related manager is a single object and is inflated, auto resolve the resource.get(key) to that object
// @todo Maybe we should always return the manager? Or maybe we should always return the resolved object(s)? I am skeptical about this part
return (!manager.many && manager.resolved ? manager.resource : manager) as any
} else {
return thisValue
}
} else {
// We're getting all attributes -- any related resources also get converted to an object
const managers = Object.keys(this.managers)
const obj = Object.assign({}, this.attributes)
while (managers.length) {
const key = String(managers.shift())
const manager = this.rel(key)
if (manager.many) {
obj[key] = manager.resources.map((subResource) => subResource.get())
} else if (!manager.many && manager.resource) {
obj[key] = manager.resource.get()
}
}
return obj as T
}
}
/**
* Persist getting an attribute and get related keys until a key can be found (or not found)
* TypeError in get() will be thrown, we're just doing the resolveRelated() work for you...
* @param key
*/
resolveAttribute<T = any>(key: string): Promise<T> {
return new Promise((resolve, reject) => {
try {
resolve(this.get(key))
} catch (e) {
if (e.name === 'AttributeError') {
const pieces = key.split('.')
const thisKey = String(pieces.shift())
const manager = this.rel(thisKey)
manager.resolve().then(() => {
let relatedKey = pieces.join('.')
let promises = manager.resources.map((resource: Resource) => {
return resource.resolveAttribute(relatedKey)
})
Promise.all(promises).then((values) => {
if (manager.many) {
resolve(values as any)
} else if (values.length === 1) {
resolve(values[0] as any)
} else {
resolve(values as any)
}
})
})
} else {
reject(e)
}
}
})
}
/**
* Alias of resource.resolveAttribute(key)
* @param key
*/
getAsync<T = any>(key: string) {
return this.resolveAttribute<T>(key)
}
/**
* Setter -- Translate new value into an internal value onto this._attributes[key]
* Usually this is just setting a key/value but we want to be able to accept
* anything -- another Resource instance for example. If a Resource instance is
* provided, set the this.managers[key] as the new manager instance, then set the
* this.attributes[key] field as just the primary key of the related Resource instance
* @param key
* @param value
*/
toInternalValue(key: string, value: any): any {
let currentValue = this.attributes[key]
let newValue = value
let Ctor = this.getConstructor()
if (!_.isEqual(currentValue, newValue)) {
// Also resolve any related Resources back into foreign keys
if (newValue && this.rel(key) instanceof RelatedManager) {
// newValue has an old manager -- needs a new one
// Create a new RelatedManager
let manager = this.rel(key).fromValue(newValue)
newValue = manager.toJSON()
this.managers[key] = manager
}
this.changes[key] = newValue
}
if ('undefined' !== typeof Ctor.normalization[key]) {
let normalizer = <BaseNormalizer | Function & { normalize: () => any }>Ctor.normalization[key]
if ('function' === typeof normalizer.normalize) {
newValue = normalizer.normalize(newValue)
} else if ('function' === typeof normalizer) {
newValue = normalizer(newValue)
}
if (this.changes[key]) {
this.changes[key] = newValue
}
}
return newValue
}
/**
* Like calling instance.constructor but safer:
* changing objects down the line won't creep up the prototype chain and end up on native global objects like Function or Object
*/
getConstructor<T extends typeof Resource>(): T {
if (this.constructor === Function) {
// Safe guard in case something goes wrong in subclasses, we don't want to change native Function
return Resource as T
}
return this.constructor as T
}
/**
* Match all related values in `attributes[key]` where key is primary key of related instance defined in `Resource.related[key]`
* @param options resolveRelatedDict
*/
resolveRelated({ deep = false, managers = [] }: ResolveRelatedOpts = {}): Promise<void> {
const promises: Promise<void>[] = []
for (const resourceKey in this.managers) {
if (Array.isArray(managers) && managers.length > 0 && !~managers.indexOf(resourceKey)) {
continue
}
const manager = this.rel(resourceKey)
const promise = manager.resolve().then((objects) => {
if (deep) {
let otherPromises = objects.map((resource) => resource.resolveRelated({ deep, managers }))
return Promise.all(otherPromises).then(() => {
return void {}
})
} else {
return void {}
}
})
promises.push(promise)
}
return Promise.all(promises).then(() => void {})
}
/**
* Same as `Resource.prototype.resolveRelated` except `options.deep` defaults to `true`
* @param options
*/
resolveRelatedDeep(options?: ResolveRelatedOpts): Promise<void> {
const opts = Object.assign({ deep: true }, options || {})
return this.resolveRelated(opts)
}
/**
* Get related manager class by key
* @param key
*/
rel<T extends typeof Resource>(key: string) {
return this.managers[key] as RelatedManager<T>
}
/**
* Create a manager instance on based on current attributes
* @param relatedKey
*/
createManagerFor(relatedKey: string) {
let Ctor = this.getConstructor()
let related = Ctor.getRelatedClasses()
let to = related[relatedKey]
let nested = false
try {
if ('object' === typeof to) {
let relatedLiteral = to as RelatedLiteral
to = relatedLiteral.to
nested = !!relatedLiteral.nested
}
assert('function' === typeof to, `Couldn't find RelatedResource class with key "${relatedKey}". Does it exist?`)
let RelatedManagerCtor = to.RelatedManagerClass
let relatedManager = new RelatedManagerCtor(to, this._attributes[relatedKey])
if (nested && relatedManager.canAutoResolve()) {
relatedManager.resolveFromObjectValue()
}
return relatedManager
} catch (e) {
if (e instanceof assert.AssertionError) {
e.message = `${e.message} -- Relation: ${this.toResourceName()}.related[${relatedKey}]`
}
throw e
}
}
/**
* Saves the instance -- sends changes as a PATCH or sends whole object as a POST if it's new
*/
save<T extends this>(options: SaveOptions = {}): Promise<ResourceResponse<T>> {
let promise
const Ctor = this.getConstructor()
let errors = this.validate()
let fields = options.fields || Ctor.fields
if (errors.length > 0 && !options.force) {
throw new exceptions.ValidationError(errors)
}
if (this.isNew()) {
let attrs = fields.length ? _.pick(this.attributes, fields) : this.attributes
promise = Ctor.client.post(Ctor.getListRoutePath(), attrs)
} else if (options.partial === false) {
let attrs = fields.length ? _.pick(this.attributes, fields) : this.attributes
promise = Ctor.client.put(Ctor.getDetailRoutePath(this.id), attrs)
} else {
let attrs = fields.length ? _.pick(this.changes, fields) : this.changes
promise = Ctor.client.patch(Ctor.getDetailRoutePath(this.id), attrs)
}
return promise.then((response: AxiosResponse<T>) => {
this.changes = {}
for (const resKey in response.data) {
this.set(resKey, response.data[resKey])
}
if (this.id) {
// Replace cache
this.cache(options.replaceCache === false ? false : true)
}
return {
response,
resources: [this],
} as ResourceResponse<T>
})
}
/**
* Validate attributes -- returns empty if no errors exist -- you should throw new errors here
* @returns `Error[]` Array of Exceptions
*/
validate(): Error[] {
let errs: Error[] = []
let validators = this.getConstructor().getValidatorObject()
let tryFn = (func: ValidatorFunc, key: string) => {
try {
// Declare call of validator with params:
// attribute, resource, ValidationError class
func.call(null, this.attributes[key], this, exceptions.ValidationError)
} catch (e) {
errs.push(e)
}
}
for (let key in validators) {
if ('function' === typeof validators[key]) {
tryFn(validators[key] as ValidatorFunc, key)
} else if (Array.isArray(validators[key])) {
let validatorArray = validators[key] as ValidatorFunc[]
for (let vKey in validatorArray) {
tryFn(validatorArray[vKey], key)
}
}
}
return errs
}
update<T extends Resource>(this: T): Promise<T> {
return this.getConstructor()
.detail(this.id, { useCache: false })
.then((resource) => {
for (let key in resource.attributes) {
this.attributes[key] = resource.attributes[key]
}
}) as Promise<T>
}
delete(options?: RequestConfig) {
return this.getConstructor().client.delete(this.getConstructor().getDetailRoutePath(this.id), options)
}
cache<T extends Resource>(this: T, replace: boolean = false): T {
this.getConstructor().cacheResource(this, !!replace)
return this
}
getCached<T extends Resource>(this: T) {
return this.getConstructor().getCached(this.id) as CachedResource<T>
}
wrap(relativePath: string, query?: any) {
assert(relativePath && relativePath[0] === '/', `Relative path "${relativePath}" must start with a "/"`)
assert(this.id, "Can't look up a relative route on a resource that has not been created yet.")
let Ctor = this.getConstructor()
let thisPath = '/' + this.id + relativePath
return Ctor.wrap(thisPath, query)
}
isNew(): boolean {
return !this.id
}
get id(): string {
let uniqueKey = this.getConstructor().uniqueKey
return this.attributes[uniqueKey]
}
set id(value) {
throw new exceptions.AttributeError('Cannot set ID manually. Set ID by using attributes[id] = value')
}
toString(): string {
return `${this.toResourceName()} ${this.id || '(New)'}`
}
toResourceName(): string {
return this.getConstructor().toResourceName()
}
toJSON(): any {
return this.get()
}
}
export type TypeOrFunctionReturningType<T> = (() => T) | T
export type RelatedDict = Record<string, typeof Resource | RelatedLiteral>
export type RelatedDictOrFunction = TypeOrFunctionReturningType<RelatedDict>
export interface RelatedLiteral {
to: typeof Resource
nested?: boolean
// To add later... Eg. "alias?: string"
}
export type ValidatorFunc = (value?: any, resource?: Resource, validationExceptionClass?: typeof exceptions.ValidationError) => void
export type ValidatorDict = Record<string, ValidatorFunc | ValidatorFunc[]>
export type ValidatorDictOrFunction = TypeOrFunctionReturningType<ValidatorDict>
export interface CachedResource<T extends Resource> {
expires: number
resource: T
}
export interface SaveOptions {
partial?: boolean
replaceCache?: boolean
force?: boolean
fields?: any
}
export interface ResolveRelatedOpts {
managers?: string[]
deep?: boolean
}
export type ListOpts = RequestConfig & {
resolveRelated?: boolean
resolveRelatedDeep?: boolean
}
export type ListResponse<T extends typeof Resource> = Promise<ResourceResponse<InstanceType<T>, any>>
export type DetailOpts = RequestConfig & {
resolveRelated?: boolean
resolveRelatedDeep?: boolean
} | the_stack |
import { Nodes } from './ivr_nodes';
import * as d3 from 'd3';
import { inNodes } from './ivr_in_nodes';
import * as $ from 'jquery';
import { AddIVRComponent, total_apps } from './ivr-form-component';
let oBB_box;
let ox;
let oy;
let d_of_x;
let d_of_y;
export abstract class Applications {
display_name: string;
color: any;
application_name: any;
in_nod = [];
out_nod = [];
app_type: string;
isRemoved: any;
app_index: number;
app_img: any;
app_icon: any;
app_link: any;
inNodes: any;
text_area: any;
text_display: any;
left: any;
top: any;
set: any;
oBB: any;
r_set: any;
isActive: any;
image_border: any;
removeBtnBack: any;
removeBtnText: any;
// Abstract properties to be set in subclass
// Abstract properties to be set in subclass
// Use getter syntax
public type = 'application';
imgSrc = '';
outNodes: any = [];
app_form: any = '';
data: any;
resources:any;
public static currentAppIndex: any;
constructor(app_index , left, top) {
this.app_index = app_index;
this.left = left;
this.top = top;
}
setup () {
this.build_set();
this.app_img.drag(this.mover, this.starter, this.upper);
this.build_Nodes();
this.setControls();
this.setActive();
}
build_set() {
this.set = AddIVRComponent.r.set();
this.app_img = AddIVRComponent.r.image(this.imgSrc , this.left, this.top, 80, 60).attr({title: this.type, index: this.app_index, cursor: 'move'});
this.app_img.app_index = this.app_index;
this.set.push(this.app_img);
this.image_border = AddIVRComponent.r.rect(this.left - 2, this.top - 2, 80 + 4, 60 + 4, 4).attr({'opacity': 0});
this.removeBtnBack = AddIVRComponent.r.rect(this.left + 2, this.top + 2, 8, 8).attr({'fill-opacity': 100, 'fill': 'white', 'opacity': 0});
this.removeBtnText = AddIVRComponent.r.text(this.left + 4, this.top + 4, 'x').attr({font: '11px Arial', 'text-anchor': 'start', 'fill': 'black', 'cursor': 'pointer', 'opacity': 0});
this.set.push(this.image_border);
this.set.push(this.removeBtnBack);
this.set.push(this.removeBtnText);
}
starter = () => {
ox = this.app_img.attr('x');
oy = this.app_img.attr('y');
}
mover = (dx, dy) => {
const att = {x: ox + dx, y: oy + dy};
this.app_img.attr(att);
const abc: any = att;
// moving the outnode
for (let i = 0; i < this.out_nod.length; i++) {
if (this.type != 'play_menu') {
var att2 = { x: abc.x + 80, y: abc.y + (25+(10*i))};
}
else {
var att2 = { x: abc.x + 80, y: abc.y + (10*i)};
}
this.out_nod[i].node_rect.attr(att2);
}
// moving the unattached pointer
for (let i = 0; i < this.out_nod.length; i++) {
if (this.out_nod[i].pointer.is_attached === 'no') {
if (this.type != 'play_menu') {
var att3 = { x: abc.x + 80, y: abc.y + (25+(10*i))};
}
else {
var att3 = { x: abc.x + 80, y: abc.y + (10*i)};
}
this.out_nod[i].pointer.ptr_link.attr(att3);
}
}
//moving the node text
for (let i = 0; i < this.out_nod.length; i++) {
if (this.type != 'play_menu') {
var att4 = {x: abc.x + 78, y: abc.y + (30+(10*i))};
} else {
var att4 = {x: abc.x + 78, y: abc.y + (3+(10 * i))};
}
this.out_nod[i].node_text.attr(att4);
}
//moving the in node
for ( let i = 0; i < this.in_nod.length; i++) {
const att5 = {x: abc.x, y: abc.y + 30};
this.in_nod[i].node_link.attr(att5);
}
//If in node length is greater than also update the attached pointer
if ( this.in_nod.length > 0 ) {
for ( let i = 0; i < this.in_nod[0].pointers.length; i++) {
const att5 = {x: abc.x, y: abc.y + 30};
this.in_nod[0].pointers[i].ptr_link.attr(att5);
}
}
//Update the connection for out node
for (let i = 0; i < this.out_nod.length; i++) {
AddIVRComponent.r.connection(this.out_nod[i].pointer.connec_tions);
}
//Update the connection for the in node pointers
if ( this.in_nod.length > 0 ) {
for (let i = 0; i < this.in_nod[0].pointers.length; i++) {
AddIVRComponent.r.connection(this.in_nod[0].pointers[i].connec_tions);
}
}
//Move the image border along with it
const att6 = { x: abc.x - 2, y: abc.y - 2};
this.image_border.attr(att6);
//Move the remove button back
const att7 = {x: abc.x + 2, y: abc.y + 2};
this.removeBtnBack.attr(att7);
// Move the remove button text
const att8 = {x: abc.x + 4, y: abc.y + 4};
this.removeBtnText.attr(att8);
//Move the edit icon
const att9 = {x: abc.x + 2, y: abc.y + 60 - 14};
}
upper = () => {
}
app_mouseOver = () => {
Applications.currentAppIndex = this.app_index;
this.app_img.attr({ 'opacity': .5 });
}
app_mouseOut = () => {
this.app_img.attr({ 'opacity': 1 });
}
app_imgclick = () => {
for (const i in total_apps) {
total_apps[i].image_border.attr({'opacity': 0});
total_apps[i].removeBtnBack.attr({'fill-opacity': 100, 'fill': 'white', 'opacity': 0});
total_apps[i].removeBtnText.attr({font: '11px Arial', 'text-anchor': 'start', 'fill': 'black', 'cursor': 'pointer', 'opacity': 0});
// Hide all forms
AddIVRComponent.voice_play_form.hide();
AddIVRComponent.call_transfer_form.hide();
AddIVRComponent.record_form.hide();
AddIVRComponent.play_ivr_menu_form.hide();
AddIVRComponent.tts_form.hide();
AddIVRComponent.say_alpha_form.hide();
AddIVRComponent.say_digit_form.hide();
AddIVRComponent.say_number_form.hide();
AddIVRComponent.say_date_form.hide();
AddIVRComponent.say_time_form.hide();
AddIVRComponent.caller_id_form.hide();
}
if (this.type != 'start') {
this.isActive = 'true';
this.image_border.attr({'opacity': 1, 'stroke': 'red'});
this.removeBtnBack.attr({'opacity': 1, 'stroke': 'white'});
this.removeBtnText.attr({'opacity': 1});
if (total_apps[this.app_index].type != 'voice_play'
&& total_apps[this.app_index].type != 'play_menu'
&& total_apps[this.app_index].type != 'transfer'
&& total_apps[this.app_index].type != 'tts'
&& total_apps[this.app_index].type != 'say_alpha'
&& total_apps[this.app_index].type != 'say_digit'
&& total_apps[this.app_index].type != 'say_number'
&& total_apps[this.app_index].type != 'say_date'
&& total_apps[this.app_index].type != 'say_time'
&& total_apps[this.app_index].type != 'record'
&& total_apps[this.app_index].type != 'callerid_set'
) {
// total_apps[this.app_index].editIcon.attr({'opacity': 0});
} else {
this.editIconClickHandler();
// total_apps[this.app_index].editIcon.attr({'opacity': 1});
}
}
}
removeBtnClick = () => {
if (this.type === 'start') {
return;
}
let remove = -1;
for (let i = 0; i < total_apps[this.app_index].out_nod.length; i++) {
if (total_apps[this.app_index].out_nod[i].pointer.is_attached === 'yes'){
remove++;
}
}
if (total_apps[this.app_index].in_nod[0].pointers.length > 0) {
remove++;
}
if (remove === -1) {
// Remove outPointer
for (let i = 0; i < total_apps[this.app_index].out_nod.length; i++) {
total_apps[this.app_index].out_nod[i].pointer.ptr_link.remove();
total_apps[this.app_index].out_nod[i].pointer.connec_tions.line.remove();
total_apps[this.app_index].out_nod[i].pointer.connec_tions.bg.remove();
}
// FormsIVRComponent.r.safari();
total_apps[this.app_index].set.hide();
total_apps[this.app_index].isRemoved = 'yes';
delete total_apps[this.app_index];
if (this.type != 'voice_play'
&& this.type != 'play_menu'
&& this.type != 'transfer'
&& this.type != 'tts'
&& this.type != 'say_alpha'
&& this.type != 'say_digit'
&& this.type != 'say_number'
&& this.type != 'say_date'
&& this.type != 'say_time'
&& this.type != 'record'
&& this.type != 'callerid_set'
) {
} else {
this.app_form.hide();
}
}
else {
alert('Please remove links before deleting an Application');
}
}
editIconClickHandler = () => {
this.activate_form();
}
activate_form() {
/* it will be overriden later by child classes */
}
setControls() {
this.app_img.mouseover(this.app_mouseOver);
this.app_img.mouseout(this.app_mouseOut);
this.app_img.click(this.app_imgclick);
if (this.type != 'start') {
this.removeBtnText.click(this.removeBtnClick);
}
}
setActive() {
for (const k in total_apps) {
total_apps[k].image_border.attr({'opacity': 0});
total_apps[k].removeBtnBack.attr({'fill-opacity': 100, 'fill': 'white', 'opacity': 0});
total_apps[k].removeBtnText.attr({font: '11px Arial', 'text-anchor': 'start', 'fill': 'black', 'cursor': 'pointer', 'opacity': 0});
}
if (this.type != 'start') {
this.image_border.attr({'opacity': 1, 'stroke': 'red'});
this.removeBtnBack.attr({'opacity': 1, 'stroke': 'white'});
this.removeBtnText.attr({'opacity': 1});
// Hide all forms
AddIVRComponent.voice_play_form.hide();
AddIVRComponent.call_transfer_form.hide();
AddIVRComponent.record_form.hide();
AddIVRComponent.play_ivr_menu_form.hide();
AddIVRComponent.tts_form.hide();
AddIVRComponent.say_alpha_form.hide();
AddIVRComponent.say_digit_form.hide();
AddIVRComponent.say_number_form.hide();
AddIVRComponent.say_date_form.hide();
AddIVRComponent.say_time_form.hide();
AddIVRComponent.caller_id_form.hide();
if (this.type != 'voice_play'
&& this.type != 'play_menu'
&& this.type != 'transfer'
&& this.type != 'tts'
&& this.type != 'say_alpha'
&& this.type != 'say_digit'
&& this.type != 'say_number'
&& this.type != 'say_date'
&& this.type != 'say_time'
&& this.type != 'record'
&& this.type != 'callerid_set'
) {
} else {
this.activate_form();
}
}
}
restoreData(data) {
this.data = data;
}
restoreResources(resources) {
this.resources = resources;
}
restoreTooltip(data) {
this.app_img.attr({title: data});
}
build_Nodes() {
if (this.type != 'start') {
const i_n = new inNodes(this.type, this.inNodes, this.left, this.top, this.set);
this.in_nod.push(i_n);
}
// Out Nodes
for (let i = 0; i < this.outNodes.length; i++) {
const nodeColor = this.outNodes[i] === 'error' ? '#E60876' : this.outNodes[i] === 'success' ? '#4CC417' : '#3C8BE5';
const o_n = new Nodes(this.outNodes[i], this.type, this.left, this.top, this.set, i, 'white', nodeColor, this.app_index);
this.out_nod.push(o_n);
}
}
} | the_stack |
import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, InjectionToken, Optional } from '@angular/core';
import { APIClientInterface } from './api-client.interface';
import { Observable } from 'rxjs';import { DefaultHttpOptions, HttpOptions } from './types';
import * as models from './models';
export const USE_DOMAIN = new InjectionToken<string>('APIClient_USE_DOMAIN');
export const USE_HTTP_OPTIONS = new InjectionToken<HttpOptions>('APIClient_USE_HTTP_OPTIONS');
type APIHttpOptions = HttpOptions & {
headers: HttpHeaders;
params: HttpParams;
};
@Injectable()
export class APIClient implements APIClientInterface {
readonly options: APIHttpOptions;
readonly domain: string = `//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}`;
constructor(
private readonly http: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
if (domain != null) {
this.domain = domain;
}
this.options = {
headers: new HttpHeaders(options && options.headers ? options.headers : {}),
params: new HttpParams(options && options.params ? options.params : {}),
...(options && options.reportProgress ? { reportProgress: options.reportProgress } : {}),
...(options && options.withCredentials ? { withCredentials: options.withCredentials } : {})
};
}
/**
* 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>>;
getItems(
args: Exclude<APIClientInterface['getItemsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ItemList | HttpResponse<models.ItemList> | HttpEvent<models.ItemList>> {
const path = `/items`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('pageSize' in args) {
options.params = options.params.set('pageSize', String(args.pageSize));
}
if ('page' in args) {
options.params = options.params.set('page', String(args.page));
}
return this.http.get<models.ItemList>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getItemModels(
args: Exclude<APIClientInterface['getItemModelsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
const path = `/itemModels`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('pageSize' in args) {
options.params = options.params.set('pageSize', String(args.pageSize));
}
if ('page' in args) {
options.params = options.params.set('page', String(args.page));
}
return this.http.get<object>(`${this.domain}${path}`, options);
}
/**
* 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[]>>;
getPetsId(
args: Exclude<APIClientInterface['getPetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet[] | HttpResponse<models.Pet[]> | HttpEvent<models.Pet[]>> {
const path = `/pets/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.Pet[]>(`${this.domain}${path}`, options);
}
/**
* 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>>;
deletePetsId(
args: Exclude<APIClientInterface['deletePetsIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pets/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.delete<void>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['getPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Pet | HttpResponse<models.Pet> | HttpEvent<models.Pet>> {
const path = `/pets-with-default-id-param/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.Pet>(`${this.domain}${path}`, options);
}
/**
* 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>>;
patchPetsWithDefaultIdParamId(
args: Exclude<APIClientInterface['patchPetsWithDefaultIdParamIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
const path = `/pets-with-default-id-param/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.patch<void>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* 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>>;
getCustomers(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<(models.Customer[]) | null | HttpResponse<(models.Customer[]) | null> | HttpEvent<(models.Customer[]) | null>> {
const path = `/customers`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<(models.Customer[]) | null>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getDictionaries(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Dictionary | HttpResponse<models.Dictionary> | HttpEvent<models.Dictionary>> {
const path = `/dictionaries`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<models.Dictionary>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getFileId(
args: Exclude<APIClientInterface['getFileIdParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
const path = `/file/${args.id}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
responseType: 'blob' as 'json',
};
return this.http.get<File>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getRandomObject(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
const path = `/randomObject`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<object>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getRandomModel(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
const path = `/randomModel`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<object>(`${this.domain}${path}`, options);
}
/**
* 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>>;
getRandomString(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<string | HttpResponse<string> | HttpEvent<string>> {
const path = `/randomString`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<string>(`${this.domain}${path}`, options);
}
/**
* 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 }>>;
getDictionary(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<{ [key: string]: number } | HttpResponse<{ [key: string]: number }> | HttpEvent<{ [key: string]: number }>> {
const path = `/store/dictionary`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<{ [key: string]: number }>(`${this.domain}${path}`, options);
}
/**
* 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 }[]>>;
getArrayOfDictionaries(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<{ [key: string]: number }[] | HttpResponse<{ [key: string]: number }[]> | HttpEvent<{ [key: string]: number }[]>> {
const path = `/store/arrayOfdictionaries`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
return this.http.get<{ [key: string]: number }[]>(`${this.domain}${path}`, options);
}
/**
* 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>>;
firestoreProjectsDatabasesDocumentsCommit(
args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Dictionary | HttpResponse<models.Dictionary> | HttpEvent<models.Dictionary>> {
const path = `/${args.database}/write`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('wololo' in args) {
options.params = options.params.set('wololo', String(args.wololo));
}
if ('alt' in args) {
options.params = options.params.set('alt', String(args.alt));
}
if ('accessToken' in args) {
options.params = options.params.set('access_token', String(args.accessToken));
}
if ('pp' in args) {
options.params = options.params.set('pp', String(args.pp));
}
if ('prettyPrint' in args) {
options.params = options.params.set('prettyPrint', String(args.prettyPrint));
}
if ('simpleQueryParam' in args) {
options.params = options.params.set('simpleQueryParam', String(args.simpleQueryParam));
}
if ('simpleArrayQueryParam' in args) {
options.params = options.params.set('simpleArrayQueryParam', String(args.simpleArrayQueryParam));
}
return this.http.post<models.Dictionary>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* 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[]>>;
postReposOwnerRepoGitBlobs(
args: Exclude<APIClientInterface['postReposOwnerRepoGitBlobsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Blob[] | HttpResponse<models.Blob[]> | HttpEvent<models.Blob[]>> {
const path = `/repos/${args.owner}/${args.repo}/git/blobs`;
const options = {
...this.options,
...requestHttpOptions,
observe,
};
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
return this.http.post<models.Blob[]>(`${this.domain}${path}`, JSON.stringify(args.body), options);
}
/**
* 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>>;
getReposOwnerRepoGitBlobsShaCode(
args: Exclude<APIClientInterface['getReposOwnerRepoGitBlobsShaCodeParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
const path = `/repos/${args.owner}/${args.repo}/git/blobs/${args.shaCode}`;
const options = {
...this.options,
...requestHttpOptions,
observe,
responseType: 'blob' as 'json',
};
if ('accept' in args) {
options.headers = options.headers.set('Accept', String(args.accept));
}
return this.http.get<File>(`${this.domain}${path}`, options);
}
} | the_stack |
import { Base, BaseParams } from "./base";
import { Array2Object } from "src/util/tools";
export class Tedis extends Base {
constructor(options?: BaseParams) {
super(options);
}
/*******************************************************************************************************
* KEY *************************************************************************************************
*******************************************************************************************************/
/**
* Removes the specified keys. A key is ignored if it does not exist.
*
* @param key The first key.
* @param keys The other key.
* @returns The number of keys that were removed.
*/
public del(key: string, ...keys: string[]) {
return this.command<number>("DEL", key, ...keys);
}
/**
* Returns if key exists.
*
* Since Redis 3.0.3 it is possible to specify multiple keys instead of a single one. In such a case,
* it returns the total number of keys existing. Note that returning 1 or 0 for a single key is just
* a special case of the variadic usage, so the command is completely backward compatible.
*
* The user should be aware that if the same existing key is mentioned in the arguments multiple times,
* it will be counted multiple times. So if somekey exists, EXISTS somekey somekey will return 2.
*
* @param key The first key.
* @param keys The other key.
* @returns 1 if the key exists. 0 if the key does not exist.
*/
public exists(key: string, ...keys: string[]) {
return this.command<number>("EXISTS", key, ...keys);
}
/**
* Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key
* with an associated timeout is often said to be volatile in Redis terminology.
*
* @param key The key.
* @param seconds Expiration time in seconds.
* @returns 1 if the timeout was set. 0 if key does not exist.
*/
public expire(key: string, seconds: number) {
return this.command<number>("EXPIRE", key, seconds);
}
/**
* `EXPIREAT` has the same effect and semantic as `EXPIRE`, but instead of specifying the number of
* seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since
* January 1, 1970). A timestamp in the past will delete the key immediately.
*
* Please for the specific semantics of the command refer to the documentation of `EXPIRE`.
*
* @param key The key.
* @param timestamp Expiration time in timestamp.
* @returns 1 if the timeout was set. 0 if key does not exist.
*/
public expireat(key: string, timestamp: number) {
return this.command<number>("EXPIREAT", key, timestamp);
}
/**
* Returns all keys matching pattern.
*
* @param pattern Pattern string.
* @returns List of keys matching pattern.
*/
public keys(pattern: string) {
return this.command<string[]>("KEYS", pattern);
}
/**
* Move key from the currently selected database (see `SELECT`) to the specified destination database.
* When key already exists in the destination database, or it does not exist in the source database,
* it does nothing. It is possible to use `MOVE` as a locking primitive because of this.
*
* @param key The key.
* @param db The specified database number.
* @returns 1 if key was moved. 0 if key was not moved.
*/
public move(key: string, db: number) {
return this.command<number>("MOVE", key, db);
}
/**
* Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to
* persistent (a key that will never expire as no timeout is associated).
*
* @param key The key.
* @returns 1 if the timeout was removed. 0 if key does not exist or does not have an associated timeout.
*/
public persist(key: string) {
return this.command<number>("PERSIST", key);
}
/**
* This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds
* instead of seconds.
*
* @param key The key.
* @param milliseconds Expiration time in milliseconds.
* @returns 1 if the timeout was set. 0 if key does not exist.
*/
public pexpire(key: string, milliseconds: number) {
return this.command<number>("PEXPIRE", key, milliseconds);
}
/**
* `PEXPIREAT` has the same effect and semantic as `EXPIREAT`, but the Unix time at which the key will
* expire is specified in milliseconds instead of seconds.
*
* @param key The key.
* @param millisecondsTimestamp Expiration time in millisecondsTimestamp.
* @returns 1 if the timeout was set. 0 if key does not exist.
*/
public pexpireat(key: string, millisecondsTimestamp: number) {
return this.command<number>("PEXPIREAT", key, millisecondsTimestamp);
}
/**
* Like `TTL` this command returns the remaining time to live of a key that has an expire set, with the
* sole difference that `TTL` returns the amount of remaining time in seconds while `PTTL` returns it in
* milliseconds.
*
* @param key The key.
* @returns `TTL` in milliseconds, or a negative value in order to signal an error (see the description
* above). The command returns -2 if the key does not exist. The command returns -1 if the key exists
* but has no associated expire.
*/
public pttl(key: string) {
return this.command<number>("PTTL", key);
}
/**
* Return a random key from the currently selected database.
*
* @returns The random key, or nil when the database is empty.
*/
public randomkey() {
return this.command<string | null>("RANDOMKEY");
}
/**
* Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is
* overwritten, when this happens `RENAME` executes an implicit DEL operation, so if the deleted key
* contains a very big value it may cause high latency even if `RENAME` itself is usually a constant-time
* operation.
*
* Note: Before Redis 3.2.0, an error is returned if source and destination names are the same.
*
* @param key The key.
* @param newKey The newKey.
* @returns "OK".
*/
public rename(key: string, newKey: string) {
return this.command<string>("RENAME", key, newKey);
}
/**
* Renames key to newkey if newkey does not yet exist. It returns an error when key does not exist.
*
* Note: Before Redis 3.2.0, an error is returned if source and destination names are the same.
*
* @param key The key.
* @param newKey The newKey.
* @returns 1 if key was renamed to newkey. 0 if newkey already exists.
*/
public renamenx(key: string, newKey: string) {
return this.command<0 | 1>("RENAMENX", key, newKey);
}
/**
* Returns the remaining time to live of a key that has a timeout. This introspection capability allows
* a Redis client to check how many seconds a given key will continue to be part of the dataset.
*
* In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has
* no associated expire.
*
* Starting with Redis 2.8 the return value in case of error changed:
* - The command returns -2 if the key does not exist.
* - The command returns -1 if the key exists but has no associated expire.
*
* See also the `PTTL` command that returns the same information with milliseconds resolution (Only
* available in Redis 2.6 or greater).
*
* @param key The key.
* @returns TTL in seconds, or a negative value in order to signal an error (see the description above).
*/
public ttl(key: string) {
return this.command<number>("TTL", key);
}
/**
* Returns the string representation of the type of the value stored at key. The different types that
* can be returned are: string, list, set, zset and hash.
*
* @param key The key.
* @returns Type of key(string, hash, list, set, zset), or none when key does not exist.
*/
public type(key: string) {
return this.command<string>("TYPE", key);
}
/*******************************************************************************************************
* STRING **********************************************************************************************
*******************************************************************************************************/
/**
* If key already exists and is a string, this command appends the value at the end of the string. If
* key does not exist it is created and set as an empty string, so `APPEND` will be similar to SET in
* this special case.
*
* @param key The key.
* @param value The value.
* @returns The length of the string after the append operation.
*/
public append(key: string, value: string) {
return this.command<number>("APPEND", key, value);
}
/**
* Decrements the number stored at key by one. If the key does not exist, it is set to 0 before performing
* the operation. An error is returned if the key contains a value of the wrong type or contains a string
* that can not be represented as integer. This operation is limited to 64 bit signed integers.
*
* @param key The key.
* @returns The value of key after the decrement.
*/
public decr(key: string) {
return this.command<number>("DECR", key);
}
/**
* Decrements the number stored at key by decrement. If the key does not exist, it is set to 0 before
* performing the operation. An error is returned if the key contains a value of the wrong type or
* contains a string that can not be represented as integer. This operation is limited to 64 bit
* signed integers.
*
* @param key The key.
* @param increment The increment.
* @returns The value of key after the decrement.
*/
public decrby(key: string, increment: number) {
return this.command<number>("DECRBY", key, increment);
}
/**
* Get the value of key. If the key does not exist the special value nil is returned. An error is returned
* if the value stored at key is not a string, because `GET` only handles string values.
*
* @param key The key.
* @returns The value of key, or nil when key does not exist.
*/
public get(key: string) {
return this.command<string | number | null>("GET", key);
}
/**
* Returns the bit value at offset in the string value stored at key.
*
* When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits.
* When key does not exist it is assumed to be an empty string, so offset is always out of range and
* the value is also assumed to be a contiguous space with 0 bits.
*
* @param key The key.
* @param offset The offset.
* @returns The bit value stored at offset.
*/
public getbit(key: string, offset: number) {
return this.command<0 | 1>("GETBIT", key, offset);
}
/**
* Returns the substring of the string value stored at key, determined by the offsets start and end
* (both are inclusive). Negative offsets can be used in order to provide an offset starting from
* the end of the string. So -1 means the last character, -2 the penultimate and so forth.
*
* The function handles out of range requests by limiting the resulting range to the actual length
* of the string.
*
* @param key The key.
* @param range The range. Start is the start position, and end is the end position
* @returns Substring.
*/
public getrange(key: string, [start, end]: [number, number] = [0, -1]) {
return this.command<string>("GETRANGE", key, start, end);
}
/**
* Atomically sets key to value and returns the old value stored at key. Returns an error when key
* exists but does not hold a string value.
*
* @param key The key.
* @param value The value.
* @returns The old value stored at key, or nil when key did not exist.
*/
public getset(key: string, value: string) {
return this.command<string | null>("GETSET", key, value);
}
/**
* Increments the number stored at key by one. If the key does not exist, it is set to 0 before
* performing the operation. An error is returned if the key contains a value of the wrong type
* or contains a string that can not be represented as integer. This operation is limited to 64
* bit signed integers.
*
*
* Note: this is a string operation because Redis does not have a dedicated integer type. The
* string stored at the key is interpreted as a base-10 64 bit signed integer to execute the
* operation.
*
* Redis stores integers in their integer representation, so for string values that actually
* hold an integer, there is no overhead for storing the string representation of the integer.
*
* @param key The key.
* @returns the value of key after the increment.
*/
public incr(key: string) {
return this.command<number>("INCR", key);
}
/**
* Increments the number stored at key by increment. If the key does not exist, it is set to 0 before
* performing the operation. An error is returned if the key contains a value of the wrong type or
* contains a string that can not be represented as integer. This operation is limited to 64 bit signed
* integers.
*
* @param key The key.
* @param increment The increment.
* @returns The value of key after the increment.
*/
public incrby(key: string, increment: number) {
return this.command<number>("INCRBY", key, increment);
}
/**
* Increment the string representing a floating point number stored at key by the specified increment.
* By using a negative increment value, the result is that the value stored at the key is decremented
* (by the obvious properties of addition). If the key does not exist, it is set to 0 before performing
* the operation. An error is returned if one of the following conditions occur:
* - The key contains a value of the wrong type (not a string).
* - The current key content or the specified increment are not parsable as a double precision floating
* point number.
*
* If the command is successful the new incremented value is stored as the new value of the key (replacing
* the old one), and returned to the caller as a string.
*
* @param key The key.
* @param increment The increment.
* @returns The value of key after the increment.
*/
public incrbyfloat(key: string, increment: number) {
return this.command<string>("INCRBYFLOAT", key, increment);
}
/**
* Returns the values of all specified keys. For every key that does not hold a string value or does not
* exist, the special value nil is returned. Because of this, the operation never fails.
*
* @param key The key.
* @param keys The other key.
* @returns List of values at the specified keys.
*/
public mget(key: string, ...keys: string[]) {
return this.command<Array<string | number | null>>("MGET", key, ...keys);
}
/**
* Sets the given keys to their respective values. `MSET` replaces existing values with new values, just
* as regular `SET`. See `MSETNX` if you don't want to overwrite existing values.
*
* `MSET` is atomic, so all given keys are set at once. It is not possible for clients to see that some
* of the keys were updated while others are unchanged.
*
* @param objKV The objects that need to be saved
* @returns Always OK since `MSET` can't fail.
*/
public mset(objKV: { [propName: string]: string }) {
const arrayKV: string[] = [];
(Reflect.ownKeys(objKV) as string[]).forEach(key => {
arrayKV.push(key, objKV[key]);
});
return this.command<string>("MSET", ...arrayKV);
}
/**
* Sets the given keys to their respective values. `MSETNX` will not perform any operation at all even
* if just a single key already exists.
*
* Because of this semantic `MSETNX` can be used in order to set different keys representing different
* fields of an unique logic object in a way that ensures that either all the fields or none at all are
* set.
*
* `MSETNX` is atomic, so all given keys are set at once. It is not possible for clients to see that
* some of the keys were updated while others are unchanged.
*
* @param objKv The objects that need to be saved
* @returns 1 if the all the keys were set. 0 if no key was set (at least one key already existed).
*/
public msetnx(objKv: { [propName: string]: string }) {
const arrayKV: string[] = [];
(Reflect.ownKeys(objKv) as string[]).forEach(key => {
arrayKV.push(key, objKv[key]);
});
return this.command<number>("MSETNX", ...arrayKV);
}
/**
* `PSETEX` works exactly like `SETEX` with the sole difference that the expire time is specified in
* milliseconds instead of seconds.
*
* @param key The key.
* @param milliseconds Expiration time in milliseconds.
* @param value The value.
* @returns "OK".
*/
public psetex(key: string, milliseconds: number, value: string) {
return this.command<string>("PSETEX", key, milliseconds, value);
}
/**
* Set key to hold the string value. If key already holds a value, it is overwritten, regardless of
* its type. Any previous time to live associated with the key is discarded on successful SET operation.
*
* Options Starting with Redis 2.6.12 SET supports a set of options that modify its behavior:
* - EX seconds -- Set the specified expire time, in seconds.
* - PX milliseconds -- Set the specified expire time, in milliseconds.
* - NX -- Only set the key if it does not already exist.
* - XX -- Only set the key if it already exist.
*
* @param key The key.
* @param value The value.
* @returns OK if `SET` was executed correctly. Null reply: a Null Bulk Reply is returned if the `SET`
* operation was not performed because the user specified the NX or XX option but the condition was
* not met.
*/
public set(key: string, value: string) {
return this.command<string>("SET", key, value);
}
/**
* Sets or clears the bit at offset in the string value stored at key.
*
* The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not
* exist, a new string value is created. The string is grown to make sure it can hold a bit at offset.
* The offset argument is required to be greater than or equal to 0, and smaller than 2^32 (this limits
* bitmaps to 512MB). When the string at key is grown, added bits are set to 0.
*
* @param key The key.
* @param offset The offset
* @param value The value.
* @returns The original bit value stored at offset.
*/
public setbit(key: string, offset: number, value: 0 | 1) {
return this.command<0 | 1>("SETBIT", key, offset, value);
}
/**
* Set key to hold the string value and set key to timeout after a given number of seconds.
*
* @param key The key.
* @param seconds Expiration time in seconds.
* @param value The value.
* @returns "OK".
*/
public setex(key: string, seconds: number, value: string) {
return this.command<string>("SETEX", key, seconds, value);
}
/**
* Set key to hold string value if key does not exist. In that case, it is equal to `SET`. When key already
* holds a value, no operation is performed. `SETNX` is short for "SET if Not eXists".
*
* @param key The key.
* @param keys The other key.
* @returns 1 if the key was set, 0 if the key was not set.
*/
public setnx(key: string, ...keys: string[]) {
return this.command<0 | 1>("SETNX", key, ...keys);
}
/**
* Overwrites part of the string stored at key, starting at the specified offset, for the entire length of
* value. If the offset is larger than the current length of the string at key, the string is padded with
* zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will
* make sure it holds a string large enough to be able to set value at offset.
*
* @param key The key.
* @param offset The offset.
* @param value The value.
* @returns The length of the string after it was modified by the command.
*/
public setrange(key: string, offset: number, value: string) {
return this.command<number>("SETRANGE", key, offset, value);
}
/**
* Returns the length of the string value stored at key. An error is returned when key holds a non-string value.
*
* @param key The key.
* @returns The length of the string at key, or 0 when key does not exist.
*/
public strlen(key: string) {
return this.command<number>("STRLEN", key);
}
/*******************************************************************************************************
* HASH ************************************************************************************************
*******************************************************************************************************/
/**
* Removes the specified fields from the hash stored at key. Specified fields that do not exist within
* this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns 0.
*
* @param key The key.
* @param field The field.
* @param fields The other field.
* @returns The number of fields that were removed from the hash, not including specified but non existing
* fields.
*/
public hdel(key: string, field: string, ...fields: string[]) {
return this.command<number>("HDEL", key, field, ...fields);
}
/**
* Returns if field is an existing field in the hash stored at key.
* @param key The key.
* @param field The field.
* @returns 1 if the hash contains field. 0 if the hash does not contain field, or key does not exist.
*/
public hexists(key: string, field: string) {
return this.command<number>("HEXISTS", key, field);
}
/**
* Returns the value associated with field in the hash stored at key.
*
* @param key The key.
* @param field The field.
* @returns The value associated with field, or nil when field is not present in the hash or key does not exist.
*/
public hget(key: string, field: string) {
return this.command<string | null>("HGET", key, field);
}
/**
* Returns all fields and values of the hash stored at key. In the returned value, every field name is followed
* by its value, so the length of the reply is twice the size of the hash.
*
* @param key The key.
* @returns List of fields and their values stored in the hash, or an empty list when key does not exist.
*/
public async hgetall(key: string) {
return Array2Object(await this.command<string[]>("HGETALL", key));
}
/**
* Increments the number stored at field in the hash stored at key by increment. If key does not exist, a new
* key holding a hash is created. If field does not exist the value is set to 0 before the operation is performed.
*
* The range of values supported by `HINCRBY` is limited to 64 bit signed integers.
*
* @param key The key.
* @param field The field.
* @param increment The increment.
* @returns The value at field after the increment.
*/
public hincrby(key: string, field: string, increment: number) {
return this.command<number>("HINCRBY", key, field, increment);
}
/**
* Increment the specified field of a hash stored at key, and representing a floating point number, by the
* specified increment. If the increment value is negative, the result is to have the hash field value
* decremented instead of incremented. If the field does not exist, it is set to 0 before performing the
* operation. An error is returned if one of the following conditions occur:
* - The field contains a value of the wrong type (not a string).
* - The current field content or the specified increment are not parsable as a double precision floating point number.
*
* @param key The key.
* @param field The field.
* @param increment The increment.
* @returns The value at field after the increment.
*/
public hincrbyfloat(key: string, field: string, increment: number) {
return this.command<string>("HINCRBYFLOAT", key, field, increment);
}
/**
* Returns all field names in the hash stored at key.
*
* @param key The key.
* @returns List of fields in the hash, or an empty list when key does not exist.
*/
public hkeys(key: string) {
return this.command<string[]>("HKEYS", key);
}
/**
* Returns the number of fields contained in the hash stored at key.
* @param key The key.
* @returns Number of fields in the hash, or 0 when key does not exist.
*/
public hlen(key: string) {
return this.command<number>("HLEN", key);
}
/**
* Returns the values associated with the specified fields in the hash stored at key.
*
* For every field that does not exist in the hash, a nil value is returned. Because non-existing keys are
* treated as empty hashes, running HMGET against a non-existing key will return a list of nil values.
*
* @param key The key.
* @param field The field.
* @param fields The other field.
* @returns List of values associated with the given fields, in the same order as they are requested.
*/
public hmget(key: string, field: string, ...fields: string[]) {
return this.command<Array<string | null>>("HMGET", key, field, ...fields);
}
/**
* Sets the specified fields to their respective values in the hash stored at key. This command overwrites
* any specified fields already existing in the hash. If key does not exist, a new key holding a hash is
* created.
*
* @param key The key.
* @param data The data.
* @returns "OK".
*/
public hmset(
key: string,
data: {
[propName: string]: string | number;
},
) {
const arrayFV: any[] = [];
(Reflect.ownKeys(data) as string[]).forEach(field => {
arrayFV.push(field, data[field]);
});
return this.command("HMSET", key, ...arrayFV);
}
/**
* Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created.
* If field already exists in the hash, it is overwritten.
*
* @param key The key.
* @param field The field.
* @param value The value.
* @returns 1 if field is a new field in the hash and value was set. 0 if field already exists in the hash
* and the value was updated.
*/
public hset(key: string, field: string, value: string) {
return this.command<0 | 1>("HSET", key, field, value);
}
/**
* Sets field in the hash stored at key to value, only if field does not yet exist. If key does not exist,
* a new key holding a hash is created. If field already exists, this operation has no effect.
*
* @param key The key.
* @param field The field.
* @param value The value.
* @returns 1 if field is a new field in the hash and value was set. 0 if field already exists in the hash
* and no operation was performed.
*/
public hsetnx(key: string, field: string, value: string) {
return this.command<0 | 1>("HSETNX", key, field, value);
}
/**
* Returns the string length of the value associated with field in the hash stored at key. If the key or the
* field do not exist, 0 is returned.
*
* @param key The key.
* @param field The field.
* @returns The string length of the value associated with field, or zero when field is not present in the
* hash or key does not exist at all.
*/
public hstrlen(key: string, field: string) {
return this.command<number>("HSTRLEN", key, field);
}
/**
* Returns all values in the hash stored at key.
* @param key The key.
* @returns List of values in the hash, or an empty list when key does not exist.
*/
public hvals(key: string) {
return this.command<string[]>("HVALS", key);
}
/*******************************************************************************************************
* LIST ************************************************************************************************
*******************************************************************************************************/
/**
* BLPOP is a blocking list pop primitive. It is the blocking version of LPOP because it blocks the
* connection when there are no elements to pop from any of the given lists. An element is popped from
* the head of the first list that is non-empty, with the given keys being checked in the order that
* they are given.
*
* @param timeout The timeout.
* @param keys The keys.
* @returns
* - A nil multi-bulk when no element could be popped and the timeout expired.
* - A two-element multi-bulk with the first element being the name of the key where an element was
* popped and the second element being the value of the popped element.
*/
public blpop(timeout: number, ...keys: string[]) {
return this.command<Array<string | null>>("BLPOP", ...keys, timeout);
}
/**
* BRPOP is a blocking list pop primitive. It is the blocking version of RPOP because it blocks the
* connection when there are no elements to pop from any of the given lists. An element is popped
* from the tail of the first list that is non-empty, with the given keys being checked in the order
* that they are given.
*
* @param timeout The timeout.
* @param keys The keys.
* @returns
* - A nil multi-bulk when no element could be popped and the timeout expired.
* - A two-element multi-bulk with the first element being the name of the key where an element was
* popped and the second element being the value of the popped element.
*/
public brpop(timeout: number, ...keys: string[]) {
return this.command<Array<string | null>>("BRPOP", ...keys, timeout);
}
/**
* BRPOPLPUSH is the blocking variant of RPOPLPUSH. When source contains elements, this command behaves
* exactly like RPOPLPUSH. When used inside a MULTI/EXEC block, this command behaves exactly like
* RPOPLPUSH. When source is empty, Redis will block the connection until another client pushes to it
* or until timeout is reached. A timeout of zero can be used to block indefinitely.
*
* @param source The source.
* @param destination The destination.
* @param timeout The timeout.
* @returns The element being popped from source and pushed to destination. If timeout is reached, a
* Null reply is returned.
*/
public brpoplpush(source: string, destination: string, timeout: number) {
return this.command("BRPOPLPUSH", source, destination, timeout);
}
/**
* Returns the element at index index in the list stored at key. The index is zero-based, so 0 means
* the first element, 1 the second element and so on. Negative indices can be used to designate elements
* starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate and so
* forth.
*
* When the value at key is not a list, an error is returned.
*
* @param key The key.
* @param index The index.
* @returns The requested element, or nil when index is out of range.
*/
public lindex(key: string, index: number) {
return this.command("LINDEX", key, index);
}
/**
* Inserts value in the list stored at key either before or after the reference value pivot.
*
* When key does not exist, it is considered an empty list and no operation is performed.
*
* An error is returned when key exists but does not hold a list value.
*
* @param key The key.
* @param type The type.
* @param pivot The pivot.
* @param value The value.
* @returns the length of the list after the insert operation, or -1 when the value pivot was not found.
*/
public linsert(key: string, type: "BEFORE" | "AFTER", pivot: string, value: string) {
return this.command<number>("LINSERT", key, type, pivot, value);
}
/**
* Returns the length of the list stored at key. If key does not exist, it is interpreted as an empty
* list and 0 is returned. An error is returned when the value stored at key is not a list.
*
* @param key The key.
* @returns The length of the list at key.
*/
public llen(key: string) {
return this.command<number>("LLEN", key);
}
/**
* Removes and returns the first element of the list stored at key.
*
* @param key The key.
* @returns The value of the first element, or nil when key does not exist.
*/
public lpop(key: string) {
return this.command<string | null>("LPOP", key);
}
/**
* Insert all the specified values at the head of the list stored at key. If key does not exist, it is
* created as empty list before performing the push operations. When key holds a value that is not a list,
* an error is returned.
*
* It is possible to push multiple elements using a single command call just specifying multiple arguments
* at the end of the command. Elements are inserted one after the other to the head of the list, from the
* leftmost element to the rightmost element. So for instance the command LPUSH mylist a b c will result
* into a list containing c as first element, b as second element and a as third element.
*
* @param key The key.
* @param value The value.
* @param values The other value.
* @returns The length of the list after the push operations.
*/
public lpush(key: string, value: string | number, ...values: Array<string | number>) {
return this.command<number>("LPUSH", key, value, ...values);
}
/**
* Inserts value at the head of the list stored at key, only if key already exists and holds a list. In
* contrary to LPUSH, no operation will be performed when key does not yet exist.
*
* @param key The key.
* @param value The value.
* @returns The length of the list after the push operation.
*/
public lpushx(key: string, value: string | number) {
return this.command<number>("LPUSHX", key, value);
}
/**
* Returns the specified elements of the list stored at key. The offsets start and stop are zero-based
* indexes, with 0 being the first element of the list (the head of the list), 1 being the next element
* and so on.
*
* These offsets can also be negative numbers indicating offsets starting at the end of the list. For
* example, -1 is the last element of the list, -2 the penultimate, and so on.
*
* ### Consistency with range functions in various programming languages
* Note that if you have a list of numbers from 0 to 100, LRANGE list 0 10 will return 11 elements,
* that is, the rightmost item is included. This may or may not be consistent with behavior of
* range-related functions in your programming language of choice (think Ruby's Range.new, Array#slice
* or Python's range() function).
*
* ### Out-of-range indexes
* Out of range indexes will not produce an error. If start is larger than the end of the list, an empty
* list is returned. If stop is larger than the actual end of the list, Redis will treat it like the
* last element of the list.
*
* @param key The key.
* @param start The start.
* @param stop The stop.
* @returns List of elements in the specified range.
*/
public lrange(key: string, start: number, stop: number) {
return this.command<string[]>("LRANGE", key, start, stop);
}
/**
* Removes the first count occurrences of elements equal to value from the list stored at key. The count
* argument influences the operation in the following ways:
* - count > 0: Remove elements equal to value moving from head to tail.
* - count < 0: Remove elements equal to value moving from tail to head.
* - count = 0: Remove all elements equal to value.
*
* For example, LREM list -2 "hello" will remove the last two occurrences of "hello" in the list stored
* at list.
*
* Note that non-existing keys are treated like empty lists, so when key does not exist, the command will
* always return 0.
*
* @param key The key.
* @param count The count.
* @param value The value.
* @returns The number of removed elements.
*/
public lrem(key: string, count: number, value: string) {
return this.command<number>("LREM", key, count, value);
}
/**
* Sets the list element at index to value. For more information on the index argument, see LINDEX.
*
* An error is returned for out of range indexes.
*
* @param key The key.
* @param count The count.
* @param value The value.
* @returns "OK".
*/
public lset(key: string, index: number, value: string) {
return this.command("LSET", key, index, value);
}
/**
* Trim an existing list so that it will contain only the specified range of elements specified. Both
* start and stop are zero-based indexes, where 0 is the first element of the list (the head), 1 the
* next element and so on.
*
* For example: LTRIM foobar 0 2 will modify the list stored at foobar so that only the first three
* elements of the list will remain.
*
* start and end can also be negative numbers indicating offsets from the end of the list, where -1
* is the last element of the list, -2 the penultimate element and so on.
*
* Out of range indexes will not produce an error: if start is larger than the end of the list, or
* start > end, the result will be an empty list (which causes key to be removed). If end is larger
* than the end of the list, Redis will treat it like the last element of the list.
*
* A common use of LTRIM is together with LPUSH / RPUSH. For example:
* ```bash
* LPUSH mylist someelement
* LTRIM mylist 0 99
* ```
*
* This pair of commands will push a new element on the list, while making sure that the list will
* not grow larger than 100 elements. This is very useful when using Redis to store logs for example.
* It is important to note that when used in this way LTRIM is an O(1) operation because in the
* average case just one element is removed from the tail of the list.
*
* @param key The key.
* @param start The start.
* @param stop The stop.
* @returns "OK".
*/
public ltrim(key: string, start: number, stop: number) {
return this.command("LTRIM", key, start, stop);
}
/**
* Removes and returns the last element of the list stored at key.
* @param key The key.
* @returns The value of the last element, or nil when key does not exist.
*/
public rpop(key: string) {
return this.command<string | null>("RPOP", key);
}
/**
* Atomically returns and removes the last element (tail) of the list stored at source, and pushes
* the element at the first element (head) of the list stored at destination.
*
* For example: consider source holding the list a,b,c, and destination holding the list x,y,z.
* Executing RPOPLPUSH results in source holding a,b and destination holding c,x,y,z.
*
* If source does not exist, the value nil is returned and no operation is performed. If source and
* destination are the same, the operation is equivalent to removing the last element from the list
* and pushing it as first element of the list, so it can be considered as a list rotation command.
*
* @param source The source.
* @param destination The destination.
* @returns The element being popped and pushed.
*/
public rpoplpush(source: string, destination: string) {
return this.command<string | null>("RPOPLPUSH", source, destination);
}
/**
* Insert all the specified values at the tail of the list stored at key. If key does not exist,
* it is created as empty list before performing the push operation. When key holds a value that
* is not a list, an error is returned.
*
* It is possible to push multiple elements using a single command call just specifying multiple
* arguments at the end of the command. Elements are inserted one after the other to the tail of
* the list, from the leftmost element to the rightmost element. So for instance the command RPUSH
* mylist a b c will result into a list containing a as first element, b as second element and c
* as third element.
*
* @param key The key.
* @param value The value.
* @param values The other value.
* @returns The length of the list after the push operation.
*/
public rpush(key: string, value: string | number, ...values: Array<string | number>) {
return this.command<number>("RPUSH", key, value, ...values);
}
/**
* Inserts value at the tail of the list stored at key, only if key already exists and holds a list.
* In contrary to RPUSH, no operation will be performed when key does not yet exist.
*
* @param key The key.
* @param value The value.
* @returns The length of the list after the push operation.
*/
public rpushx(key: string, value: string | number) {
return this.command<number>("RPUSHX", key, value);
}
/*******************************************************************************************************
* SET *************************************************************************************************
*******************************************************************************************************/
/**
* Add the specified members to the set stored at key. Specified members that are already a member of
* this set are ignored. If key does not exist, a new set is created before adding the specified members.
*
* An error is returned when the value stored at key is not a set.
*
* @param key The key.
* @param member The member.
* @param members The other member.
* @returns The number of elements that were added to the set, not including all the elements already
* present into the set.
*/
public sadd(key: string, member: string | number, ...members: Array<string | number>) {
return this.command<number>("SADD", key, member, ...members);
}
/**
* Returns the set cardinality (number of elements) of the set stored at key.
*
* @param key The key.
* @returns The cardinality (number of elements) of the set, or 0 if key does not exist.
*/
public scard(key: string) {
return this.command<number>("SCARD", key);
}
/**
* Returns the members of the set resulting from the difference between the first set and all the
* successive sets. Keys that do not exist are considered to be empty sets.
*
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The keys.
* @returns List with members of the resulting set.
*/
public sdiff(key: string, anotherkey: string, ...keys: string[]) {
return this.command<string[]>("SDIFF", key, anotherkey, ...keys);
}
/**
* This command is equal to SDIFF, but instead of returning the resulting set, it is stored in destination.
*
* If destination already exists, it is overwritten.
*
* @param destination The destination.
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The keys.
* @returns The number of elements in the resulting set.
*/
public sdiffstore(
destination: string,
key: string,
anotherkey: string,
...keys: string[]
): Promise<number> {
return this.command("SDIFFSTORE", destination, key, anotherkey, ...keys);
}
/**
* Returns the members of the set resulting from the intersection of all the given sets.
*
* Keys that do not exist are considered to be empty sets. With one of the keys being an empty set,
* the resulting set is also empty (since set intersection with an empty set always results in an
* empty set).
*
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The keys.
* @returns List with members of the resulting set.
*/
public sinter(key: string, anotherkey: string, ...keys: string[]) {
return this.command<string[]>("SINTER", key, anotherkey, ...keys);
}
/**
* This command is equal to SINTER, but instead of returning the resulting set, it is stored in destination.
*
* If destination already exists, it is overwritten.
*
* @param destination The destination.
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The keys.
* @returns The number of elements in the resulting set.
*/
public sinterstore(
destination: string,
key: string,
anotherkey: string,
...keys: string[]
): Promise<number> {
return this.command("SINTERSTORE", destination, key, anotherkey, ...keys);
}
/**
* Returns if member is a member of the set stored at key.
*
* @param key The key.
* @param member The member.
* @returns 1 if the element is a member of the set. 0 if the element is not a member of the set, or if key
* does not exist.
*/
public sismember(key: string, member: string | number) {
return this.command<number>("SISMEMBER", key, member);
}
/**
* Returns all the members of the set value stored at key.
*
* This has the same effect as running SINTER with one argument key.
*
* @param key The key.
* @returns All elements of the set.
*/
public smembers(key: string) {
return this.command<string[]>("SMEMBERS", key);
}
/**
* Move member from the set at source to the set at destination. This operation is atomic. In every given
* moment the element will appear to be a member of source or destination for other clients.
*
* If the source set does not exist or does not contain the specified element, no operation is performed
* and 0 is returned. Otherwise, the element is removed from the source set and added to the destination
* set. When the specified element already exists in the destination set, it is only removed from the
* source set.
*
* An error is returned if source or destination does not hold a set value.
*
* @param source The source.
* @param destination The destination.
* @param member The member.
* @returns 1 if the element is moved. 0 if the element is not a member of source and no operation was
* performed.
*/
public smove(source: string, destination: string, member: string) {
return this.command<number>("SMOVE", source, destination, member);
}
/**
* Removes and returns one or more random elements from the set value store at key.
* @param key The key.
* @param count The count.
* @returns The removed element, or nil when key does not exist.
*/
public spop(key: string, count: number): Promise<string[]>;
/**
* Removes and returns one or more random elements from the set value store at key.
* @param key The key.
* @param count The count.
* @returns The removed element, or nil when key does not exist.
*/
public spop(key: string): Promise<string | null>;
public spop(key: string, count?: number) {
if (typeof count === "number") {
return this.command("SPOP", key, count);
} else {
return this.command("SPOP", key);
}
}
/**
* When called with just the key argument, return a random element from the set value stored at key.
* @param key The key.
* @param count The count.
*/
public srandmember(key: string, count: number): Promise<string[]>;
/**
* When called with just the key argument, return a random element from the set value stored at key.
* @param key The key.
*/
public srandmember(key: string): Promise<string | null>;
public srandmember(key: string, count?: number) {
if (typeof count === "number") {
return this.command("SRANDMEMBER", key, count);
} else {
return this.command("SRANDMEMBER", key);
}
}
/**
* Remove the specified members from the set stored at key. Specified members that are not a member
* of this set are ignored. If key does not exist, it is treated as an empty set and this command
* returns 0.
*
* An error is returned when the value stored at key is not a set.
*
* @param key The key.
* @param member The member.
* @param members The other member.
* @returns The number of members that were removed from the set, not including non existing members.
*/
public srem(key: string, member: string | number, ...members: Array<string | number>) {
return this.command<number>("SREM", key, member, ...members);
}
/**
* Returns the members of the set resulting from the union of all the given sets. Keys that do not
* exist are considered to be empty sets.
*
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The other key.
* @returns List with members of the resulting set.
*/
public sunion(key: string, anotherkey: string, ...keys: string[]) {
return this.command<string[]>("SUNION", key, anotherkey, ...keys);
}
/**
* This command is equal to SUNION, but instead of returning the resulting set, it is stored in destination.
*
* If destination already exists, it is overwritten.
*
* @param destination The destination.
* @param key The key.
* @param anotherkey The anotherkey.
* @param keys The keys.
* @returns The number of elements in the resulting set.
*/
public sunionstore(
destination: string,
key: string,
anotherkey: string,
...keys: string[]
) {
return this.command<number>("SUNIONSTORE", destination, key, anotherkey, ...keys);
}
/*******************************************************************************************************
* ZSET ************************************************************************************************
*******************************************************************************************************/
/**
* Adds all the specified members with the specified scores to the sorted set stored at key. It is
* possible to specify multiple score / member pairs. If a specified member is already a member of the
* sorted set, the score is updated and the element reinserted at the right position to ensure the
* correct ordering.
*
* If key does not exist, a new sorted set with the specified members as sole members is created,
* like if the sorted set was empty. If the key exists but does not hold a sorted set, an error
* is returned.
*
* @param key The key.
* @param objMS The objMS.
* @param options The options.
* @returns
* - The number of elements added to the sorted sets, not including elements already existing for which
* the score was updated. If the INCR option is specified, the return value will be Bulk string reply
* - the new score of member (a double precision floating point number), represented as string.
*/
public zadd(
key: string,
objMS: { [propName: string]: number },
options?: {
nxxx?: "NX" | "XX";
ch?: "CH";
},
): Promise<number>;
public zadd(
key: string,
objMS: { [propName: string]: number },
options?: {
nxxx?: "NX" | "XX";
ch?: "CH";
incr?: "INCR";
},
): Promise<string | null>;
public zadd(
key: string,
objMS: { [propName: string]: number },
options: {
nxxx?: "NX" | "XX";
ch?: "CH";
incr?: "INCR";
} = {},
) {
const array = new Array<any>();
const { nxxx, ch, incr } = options;
Reflect.ownKeys(objMS).forEach(member => {
array.push(objMS[member as string], member);
});
if ("undefined" !== typeof nxxx) {
if ("undefined" !== typeof ch) {
if ("undefined" !== typeof incr) {
return this.command("ZADD", key, nxxx, ch, incr, ...array);
} else {
return this.command("ZADD", key, nxxx, ch, ...array);
}
} else if ("undefined" !== typeof incr) {
return this.command("ZADD", key, nxxx, incr, ...array);
} else {
return this.command("ZADD", key, nxxx, ...array);
}
} else if ("undefined" !== typeof ch) {
if ("undefined" !== typeof incr) {
return this.command("ZADD", key, ch, incr, ...array);
} else {
return this.command("ZADD", key, ch, ...array);
}
} else if ("undefined" !== typeof incr) {
return this.command("ZADD", key, incr, ...array);
} else {
return this.command("ZADD", key, ...array);
}
}
/**
* Returns the sorted set cardinality (number of elements) of the sorted set stored at key.
*
* @param key The key.
* @returns The cardinality (number of elements) of the sorted set, or 0 if key does not exist.
*/
public zcard(key: string) {
return this.command<number>("ZCARD", key);
}
/**
* Returns the number of elements in the sorted set at key with a score between min and max.
* @param key The key.
* @param min The min.
* @param max The max.
* @returns The number of elements in the specified score range.
*/
public zcount(key: string, min: string, max: string) {
return this.command<number>("ZCOUNT", key, min, max);
}
/**
* Increments the score of member in the sorted set stored at key by increment. If member does not
* exist in the sorted set, it is added with increment as its score (as if its previous score was
* 0.0). If key does not exist, a new sorted set with the specified member as its sole member is
* created.
*
* An error is returned when key exists but does not hold a sorted set.
*
* The score value should be the string representation of a numeric value, and accepts double
* precision floating point numbers. It is possible to provide a negative value to decrement
* the score.
*
* @param key The key.
* @param increment The increment.
* @param member The member.
* @returns The new score of member (a double precision floating point number), represented as string.
*/
public zincrby(key: string, increment: number, member: string) {
return this.command<string>("ZINCRBY", key, increment, member);
}
/**
* Computes the intersection of numkeys sorted sets given by the specified keys, and stores the result
* in destination. It is mandatory to provide the number of input keys (numkeys) before passing the
* input keys and the other (optional) arguments.
*
* By default, the resulting score of an element is the sum of its scores in the sorted sets where it
* exists. Because intersection requires an element to be a member of every given sorted set, this
* results in the score of every element in the resulting sorted set to be equal to the number of
* input sorted sets.
*
* If destination already exists, it is overwritten.
*
* @param destination The destination.
* @param objectKW The objectKW.
* @param aggregate The aggregate.
* @returns The number of elements in the resulting sorted set at destination.
*/
public zinterstore(
destination: string,
objectKW: { [PropName: string]: number },
aggregate: "SUM" | "MIN" | "MAX" = "SUM",
) {
const keys: any[] = [];
const weights: any[] = [];
Reflect.ownKeys(objectKW).forEach(key => {
keys.push(key);
weights.push(objectKW[key as string]);
});
return this.command<number>(
"ZINTERSTORE",
destination,
keys.length,
...keys,
"WEIGHTS",
...weights,
"AGGREGATE",
aggregate,
);
}
/**
* this command returns the number of elements in the sorted set at key with a value between min and max.
#
* @param key The key.
* @param min The min.
* @param max The max.
* @returns The number of elements in the specified score range.
*/
public zlexcount(key: string, min: string, max: string) {
return this.command<number>("ZLEXCOUNT", key, min, max);
}
public zrange(key: string, start: number, stop: number): Promise<string[]>;
public zrange(
key: string,
start: number,
stop: number,
withscores: "WITHSCORES",
): Promise<{ [propName: string]: string }>;
public async zrange(
key: string,
start: number,
stop: number,
withscores?: "WITHSCORES",
) {
if ("WITHSCORES" === withscores) {
return Array2Object(
await this.command<string[]>("ZRANGE", key, start, stop, "WITHSCORES"),
);
}
return this.command("ZRANGE", key, start, stop);
}
/**
* When all the elements in a sorted set are inserted with the same score, in order to force
* lexicographical ordering, this command returns all the elements in the sorted set at key
* with a value between min and max.
*
* If the elements in the sorted set have different scores, the returned elements are unspecified.
*
* @param key The key.
* @param min The min.
* @param max The max.
* @param options The options.
* @returns List of elements in the specified score range.
*/
public zrangebylex(
key: string,
min: string,
max: string,
options?: {
offset: number;
count: number;
},
) {
if ("object" === typeof options) {
return this.command<string[]>(
"ZRANGEBYLEX",
key,
min,
max,
"LIMIT",
options.offset,
options.count,
);
}
return this.command<string[]>("ZRANGEBYLEX", key, min, max);
}
/**
* Returns all the elements in the sorted set at key with a score between min and max (including elements
* with score equal to min or max). The elements are considered to be ordered from low to high scores.
*
* The elements having the same score are returned in lexicographical order (this follows from a property
* of the sorted set implementation in Redis and does not involve further computation).
*
* @param key The key.
* @param min The min.
* @param max The max.
* @param options The options.
* @returns List of elements in the specified score range (optionally with their scores).
*/
public zrangebyscore(
key: string,
min: string,
max: string,
options?: {
limit?: {
offset: number;
count: number;
};
},
): Promise<string[]>;
public zrangebyscore(
key: string,
min: string,
max: string,
options?: {
limit?: {
offset: number;
count: number;
};
withscores: "WITHSCORES";
},
): Promise<{ [propName: string]: string }>;
public async zrangebyscore(
key: string,
min: string,
max: string,
options: {
limit?: {
offset: number;
count: number;
};
withscores?: "WITHSCORES";
} = {},
) {
if ("object" === typeof options.limit) {
const { offset, count } = options.limit;
if ("WITHSCORES" === options.withscores) {
return Array2Object(
await this.command<string[]>(
"ZRANGEBYSCORE",
key,
min,
max,
"WITHSCORES",
"LIMIT",
offset,
count,
),
);
} else {
return this.command("ZRANGEBYSCORE", key, min, max, "LIMIT", offset, count);
}
} else if ("WITHSCORES" === options.withscores) {
return Array2Object(
await this.command<string[]>("ZRANGEBYSCORE", key, min, max, "WITHSCORES"),
);
} else {
return this.command("ZRANGEBYSCORE", key, min, max);
}
}
/**
* Returns the rank of member in the sorted set stored at key, with the scores ordered from low
* to high. The rank (or index) is 0-based, which means that the member with the lowest score
* has rank 0.
*
* @param key The key.
* @param member The member.
* @returns
* - If member exists in the sorted set, Integer reply: the rank of member.
* - If member does not exist in the sorted set or key does not exist, Bulk string reply: nil.
*/
public zrank(key: string, member: string) {
return this.command<number | null>("ZRANK", key, member);
}
/**
* Removes the specified members from the sorted set stored at key. Non existing members are ignored.
*
* An error is returned when key exists and does not hold a sorted set.
*
* @param key The key.
* @param member The member.
* @param members The other member.
* @returns The number of members removed from the sorted set, not including non existing members.
*/
public zrem(key: string, member: string, ...members: string[]) {
return this.command<number>("ZREM", key, member, ...members);
}
/**
* This command removes all elements in the sorted set stored at key between the lexicographical
* range specified by min and max.
*
* @param key The key.
* @param min The min.
* @param max The max.
* @returns The number of elements removed.
*/
public zremrangebylex(key: string, min: string, max: string) {
return this.command<number>("ZREMRANGEBYLEX", key, min, max);
}
/**
* Removes all elements in the sorted set stored at key with rank between start and stop. Both start
* and stop are 0 -based indexes with 0 being the element with the lowest score. These indexes can be
* negative numbers, where they indicate offsets starting at the element with the highest score. For
* example: -1 is the element with the highest score, -2 the element with the second highest score
* and so forth.
*
* @param key The key.
* @param start The start.
* @param stop The stop.
* @returns The number of elements removed.
*/
public zremrangebyrank(key: string, start: number, stop: number) {
return this.command("ZREMRANGEBYRANK", key, start, stop);
}
/**
* Removes all elements in the sorted set stored at key with a score between min and max (inclusive).
*
* Since version 2.1.6, min and max can be exclusive
*
* @param key The key.
* @param min The min.
* @param max The max.
* @returns The number of elements removed.
*/
public zremrangebyscore(key: string, min: string, max: string) {
return this.command("ZREMRANGEBYSCORE", key, min, max);
}
/**
* Returns the specified range of elements in the sorted set stored at key. The elements are considered
* to be ordered from the highest to the lowest score. Descending lexicographical order is used for
* elements with equal score.
*
* @param key The key.
* @param start The start.
* @param stop The stop.
* @returns List of elements in the specified range (optionally with their scores).
*/
public zrevrange(key: string, start: number, stop: number): Promise<string[]>;
public zrevrange(
key: string,
start: number,
stop: number,
withscores: "WITHSCORES",
): Promise<{ [propName: string]: string }>;
public async zrevrange(
key: string,
start: number,
stop: number,
withscores?: "WITHSCORES",
) {
if ("WITHSCORES" === withscores) {
return Array2Object(
await this.command<string[]>("ZREVRANGE", key, start, stop, "WITHSCORES"),
);
} else {
return this.command("ZREVRANGE", key, start, stop);
}
}
/**
* Returns all the elements in the sorted set at key with a score between max and min (including elements
* with score equal to max or min). In contrary to the default ordering of sorted sets, for this command
* the elements are considered to be ordered from high to low scores.
*
* The elements having the same score are returned in reverse lexicographical order.
*
* @param key The key.
* @param max The max.
* @param min The min.
* @param options The options.
* @returns list of elements in the specified score range (optionally with their scores).
*/
public zrevrangebyscore(
key: string,
max: string,
min: string,
options?: {
limit?: {
offset: number;
count: number;
};
},
): Promise<string[]>;
public zrevrangebyscore(
key: string,
max: string,
min: string,
options?: {
limit?: {
offset: number;
count: number;
};
withscores: "WITHSCORES";
},
): Promise<{ [propName: string]: string }>;
public async zrevrangebyscore(
key: string,
max: string,
min: string,
options: {
limit?: {
offset: number;
count: number;
};
withscores?: "WITHSCORES";
} = {},
) {
if ("object" === typeof options.limit) {
const { offset, count } = options.limit;
if ("WITHSCORES" === options.withscores) {
return Array2Object(
await this.command<string[]>(
"ZREVRANGEBYSCORE",
key,
max,
min,
"WITHSCORES",
"LIMIT",
offset,
count,
),
);
} else {
return this.command("ZREVRANGEBYSCORE", key, max, min, "LIMIT", offset, count);
}
} else if ("WITHSCORES" === options.withscores) {
return Array2Object(
await this.command<string[]>("ZREVRANGEBYSCORE", key, max, min, "WITHSCORES"),
);
} else {
return this.command("ZREVRANGEBYSCORE", key, max, min);
}
}
/**
* Returns the rank of member in the sorted set stored at key, with the scores ordered from high to low.
* The rank (or index) is 0-based, which means that the member with the highest score has rank 0.
* @param key The key.
* @param member The member.
* @returns
* - If member exists in the sorted set, Integer reply: the rank of member.
* - If member does not exist in the sorted set or key does not exist, Bulk string reply: nil.
*/
public zrevrank(key: string, member: string) {
return this.command<number | null>("ZREVRANK", key, member);
}
/**
* Returns the score of member in the sorted set at key.
*
* If member does not exist in the sorted set, or key does not exist, nil is returned.
*
* @param key The key.
* @param member The member.
* @returns The score of member (a double precision floating point number), represented as string.
*/
public zscore(key: string, member: string) {
return this.command<string | null>("ZSCORE", key, member);
}
/**
* Computes the union of numkeys sorted sets given by the specified keys, and stores the result in
* destination. It is mandatory to provide the number of input keys (numkeys) before passing the
* input keys and the other (optional) arguments.
*
* By default, the resulting score of an element is the sum of its scores in the sorted sets where
* it exists.
*
* @param destination The destination.
* @param objectKW The objectKW.
* @param aggregate The aggregate.
* @returns The number of elements in the resulting sorted set at destination.
*/
public zunionstore(
destination: string,
objectKW: { [PropName: string]: number },
aggregate: "SUM" | "MIN" | "MAX" = "SUM",
) {
const keys: string[] = [];
const weights: number[] = [];
Reflect.ownKeys(objectKW).forEach(key => {
keys.push(key as string);
weights.push(objectKW[key as string]);
});
return this.command(
"ZUNIONSTORE",
destination,
keys.length,
...keys,
"WEIGHTS",
...weights,
"AGGREGATE",
aggregate,
);
}
} | the_stack |
import { getCookie } from '@guardian/libs';
import type { UserFeaturesResponse } from 'types/membership';
import config from '../../../../lib/config';
import { addCookie, removeCookie } from '../../../../lib/cookies';
import { fetchJson } from '../../../../lib/fetch-json';
import { isUserLoggedIn as isUserLoggedIn_ } from '../identity/api';
import {
accountDataUpdateWarning,
getDaysSinceLastOneOffContribution,
getLastOneOffContributionTimestamp,
getLastRecurringContributionDate,
isAdFreeUser,
isDigitalSubscriber,
isPayingMember,
isPostAskPauseOneOffContributor,
isRecentOneOffContributor,
isRecurringContributor,
refresh,
shouldNotBeShownSupportMessaging,
} from './user-features';
jest.mock('../../../../lib/raven');
jest.mock('projects/common/modules/identity/api', () => ({
isUserLoggedIn: jest.fn(),
}));
jest.mock('../../../../lib/fetch-json', () => ({
fetchJson: jest.fn(() => Promise.resolve()),
}));
const fetchJsonSpy = fetchJson as jest.MockedFunction<typeof fetchJson>;
const isUserLoggedIn = isUserLoggedIn_ as jest.MockedFunction<
typeof isUserLoggedIn_
>;
const PERSISTENCE_KEYS = {
USER_FEATURES_EXPIRY_COOKIE: 'gu_user_features_expiry',
PAYING_MEMBER_COOKIE: 'gu_paying_member',
RECURRING_CONTRIBUTOR_COOKIE: 'gu_recurring_contributor',
AD_FREE_USER_COOKIE: 'GU_AF1',
ACTION_REQUIRED_FOR_COOKIE: 'gu_action_required_for',
DIGITAL_SUBSCRIBER_COOKIE: 'gu_digital_subscriber',
SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE: 'gu.contributions.contrib-timestamp',
ONE_OFF_CONTRIBUTION_DATE_COOKIE: 'gu_one_off_contribution_date',
HIDE_SUPPORT_MESSAGING_COOKIE: 'gu_hide_support_messaging',
SUPPORT_MONTHLY_CONTRIBUTION_COOKIE:
'gu.contributions.recurring.contrib-timestamp.Monthly',
SUPPORT_ANNUAL_CONTRIBUTION_COOKIE:
'gu.contributions.recurring.contrib-timestamp.Annual',
};
const setAllFeaturesData = (opts: { isExpired: boolean }) => {
const currentTime = new Date().getTime();
const msInOneDay = 24 * 60 * 60 * 1000;
const expiryDate = opts.isExpired
? new Date(currentTime - msInOneDay)
: new Date(currentTime + msInOneDay);
const adFreeExpiryDate = opts.isExpired
? new Date(currentTime - msInOneDay * 2)
: new Date(currentTime + msInOneDay * 2);
addCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE, 'true');
addCookie(PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE, 'true');
addCookie(PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE, 'true');
addCookie(PERSISTENCE_KEYS.HIDE_SUPPORT_MESSAGING_COOKIE, 'true');
addCookie(
PERSISTENCE_KEYS.AD_FREE_USER_COOKIE,
adFreeExpiryDate.getTime().toString(),
);
addCookie(
PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE,
expiryDate.getTime().toString(),
);
addCookie(PERSISTENCE_KEYS.ACTION_REQUIRED_FOR_COOKIE, 'test');
};
const setExpiredAdFreeData = () => {
const currentTime = new Date().getTime();
const msInOneDay = 24 * 60 * 60 * 1000;
const expiryDate = new Date(currentTime - msInOneDay * 2);
addCookie(
PERSISTENCE_KEYS.AD_FREE_USER_COOKIE,
expiryDate.getTime().toString(),
);
};
const deleteAllFeaturesData = () => {
removeCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE);
removeCookie(PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE);
removeCookie(PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE);
removeCookie(PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE);
removeCookie(PERSISTENCE_KEYS.AD_FREE_USER_COOKIE);
removeCookie(PERSISTENCE_KEYS.ACTION_REQUIRED_FOR_COOKIE);
removeCookie(PERSISTENCE_KEYS.HIDE_SUPPORT_MESSAGING_COOKIE);
};
beforeAll(() => {
config.set('switches.adFreeStrictExpiryEnforcement', true);
config.set('page.userAttributesApiUrl', '');
});
describe('Refreshing the features data', () => {
describe('If user signed in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
fetchJsonSpy.mockReturnValue(Promise.resolve());
});
it('Performs an update if the user has missing data', async () => {
deleteAllFeaturesData();
await refresh();
expect(fetchJsonSpy).toHaveBeenCalledTimes(1);
});
it('Performs an update if the user has expired data', async () => {
setAllFeaturesData({ isExpired: true });
await refresh();
expect(fetchJsonSpy).toHaveBeenCalledTimes(1);
});
it('Does not delete the data just because it has expired', async () => {
setAllFeaturesData({ isExpired: true });
await refresh();
expect(
getCookie({ name: PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE }),
).toBe('true');
expect(
getCookie({
name: PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE,
}),
).toBe('true');
expect(
getCookie({
name: PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE,
}),
).toEqual(expect.stringMatching(/\d{13}/));
expect(
getCookie({ name: PERSISTENCE_KEYS.AD_FREE_USER_COOKIE }),
).toEqual(expect.stringMatching(/\d{13}/));
});
it('Does not perform update if user has fresh feature data', async () => {
setAllFeaturesData({ isExpired: false });
await refresh();
expect(fetchJsonSpy).not.toHaveBeenCalled();
});
it('Performs an update if membership-frontend wipes just the paying-member cookie', async () => {
// Set everything except paying-member cookie
setAllFeaturesData({ isExpired: true });
removeCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE);
await refresh();
expect(fetchJsonSpy).toHaveBeenCalledTimes(1);
});
it('Performs an update if the ad-free state is stale and strict expiry enforcement is enabled', async () => {
// This is a slightly synthetic setup - the ad-free cookie is rewritten with every
// refresh that happens as a result of expired features data, but we want to check
// that a refresh could be triggered based on ad-free state alone if the strict
// expiry enforcement switch is ON.
// Set everything except the ad-free cookie
setAllFeaturesData({ isExpired: false });
setExpiredAdFreeData();
await refresh();
expect(fetchJsonSpy).toHaveBeenCalledTimes(1);
});
});
describe('If user signed out', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
fetchJsonSpy.mockReturnValue(Promise.resolve());
});
it('Does not perform update, even if feature data missing', async () => {
deleteAllFeaturesData();
await refresh();
expect(fetchJsonSpy).not.toHaveBeenCalled();
});
it('Deletes leftover feature data', async () => {
setAllFeaturesData({ isExpired: false });
await refresh();
expect(
getCookie({ name: PERSISTENCE_KEYS.AD_FREE_USER_COOKIE }),
).toBeNull();
expect(
getCookie({ name: PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE }),
).toBeNull();
expect(
getCookie({
name: PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE,
}),
).toBeNull();
expect(
getCookie({ name: PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE }),
).toBeNull();
expect(
getCookie({
name: PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE,
}),
).toBeNull();
});
});
});
describe('The account data update warning getter', () => {
it('Is not set when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(accountDataUpdateWarning()).toBe(null);
});
describe('When the user is logged in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
});
it('Is the same when the user has an account data update link cookie', () => {
addCookie(PERSISTENCE_KEYS.ACTION_REQUIRED_FOR_COOKIE, 'the-same');
expect(accountDataUpdateWarning()).toBe('the-same');
});
it('Is null when the user does not have an account data update link cookie', () => {
removeCookie(PERSISTENCE_KEYS.ACTION_REQUIRED_FOR_COOKIE);
expect(accountDataUpdateWarning()).toBe(null);
});
});
});
describe('The isAdFreeUser getter', () => {
it('Is false when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(isAdFreeUser()).toBe(false);
});
});
describe('The isPayingMember getter', () => {
it('Is false when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(isPayingMember()).toBe(false);
});
describe('When the user is logged in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
});
it('Is true when the user has a `true` paying member cookie', () => {
addCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE, 'true');
expect(isPayingMember()).toBe(true);
});
it('Is false when the user has a `false` paying member cookie', () => {
addCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE, 'false');
expect(isPayingMember()).toBe(false);
});
it('Is true when the user has no paying member cookie', () => {
// If we don't know, we err on the side of caution, rather than annoy paying users
removeCookie(PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE);
expect(isPayingMember()).toBe(true);
});
});
});
describe('The isRecurringContributor getter', () => {
it('Is false when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(isRecurringContributor()).toBe(false);
});
describe('When the user is logged in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
});
it('Is true when the user has a `true` recurring contributor cookie', () => {
addCookie(PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE, 'true');
expect(isRecurringContributor()).toBe(true);
});
it('Is false when the user has a `false` recurring contributor cookie', () => {
addCookie(PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE, 'false');
expect(isRecurringContributor()).toBe(false);
});
it('Is true when the user has no recurring contributor cookie', () => {
// If we don't know, we err on the side of caution, rather than annoy paying users
removeCookie(PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE);
expect(isRecurringContributor()).toBe(true);
});
});
});
describe('The isDigitalSubscriber getter', () => {
it('Is false when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(isDigitalSubscriber()).toBe(false);
});
describe('When the user is logged in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
});
it('Is true when the user has a `true` digital subscriber cookie', () => {
addCookie(PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE, 'true');
expect(isDigitalSubscriber()).toBe(true);
});
it('Is false when the user has a `false` digital subscriber cookie', () => {
addCookie(PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE, 'false');
expect(isDigitalSubscriber()).toBe(false);
});
it('Is false when the user has no digital subscriber cookie', () => {
removeCookie(PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE);
expect(isDigitalSubscriber()).toBe(false);
});
});
});
describe('The shouldNotBeShownSupportMessaging getter', () => {
it('Returns false when the user is logged out', () => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(false);
expect(shouldNotBeShownSupportMessaging()).toBe(false);
});
describe('When the user is logged in', () => {
beforeEach(() => {
jest.resetAllMocks();
isUserLoggedIn.mockReturnValue(true);
});
it('Returns true when the user has a `true` hide support messaging cookie', () => {
addCookie(PERSISTENCE_KEYS.HIDE_SUPPORT_MESSAGING_COOKIE, 'true');
expect(shouldNotBeShownSupportMessaging()).toBe(true);
});
it('Returns false when the user has a `false` hide support messaging cookie', () => {
addCookie(PERSISTENCE_KEYS.HIDE_SUPPORT_MESSAGING_COOKIE, 'false');
expect(shouldNotBeShownSupportMessaging()).toBe(false);
});
it('Returns false when the user has no hide support messaging cookie', () => {
removeCookie(PERSISTENCE_KEYS.HIDE_SUPPORT_MESSAGING_COOKIE);
expect(shouldNotBeShownSupportMessaging()).toBe(false);
});
});
});
describe('Storing new feature data', () => {
beforeEach(() => {
const mockResponse: UserFeaturesResponse = {
userId: 'abc',
showSupportMessaging: false,
contentAccess: {
member: false,
paidMember: false,
recurringContributor: false,
digitalPack: false,
paperSubscriber: false,
guardianWeeklySubscriber: false,
},
};
jest.resetAllMocks();
fetchJsonSpy.mockReturnValue(Promise.resolve(mockResponse));
deleteAllFeaturesData();
isUserLoggedIn.mockReturnValue(true);
});
it('Puts the paying-member state and ad-free state in appropriate cookie', () => {
fetchJsonSpy.mockReturnValueOnce(
Promise.resolve({
contentAccess: {
paidMember: false,
recurringContributor: false,
digitalPack: false,
},
adFree: false,
}),
);
return refresh().then(() => {
expect(
getCookie({ name: PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE }),
).toBe('false');
expect(
getCookie({
name: PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE,
}),
).toBe('false');
expect(
getCookie({ name: PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE }),
).toBe('false');
expect(
getCookie({ name: PERSISTENCE_KEYS.AD_FREE_USER_COOKIE }),
).toBeNull();
});
});
it('Puts the paying-member state and ad-free state in appropriate cookie', () => {
fetchJsonSpy.mockReturnValueOnce(
Promise.resolve({
contentAccess: {
paidMember: true,
recurringContributor: true,
digitalPack: true,
},
adFree: true,
}),
);
return refresh().then(() => {
expect(
getCookie({ name: PERSISTENCE_KEYS.PAYING_MEMBER_COOKIE }),
).toBe('true');
expect(
getCookie({
name: PERSISTENCE_KEYS.RECURRING_CONTRIBUTOR_COOKIE,
}),
).toBe('true');
expect(
getCookie({ name: PERSISTENCE_KEYS.DIGITAL_SUBSCRIBER_COOKIE }),
).toBe('true');
expect(
getCookie({ name: PERSISTENCE_KEYS.AD_FREE_USER_COOKIE }),
).toBeTruthy();
expect(
Number.isNaN(
parseInt(
// @ts-expect-error -- we’re testing it
getCookie({
name: PERSISTENCE_KEYS.AD_FREE_USER_COOKIE,
}),
10,
),
),
).toBe(false);
});
});
it('Puts an expiry date in an accompanying cookie', () =>
refresh().then(() => {
const expiryDate = getCookie({
name: PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE,
});
expect(expiryDate).toBeTruthy();
// @ts-expect-error -- we’re testing it
expect(Number.isNaN(parseInt(expiryDate, 10))).toBe(false);
}));
it('The expiry date is in the future', () =>
refresh().then(() => {
const expiryDateString = getCookie({
name: PERSISTENCE_KEYS.USER_FEATURES_EXPIRY_COOKIE,
});
// @ts-expect-error -- we’re testing it
const expiryDateEpoch = parseInt(expiryDateString, 10);
const currentTimeEpoch = new Date().getTime();
expect(currentTimeEpoch < expiryDateEpoch).toBe(true);
}));
});
const setSupportFrontendOneOffContributionCookie = (value: string) =>
addCookie(PERSISTENCE_KEYS.SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE, value);
const removeSupportFrontendOneOffContributionCookie = () =>
removeCookie(PERSISTENCE_KEYS.SUPPORT_ONE_OFF_CONTRIBUTION_COOKIE);
const setAttributesOneOffContributionCookie = (value: string) =>
addCookie(PERSISTENCE_KEYS.ONE_OFF_CONTRIBUTION_DATE_COOKIE, value);
const removeAttributesOneOffContributionCookie = () =>
removeCookie(PERSISTENCE_KEYS.ONE_OFF_CONTRIBUTION_DATE_COOKIE);
describe('getting the last one-off contribution date of a user', () => {
beforeEach(() => {
removeSupportFrontendOneOffContributionCookie();
removeAttributesOneOffContributionCookie();
});
const contributionDate = '2018-01-06';
const contributionDateTimeEpoch = Date.parse(contributionDate);
it("returns null if the user hasn't previously contributed", () => {
expect(getLastOneOffContributionTimestamp()).toBe(null);
});
it('return the correct date if the user support-frontend contribution cookie is set', () => {
setSupportFrontendOneOffContributionCookie(
contributionDateTimeEpoch.toString(),
);
expect(getLastOneOffContributionTimestamp()).toBe(
contributionDateTimeEpoch,
);
});
it('returns null if the cookie has been set with an invalid value', () => {
setSupportFrontendOneOffContributionCookie('invalid value');
expect(getLastOneOffContributionTimestamp()).toBe(null);
});
it('returns the correct date if cookie from attributes is set', () => {
setAttributesOneOffContributionCookie(contributionDate.toString());
expect(getLastOneOffContributionTimestamp()).toBe(
contributionDateTimeEpoch,
);
});
});
const setMonthlyContributionCookie = (value: string) =>
addCookie(PERSISTENCE_KEYS.SUPPORT_MONTHLY_CONTRIBUTION_COOKIE, value);
const setAnnualContributionCookie = (value: string) =>
addCookie(PERSISTENCE_KEYS.SUPPORT_ANNUAL_CONTRIBUTION_COOKIE, value);
const removeMonthlyContributionCookie = () =>
removeCookie(PERSISTENCE_KEYS.SUPPORT_MONTHLY_CONTRIBUTION_COOKIE);
const removeAnnualContributionCookie = () =>
removeCookie(PERSISTENCE_KEYS.SUPPORT_ANNUAL_CONTRIBUTION_COOKIE);
describe('getting the last recurring contribution date of a user', () => {
beforeEach(() => {
removeMonthlyContributionCookie();
removeAnnualContributionCookie();
});
const monthlyContributionTimestamp = 1556124724;
const annualContributionTimestamp = 1556125286;
it("returns null if the user isn't a recurring contributor", () => {
expect(getLastRecurringContributionDate()).toBe(null);
});
it('return the correct date if the user is a monthly recurring contributor', () => {
setMonthlyContributionCookie(monthlyContributionTimestamp.toString());
expect(getLastRecurringContributionDate()).toBe(
monthlyContributionTimestamp,
);
});
it('return the correct date if the user is a annual recurring contributor', () => {
setAnnualContributionCookie(annualContributionTimestamp.toString());
expect(getLastRecurringContributionDate()).toBe(
annualContributionTimestamp,
);
});
it('return the correct date if the user is both annual and monthly recurring contributor', () => {
setAnnualContributionCookie(annualContributionTimestamp.toString());
setMonthlyContributionCookie(monthlyContributionTimestamp.toString());
expect(getLastRecurringContributionDate()).toBe(
annualContributionTimestamp,
);
});
it('returns null if the cookie has been set with an invalid value', () => {
setAnnualContributionCookie('not a date string one');
setMonthlyContributionCookie('not a date string two');
expect(getLastRecurringContributionDate()).toBe(null);
});
});
describe('getting the days since last contribution', () => {
beforeEach(() => {
removeSupportFrontendOneOffContributionCookie();
removeAttributesOneOffContributionCookie();
});
const contributionDateTimeEpoch = String(
Date.parse('2018-08-01T12:00:30Z'),
);
it('returns null if the last one-off contribution date is null', () => {
expect(getDaysSinceLastOneOffContribution()).toBe(null);
});
it('returns the difference in days between the last contribution date and now if the last contribution date is set', () => {
global.Date.now = jest.fn(() => Date.parse('2018-08-07T10:50:34'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(getDaysSinceLastOneOffContribution()).toBe(5);
});
});
describe('isRecentOneOffContributor', () => {
beforeEach(() => {
removeSupportFrontendOneOffContributionCookie();
removeAttributesOneOffContributionCookie();
});
const contributionDateTimeEpoch = String(
Date.parse('2018-08-01T12:00:30Z'),
);
it('returns false if there is no one-off contribution cookie', () => {
expect(isRecentOneOffContributor()).toBe(false);
});
it('returns true if there are 5 days between the last contribution date and now', () => {
global.Date.now = jest.fn(() => Date.parse('2018-08-07T10:50:34'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(isRecentOneOffContributor()).toBe(true);
});
it('returns true if there are 0 days between the last contribution date and now', () => {
global.Date.now = jest.fn(() => Date.parse('2018-08-01T13:00:30'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(isRecentOneOffContributor()).toBe(true);
});
it('returns false if the one-off contribution was more than 3 months ago', () => {
global.Date.now = jest.fn(() => Date.parse('2019-08-01T13:00:30'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(isRecentOneOffContributor()).toBe(false);
});
});
describe('isPostAskPauseOneOffContributor', () => {
beforeEach(() => {
removeSupportFrontendOneOffContributionCookie();
removeAttributesOneOffContributionCookie();
});
const contributionDateTimeEpoch = String(
Date.parse('2018-08-01T12:00:30Z'),
);
it('returns false if there is no one-off contribution cookie', () => {
expect(isPostAskPauseOneOffContributor()).toBe(false);
});
it('returns false if there are 5 days between the last contribution date and now', () => {
global.Date.now = jest.fn(() => Date.parse('2018-08-07T10:50:34'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(isPostAskPauseOneOffContributor()).toBe(false);
});
it('returns true if the one-off contribution was more than 3 months ago', () => {
global.Date.now = jest.fn(() => Date.parse('2019-02-01T13:00:30'));
setSupportFrontendOneOffContributionCookie(contributionDateTimeEpoch);
expect(isPostAskPauseOneOffContributor()).toBe(true);
});
}); | the_stack |
import {
AnimationItem
} from "lottie-web";
import {
LottieAnimationLoader,
IElement,
ILottieProperty,
ITrigger,
ITriggerConstructor,
} from "../interfaces.js";
import {
allProperties,
resetProperty,
updateProperty,
replaceProperty,
resetColors,
updateColors,
lottieColorToHex,
updateColor,
resetColor,
iconFeatures,
} from "../helpers/lottie.js";
import {
get,
isObjectLike,
isNil,
deepClone,
} from "../helpers/utils.js";
import {
loadIcon,
loadLottieAnimation,
registerIcon,
registerAnimationLoader,
registerTrigger,
connectInstance,
disconnectInstance,
getIcon,
getTrigger,
} from "./manager.js";
export const VERSION = '3.3.3';
/**
* Loads lottie dom elements when needed.
*/
const PROGRESSIVE_LOAD = false;
/**
* Prefix for icon states.
*/
const STATE_PREFIX = 'State-';
/**
* Use constructable stylesheets if supported (https://developers.google.com/web/updates/2019/02/constructable-stylesheets)
*/
const SUPPORTS_ADOPTING_STYLE_SHEETS = "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype;
/**
* Style for this element.
*/
const ELEMENT_STYLE = `
:host {
display: inline-flex;
width: 32px;
height: 32px;
align-items: center;
justify-content: center;
position: relative;
vertical-align: middle;
overflow: hidden;
}
:host(.current-color) svg path[fill] {
fill: currentColor;
}
:host(.current-color) svg path[stroke] {
stroke: currentColor;
}
:not(.current-color) svg .primary path[fill] {
fill: var(--lord-icon-primary, var(--lord-icon-primary-base));
}
:not(.current-color) svg .primary path[stroke] {
stroke: var(--lord-icon-primary, var(--lord-icon-primary-base));
}
:not(.current-color) svg .secondary path[fill] {
fill: var(--lord-icon-secondary, var(--lord-icon-secondary-base));
}
:not(.current-color) svg .secondary path[stroke] {
stroke: var(--lord-icon-secondary, var(--lord-icon-secondary-base));
}
svg {
pointer-events: none;
display: block;
}
div {
width: 100%;
height: 100%;
}
div.slot {
position: absolute;
left: 0;
top: 0;
z-index: 2;
}
`;
/**
* Current style sheet.
*/
let styleSheet: CSSStyleSheet;
/**
* Observed attributes for this custom element.
*/
const OBSERVED_ATTRIBUTES = [
"colors",
"src",
"icon",
"state",
"trigger",
"speed",
"stroke",
"scale",
"axis-x",
"axis-y",
];
type SUPPORTED_ATTRIBUTES = |
"colors" |
"src" |
"icon" |
"state" |
"trigger" |
"speed" |
"stroke" |
"scale" |
"axis-x" |
"axis-y";
export class Element extends HTMLElement implements IElement {
#root: ShadowRoot;
#isReady: boolean = false;
#lottie?: AnimationItem;
#properties?: ILottieProperty[];
#connectedTrigger?: ITrigger;
#storedIconData?: any;
#palette?: any;
/**
* Register Lottie library.
* @param animationLoader Provide "loadAnimation" here from Lottie.
*/
static registerAnimationLoader(animationLoader: LottieAnimationLoader) {
registerAnimationLoader(animationLoader);
}
/**
* Register supported icon. This is helpful with any kind of preload icons.
* @param name Icon name.
* @param iconData Icon data.
*/
static registerIcon(name: string, iconData: any) {
registerIcon(name, iconData);
}
/**
* Register supported animation.
* @param name
* @param triggerClass
*/
static registerTrigger(name: string, triggerClass: ITriggerConstructor) {
registerTrigger(name, triggerClass);
}
/**
* Custom element observed attributes.
*/
static get observedAttributes() {
return OBSERVED_ATTRIBUTES;
}
/**
* Check element version.
*/
static get version() {
return VERSION;
}
constructor() {
super();
// create shadow root for this element
this.#root = this.attachShadow({
mode: "open"
});
}
/**
* Element connected.
*/
protected connectedCallback() {
connectInstance(this);
// execute init only once after connected
if (!this.#isReady) {
this.init();
}
}
/**
* Element disconnected.
*/
protected disconnectedCallback() {
this.unregisterLottie();
disconnectInstance(this);
}
/**
* Handle attribute update.
* @param name
* @param oldValue
* @param newValue
*/
protected attributeChangedCallback(
name: SUPPORTED_ATTRIBUTES,
oldValue: any,
newValue: any
) {
if (name === 'axis-x') {
this.axisXChanged();
} else if (name === 'axis-y') {
this.axisYChanged();
} else {
const method = (this as any)[`${name}Changed`];
if (method) {
method.call(this);
}
}
}
/**
* Init element.
* @returns
*/
protected init() {
if (this.#isReady) {
return;
}
this.#isReady = true;
if (SUPPORTS_ADOPTING_STYLE_SHEETS) {
if (!styleSheet) {
styleSheet = new CSSStyleSheet();
(styleSheet as any).replaceSync(ELEMENT_STYLE);
}
(this.#root as any).adoptedStyleSheets = [ styleSheet ];
} else {
const style = document.createElement("style");
style.innerHTML = ELEMENT_STYLE;
this.#root.appendChild(style);
}
const slotContainer = document.createElement("div");
slotContainer.innerHTML = "<slot></slot>";
slotContainer.classList.add("slot");
this.#root.appendChild(slotContainer);
const container = document.createElement("div");
container.classList.add('body');
this.#root.appendChild(container);
this.registerLottie();
}
protected registerLottie() {
let iconData = this.#iconData;
if (!iconData) {
return;
}
this.#lottie = loadLottieAnimation({
container: this.#container as Element,
renderer: "svg",
loop: false,
autoplay: false,
animationData: deepClone(iconData),
rendererSettings: {
preserveAspectRatio: "xMidYMid meet",
progressiveLoad: PROGRESSIVE_LOAD,
hideOnTransparent: true,
},
});
if (this.state || this.colors || this.stroke || this.scale || this.axisX || this.axisY) {
const properties = this.properties;
if (properties) {
if (this.colors) {
updateColors(this.#lottie, properties, this.colors);
}
if (this.state) {
for (const state of this.states) {
replaceProperty(this.#lottie, properties, STATE_PREFIX + state, 0);
}
replaceProperty(this.#lottie, properties, STATE_PREFIX + this.state, 1);
}
if (this.stroke) {
updateProperty(this.#lottie, properties, 'stroke', this.stroke);
}
if (this.scale) {
updateProperty(this.#lottie, properties, 'scale', this.scale);
}
if (this.axisX) {
updateProperty(this.#lottie, properties, 'axis', this.axisX, '0');
}
if (this.axisY) {
updateProperty(this.#lottie, properties, 'axis', this.axisY, '1');
}
this.#lottie!.renderer.renderFrame(null);
}
}
// set speed
this.#lottie.setSpeed(this.#animationSpeed);
// dispatch animation-complete
this.#lottie.addEventListener("complete", () => {
this.dispatchEvent(new CustomEvent("animation-complete"));
});
this.triggerChanged();
this.dispatchEvent(new CustomEvent("icon-ready"));
// move palette to css variables instantly on this icon
if (iconFeatures(iconData).includes('css-variables')) {
this.movePaletteToCssVariables();
}
}
protected unregisterLottie() {
this.#properties = undefined;
if (this.#connectedTrigger) {
this.#connectedTrigger.disconnectedCallback();
this.#connectedTrigger = undefined;
}
if (this.#lottie) {
this.#lottie.destroy();
this.#lottie = undefined;
this.#container!.innerHTML = "";
}
}
protected refresh() {
this.#lottie!.renderer.renderFrame(null);
this.movePaletteToCssVariables();
}
protected notify(name: string, from: "icon" | "trigger") {
if (this[from] !== name) {
return;
}
if (from === "icon") {
if (this.#lottie) {
this.unregisterLottie();
}
this.registerLottie();
} else if (from === "trigger" && !this.#connectedTrigger) {
this.triggerChanged();
}
}
protected triggerChanged() {
if (this.#connectedTrigger) {
this.#connectedTrigger.disconnectedCallback();
this.#connectedTrigger = undefined;
}
if (this.trigger && this.#lottie) {
const TriggerClass = getTrigger(this.trigger);
if (TriggerClass) {
this.#connectedTrigger = new TriggerClass(this, this.#lottie);
this.#connectedTrigger!.connectedCallback();
}
}
}
protected colorsChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (this.colors) {
updateColors(this.#lottie, this.properties, this.colors);
} else {
resetColors(this.#lottie, this.properties);
}
this.refresh();
}
protected strokeChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (isNil(this.stroke)) {
resetProperty(this.#lottie, this.properties, 'stroke');
} else {
updateProperty(this.#lottie, this.properties, 'stroke', this.stroke);
}
this.refresh();
}
protected stateChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (this.state) {
for (const state of this.states) {
replaceProperty(this.#lottie, this.properties, STATE_PREFIX + state, 0);
}
replaceProperty(this.#lottie, this.properties, STATE_PREFIX + this.state, 1);
} else {
for (const state of this.states) {
resetProperty(this.#lottie, this.properties, STATE_PREFIX + state);
}
}
this.refresh();
}
protected scaleChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (isNil(this.scale)) {
resetProperty(this.#lottie, this.properties, 'scale');
} else {
updateProperty(this.#lottie, this.properties, 'scale', this.scale);
}
this.refresh();
}
protected axisXChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (isNil(this.axisX)) {
resetProperty(this.#lottie, this.properties, 'axis', '0');
} else {
updateProperty(this.#lottie, this.properties, 'axis', this.axisX, '0');
}
this.refresh();
}
protected axisYChanged() {
if (!this.#isReady || !this.properties) {
return;
}
if (isNil(this.axisY)) {
resetProperty(this.#lottie, this.properties, 'axis', '1');
} else {
updateProperty(this.#lottie, this.properties, 'axis', this.axisY, '1');
}
this.refresh();
}
protected speedChanged() {
if (this.#lottie) {
this.#lottie.setSpeed(this.#animationSpeed);
}
}
protected iconChanged() {
if (!this.#isReady) {
return;
}
this.unregisterLottie();
this.registerLottie();
}
protected async srcChanged() {
if (this.src) {
await loadIcon(this.src);
}
if (!this.#isReady) {
return;
}
this.unregisterLottie();
this.registerLottie();
}
protected movePaletteToCssVariables() {
for (const [key, value] of Object.entries(this.palette)) {
(this.#root.querySelector('.body') as HTMLElement).style.setProperty(`--lord-icon-${key}-base`, value);
}
}
/**
* Access current trigger instance.
*/
get connectedTrigger() {
return this.#connectedTrigger;
}
/**
* Available properties for current icon.
*/
get properties() {
if (!this.#properties && this.#iconData) {
this.#properties = allProperties(this.#iconData, true);
}
return this.#properties || [];
}
/**
* Available states for current icon.
*/
get states(): string[] {
return this.properties.filter(c => c.name.startsWith(STATE_PREFIX)).map(c => {
return c.name.substr(STATE_PREFIX.length).toLowerCase();
});
}
/**
* Check whether the element is ready.
*/
get isReady() {
return this.#isReady;
}
/**
* Access lottie animation instance.
*/
get lottie() {
return this.#lottie;
}
/**
* Update palette.
*/
set palette(colors: { [key: string]: string }) {
if (!colors || typeof colors !== 'object') {
return;
}
for (const current of this.properties) {
if (current.type !== 'color') {
continue;
}
const name = current.name.toLowerCase();
if (name in colors && colors[name]) {
updateColor(this.lottie, this.properties, name, colors[name]);
} else {
resetColor(this.lottie, this.properties, name);
}
}
this.refresh();
}
/**
* Access to colors get / update with convenient way.
*/
get palette() {
if (!this.#palette) {
this.#palette = new Proxy(this, {
set: (target, property, value, receiver): boolean => {
for (const current of target.properties) {
if (current.type == 'color' && typeof property === 'string' && property.toLowerCase() == current.name.toLowerCase()) {
if (value) {
updateColor(target.lottie, target.properties, property, value);
} else if (value === undefined) {
resetColor(target.lottie, target.properties, property);
}
target.refresh();
}
}
return true;
},
get: (target, property, receiver) => {
for (const current of target.properties) {
if (current.type == 'color' && typeof property === 'string' && property.toLowerCase() == current.name.toLowerCase()) {
return lottieColorToHex(get(target.lottie, current.path));
}
}
return undefined;
},
deleteProperty: (target, property) => {
for (const current of target.properties) {
if (current.type == 'color' && typeof property === 'string' && property.toLowerCase() == current.name.toLowerCase()) {
resetColor(target.lottie, target.properties, property);
target.refresh();
}
}
return true;
},
ownKeys: (target) => {
return target.properties.filter(c => c.type == 'color').map(c => c.name.toLowerCase());
},
has: (target, property) => {
for (const current of target.properties) {
if (current.type == 'color' && typeof property === 'string' && property.toLowerCase() == current.name.toLowerCase()) {
return true;
}
}
return false;
},
getOwnPropertyDescriptor: (target) => {
return {
enumerable: true,
configurable: true,
};
},
});
}
return this.#palette;
}
set icon(value: any) {
if (value && isObjectLike(value)) {
this.#storedIconData = value;
if (this.hasAttribute('icon')) {
this.removeAttribute('icon');
} else {
this.iconChanged();
}
} else {
const oldIconData = this.#storedIconData;
this.#storedIconData = undefined;
if (value) {
this.setAttribute('icon', value);
} else {
this.removeAttribute('icon');
if (oldIconData) {
this.iconChanged();
}
}
}
}
get icon(): any {
return this.#storedIconData || this.getAttribute('icon');
}
set src(value: string|null) {
if (value) {
this.setAttribute('src', value);
} else {
this.removeAttribute('src');
}
}
get src(): string|null {
return this.getAttribute('src');
}
set state(value: string|null) {
if (value) {
this.setAttribute('state', value);
} else {
this.removeAttribute('state');
}
}
get state(): string|null {
return this.getAttribute('state');
}
set colors(value: string|null) {
if (value) {
this.setAttribute('colors', value);
} else {
this.removeAttribute('colors');
}
}
get colors(): string|null {
return this.getAttribute('colors');
}
set trigger(value: string|null) {
if (value) {
this.setAttribute('trigger', value);
} else {
this.removeAttribute('trigger');
}
}
get trigger(): string|null {
return this.getAttribute('trigger');
}
set speed(value: any) {
if (isNil(value)) {
this.removeAttribute('speed');
} else {
this.setAttribute('speed', value);
}
}
get speed(): number|null {
if (this.hasAttribute('speed')) {
return parseFloat(this.getAttribute('speed')!);
}
return null;
}
set stroke(value: any) {
if (isNil(value)) {
this.removeAttribute('stroke');
} else {
this.setAttribute('stroke', value);
}
}
get stroke(): number|null {
if (this.hasAttribute('stroke')) {
return parseFloat(this.getAttribute('stroke')!);
}
return null;
}
set scale(value: any) {
if (isNil(value)) {
this.removeAttribute('scale');
} else {
this.setAttribute('scale', value);
}
}
get scale(): number|null {
if (this.hasAttribute('scale')) {
return parseFloat(this.getAttribute('scale')!);
}
return null;
}
set axisX(value: any) {
if (isNil(value)) {
this.removeAttribute('axis-x');
} else {
this.setAttribute('axis-x', value);
}
}
get axisX(): number|null {
if (this.hasAttribute('axis-x')) {
return parseFloat(this.getAttribute('axis-x')!);
}
return null;
}
set axisY(value: any) {
if (isNil(value)) {
this.removeAttribute('axis-y');
} else {
this.setAttribute('axis-y', value);
}
}
get axisY() {
if (this.hasAttribute('axis-y')) {
return parseFloat(this.getAttribute('axis-y')!);
}
return null;
}
/**
* Access animation container element.
*/
get #container(): HTMLElement | undefined {
return this.#root.lastElementChild as any;
}
/**
* Access icon data for this element.
*/
get #iconData(): any {
if (this.icon && typeof this.icon === "object") {
return this.icon;
}
return getIcon(this.icon! || this.src!);
}
/**
* Current animation speed.
*/
get #animationSpeed(): number {
if (this.hasAttribute('speed')) {
const v = this.getAttribute('speed');
return v === null ? 1 : parseFloat(v);
}
return 1;
}
} | the_stack |
declare namespace UnityEngine {
class Physics {
// Static Fields
static readonly IgnoreRaycastLayer: number;
static readonly DefaultRaycastLayers: number;
static readonly AllLayers: number;
// Static Property Accessors
static gravity: UnityEngine.Vector3;
static defaultContactOffset: number;
static sleepThreshold: number;
static queriesHitTriggers: boolean;
static queriesHitBackfaces: boolean;
static bounceThreshold: number;
static defaultSolverIterations: number;
static defaultSolverVelocityIterations: number;
static autoSimulation: boolean;
static autoSyncTransforms: boolean;
static interCollisionDistance: number;
static interCollisionStiffness: number;
static interCollisionSettingsToggle: boolean;
// Static Methods
static IgnoreCollision(
collider1: UnityEngine.Collider,
collider2: UnityEngine.Collider,
ignore: boolean
): void;
static IgnoreCollision(
collider1: UnityEngine.Collider,
collider2: UnityEngine.Collider
): void;
static IgnoreLayerCollision(
layer1: number,
layer2: number,
ignore: boolean
): void;
static IgnoreLayerCollision(layer1: number, layer2: number): void;
static GetIgnoreLayerCollision(layer1: number, layer2: number): boolean;
// static Raycast(
// origin: UnityEngine.Vector3,
// direction: UnityEngine.Vector3,
// maxDistance: number,
// layerMask: number,
// queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
// ): boolean;
// static Raycast(
// origin: UnityEngine.Vector3,
// direction: UnityEngine.Vector3,
// maxDistance: number,
// layerMask: number
// ): boolean;
// static Raycast(
// origin: UnityEngine.Vector3,
// direction: UnityEngine.Vector3,
// maxDistance: number
// ): boolean;
// static Raycast(
// origin: UnityEngine.Vector3,
// direction: UnityEngine.Vector3
// ): boolean;
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
// static Raycast(
// ray: UnityEngine.Ray,
// maxDistance: number,
// layerMask: number,
// queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
// ): boolean;
// static Raycast(
// ray: UnityEngine.Ray,
// maxDistance: number,
// layerMask: number
// ): boolean;
// static Raycast(ray: UnityEngine.Ray, maxDistance: number): boolean;
// static Raycast(ray: UnityEngine.Ray): boolean;
// TODO
static Raycast(ray: Ray): { hit: boolean; hitInfo: RaycastHit };
static Raycast(
origin: Vector3,
direction: Vector3
): { hit: boolean; hitInfo: RaycastHit };
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
/*
Physics Raycast
parameter hitInfo is out
*/
static Linecast(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static Linecast(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3,
layerMask: number
): boolean;
static Linecast(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3
): boolean;
/*
Physics Linecast
parameter hitInfo is out
*/
/*
Physics Linecast
parameter hitInfo is out
*/
/*
Physics Linecast
parameter hitInfo is out
*/
static CapsuleCast(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static CapsuleCast(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number
): boolean;
static CapsuleCast(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number
): boolean;
static CapsuleCast(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3
): boolean;
/*
Physics CapsuleCast
parameter hitInfo is out
*/
/*
Physics CapsuleCast
parameter hitInfo is out
*/
/*
Physics CapsuleCast
parameter hitInfo is out
*/
/*
Physics CapsuleCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
static SphereCast(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static SphereCast(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number,
layerMask: number
): boolean;
static SphereCast(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number
): boolean;
static SphereCast(ray: UnityEngine.Ray, radius: number): boolean;
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
/*
Physics SphereCast
parameter hitInfo is out
*/
static BoxCast(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static BoxCast(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number
): boolean;
static BoxCast(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number
): boolean;
static BoxCast(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion
): boolean;
static BoxCast(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3
): boolean;
/*
Physics BoxCast
parameter hitInfo is out
*/
/*
Physics BoxCast
parameter hitInfo is out
*/
/*
Physics BoxCast
parameter hitInfo is out
*/
/*
Physics BoxCast
parameter hitInfo is out
*/
/*
Physics BoxCast
parameter hitInfo is out
*/
static RaycastAll(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static RaycastAll(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static RaycastAll(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
maxDistance: number
): UnityEngine.RaycastHit[];
static RaycastAll(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3
): UnityEngine.RaycastHit[];
static RaycastAll(
ray: UnityEngine.Ray,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static RaycastAll(
ray: UnityEngine.Ray,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static RaycastAll(
ray: UnityEngine.Ray,
maxDistance: number
): UnityEngine.RaycastHit[];
static RaycastAll(ray: UnityEngine.Ray): UnityEngine.RaycastHit[];
static CapsuleCastAll(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static CapsuleCastAll(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static CapsuleCastAll(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number
): UnityEngine.RaycastHit[];
static CapsuleCastAll(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3
): UnityEngine.RaycastHit[];
static SphereCastAll(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static SphereCastAll(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static SphereCastAll(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
maxDistance: number
): UnityEngine.RaycastHit[];
static SphereCastAll(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3
): UnityEngine.RaycastHit[];
static SphereCastAll(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static SphereCastAll(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static SphereCastAll(
ray: UnityEngine.Ray,
radius: number,
maxDistance: number
): UnityEngine.RaycastHit[];
static SphereCastAll(
ray: UnityEngine.Ray,
radius: number
): UnityEngine.RaycastHit[];
static OverlapCapsule(
point0: UnityEngine.Vector3,
point1: UnityEngine.Vector3,
radius: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.Collider[];
static OverlapCapsule(
point0: UnityEngine.Vector3,
point1: UnityEngine.Vector3,
radius: number,
layerMask: number
): UnityEngine.Collider[];
static OverlapCapsule(
point0: UnityEngine.Vector3,
point1: UnityEngine.Vector3,
radius: number
): UnityEngine.Collider[];
static OverlapSphere(
position: UnityEngine.Vector3,
radius: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.Collider[];
static OverlapSphere(
position: UnityEngine.Vector3,
radius: number,
layerMask: number
): UnityEngine.Collider[];
static OverlapSphere(
position: UnityEngine.Vector3,
radius: number
): UnityEngine.Collider[];
static Simulate(step: number): void;
static SyncTransforms(): void;
/*
Physics ComputePenetration
parameter direction is out
*/
static ClosestPoint(
point: UnityEngine.Vector3,
collider: UnityEngine.Collider,
position: UnityEngine.Vector3,
rotation: UnityEngine.Quaternion
): UnityEngine.Vector3;
static RaycastNonAlloc(
ray: UnityEngine.Ray,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static RaycastNonAlloc(
ray: UnityEngine.Ray,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number
): number;
static RaycastNonAlloc(
ray: UnityEngine.Ray,
results: UnityEngine.RaycastHit[],
maxDistance: number
): number;
static RaycastNonAlloc(
ray: UnityEngine.Ray,
results: UnityEngine.RaycastHit[]
): number;
static RaycastNonAlloc(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static RaycastNonAlloc(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number
): number;
static RaycastNonAlloc(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number
): number;
static RaycastNonAlloc(
origin: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[]
): number;
/*
Physics OverlapSphereNonAlloc
parameter results is out
*/
/*
Physics OverlapSphereNonAlloc
parameter results is out
*/
/*
Physics OverlapSphereNonAlloc
parameter results is out
*/
static CheckSphere(
position: UnityEngine.Vector3,
radius: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static CheckSphere(
position: UnityEngine.Vector3,
radius: number,
layerMask: number
): boolean;
static CheckSphere(position: UnityEngine.Vector3, radius: number): boolean;
static CapsuleCastNonAlloc(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static CapsuleCastNonAlloc(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number
): number;
static CapsuleCastNonAlloc(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number
): number;
static CapsuleCastNonAlloc(
point1: UnityEngine.Vector3,
point2: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[]
): number;
static SphereCastNonAlloc(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static SphereCastNonAlloc(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number
): number;
static SphereCastNonAlloc(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
maxDistance: number
): number;
static SphereCastNonAlloc(
origin: UnityEngine.Vector3,
radius: number,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[]
): number;
static SphereCastNonAlloc(
ray: UnityEngine.Ray,
radius: number,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static SphereCastNonAlloc(
ray: UnityEngine.Ray,
radius: number,
results: UnityEngine.RaycastHit[],
maxDistance: number,
layerMask: number
): number;
static SphereCastNonAlloc(
ray: UnityEngine.Ray,
radius: number,
results: UnityEngine.RaycastHit[],
maxDistance: number
): number;
static SphereCastNonAlloc(
ray: UnityEngine.Ray,
radius: number,
results: UnityEngine.RaycastHit[]
): number;
static CheckCapsule(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3,
radius: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static CheckCapsule(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3,
radius: number,
layerMask: number
): boolean;
static CheckCapsule(
start: UnityEngine.Vector3,
end: UnityEngine.Vector3,
radius: number
): boolean;
static CheckBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
layermask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): boolean;
static CheckBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
layerMask: number
): boolean;
static CheckBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion
): boolean;
static CheckBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3
): boolean;
static OverlapBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.Collider[];
static OverlapBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
layerMask: number
): UnityEngine.Collider[];
static OverlapBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion
): UnityEngine.Collider[];
static OverlapBox(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3
): UnityEngine.Collider[];
/*
Physics OverlapBoxNonAlloc
parameter results is out
*/
/*
Physics OverlapBoxNonAlloc
parameter results is out
*/
/*
Physics OverlapBoxNonAlloc
parameter results is out
*/
/*
Physics OverlapBoxNonAlloc
parameter results is out
*/
static BoxCastNonAlloc(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): number;
static BoxCastNonAlloc(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
orientation: UnityEngine.Quaternion
): number;
static BoxCastNonAlloc(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
orientation: UnityEngine.Quaternion,
maxDistance: number
): number;
static BoxCastNonAlloc(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[],
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number
): number;
static BoxCastNonAlloc(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
results: UnityEngine.RaycastHit[]
): number;
static BoxCastAll(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number,
queryTriggerInteraction: UnityEngine.QueryTriggerInteraction
): UnityEngine.RaycastHit[];
static BoxCastAll(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number,
layerMask: number
): UnityEngine.RaycastHit[];
static BoxCastAll(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion,
maxDistance: number
): UnityEngine.RaycastHit[];
static BoxCastAll(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3,
orientation: UnityEngine.Quaternion
): UnityEngine.RaycastHit[];
static BoxCastAll(
center: UnityEngine.Vector3,
halfExtents: UnityEngine.Vector3,
direction: UnityEngine.Vector3
): UnityEngine.RaycastHit[];
/*
Physics OverlapCapsuleNonAlloc
parameter results is out
*/
/*
Physics OverlapCapsuleNonAlloc
parameter results is out
*/
/*
Physics OverlapCapsuleNonAlloc
parameter results is out
*/
static RebuildBroadphaseRegions(
worldBounds: UnityEngine.Bounds,
subdivisions: number
): void;
// Instance Fields
// Instance Property Accessors
// Instance Methods
}
} | the_stack |
import { forwardRef, HttpException, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { SmsComponent } from '@notadd/addon-sms';
import { __ as t } from 'i18n';
import { Repository } from 'typeorm';
import * as _ from 'underscore';
import { AuthService } from '../auth/auth.service';
import { User } from '../entities/user.entity';
import { CreateUserInput, UpdateUserInput, UserInfoData } from '../interfaces/user.interface';
import { CryptoUtil } from '../utils/crypto.util';
import { RoleService } from './role.service';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User) private readonly userRepo: Repository<User>,
@Inject(CryptoUtil) private readonly cryptoUtil: CryptoUtil,
@Inject(forwardRef(() => AuthService)) private readonly authService: AuthService,
@Inject(RoleService) private readonly roleService: RoleService,
@Inject('SmsComponentToken') private readonly smsComponentProvider: SmsComponent,
) { }
/**
* Cteate a user
*
* @param user The user object
*/
async createUser(createUserInput: CreateUserInput): Promise<void> {
if (!(createUserInput.username || createUserInput.mobile || createUserInput.email)) {
throw new HttpException(t('Please make sure the username, mobile phone number, and email exist at least one'), 406);
}
if (createUserInput.username && await this.userRepo.findOne({ where: { username: createUserInput.username } })) {
throw new HttpException(t('Username already exists'), 409);
}
if (createUserInput.mobile && await this.userRepo.findOne({ where: { mobile: createUserInput.mobile } })) {
throw new HttpException(t('Mobile already exists'), 409);
}
if (createUserInput.email && await this.userRepo.findOne({ where: { email: createUserInput.email } })) {
throw new HttpException(t('Email already exists'), 409);
}
if (!createUserInput.mobile && createUserInput.username) {
createUserInput.mobile = createUserInput.username;
}
createUserInput.password = await this.cryptoUtil.encryptPassword(createUserInput.password);
if (createUserInput.email) createUserInput.email = createUserInput.email.toLocaleLowerCase();
const user = await this.userRepo.save(this.userRepo.create(createUserInput));
if (createUserInput.roleIds && createUserInput.roleIds.length) {
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(user).add(createUserInput.roleIds);
}
}
/**
* Add a role to the user
*
* @param userId The specified user id
* @param roleId The specified role id
*/
async addUserRole(userId: number, roleId: number) {
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(userId).add(roleId);
}
/**
* Delete a role from the user
*
* @param userId The specified user id
* @param roleId The specified role id
*/
async deleteUserRole(userId: number, roleId: number) {
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(userId).remove(roleId);
}
/**
* Delete user to recycle bin or ban user
*
* @param id The specified user id
*/
async recycleOrBanUser(id: number, action: 'recycle' | 'ban'): Promise<void> {
const user = await this.findOneById(id);
if (action === 'recycle') {
user.recycle = true;
}
if (action === 'ban') {
user.banned = true;
}
await this.userRepo.save(user);
}
/**
* Delete users in the recycle bin
*
* @param id The specified user id
*/
async deleteUser(id: number | number[]): Promise<void> {
const exist = <UserInfoData[]>await this.findUserInfoById(id);
const a = exist.map(item => item.id);
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < a.length; i++) {
const user = await this.userRepo.findOne(a[i], { relations: ['roles'] });
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(user).remove(user.roles);
await this.userRepo.remove(user);
}
}
/**
* Revert user from which was banned or recycled
*
* @param id The specified user id
*/
async revertBannedOrRecycledUser(id: number, status: 'recycled' | 'banned') {
const user = await this.findOneById(id);
if (status === 'recycled') {
user.recycle = false;
}
if (status === 'banned') {
user.banned = false;
}
await this.userRepo.save(user);
}
/**
* Update user's information
*
* @param id The specified user id
* @param updateUserInput The information to be update
*/
async updateUserInfo(id: number, updateUserInput: UpdateUserInput): Promise<void> {
const user = await this.userRepo.findOne(id);
if (updateUserInput.username && updateUserInput.username !== user.username) {
if (await this.userRepo.findOne({ where: { username: updateUserInput.username } })) {
throw new HttpException(t('Username already exists'), 409);
}
await this.userRepo.update(user.id, { username: updateUserInput.username });
}
if (updateUserInput.mobile && updateUserInput.mobile !== user.mobile) {
if (await this.userRepo.findOne({ where: { mobile: updateUserInput.mobile } })) {
throw new HttpException(t('Mobile already exists'), 409);
}
await this.userRepo.update(user.id, { mobile: updateUserInput.mobile });
}
if (updateUserInput.email && updateUserInput.email !== user.email) {
if (await this.userRepo.findOne({ where: { email: updateUserInput.email } })) {
throw new HttpException(t('Email already exists'), 409);
}
await this.userRepo.update(user.id, { email: updateUserInput.email.toLocaleLowerCase() });
}
if (updateUserInput.password) {
const newPassword = await this.cryptoUtil.encryptPassword(updateUserInput.password);
await this.userRepo.update(user.id, { password: newPassword });
}
if (updateUserInput.roleIds && updateUserInput.roleIds.length) {
updateUserInput.roleIds.forEach(async roleId => {
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(user).remove(roleId.before);
await this.userRepo.createQueryBuilder('user').relation(User, 'roles').of(user).add(roleId.after);
});
}
}
/**
* Query the user by role ID
*
* @param roleId The specified role id
*/
async findByRoleId(roleId: number) {
const users = await this.userRepo.createQueryBuilder('user')
.leftJoinAndSelect('user.roles', 'roles')
.where('roles.id = :roleId', { roleId })
.andWhere('user.recycle = false')
.getMany();
if (!users.length) {
throw new HttpException(t('No users belong to this role'), 404);
}
return this.findUserInfoById(users.map(user => user.id)) as Promise<UserInfoData[]>;
}
/**
* Querying users and their associated information by username
*
* @param username username
*/
async findOneWithRoles(loginName: string): Promise<User> {
const user = await this.userRepo.createQueryBuilder('user')
.leftJoinAndSelect('user.roles', 'roles')
.where('user.username = :loginName', { loginName })
.orWhere('user.mobile = :loginName', { loginName })
.orWhere('user.email = :loginName', { loginName: loginName.toLocaleLowerCase() })
.getOne();
if (!user) {
throw new HttpException(t('User does not exist'), 404);
}
return user;
}
/**
* Querying user information by user ID
*
* @param id The specified user id
*/
async findUserInfoById(id: number | number[]): Promise<UserInfoData | UserInfoData[]> {
const userQb = this.userRepo.createQueryBuilder('user')
.leftJoinAndSelect('user.roles', 'roles');
if (id instanceof Array) {
const userInfoData: UserInfoData[] = [];
const users = await userQb.whereInIds(id).getMany();
for (const user of users) {
(userInfoData as UserInfoData[]).push(this.refactorUserData(user));
}
return userInfoData;
} else {
const user = await userQb.where('user.id = :id', { id }).getOne();
return this.refactorUserData(user);
}
}
/**
* user login by username or email
*
* @param loginName loginName: username or email
* @param password password
*/
async login(loginName: string, password: string) {
const user = await this.userRepo.createQueryBuilder('user')
.leftJoinAndSelect('user.roles', 'roles')
.where('user.username = :loginName', { loginName })
.orWhere('user.mobile = :loginName', { loginName })
.orWhere('user.email = :loginName', { loginName: loginName.toLocaleLowerCase() })
.getOne();
await this.checkUserStatus(user);
if (!await this.cryptoUtil.checkPassword(password, user.password)) {
throw new HttpException(t('invalid password'), 406);
}
const userInfoData = this.refactorUserData(user);
const tokenInfo = await this.authService.createToken({ loginName });
return { tokenInfo, userInfoData };
}
async checkPwd(loginName: string, password: string) {
const user = await this.userRepo.createQueryBuilder('user')
.where('user.username = :loginName', { loginName })
.orWhere('user.mobile = :loginName', { loginName })
.orWhere('user.email = :loginName', { loginName: loginName.toLocaleLowerCase() })
.getOne();
if (!await this.cryptoUtil.checkPassword(password, user.password)) {
return false;
}
return true;
}
/**
* user login by mobile (use tencent cloud sms service)
*
* @param mobile mobile
* @param validationCode validationCode
*/
async mobileLogin(mobile: string, validationCode: number) {
await this.smsComponentProvider.smsValidator(mobile, validationCode);
const user = await this.userRepo.findOne({ mobile }, { relations: ['roles'] });
await this.checkUserStatus(user);
const userInfoData = this.refactorUserData(user);
const tokenInfo = await this.authService.createToken({ loginName: mobile });
return { tokenInfo, userInfoData };
}
/**
* Ordinary user registration
*
* @param username username
* @param password password
*/
async register(createUserInput: CreateUserInput): Promise<void> {
createUserInput.roleIds = [1];
await this.createUser(createUserInput);
}
private checkUserStatus(user: User) {
if (!user) throw new HttpException(t('User does not exist'), 404);
if (user.banned || user.recycle) throw new HttpException(t('User is banned'), 400);
}
/**
* Query users by ID
*
* @param id The specified user id
*/
private async findOneById(id: number): Promise<User> {
const exist = this.userRepo.findOne(id);
if (!exist) {
throw new HttpException(t('User does not exist'), 404);
}
return exist;
}
/**
* Refactor the user information data
*
* @param user The user object
*/
private refactorUserData(user: User) {
const userInfoData: UserInfoData = {
id: user.id,
username: user.username,
email: user.email,
mobile: user.mobile,
banned: user.banned,
recycle: user.recycle,
createTime: user.createTime,
updateTime: user.updateTime,
userRoles: user.roles,
};
return userInfoData;
}
async findPassword(mobile: string, password: string): Promise<void> {
const user = await this.userRepo.findOne({ where: { mobile } });
if (!user) {
throw new HttpException(t('User does not exist'), 404);
}
const newPassword = await this.cryptoUtil.encryptPassword(password);
user.password = newPassword;
await this.userRepo.save(await this.userRepo.create(user));
}
} | the_stack |
import CapabilityDiscovery from "../../../../../main/js/joynr/capabilities/discovery/CapabilityDiscovery";
import DiscoveryQos from "../../../../../main/js/generated/joynr/types/DiscoveryQos";
import ProviderQos from "../../../../../main/js/generated/joynr/types/ProviderQos";
import CustomParameter from "../../../../../main/js/generated/joynr/types/CustomParameter";
import ProviderScope from "../../../../../main/js/generated/joynr/types/ProviderScope";
import DiscoveryScope from "../../../../../main/js/generated/joynr/types/DiscoveryScope";
import DiscoveryEntry from "../../../../../main/js/generated/joynr/types/DiscoveryEntry";
import GlobalDiscoveryEntry from "../../../../../main/js/generated/joynr/types/GlobalDiscoveryEntry";
import ChannelAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/ChannelAddress";
import Version from "../../../../../main/js/generated/joynr/types/Version";
import * as CapabilitiesUtil from "../../../../../main/js/joynr/util/CapabilitiesUtil";
import { multipleSetImmediate, reversePromise } from "../../../testUtil";
import testUtil = require("../../../testUtil");
import ApplicationException from "joynr/joynr/exceptions/ApplicationException";
import DiscoveryError from "joynr/generated/joynr/types/DiscoveryError";
const typeRegistry = require("../../../../../main/js/joynr/types/TypeRegistrySingleton").getInstance();
typeRegistry
.addType(DiscoveryQos)
.addType(ProviderQos)
.addType(CustomParameter)
.addType(ProviderScope)
.addType(DiscoveryScope)
.addType(DiscoveryEntry)
.addType(GlobalDiscoveryEntry)
.addType(ChannelAddress)
.addType(Version);
let participantId: any, domain: any, interfaceName: string, discoveryQos: DiscoveryQos;
let discoveryEntries: any,
discoveryEntriesReturned: any,
globalDiscoveryEntries: any,
globalDiscoveryEntriesReturned: any;
let capabilityDiscovery: CapabilityDiscovery, proxyBuilderSpy: any, address: any, localCapStoreSpy: any;
let globalCapCacheSpy: any, globalCapDirSpy: any;
let startDateMs: number;
const expiryDateMs = Date.now() + 1e10;
const knownGbids = ["joynrdefaultgbid", "someOtherGbid"];
const gbids = ["joynrdefaultgbid"];
const messageRouterSpy: any = {
addNextHop: jest.fn(),
resolveNextHop: jest.fn()
};
messageRouterSpy.addNextHop.mockReturnValue(Promise.resolve());
messageRouterSpy.resolveNextHop.mockReturnValue(Promise.resolve());
function getSpiedLookupObjWithReturnValue(returnValue: any) {
const spyObj = {
lookup: jest.fn(),
add: jest.fn(),
remove: jest.fn(),
touch: jest.fn()
};
spyObj.lookup.mockReturnValue(returnValue);
spyObj.add.mockReturnValue(returnValue);
spyObj.remove.mockReturnValue(spyObj);
return spyObj;
}
function getGlobalDiscoveryEntry(domain: any, interfaceName: string, newGlobalAddress: any) {
return new GlobalDiscoveryEntry({
providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }),
domain,
interfaceName,
lastSeenDateMs: Date.now(),
qos: new ProviderQos({
customParameters: [
new CustomParameter({
name: "theName",
value: "theValue"
})
],
priority: 1234,
scope:
discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL,
supportsOnChangeSubscriptions: true
}),
address: JSON.stringify(newGlobalAddress !== undefined ? newGlobalAddress : address),
participantId: "700",
publicKeyId: "",
expiryDateMs
});
}
function assertDiscoveryEntryEquals(expected: any, actual: any) {
expect(actual.providerVersion).toEqual(expected.providerVersion);
expect(actual.domain).toEqual(expected.domain);
expect(actual.interfaceName).toEqual(expected.interfaceName);
expect(actual.participantId).toEqual(expected.participantId);
expect(actual.qos).toEqual(expected.qos);
expect(actual.lastSeenDateMs).toEqual(expected.lastSeenDateMs);
expect(actual.expiryDateMs).toEqual(expected.expiryDateMs);
expect(actual.publicKeyId).toEqual(expected.publicKeyId);
expect(actual.isLocal).toEqual(expected.isLocal);
expect(actual.address).toEqual(expected.address);
}
function getDiscoveryEntry(domain: any, interfaceName: string) {
return new DiscoveryEntry({
providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }),
domain,
interfaceName,
qos: new ProviderQos({
customParameters: [
new CustomParameter({
name: "theName",
value: "theValue"
})
],
priority: 1234,
scope:
discoveryQos.discoveryScope === DiscoveryScope.LOCAL_ONLY ? ProviderScope.LOCAL : ProviderScope.GLOBAL,
supportsOnChangeSubscriptions: true
}),
participantId: "700",
lastSeenDateMs: Date.now(),
publicKeyId: "",
expiryDateMs
});
}
describe("libjoynr-js.joynr.capabilities.discovery.CapabilityDiscovery", () => {
beforeEach(done => {
let i: number, discoveryEntry: DiscoveryEntry;
startDateMs = Date.now();
domain = "myDomain";
interfaceName = "myInterfaceName";
address = new ChannelAddress({
channelId: `${domain}TestCapabilityDiscoveryChannel`,
messagingEndpointUrl: "http://testUrl"
});
discoveryQos = new DiscoveryQos({
cacheMaxAge: 0,
discoveryScope: DiscoveryScope.LOCAL_THEN_GLOBAL
} as any);
discoveryEntries = [];
discoveryEntriesReturned = [];
for (i = 0; i < 12; ++i) {
discoveryEntry = getDiscoveryEntry(domain + i.toString(), interfaceName + i.toString());
discoveryEntries.push(discoveryEntry);
discoveryEntriesReturned.push(CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(true, discoveryEntry));
}
globalDiscoveryEntries = [];
globalDiscoveryEntriesReturned = [];
for (i = 0; i < 12; ++i) {
discoveryEntry = getGlobalDiscoveryEntry(
domain + i.toString(),
interfaceName + i.toString(),
new ChannelAddress({
channelId: `globalCapInfo${i.toString()}`,
messagingEndpointUrl: "http://testurl"
})
);
globalDiscoveryEntries.push(discoveryEntry);
globalDiscoveryEntriesReturned.push(
CapabilitiesUtil.convertToDiscoveryEntryWithMetaInfo(false, discoveryEntry)
);
}
localCapStoreSpy = getSpiedLookupObjWithReturnValue([]);
globalCapCacheSpy = getSpiedLookupObjWithReturnValue([]);
globalCapDirSpy = getSpiedLookupObjWithReturnValue(Promise.resolve({ result: [] }));
proxyBuilderSpy = {
build: jest.fn()
};
proxyBuilderSpy.build.mockReturnValue(Promise.resolve(globalCapDirSpy));
capabilityDiscovery = new CapabilityDiscovery(localCapStoreSpy, globalCapCacheSpy, "io.joynr", knownGbids);
capabilityDiscovery.setDependencies(messageRouterSpy, proxyBuilderSpy);
capabilityDiscovery.globalAddressReady(address);
done();
});
describe("lookupByParticipantId", () => {
beforeEach(done => {
globalCapDirSpy = getSpiedLookupObjWithReturnValue(Promise.resolve({ result: undefined }));
proxyBuilderSpy.build.mockReturnValue(Promise.resolve(globalCapDirSpy));
done();
});
it("calls local capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when local cache provides non-empty result", () => {
localCapStoreSpy.lookup.mockReturnValue(discoveryEntries);
capabilityDiscovery.lookupByParticipantId(participantId, discoveryQos, gbids);
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
participantId
});
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
expect(globalCapCacheSpy.lookup).not.toHaveBeenCalled();
});
it("calls local capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when global cache provides non-empty result", () => {
// discoveryEntries cached in globalCapabilitiesCache
globalCapCacheSpy.lookup.mockReturnValue(discoveryEntries);
capabilityDiscovery.lookupByParticipantId(participantId, discoveryQos, gbids);
expect(globalCapCacheSpy.lookup).toHaveBeenCalledWith({
participantId,
cacheMaxAge: discoveryQos.cacheMaxAge
});
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
participantId
});
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
});
it("calls local and global capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when local store and global cache provide empty result", async done => {
discoveryQos.discoveryScope = DiscoveryScope.LOCAL_THEN_GLOBAL;
try {
await capabilityDiscovery.lookupByParticipantId(participantId, discoveryQos, gbids);
done.fail("lookupByParticipantId should throw ApplicationException.");
} catch (e) {
expect(e).toBeInstanceOf(ApplicationException);
expect(e.error).toBeInstanceOf(DiscoveryError);
expect(e.error).toEqual(DiscoveryError.INTERNAL_ERROR);
}
await multipleSetImmediate();
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
participantId
});
expect(globalCapCacheSpy.lookup).toHaveBeenCalledWith({
participantId,
cacheMaxAge: discoveryQos.cacheMaxAge
});
expect(globalCapDirSpy.lookup).toHaveBeenCalledWith({
participantId,
gbids
});
done();
});
});
it(`throws if instantiated without knownGbids`, () => {
expect(() => {
new CapabilityDiscovery(localCapStoreSpy, globalCapCacheSpy, "io.joynr", []);
}).toThrow();
});
it("is instantiable, of correct type and has all members", () => {
expect(capabilityDiscovery).toBeDefined();
expect(capabilityDiscovery instanceof CapabilityDiscovery).toBeTruthy();
expect(capabilityDiscovery.lookup).toBeDefined();
expect(typeof capabilityDiscovery.lookup === "function").toBeTruthy();
expect(capabilityDiscovery.lookupByParticipantId).toBeDefined();
expect(typeof capabilityDiscovery.lookupByParticipantId === "function").toBeTruthy();
});
it("calls local capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when local store provides non-empty result", () => {
localCapStoreSpy = getSpiedLookupObjWithReturnValue(discoveryEntries);
globalCapCacheSpy = getSpiedLookupObjWithReturnValue([]);
capabilityDiscovery = new CapabilityDiscovery(localCapStoreSpy, globalCapCacheSpy, "io.joynr", knownGbids);
capabilityDiscovery.setDependencies(messageRouterSpy, proxyBuilderSpy);
capabilityDiscovery.globalAddressReady(address);
capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName
});
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
expect(globalCapCacheSpy.lookup).not.toHaveBeenCalled();
});
it("calls local and global capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when local store and global cache provide empty result", async () => {
discoveryQos.discoveryScope = DiscoveryScope.LOCAL_THEN_GLOBAL;
await capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
await multipleSetImmediate();
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName
});
expect(globalCapCacheSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
expect(globalCapDirSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName,
gbids
});
});
it("calls local and not global cache and not global capabilities directory according to discoveryQos.discoveryScope LOCAL_THEN_GLOBAL when local store provides non-empty result", () => {
localCapStoreSpy.lookup.mockReturnValue([getDiscoveryEntry(domain, interfaceName)]);
capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName
});
expect(globalCapCacheSpy.lookup).not.toHaveBeenCalled();
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
});
it("calls local capabilities directory according to discoveryQos.discoveryScope LOCAL_ONLY", () => {
discoveryQos.discoveryScope = DiscoveryScope.LOCAL_ONLY;
capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
expect(localCapStoreSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName
});
expect(globalCapCacheSpy.lookup).not.toHaveBeenCalled();
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
});
it("calls global capabilities directory according to discoveryQos.discoveryScope GLOBAL_ONLY", async () => {
discoveryQos.discoveryScope = DiscoveryScope.GLOBAL_ONLY;
capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
await testUtil.multipleSetImmediate();
expect(localCapStoreSpy.lookup).not.toHaveBeenCalled();
expect(globalCapCacheSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
expect(globalCapDirSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName,
gbids
});
});
it("does not call global capabilities directory according to discoveryQos.discoveryScope GLOBAL_ONLY, if global cache is non-empty", () => {
globalCapCacheSpy.lookup.mockReturnValue([getDiscoveryEntry(domain, interfaceName)]);
discoveryQos.discoveryScope = DiscoveryScope.GLOBAL_ONLY;
capabilityDiscovery.lookup([domain], interfaceName, discoveryQos, gbids);
expect(localCapStoreSpy.lookup).not.toHaveBeenCalled();
expect(globalCapCacheSpy.lookup).toHaveBeenCalledWith({
domains: [domain],
interfaceName,
cacheMaxAge: discoveryQos.cacheMaxAge
});
expect(globalCapDirSpy.lookup).not.toHaveBeenCalled();
});
function testDiscoveryResult(
_descriptor: string,
discoveryScope: DiscoveryScope,
localdiscoveryEntries: any,
globalCapCacheEntries: any,
globalCapabilityInfos: any,
expectedReturnValue: any
) {
const localCapStoreSpy = getSpiedLookupObjWithReturnValue(localdiscoveryEntries);
const globalCapCacheSpy = getSpiedLookupObjWithReturnValue(globalCapCacheEntries);
const globalCapDirSpy = getSpiedLookupObjWithReturnValue(
Promise.resolve({
result: globalCapabilityInfos
})
);
const proxyBuilderSpy = {
build: jest.fn()
};
proxyBuilderSpy.build.mockReturnValue(Promise.resolve(globalCapDirSpy));
const capabilityDiscovery = new CapabilityDiscovery(
localCapStoreSpy as any,
globalCapCacheSpy as any,
"io.joynr",
knownGbids
);
capabilityDiscovery.setDependencies(messageRouterSpy, proxyBuilderSpy as any);
capabilityDiscovery.globalAddressReady(address);
const discoveryQos = new DiscoveryQos({
cacheMaxAge: 0,
discoveryScope
} as any);
return capabilityDiscovery
.lookup([domain], interfaceName, discoveryQos, gbids)
.then(fulfilledWith => {
const endDateMs = Date.now();
if (expectedReturnValue === undefined) {
throw new Error("no return value was expected");
} else {
expect(fulfilledWith.length).toEqual(expectedReturnValue.length);
for (let i = 0; i < fulfilledWith.length; i++) {
assertDiscoveryEntryEquals(expectedReturnValue[i], fulfilledWith[i]);
expect(fulfilledWith[i].lastSeenDateMs >= startDateMs).toBeTruthy();
expect(fulfilledWith[i].lastSeenDateMs <= endDateMs).toBeTruthy();
}
}
})
.catch(() => {
if (expectedReturnValue !== undefined) {
// eslint-disable-next-line prefer-promise-reject-errors
throw new Error(`a return value was expected: ${expectedReturnValue}`);
}
});
}
it("discovers correct discoveryEntries according to discoveryScope", async () => {
await testDiscoveryResult("00", DiscoveryScope.LOCAL_THEN_GLOBAL, [], [], [], []);
await testDiscoveryResult(
"01",
DiscoveryScope.LOCAL_THEN_GLOBAL,
[discoveryEntries[1]],
[],
[],
[discoveryEntries[1]]
);
await testDiscoveryResult(
"02",
DiscoveryScope.LOCAL_THEN_GLOBAL,
[],
[globalDiscoveryEntries[1]],
[],
[globalDiscoveryEntriesReturned[1]]
);
await testDiscoveryResult(
"03",
DiscoveryScope.LOCAL_THEN_GLOBAL,
[],
[],
[globalDiscoveryEntries[2]],
[globalDiscoveryEntriesReturned[2]]
);
await testDiscoveryResult(
"04",
DiscoveryScope.LOCAL_THEN_GLOBAL,
[discoveryEntries[3]],
[],
[globalDiscoveryEntries[3]],
[discoveryEntriesReturned[3]]
);
await testDiscoveryResult(
"05",
DiscoveryScope.LOCAL_THEN_GLOBAL,
[discoveryEntries[3]],
[globalDiscoveryEntries[1]],
[globalDiscoveryEntries[3]],
[discoveryEntriesReturned[3]]
);
await testDiscoveryResult("06", DiscoveryScope.LOCAL_ONLY, [], [], [], []);
await testDiscoveryResult(
"07",
DiscoveryScope.LOCAL_ONLY,
[discoveryEntries[5]],
[],
[],
[discoveryEntriesReturned[5]]
);
await testDiscoveryResult("08", DiscoveryScope.LOCAL_ONLY, [], [], [globalDiscoveryEntries[6]], []);
await testDiscoveryResult("09", DiscoveryScope.LOCAL_ONLY, [], [globalDiscoveryEntries[5]], [], []);
await testDiscoveryResult(
"10",
DiscoveryScope.LOCAL_ONLY,
[],
[globalDiscoveryEntries[5]],
[globalDiscoveryEntries[6]],
[]
);
await testDiscoveryResult(
"11",
DiscoveryScope.LOCAL_ONLY,
[discoveryEntries[7]],
[],
[globalDiscoveryEntries[7]],
[discoveryEntriesReturned[7]]
);
await testDiscoveryResult(
"12",
DiscoveryScope.LOCAL_ONLY,
[discoveryEntries[7]],
[globalDiscoveryEntries[1]],
[globalDiscoveryEntries[7]],
[discoveryEntriesReturned[7]]
);
await testDiscoveryResult("13", DiscoveryScope.GLOBAL_ONLY, [], [], [], []);
await testDiscoveryResult(
"14",
DiscoveryScope.GLOBAL_ONLY,
[],
[globalDiscoveryEntries[9]],
[],
[globalDiscoveryEntriesReturned[9]]
);
await testDiscoveryResult("15", DiscoveryScope.GLOBAL_ONLY, [discoveryEntries[9]], [], [], []);
await testDiscoveryResult(
"16",
DiscoveryScope.GLOBAL_ONLY,
[],
[globalDiscoveryEntries[10]],
[globalDiscoveryEntries[10]],
[globalDiscoveryEntriesReturned[10]]
);
await testDiscoveryResult(
"17",
DiscoveryScope.GLOBAL_ONLY,
[],
[],
[globalDiscoveryEntries[10]],
[globalDiscoveryEntriesReturned[10]]
);
await testDiscoveryResult(
"18",
DiscoveryScope.GLOBAL_ONLY,
[],
[globalDiscoveryEntries[11]],
[globalDiscoveryEntries[11]],
[globalDiscoveryEntriesReturned[11]]
);
await testDiscoveryResult(
"19",
DiscoveryScope.GLOBAL_ONLY,
[discoveryEntries[10]],
[globalDiscoveryEntries[11]],
[globalDiscoveryEntries[11]],
[globalDiscoveryEntriesReturned[11]]
);
await testDiscoveryResult("20", DiscoveryScope.LOCAL_AND_GLOBAL, [], [], [], []);
await testDiscoveryResult(
"21",
DiscoveryScope.LOCAL_AND_GLOBAL,
[discoveryEntries[1]],
[],
[],
[discoveryEntriesReturned[1]]
);
await testDiscoveryResult(
"22",
DiscoveryScope.LOCAL_AND_GLOBAL,
[],
[globalDiscoveryEntries[1]],
[],
[globalDiscoveryEntriesReturned[1]]
);
await testDiscoveryResult(
"23",
DiscoveryScope.LOCAL_AND_GLOBAL,
[],
[],
[globalDiscoveryEntries[2]],
[globalDiscoveryEntriesReturned[2]]
);
await testDiscoveryResult(
"24",
DiscoveryScope.LOCAL_AND_GLOBAL,
[discoveryEntries[3]],
[globalDiscoveryEntries[4]],
[],
[discoveryEntriesReturned[3], globalDiscoveryEntriesReturned[4]]
);
await testDiscoveryResult(
"25",
DiscoveryScope.LOCAL_AND_GLOBAL,
[discoveryEntries[3]],
[],
[globalDiscoveryEntries[4]],
[discoveryEntriesReturned[3], globalDiscoveryEntriesReturned[4]]
);
await testDiscoveryResult(
"26",
DiscoveryScope.LOCAL_AND_GLOBAL,
[discoveryEntries[3]],
[globalDiscoveryEntries[1]],
[globalDiscoveryEntries[3]],
[discoveryEntriesReturned[3], globalDiscoveryEntriesReturned[1]]
);
});
function getDiscoveryEntryWithScope(scope: any) {
return new DiscoveryEntry({
providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }),
domain: "domain",
interfaceName: "interfaceName",
qos: new ProviderQos({
customParameters: [
new CustomParameter({
name: "theName",
value: "theValue"
})
],
priority: 1234,
scope,
supportsOnChangeSubscriptions: true
}),
participantId: "700",
lastSeenDateMs: 123,
publicKeyId: "",
expiryDateMs
});
}
it("add calls cap dir correctly with ProviderScope.LOCAL", async () => {
const discoveryEntry = getDiscoveryEntryWithScope(ProviderScope.LOCAL);
await capabilityDiscovery.add(discoveryEntry);
expect(localCapStoreSpy.add).toHaveBeenCalled();
expect(localCapStoreSpy.add).toHaveBeenCalledWith({
discoveryEntry,
remote: false
});
expect(globalCapDirSpy.add).not.toHaveBeenCalledWith(undefined);
});
it("add calls cap dir correctly with ProviderScope.GLOBAL", async () => {
const discoveryEntry = getDiscoveryEntryWithScope(ProviderScope.GLOBAL);
const expectedDiscoveryEntry = CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry(discoveryEntry, address);
await capabilityDiscovery.add(discoveryEntry);
expect(globalCapDirSpy.add).toHaveBeenCalled();
const actualDiscoveryEntry = globalCapDirSpy.add.mock.calls[0][0].globalDiscoveryEntry;
// lastSeenDate is set to Date.now() in CapabilityDiscovery.add
expectedDiscoveryEntry.lastSeenDateMs = actualDiscoveryEntry.lastSeenDateMs;
assertDiscoveryEntryEquals(expectedDiscoveryEntry, actualDiscoveryEntry);
expect(localCapStoreSpy.add).not.toHaveBeenCalledWith();
});
it("touch calls global cap dir correctly", async () => {
const expectedTtl = 1337;
const expectedClusterControllerId = "testTouchClusterControllerId";
await capabilityDiscovery.touch(expectedClusterControllerId, expectedTtl);
expect(globalCapDirSpy.touch).toHaveBeenCalled();
const actualTtl = proxyBuilderSpy.build.mock.calls[0][1].messagingQos.ttl;
const actualClusterControllerId = globalCapDirSpy.touch.mock.calls[0][0].clusterControllerId;
expect(actualTtl).toEqual(expectedTtl);
expect(actualClusterControllerId).toEqual(expectedClusterControllerId);
});
it("reports error from global cap dir", async () => {
const discoveryEntry = getDiscoveryEntryWithScope(ProviderScope.GLOBAL);
const expectedDiscoveryEntry = CapabilitiesUtil.discoveryEntry2GlobalDiscoveryEntry(discoveryEntry, address);
globalCapDirSpy = getSpiedLookupObjWithReturnValue(Promise.reject(new Error("Some error.")));
proxyBuilderSpy.build.mockReturnValue(Promise.resolve(globalCapDirSpy));
const error = await reversePromise(capabilityDiscovery.add(discoveryEntry));
expect(globalCapDirSpy.add).toHaveBeenCalled();
const actualDiscoveryEntry = globalCapDirSpy.add.mock.calls[0][0].globalDiscoveryEntry;
// lastSeenDate is set to Date.now() in CapabilityDiscovery.add
expectedDiscoveryEntry.lastSeenDateMs = actualDiscoveryEntry.lastSeenDateMs;
assertDiscoveryEntryEquals(expectedDiscoveryEntry, actualDiscoveryEntry);
expect(localCapStoreSpy.add).not.toHaveBeenCalledWith();
expect(Object.prototype.toString.call(error === "[object Error]")).toBeTruthy();
});
it("throws on unknown provider scope", async () => {
const discoveryEntry = getDiscoveryEntryWithScope("UnknownScope");
const error = await reversePromise(capabilityDiscovery.add(discoveryEntry));
expect(globalCapDirSpy.add).not.toHaveBeenCalled();
expect(localCapStoreSpy.add).not.toHaveBeenCalledWith();
expect(Object.prototype.toString.call(error) === "[object Error]").toBeTruthy();
});
it("lookup with multiple domains should throw an exception", async () => {
localCapStoreSpy = getSpiedLookupObjWithReturnValue(discoveryEntries);
globalCapCacheSpy = getSpiedLookupObjWithReturnValue([]);
capabilityDiscovery = new CapabilityDiscovery(localCapStoreSpy, globalCapCacheSpy, "io.joynr", knownGbids);
capabilityDiscovery.setDependencies(messageRouterSpy, proxyBuilderSpy);
capabilityDiscovery.globalAddressReady(address);
await expect(
capabilityDiscovery.lookup([domain, domain], interfaceName, discoveryQos, gbids)
).rejects.toBeInstanceOf(Error);
});
}); | 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 ErrorMesssage class.
* @constructor
* Error response containing message and code.
*
* @member {string} [code] standard error code
* @member {string} [message] standard error description
* @member {string} [details] detailed summary of error
*/
export interface ErrorMesssage {
code?: string;
message?: string;
details?: string;
}
/**
* @class
* Initializes a new instance of the AsyncOperationResult class.
* @constructor
* Result of a long running operation.
*
* @member {string} [status] current status of a long running operation.
* @member {object} [error] Error message containing code, description and
* details
* @member {string} [error.code] standard error code
* @member {string} [error.message] standard error description
* @member {string} [error.details] detailed summary of error
*/
export interface AsyncOperationResult {
status?: string;
error?: ErrorMesssage;
}
/**
* @class
* Initializes a new instance of the CertificateProperties class.
* @constructor
* The description of an X509 CA Certificate.
*
* @member {string} [subject] The certificate's subject name.
* @member {date} [expiry] The certificate's expiration date and time.
* @member {string} [thumbprint] The certificate's thumbprint.
* @member {boolean} [isVerified] Determines whether certificate has been
* verified.
* @member {date} [created] The certificate's creation date and time.
* @member {date} [updated] The certificate's last update date and time.
*/
export interface CertificateProperties {
readonly subject?: string;
readonly expiry?: Date;
readonly thumbprint?: string;
readonly isVerified?: boolean;
readonly created?: Date;
readonly updated?: Date;
}
/**
* @class
* Initializes a new instance of the CertificateResponse class.
* @constructor
* The X509 Certificate.
*
* @member {object} [properties] properties of a certificate
* @member {string} [properties.subject] The certificate's subject name.
* @member {date} [properties.expiry] The certificate's expiration date and
* time.
* @member {string} [properties.thumbprint] The certificate's thumbprint.
* @member {boolean} [properties.isVerified] Determines whether certificate has
* been verified.
* @member {date} [properties.created] The certificate's creation date and
* time.
* @member {date} [properties.updated] The certificate's last update date and
* time.
* @member {string} [id] The resource identifier.
* @member {string} [name] The name of the certificate.
* @member {string} [etag] The entity tag.
* @member {string} [type] The resource type.
*/
export interface CertificateResponse extends BaseResource {
properties?: CertificateProperties;
readonly id?: string;
readonly name?: string;
readonly etag?: string;
readonly type?: string;
}
/**
* @class
* Initializes a new instance of the CertificateListDescription class.
* @constructor
* The JSON-serialized array of Certificate objects.
*
* @member {array} [value] The array of Certificate objects.
*/
export interface CertificateListDescription {
value?: CertificateResponse[];
}
/**
* @class
* Initializes a new instance of the CertificateBodyDescription class.
* @constructor
* The JSON-serialized X509 Certificate.
*
* @member {string} [certificate] Base-64 representation of the X509 leaf
* certificate .cer file or just .pem file content.
*/
export interface CertificateBodyDescription {
certificate?: string;
}
/**
* @class
* Initializes a new instance of the IotDpsSkuInfo class.
* @constructor
* List of possible provisoning service SKUs.
*
* @member {string} [name] Sku name. Possible values include: 'S1'
* @member {string} [tier] Pricing tier name of the provisioning service.
* @member {number} [capacity] The number of units to provision
*/
export interface IotDpsSkuInfo {
name?: string;
readonly tier?: string;
capacity?: number;
}
/**
* @class
* Initializes a new instance of the IotHubDefinitionDescription class.
* @constructor
* Description of the IoT hub.
*
* @member {boolean} [applyAllocationPolicy] flag for applying allocationPolicy
* or not for a given iot hub.
* @member {number} [allocationWeight] weight to apply for a given iot h.
* @member {string} [name] Host name of the IoT hub.
* @member {string} connectionString Connection string og the IoT hub.
* @member {string} location ARM region of the IoT hub.
*/
export interface IotHubDefinitionDescription {
applyAllocationPolicy?: boolean;
allocationWeight?: number;
readonly name?: string;
connectionString: string;
location: string;
}
/**
* @class
* Initializes a new instance of the SharedAccessSignatureAuthorizationRuleAccessRightsDescription class.
* @constructor
* Description of the shared access key.
*
* @member {string} keyName Name of the key.
* @member {string} [primaryKey] Primary SAS key value.
* @member {string} [secondaryKey] Secondary SAS key value.
* @member {string} rights Rights that this key has. Possible values include:
* 'ServiceConfig', 'EnrollmentRead', 'EnrollmentWrite', 'DeviceConnect',
* 'RegistrationStatusRead', 'RegistrationStatusWrite'
*/
export interface SharedAccessSignatureAuthorizationRuleAccessRightsDescription {
keyName: string;
primaryKey?: string;
secondaryKey?: string;
rights: string;
}
/**
* @class
* Initializes a new instance of the IotDpsPropertiesDescription class.
* @constructor
* the service specific properties of a provisoning service, including keys,
* linked iot hubs, current state, and system generated properties such as
* hostname and idScope
*
* @member {string} [state] Current state of the provisioning service. Possible
* values include: 'Activating', 'Active', 'Deleting', 'Deleted',
* 'ActivationFailed', 'DeletionFailed', 'Transitioning', 'Suspending',
* 'Suspended', 'Resuming', 'FailingOver', 'FailoverFailed'
* @member {string} [provisioningState] The ARM provisioning state of the
* provisioning service.
* @member {array} [iotHubs] List of IoT hubs assosciated with this
* provisioning service.
* @member {string} [allocationPolicy] Allocation policy to be used by this
* provisioning service. Possible values include: 'Hashed', 'GeoLatency',
* 'Static'
* @member {string} [serviceOperationsHostName] Service endpoint for
* provisioning service.
* @member {string} [deviceProvisioningHostName] Device endpoint for this
* provisioning service.
* @member {string} [idScope] Unique identifier of this provisioning service.
* @member {array} [authorizationPolicies] List of authorization keys for a
* provisioning service.
*/
export interface IotDpsPropertiesDescription {
state?: string;
provisioningState?: string;
iotHubs?: IotHubDefinitionDescription[];
allocationPolicy?: string;
readonly serviceOperationsHostName?: string;
readonly deviceProvisioningHostName?: string;
readonly idScope?: string;
authorizationPolicies?: SharedAccessSignatureAuthorizationRuleAccessRightsDescription[];
}
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* The common properties of an Azure resource.
*
* @member {string} [id] The resource identifier.
* @member {string} [name] The resource name.
* @member {string} [type] The resource type.
* @member {string} location The resource location.
* @member {object} [tags] The resource tags.
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the ProvisioningServiceDescription class.
* @constructor
* The description of the provisioning service.
*
* @member {string} [etag] The Etag field is *not* required. If it is provided
* in the response body, it must also be provided as a header per the normal
* ETag convention.
* @member {object} properties Service specific properties for a provisioning
* service
* @member {string} [properties.state] Current state of the provisioning
* service. Possible values include: 'Activating', 'Active', 'Deleting',
* 'Deleted', 'ActivationFailed', 'DeletionFailed', 'Transitioning',
* 'Suspending', 'Suspended', 'Resuming', 'FailingOver', 'FailoverFailed'
* @member {string} [properties.provisioningState] The ARM provisioning state
* of the provisioning service.
* @member {array} [properties.iotHubs] List of IoT hubs assosciated with this
* provisioning service.
* @member {string} [properties.allocationPolicy] Allocation policy to be used
* by this provisioning service. Possible values include: 'Hashed',
* 'GeoLatency', 'Static'
* @member {string} [properties.serviceOperationsHostName] Service endpoint for
* provisioning service.
* @member {string} [properties.deviceProvisioningHostName] Device endpoint for
* this provisioning service.
* @member {string} [properties.idScope] Unique identifier of this provisioning
* service.
* @member {array} [properties.authorizationPolicies] List of authorization
* keys for a provisioning service.
* @member {object} sku Sku info for a provisioning Service.
* @member {string} [sku.name] Sku name. Possible values include: 'S1'
* @member {string} [sku.tier] Pricing tier name of the provisioning service.
* @member {number} [sku.capacity] The number of units to provision
*/
export interface ProvisioningServiceDescription extends Resource {
etag?: string;
properties: IotDpsPropertiesDescription;
sku: IotDpsSkuInfo;
}
/**
* @class
* Initializes a new instance of the OperationDisplay class.
* @constructor
* The object that represents the operation.
*
* @member {string} [provider] Service provider: Microsoft Devices.
* @member {string} [resource] Resource Type: ProvisioningServices.
* @member {string} [operation] Name of the operation.
*/
export interface OperationDisplay {
readonly provider?: string;
readonly resource?: string;
readonly operation?: string;
}
/**
* @class
* Initializes a new instance of the Operation class.
* @constructor
* IoT Hub REST API operation.
*
* @member {string} [name] Operation name: {provider}/{resource}/{read | write
* | action | delete}
* @member {object} [display] The object that represents the operation.
* @member {string} [display.provider] Service provider: Microsoft Devices.
* @member {string} [display.resource] Resource Type: ProvisioningServices.
* @member {string} [display.operation] Name of the operation.
*/
export interface Operation {
readonly name?: string;
display?: OperationDisplay;
}
/**
* @class
* Initializes a new instance of the ErrorDetails class.
* @constructor
* Error details.
*
* @member {string} [code] The error code.
* @member {string} [httpStatusCode] The HTTP status code.
* @member {string} [message] The error message.
* @member {string} [details] The error details.
*/
export interface ErrorDetails {
readonly code?: string;
readonly httpStatusCode?: string;
readonly message?: string;
readonly details?: string;
}
/**
* @class
* Initializes a new instance of the IotDpsSkuDefinition class.
* @constructor
* Available Sku's of tier and units.
*
* @member {string} [name] Sku name. Possible values include: 'S1'
*/
export interface IotDpsSkuDefinition {
name?: string;
}
/**
* @class
* Initializes a new instance of the OperationInputs class.
* @constructor
* Input values for operation results call.
*
* @member {string} name The name of the Provisioning Service to check.
*/
export interface OperationInputs {
name: string;
}
/**
* @class
* Initializes a new instance of the NameAvailabilityInfo class.
* @constructor
* Description of name availability.
*
* @member {boolean} [nameAvailable] specifies if a name is available or not
* @member {string} [reason] specifies the reason a name is unavailable.
* Possible values include: 'Invalid', 'AlreadyExists'
* @member {string} [message] message containing a etailed reason name is
* unavailable
*/
export interface NameAvailabilityInfo {
nameAvailable?: boolean;
reason?: string;
message?: string;
}
/**
* @class
* Initializes a new instance of the TagsResource class.
* @constructor
* A container holding only the Tags for a resource, allowing the user to
* update the tags on a Provisioning Service instance.
*
* @member {object} [tags] Resource tags
*/
export interface TagsResource {
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the VerificationCodeResponseProperties class.
* @constructor
* @member {string} [verificationCode] Verification code.
* @member {string} [subject] Certificate subject.
* @member {string} [expiry] Code expiry.
* @member {string} [thumbprint] Certificate thumbprint.
* @member {boolean} [isVerified] Indicate if the certificate is verified by
* owner of private key.
* @member {string} [created] Certificate created time.
* @member {string} [updated] Certificate updated time.
*/
export interface VerificationCodeResponseProperties {
verificationCode?: string;
subject?: string;
expiry?: string;
thumbprint?: string;
isVerified?: boolean;
created?: string;
updated?: string;
}
/**
* @class
* Initializes a new instance of the VerificationCodeResponse class.
* @constructor
* Description of the response of the verification code.
*
* @member {string} [name] Name of certificate.
* @member {string} [etag] Request etag.
* @member {string} [id] The resource identifier.
* @member {string} [type] The resource type.
* @member {object} [properties]
* @member {string} [properties.verificationCode] Verification code.
* @member {string} [properties.subject] Certificate subject.
* @member {string} [properties.expiry] Code expiry.
* @member {string} [properties.thumbprint] Certificate thumbprint.
* @member {boolean} [properties.isVerified] Indicate if the certificate is
* verified by owner of private key.
* @member {string} [properties.created] Certificate created time.
* @member {string} [properties.updated] Certificate updated time.
*/
export interface VerificationCodeResponse extends BaseResource {
readonly name?: string;
readonly etag?: string;
readonly id?: string;
readonly type?: string;
properties?: VerificationCodeResponseProperties;
}
/**
* @class
* Initializes a new instance of the VerificationCodeRequest class.
* @constructor
* The JSON-serialized leaf certificate
*
* @member {string} [certificate] base-64 representation of X509 certificate
* .cer file or just .pem file content.
*/
export interface VerificationCodeRequest {
certificate?: string;
}
/**
* @class
* Initializes a new instance of the OperationListResult class.
* @constructor
* Result of the request to list IoT Hub operations. It contains a list of
* operations and a URL link to get the next set of results.
*
* @member {string} [nextLink] URL to get the next set of operation list
* results if there are any.
*/
export interface OperationListResult extends Array<Operation> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the ProvisioningServiceDescriptionListResult class.
* @constructor
* List of provisioning service descriptions.
*
* @member {string} [nextLink] the next link
*/
export interface ProvisioningServiceDescriptionListResult extends Array<ProvisioningServiceDescription> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the IotDpsSkuDefinitionListResult class.
* @constructor
* List of available SKUs.
*
* @member {string} [nextLink] The next link.
*/
export interface IotDpsSkuDefinitionListResult extends Array<IotDpsSkuDefinition> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the SharedAccessSignatureAuthorizationRuleListResult class.
* @constructor
* List of shared access keys.
*
* @member {string} [nextLink] The next link.
*/
export interface SharedAccessSignatureAuthorizationRuleListResult extends Array<SharedAccessSignatureAuthorizationRuleAccessRightsDescription> {
readonly nextLink?: string;
} | the_stack |
import * as express from 'express';
import * as bodyParser from 'body-parser';
import HAS from './HAS';
import {Pairing, Pairings} from './config';
import * as TLVEnums from './TLV/values';
import parseTLV from './TLV/parse';
import {encodeTLV, encodeTLVError, TLVITem} from './TLV/encode';
import SRP from './encryption/SRP';
import HKDF from './encryption/HKDF';
import * as ChaCha from './encryption/ChaCha20Poly1305AEAD';
const Ed25519 = require('ed25519');
const Curve25519 = require('curve25519-n2');
import Characteristic from './characteristic';
export default function (server: HAS): express.Express {
const app: express.Express = express();
// Decode TLV request body if exists / Set real TCP socket
app.use((req: any, res, next) => {
// TCP connection should stay open as lang as it wants to
req.socket.setTimeout(0);
req.socket.setKeepAlive(true, 1800000); // 30 Minutes
if (!req.headers['x-real-socket-id']) {
res.end();
return;
}
req.realSocket = server.TCPServer.connections[req.headers['x-real-socket-id']];
if (!req.realSocket) {
res.end();
return;
}
res.removeHeader('x-powered-by');
res.header('X-Real-Socket-ID', req.realSocket.ID);
if (req.headers['content-type'] && req.headers['content-type'].indexOf('tlv') > -1) {
let data = Buffer.alloc(0);
req.on('data', function (chunk: Buffer) {
data = Buffer.concat([data, chunk]);
});
req.on('end', function () {
req.body = req.body || {};
req.body.TLV = parseTLV(data);
next();
});
} else
next();
});
app.use(bodyParser.json({
type: 'application/hap+json'
}));
app.use(bodyParser.urlencoded({
extended: false
}));
// Pair Setup
app.post('/pair-setup', (req: any, res) => {
// console.log(req.body, req.realSocket.ID);
res.header('Content-Type', 'application/pairing+tlv8');
const currentState = (req.body.TLV[TLVEnums.TLVValues.state]) ? parseInt(req.body.TLV[TLVEnums.TLVValues.state].toString('hex')) : 0x00;
// Sent parameters can be wrong, So we have to be ready for errors
try {
// Server is already paired
if (server.config.statusFlag != 0x01) {
res.end(encodeTLVError(TLVEnums.TLVErrors.unavailable, currentState));
return;
}
// Too much failed tries / Server needs to be restarted
if (server.config.failedAuthCounter > 100) {
res.end(encodeTLVError(TLVEnums.TLVErrors.maxTries, currentState));
return;
}
// M1 <iOS> -> M2 <Server>
if (currentState === 0x01) {
// Another pairing is already in progress
if (server.config.lastPairStepTime && new Date().getTime() - server.config.lastPairStepTime.getTime() < 30000 && server.config.SRP && server.config.SRP.socketID !== req.realSocket.ID) {
res.end(encodeTLVError(TLVEnums.TLVErrors.busy, currentState));
return;
}
server.config.lastPairStepTime = new Date();
server.config.SRP = new SRP(server.config.setupCode);
server.config.SRP.socketID = req.realSocket.ID;
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}, {
key: TLVEnums.TLVValues.publicKey,
value: server.config.SRP.getPublicKey()
}, {
key: TLVEnums.TLVValues.salt,
value: server.config.SRP.salt
}]));
return;
}
server.config.lastPairStepTime = new Date();
// M1&M2 is passed but we don't have an SRP object yet!
if (!server.config.SRP) {
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
return;
}
// M3 <iOS> -> M4 <Server>
if (currentState === 0x03) {
server.config.SRP.setClientPublicKey(req.body.TLV[TLVEnums.TLVValues.publicKey]);
if (server.config.SRP.checkClientProof(req.body.TLV[TLVEnums.TLVValues.proof])) {
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}, {
key: TLVEnums.TLVValues.proof,
value: server.config.SRP.getM2Proof()
}]));
return;
} else {
server.config.failedAuthCounter++;
server.config.lastPairStepTime = undefined;
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
}
return;
}
// M5 <iOS> -> M6 <Server>
if (currentState === 0x05) {
const body = req.body.TLV[TLVEnums.TLVValues.encryptedData],
encryptedData = body.slice(0, body.length - 16),
tag = body.slice(body.length - 16),
key = HKDF(server.config.SRP.getSessionKey());
const data = ChaCha.decrypt(key, 'PS-Msg05', tag, encryptedData);
if (data === false)
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
else {
const info = parseTLV(data as Buffer);
const iOSDeviceInfo = Buffer.concat([HKDF(server.config.SRP.getSessionKey(), 'Pair-Setup-Controller-Sign-Salt', 'Pair-Setup-Controller-Sign-Info'), info[TLVEnums.TLVValues.identifier], info[TLVEnums.TLVValues.publicKey]]);
if (Ed25519.Verify(iOSDeviceInfo, info[TLVEnums.TLVValues.signature], info[TLVEnums.TLVValues.publicKey])) {
server.config.addPairing(info[TLVEnums.TLVValues.identifier], info[TLVEnums.TLVValues.publicKey], true);
server.config.failedAuthCounter = 0;
const accessoryInfo = Buffer.concat([HKDF(server.config.SRP.getSessionKey(), 'Pair-Setup-Accessory-Sign-Salt', 'Pair-Setup-Accessory-Sign-Info'), Buffer.from(server.config.deviceID), server.config.publicKey]);
const accessorySignature = Ed25519.Sign(accessoryInfo, server.config.privateKey);
server.config.SRP = undefined;
const plainTLV = encodeTLV([
{
key: TLVEnums.TLVValues.identifier,
value: server.config.deviceID
},
{
key: TLVEnums.TLVValues.publicKey,
value: server.config.publicKey
},
{
key: TLVEnums.TLVValues.signature,
value: accessorySignature
}
]);
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}, {
key: TLVEnums.TLVValues.encryptedData,
value: ChaCha.encrypt(key, 'PS-Msg06', plainTLV)
}]));
} else
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
}
return;
}
} catch (e) {
console.error(e);
server.config.lastPairStepTime = undefined;
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
}
});
// Pair Verify
app.post('/pair-verify', (req: any, res) => {
// onsole.log(req.body, req.realSocket.ID);
res.header('Content-Type', 'application/pairing+tlv8');
const currentState = (req.body.TLV[TLVEnums.TLVValues.state]) ? parseInt(req.body.TLV[TLVEnums.TLVValues.state].toString('hex')) : 0x00;
// Sent parameters can be wrong, So we have to be ready for errors
try {
// M1 <iOS> -> M2 <Server>
if (currentState === 0x01) {
let secretKey = Buffer.alloc(32);
secretKey = Curve25519.makeSecretKey(secretKey);
const publicKey = Curve25519.derivePublicKey(secretKey),
sharedKey = Curve25519.deriveSharedSecret(secretKey, req.body.TLV[TLVEnums.TLVValues.publicKey]);
const accessoryInfo = Buffer.concat([publicKey, Buffer.from(server.config.deviceID), req.body.TLV[TLVEnums.TLVValues.publicKey]]);
const accessorySignature = Ed25519.Sign(accessoryInfo, server.config.privateKey);
const plainTLV = encodeTLV([
{
key: TLVEnums.TLVValues.identifier,
value: server.config.deviceID
},
{
key: TLVEnums.TLVValues.signature,
value: accessorySignature
}
]);
const sessionKey = HKDF(sharedKey, 'Pair-Verify-Encrypt-Salt', 'Pair-Verify-Encrypt-Info');
req.realSocket.HAPEncryption = {
serverSecretKey: secretKey,
serverPublicKey: publicKey,
sharedKey: sharedKey,
clientPublicKey: req.body.TLV[TLVEnums.TLVValues.publicKey],
sessionKey: sessionKey,
incomingFramesCounter: 0,
outgoingFramesCounter: 0,
isAdmin: false,
};
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}, {
key: TLVEnums.TLVValues.encryptedData,
value: ChaCha.encrypt(sessionKey, 'PV-Msg02', plainTLV)
}, {
key: TLVEnums.TLVValues.publicKey,
value: publicKey
}]));
return;
}
// M1&M2 is passed but we don't have an HAPEncryption object yet!
if (!req.realSocket.HAPEncryption) {
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
return;
}
// M3 <iOS> -> M4 <Server>
if (currentState === 0x03) {
const body = req.body.TLV[TLVEnums.TLVValues.encryptedData],
encryptedData = body.slice(0, body.length - 16),
tag = body.slice(body.length - 16);
const data = ChaCha.decrypt(req.realSocket.HAPEncryption.sessionKey, 'PV-Msg03', tag, encryptedData);
if (data === false)
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
else {
const info = parseTLV(data as Buffer);
let pairing = server.config.getPairings(info[TLVEnums.TLVValues.identifier]);
if (pairing === false)
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
else {
pairing = pairing as Pairing;
const iOSDeviceInfo = Buffer.concat([req.realSocket.HAPEncryption.clientPublicKey, info[TLVEnums.TLVValues.identifier], req.realSocket.HAPEncryption.serverPublicKey]);
if (Ed25519.Verify(iOSDeviceInfo, info[TLVEnums.TLVValues.signature], Buffer.from(pairing.publicKey, 'hex'))) {
req.realSocket.HAPEncryption.accessoryToControllerKey = HKDF(req.realSocket.HAPEncryption.sharedKey, 'Control-Salt', 'Control-Read-Encryption-Key');
req.realSocket.HAPEncryption.controllerToAccessoryKey = HKDF(req.realSocket.HAPEncryption.sharedKey, 'Control-Salt', 'Control-Write-Encryption-Key');
req.realSocket.HAPEncryption.isAdmin = pairing.isAdmin;
req.realSocket.isEncrypted = true;
req.realSocket.isAuthenticated = true;
req.realSocket.clientID = info[TLVEnums.TLVValues.identifier].toString('utf8');
req.realSocket.keepAliveForEver();
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}]));
} else
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
}
}
return;
}
} catch (e) {
console.error(e);
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
}
});
// List of Accessories
app.get('/accessories', (req: any, res) => {
res.header('Content-Type', 'application/hap+json');
if (!req.realSocket.isAuthenticated) {
res.status(400).end(JSON.stringify({
status: TLVEnums.statusCodes.insufficientPrivilege
}));
return;
}
const accessoriesObject = server.getAccessories(),
accessories = [];
for (const index in accessoriesObject)
accessories.push(accessoriesObject[index].toJSON());
res.end(JSON.stringify({
accessories: accessories
}));
});
// Add or remove a pairing
app.post('/pairings', (req: any, res) => {
// console.log(req.body, req.realSocket.ID);
res.header('Content-Type', 'application/pairing+tlv8');
const currentState = (req.body.TLV[TLVEnums.TLVValues.state]) ? parseInt(req.body.TLV[TLVEnums.TLVValues.state].toString('hex')) : 0x00;
if (!req.realSocket.isAuthenticated || !req.realSocket.HAPEncryption.isAdmin) {
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
return;
}
// Add New Pairing
if (req.body.TLV[TLVEnums.TLVValues.method].toString('hex') == TLVEnums.TLVMethods.addPairing) {
let pairing = server.config.getPairings(req.body.TLV[TLVEnums.TLVValues.identifier]);
if (pairing === false) {
server.config.addPairing(req.body.TLV[TLVEnums.TLVValues.identifier], req.body.TLV[TLVEnums.TLVValues.publicKey], req.body.TLV[TLVEnums.TLVValues.permissions].toString('hex') == '01');
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}]));
} else {
pairing = pairing as Pairing;
if (pairing.publicKey == req.body.TLV[TLVEnums.TLVValues.publicKey].toString('hex')) {
server.config.updatePairing(req.body.TLV[TLVEnums.TLVValues.identifier], req.body.TLV[TLVEnums.TLVValues.permissions].toString('hex') == '01');
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}]));
} else
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
}
// Remove Pairing
} else if (req.body.TLV[TLVEnums.TLVValues.method].toString('hex') == TLVEnums.TLVMethods.removePairing) {
const pairing = server.config.getPairings(req.body.TLV[TLVEnums.TLVValues.identifier]);
if (pairing === false)
res.end(encodeTLVError(TLVEnums.TLVErrors.unknown, currentState));
else {
server.config.removePairing(req.body.TLV[TLVEnums.TLVValues.identifier]);
res.end(encodeTLV([
{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}]));
server.TCPServer.revokeConnections(req.body.TLV[TLVEnums.TLVValues.identifier].toString('utf8'));
}
} else
res.end();
});
// List of Pairings
app.get('/pairings', (req: any, res) => {
console.log(req.body, req.realSocket.ID);
res.header('Content-Type', 'application/pairing+tlv8');
const currentState = 1;
if (!req.realSocket.isAuthenticated || !req.realSocket.HAPEncryption.isAdmin) {
res.end(encodeTLVError(TLVEnums.TLVErrors.authentication, currentState));
return;
}
let offset = 0;
const pairings = server.config.getPairings() as Pairings,
response: TLVITem[] = [{
key: TLVEnums.TLVValues.state,
value: currentState + 1
}],
total = Object.keys(pairings).length;
for (const index in pairings) {
const pairing = pairings[index];
response.push({
key: TLVEnums.TLVValues.identifier,
value: Buffer.from(index, 'utf8')
});
response.push({
key: TLVEnums.TLVValues.publicKey,
value: Buffer.from(pairing.publicKey, 'hex')
});
response.push({
key: TLVEnums.TLVValues.permissions,
value: Buffer.from([pairing.isAdmin])
});
offset++;
if (offset < total)
response.push({
key: TLVEnums.TLVValues.separator,
value: Buffer.alloc(0)
});
}
res.end(response);
});
// Read value of characteristics
app.get('/characteristics', (req: any, res) => {
// console.log(req.body, req.realSocket.ID);
res.header('Content-Type', 'application/hap+json');
if (!req.realSocket.isAuthenticated) {
res.status(400).end(JSON.stringify({
status: TLVEnums.statusCodes.insufficientPrivilege
}));
return;
}
const characteristics2Read = req.query.id.split(',');
let allOK = true;
const characteristics: { [index: string]: any }[] = [];
for (let characteristic of characteristics2Read) {
characteristic = characteristic.split('.');
const accessoryID = parseInt(characteristic[0]),
characteristicID = parseInt(characteristic[1]);
const object: { [index: string]: any } = {
aid: accessoryID,
iid: characteristicID
};
let error = null,
value = null;
const accessory = server.getAccessories()[accessoryID];
if (accessory) {
let characteristic = accessory.getCharacteristic(characteristicID);
if (characteristic) {
characteristic = characteristic as Characteristic;
if (characteristic.getHasValue())
value = characteristic.getValue();
else
error = TLVEnums.statusCodes.isWriteonly;
if (req.query.meta)
characteristic.addMetadata(object);
if (req.query.perms)
object['perms'] = characteristic.getPermissions();
if (req.query.type)
object['type'] = characteristic.getType();
if (req.query.ev)
object['ev'] = characteristic.getHasNotifications();
} else
error = TLVEnums.statusCodes.notFound;
} else
error = TLVEnums.statusCodes.notFound;
if (error) {
object['status'] = error;
allOK = false;
} else {
object['value'] = value;
object['status'] = TLVEnums.statusCodes.OK;
}
characteristics.push(object);
}
if (allOK) {
for (const characteristic of characteristics)
delete characteristic['status'];
}
res.status(allOK ? 200 : 207).end(JSON.stringify({
characteristics: characteristics
}));
});
// Write value of characteristics
app.put('/characteristics', async (req: any, res) => {
// console.log(req.body);
res.header('Content-Type', 'application/hap+json');
if (!req.realSocket.isAuthenticated) {
res.status(400).end(JSON.stringify({
status: TLVEnums.statusCodes.insufficientPrivilege
}));
return;
}
let allOK = true;
const characteristics: {}[] = [];
await Promise.all(req.body.characteristics.map(async (characteristic: any) => {
const accessoryID = parseInt(characteristic.aid),
characteristicID = parseInt(characteristic.iid),
value = characteristic.value,
event = characteristic.ev,
authData = characteristic.authData;
let error = null;
const accessory = server.getAccessories()[accessoryID];
if (accessory) {
let characteristic = accessory.getCharacteristic(characteristicID);
if (characteristic) {
characteristic = characteristic as Characteristic;
if (event && !characteristic.getHasNotifications())
error = TLVEnums.statusCodes.notificationIsNotSupported;
if (!error) {
if (event)
characteristic.subscribe(req.realSocket.ID);
if (event === false)
characteristic.unsubscribe(req.realSocket.ID);
if (value != undefined && value != undefined) {
try {
await characteristic.writeValue(value, authData);
} catch (e) {
error = e;
}
}
}
} else
error = TLVEnums.statusCodes.notFound;
} else
error = TLVEnums.statusCodes.notFound;
const object: { [index: string]: any } = {
aid: accessoryID,
iid: characteristicID
};
if (error) {
object['status'] = error;
allOK = false;
} else
object['status'] = TLVEnums.statusCodes.OK;
characteristics.push(object);
}));
if (allOK)
res.removeHeader('Content-Type');
res.status(allOK ? 204 : 207).end(allOK ? null : JSON.stringify({
characteristics: characteristics
}));
});
// Accessory Identify (Only when device is unpaired)
app.get('/identify', (req: any, res) => {
res.header('Content-Type', 'application/hap+json');
// Server is already paired
if (server.config.statusFlag != 0x01) {
res.status(400).end(JSON.stringify({
status: TLVEnums.statusCodes.insufficientPrivilege
}));
return;
}
if (server.onIdentify) {
server.onIdentify(true, (status) => {
if (status == TLVEnums.statusCodes.OK) {
res.removeHeader('Content-Type');
res.status(204).end();
} else
res.status(500).end(JSON.stringify({
status: status
}));
});
} else
res.status(500).end(JSON.stringify({
status: TLVEnums.statusCodes.communicationError
}));
});
return app;
} | the_stack |
import {
CHECK_SAPARATOR,
CHECK_LOAD_PATTERN,
LOAD_SAPARATOR,
DOMDIFF,
getRef,
MAGIC_METHOD,
} from "./Event";
import {
isFunction,
html,
keyEach,
collectProps,
isString
} from "./functions/func";
import {DomEventHandler} from "./handler/DomEventHandler";
import {BindHandler} from "./handler/BindHandler";
import { retriveElement } from "./functions/registElement";
import { uuid, uuidShort } from "./functions/uuid";
import { Dom } from "./functions/Dom";
import { IBaseHandler, IDom, IEventMachine, IKeyValue } from "./types";
const REFERENCE_PROPERTY = "ref";
const TEMP_DIV = Dom.create("div");
const QUERY_PROPERTY = `[${REFERENCE_PROPERTY}]`;
const REF_CLASS = 'refclass';
const REF_CLASS_PROPERTY = `[${REF_CLASS}]`
const VARIABLE_SAPARATOR = "__ref__variable:";
export class EventMachine implements IEventMachine {
state: any;
prevState: any;
children: any;
_bindings: never[];
id: string;
__tempVariables: Map<string, any>;
handlers: (BindHandler | DomEventHandler)[];
_loadMethods: any;
__cachedMethodList: any;
constructor(opt: Object | IEventMachine, props: IKeyValue) {
this.state = {};
this.prevState = {};
this.refs = {};
this.children = {};
this._bindings = [];
this.id = uuid();
this.__tempVariables = new Map();
this.handlers = this.initializeHandler()
this.initializeProperty(opt, props);
this.initComponents();
}
private _$store: any;
public get $store(): any {
return this._$store;
}
public set $store(value: any) {
this._$store = value;
}
el: any;
$el: any;
$root: any;
refs: any;
opt!: IKeyValue;
parent!: IEventMachine;
props!: IKeyValue;
source!: string;
sourceName!: string;
childComponents!: IKeyValue;
/**
* UIElement instance 에 필요한 기본 속성 설정
*/
initializeProperty (opt: any, props = {}) {
this.opt = opt || {};
this.parent = this.opt as IEventMachine;
this.props = props;
this.source = uuid();
this.sourceName = this.constructor.name;
}
initComponents() {
this.childComponents = this.components()
}
initializeHandler () {
return [
new BindHandler(this as any),
new DomEventHandler(this as any)
]
}
/**
* state 를 초기화 한것을 리턴한다.
*
* @protected
* @returns {Object}
*/
initState() {
return {};
}
/**
* state 를 변경한다.
*
* @param {Object} state 새로운 state
* @param {Boolean} isLoad 다시 로드 할 것인지 체크 , true 면 state 변경후 다시 로드
*/
setState(state = {}, isLoad = true) {
this.prevState = this.state;
this.state = Object.assign({}, this.state, state );
if (isLoad) {
this.load();
}
}
/**
* state 에 있는 key 필드의 값을 토글한다.
* Boolean 형태의 값만 동작한다.
*
* @param {string} key
* @param {Boolean} isLoad
*/
toggleState(key: string | number, isLoad = true) {
this.setState({
[key]: !(this.state[key])
}, isLoad)
}
/**
* props 를 넘길 때 해당 참조를 그대로 넘기기 위한 함수
*
* @param {any} value
* @returns {string} 참조 id 생성
*/
variable(value: any) {
const id = `${VARIABLE_SAPARATOR}${uuidShort()}`;
this.__tempVariables.set(id, value);
return id;
}
/**
* 참조 id 를 가지고 있는 variable 을 복구한다.
*/
recoverVariable(id: string) {
if (isString(id) === false) {
return id;
}
let value = id;
if (this.__tempVariables.has(id)) {
value = this.__tempVariables.get(id);
this.__tempVariables.delete(id);
}
return value;
}
/**
* 객체를 다시 그릴 때 사용한다.
*
* @param {*} props
* @protected
*/
_reload(props: any) {
this.props = props;
this.state = {};
this.setState(this.initState(), false);
this.refresh();
}
/**
* template 을 렌더링 한다.
*
* @param {Dom|undefined} $container 컴포넌트가 그려질 대상
*/
render($container: IDom) {
this.$el = this.parseTemplate(
html`
${this.template()}
`
);
this.refs.$el = this.$el;
if ($container) {
$container.append(this.$el);
}
// LOAD 로 정의된 것들을 수행한다.
this.load();
// render 이후에 실행될 콜백을 정의한다.
this.afterRender();
}
initialize() {
this.state = this.initState();
}
/**
* render 이후에 실행될 함수
* dom 이 실제로 생성된 이후에 수행할 작업들을 정의한다.
*
* @protected
*/
afterRender() {}
/**
* 하위에 연결될 객체들을 정의한다
*
* @protected
* @returns {Object}
*/
components() {
return {};
}
/**
* ref 이름을 가진 Component 를 가지고 온다.
*
* @param {any[]} args
* @returns {EventMachine}
*/
getRef(...args: string[]) {
const key = args.join('')
return this.refs[key];
}
/**
* template() 함수의 결과물을 파싱해서 dom element 를 생성한다.
*
* @param {string} html
* @param {Boolean} [isLoad=false]
*/
parseTemplate(html: string, isLoad: boolean | undefined = false) {
//FIXME: html string, element 형태 모두 array 로 받을 수 있도록 해보자.
if (Array.isArray(html)) {
html = html.join('');
}
html = html.trim();
const list = (TEMP_DIV.html(html) as IDom).children();
/////////////////////////////////
for(var i = 0, len = list.length; i < len; i++) {
const $el = list[i];
var ref = $el.attr(REFERENCE_PROPERTY)
if (ref) {
this.refs[ref] = $el;
}
var refs = $el.$$(QUERY_PROPERTY);
var temp = {}
for(var refsIndex = 0, refsLen = refs.length; refsIndex < refsLen; refsIndex++) {
const $dom = refs[refsIndex];
const name = $dom.attr(REFERENCE_PROPERTY);
if (temp[name]) {
console.warn(`${ref} is duplicated. - ${this.sourceName}`, this)
} else {
temp[name] = true;
}
this.refs[name] = $dom;
}
}
if (!isLoad && list.length) {
return list[0];
}
return Dom.create(TEMP_DIV.createChildrenFragment());
}
parseProperty ($dom: IDom) {
let props = {};
// parse properties
for(var t of $dom.htmlEl.attributes) {
props[t.nodeName] = this.recoverVariable(t.nodeValue);
}
if (props['props']) {
props = {
...props,
...getRef(props['props'])
}
}
$dom.$$('property').forEach(($p: { attrs: (arg0: string, arg1: string, arg2: string) => [any, any, any]; text: () => any; }) => {
const [name, value, valueType] = $p.attrs('name', 'value', 'valueType')
let realValue = value || $p.text();
if (valueType === 'json') {
realValue = JSON.parse(realValue);
}
props[name] = realValue;
})
return props;
}
getEventMachineComponent (refClassName: string) {
var EventMachineComponent = retriveElement(refClassName) || this.childComponents[refClassName];
return EventMachineComponent;
}
parseComponent() {
const $el = this.$el;
let targets = $el.$$(REF_CLASS_PROPERTY);
targets.forEach(($dom: IDom) => {
const EventMachineComponent = this.getEventMachineComponent($dom.attr(REF_CLASS))
if (EventMachineComponent) {
let props = this.parseProperty($dom);
// create component
let refName = $dom.attr(REFERENCE_PROPERTY);
var instance = null;
// 동일한 refName 의 EventMachine 이 존재하면 해당 컴포넌트는 다시 그려진다.
// 루트 element 는 변경되지 않는다.
if (this.children[refName]) {
instance = this.children[refName]
instance._reload(props);
} else {
// 기존의 refName 이 존재하지 않으면 Component 를 생성해서 element 를 교체한다.
instance = new EventMachineComponent(this, props);
this.children[refName || instance.id] = instance;
instance.render();
}
if (instance.renderTarget) {
instance.$el?.appendTo(instance.renderTarget);
$dom.remove();
} else {
$dom.replace(instance.$el);
}
} else {
$dom.remove();
}
})
keyEach(this.children, (key, obj) => {
if (obj && obj.clean()) {
delete this.children[key]
}
})
}
clean () {
if (this.$el && !this.$el.hasParent()) {
keyEach(this.children, (key, child) => {
child.clean();
})
this.destroy();
this.$el = null;
return true;
}
}
/**
* refresh 는 load 함수들을 실행한다.
*/
refresh() {
this.load()
}
_afterLoad () {
this.runHandlers('initialize');
this.bindData();
this.parseComponent();
}
async load(...args: string[]) {
if (!this._loadMethods) {
this._loadMethods = this.filterProps(CHECK_LOAD_PATTERN);
}
// loop 가 비동기라 await 로 대기를 시켜줘야 나머지 html 업데이트에 대한 순서를 맞출 수 있다.
const localLoadMethods = this._loadMethods.filter((callbackName: string) => {
const elName = callbackName.split(LOAD_SAPARATOR)[1]
.split(CHECK_SAPARATOR)
.map((it: string) => it.trim())[0];
if (!args.length) return true;
return args.indexOf(elName) > -1
})
await localLoadMethods.forEach(async (callbackName: string) => {
let methodName = callbackName.split(LOAD_SAPARATOR)[1];
var [elName, ...checker] = methodName.split(CHECK_SAPARATOR).map((it: string) => it.trim())
checker = checker.map((it: string) => it.trim())
const isDomDiff = Boolean(checker.filter((it: string) => DOMDIFF.includes(it)).length);
if (this.refs[elName]) {
var newTemplate = await this[callbackName].call(this, ...args);
if (Array.isArray(newTemplate)) {
newTemplate = newTemplate.join('');
}
// create fragment
const fragment = this.parseTemplate(html`${newTemplate}`, true);
if (isDomDiff) {
this.refs[elName].htmlDiff(fragment);
} else {
this.refs[elName].html(fragment);
}
}
});
this._afterLoad();
}
runHandlers(func = 'run', ...args: any[]) {
this.handlers.forEach((h: IBaseHandler) => h[func](...args));
}
bindData (...args: string[]) {
this.runHandlers('load', ...args);
}
/**
* 템플릿 지정
*
* 템플릿을 null 로 지정하면 자동으로 DocumentFragment 을 생성한다.
* 화면에는 보이지 않지만 document, window 처럼 다른 영역의 이벤트로 정의하거나 subscribe 형태로 가져올 수 있다.
*
*/
template(): string|string[]|DocumentFragment|null {
return null;
}
eachChildren(callback: Function) {
if (!isFunction(callback)) return;
keyEach(this.children, (_, Component) => {
callback(Component);
});
}
rerender () {
var $parent = this.$el.parent();
this.destroy();
this.render($parent);
}
/**
* 자원을 해제한다.
* 이것도 역시 자식 컴포넌트까지 제어하기 때문에 가장 최상위 부모에서 한번만 호출되도 된다.
*
*/
destroy() {
this.eachChildren((childComponent: IEventMachine) => {
childComponent.destroy();
});
this.runHandlers('destroy');
if (this.$el) {
this.$el.remove();
}
this.$el = null;
this.refs = {}
this.children = {}
}
/**
* property 수집하기
* 상위 클래스의 모든 property 를 수집해서 리턴한다.
*
* @returns {string[]} 나의 상위 모든 메소드를 수집해서 리턴한다.
*/
collectProps() {
if (!this.__cachedMethodList){
this.__cachedMethodList = collectProps(this, (name: string | string[]) => {
return name.indexOf(MAGIC_METHOD) === 0;
});
}
return this.__cachedMethodList;
}
filterProps(pattern: RegExp) {
return this.collectProps().filter((key: string) => {
return key.match(pattern);
});
}
/* magic check method */
self(e: any) {
return e && e.$dt && e.$dt.is(e.target);
}
isAltKey(e: any) {
return e.altKey;
}
isCtrlKey(e: any) {
return e.ctrlKey;
}
isShiftKey(e: any) {
return e.shiftKey;
}
isMetaKey(e: any) {
return e.metaKey || e.key == 'Meta' || e.code.indexOf('Meta') > -1 ;
}
isMouseLeftButton(e: any) {
return e.buttons === 1; // 1 is left button
}
isMouseRightButton(e: any) {
return e.buttons === 2; // 2 is right button
}
hasMouse(e: any) {
return e.pointerType === 'mouse';
}
hasTouch(e: any) {
return e.pointerType === 'touch';
}
hasPen(e: any) {
return e.pointerType === 'pen';
}
/** before check method */
/* after check method */
preventDefault(e: any) {
e.preventDefault();
return true;
}
stopPropagation(e: any) {
e.stopPropagation();
return true;
}
} | the_stack |
import { Fragment, useState } from 'react'
import { Dialog, Transition } from '@headlessui/react'
import {
HomeIcon,
CashIcon,
LogoutIcon,
XIcon,
MenuIcon,
ServerIcon,
AcademicCapIcon,
VideoCameraIcon,
} from '@heroicons/react/outline'
import { useLoaderData, useMatches, Form, json, Outlet, Link } from 'remix'
import type { LoaderFunction } from 'remix'
import { useSearchParams } from 'react-router-dom'
import { UserCircleIcon } from '@heroicons/react/solid'
import { Course } from '@prisma/client'
import { requireUpdatedUser } from '~/services/auth.server'
import { LogoWithText } from '~/components/logo'
import { requireActiveSubscription, requireAuthor } from '~/utils/permissions'
import { Breadcrumbs } from '~/components/breadcrumbs'
import { SideNavigationItem } from '~/utils/types'
import { UserWithSubscriptions } from '~/models/user'
import { getFirstCourse } from '~/models/course'
export const loader: LoaderFunction = async ({ request }) => {
const user = await requireUpdatedUser(request)
const course = await getFirstCourse()
return json({ user, course })
}
const navigation: SideNavigationItem[] = [
{ name: 'Beranda', href: '/dashboard/', icon: HomeIcon },
{
name: 'Pembelian',
href: '/dashboard/purchase',
icon: CashIcon,
},
{
name: 'Transaksi',
href: '/dashboard/transactions?status=submitted',
icon: ServerIcon,
permission: requireAuthor,
},
{
name: 'Kelas',
href: '/dashboard/course',
icon: VideoCameraIcon,
permission: requireActiveSubscription,
},
{ name: 'Tentang Kelas', href: '/', icon: AcademicCapIcon },
]
function classNames(...classes: string[]) {
return classes.filter(Boolean).join(' ')
}
export default function Dashboard() {
const [sidebarOpen, setSidebarOpen] = useState(false)
const matches = useMatches()
const currentPathname = matches[2]?.pathname
const [searchParams] = useSearchParams()
const { user, course } =
useLoaderData<{ user: UserWithSubscriptions; course: Course }>()
return (
<>
{/*
This example requires updating your template:
```
<html class="h-full">
<body class="h-full">
```
*/}
<div>
<Transition.Root show={sidebarOpen} as={Fragment}>
<Dialog
as="div"
className="fixed inset-0 flex z-40 lg:hidden"
onClose={setSidebarOpen}
>
<Transition.Child
as={Fragment}
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Dialog.Overlay className="fixed inset-0 bg-gray-600 bg-opacity-75" />
</Transition.Child>
<Transition.Child
as={Fragment}
enter="transition ease-in-out duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-in-out duration-300 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<div className="relative flex-1 flex flex-col max-w-xs w-full bg-white">
<Transition.Child
as={Fragment}
enter="ease-in-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in-out duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="absolute top-0 right-0 -mr-12 pt-2">
<button
type="button"
className="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white"
onClick={() => setSidebarOpen(false)}
>
<span className="sr-only">Close sidebar</span>
<XIcon
className="h-6 w-6 text-white"
aria-hidden="true"
/>
</button>
</div>
</Transition.Child>
<div className="flex-1 h-0 pt-5 pb-4 overflow-y-auto">
<LogoWithText />
<nav className="mt-5 px-2 space-y-1">
{navigation.map((item) => {
if (item.permission && !item.permission(user, course)) {
return null
}
return (
<Link
key={item.name}
to={item.href}
className={classNames(
item.href.split('?')[0] === currentPathname
? 'bg-gray-100 text-gray-900'
: 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
'group flex items-center px-2 py-2 text-base font-medium rounded-md'
)}
onClick={() => setSidebarOpen(false)}
>
<item.icon
className={classNames(
item.href.split('?')[0] === currentPathname
? 'text-gray-500'
: 'text-gray-400 group-hover:text-gray-500',
'mr-4 shrink-0 h-6 w-6'
)}
aria-hidden="true"
/>
{item.name}
</Link>
)
})}
</nav>
</div>
<div className="shrink-0 flex items-center px-2 py-2 text-base font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
<Form action="/logout" method="post">
<button
type="submit"
className="group border-l-4 border-transparent py-2 px-3 flex items-center text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-50"
>
<LogoutIcon
className="text-gray-400 group-hover:text-gray-500 mr-4 shrink-0 h-6 w-6"
aria-hidden="true"
/>
Keluar
</button>
</Form>
</div>
<div className="shrink-0 flex border-t border-gray-200 p-4">
<Link
to="/dashboard/profile"
className="shrink-0 group block"
onClick={() => setSidebarOpen(false)}
>
<div className="flex items-center">
<div>
<UserCircleIcon
className="h-10 w-10 text-gray-500"
aria-hidden="true"
/>
</div>
<div className="ml-3">
<p className="text-base font-medium text-gray-700 group-hover:text-gray-900">
{user.name}
</p>
<p className="text-sm font-medium text-gray-500 group-hover:text-gray-700">
View profile
</p>
</div>
</div>
</Link>
</div>
</div>
</Transition.Child>
<div className="shrink-0 w-14">
{/* Force sidebar to shrink to fit close icon */}
</div>
</Dialog>
</Transition.Root>
{/* Static sidebar for desktop */}
<div className="hidden lg:flex lg:w-64 lg:flex-col lg:fixed lg:inset-y-0">
{/* Sidebar component, swap this element with another sidebar if you like */}
<div className="flex-1 flex flex-col min-h-0 border-r border-gray-200 bg-white">
<div className="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto">
<LogoWithText />
<nav className="mt-5 flex-1 px-2 bg-white space-y-1">
{navigation.map((item) => {
if (item.permission && !item.permission(user, course)) {
return null
}
return (
<Link
key={item.name}
to={item.href}
className={classNames(
item.href.split('?')[0] === currentPathname
? 'bg-gray-100 text-gray-900'
: 'text-gray-600 hover:bg-gray-50 hover:text-gray-900',
'group flex items-center px-2 py-2 text-sm font-medium rounded-md'
)}
onClick={() => setSidebarOpen(false)}
>
<item.icon
className={classNames(
item.href.split('?')[0] === currentPathname
? 'text-gray-500'
: 'text-gray-400 group-hover:text-gray-500',
'mr-3 shrink-0 h-6 w-6'
)}
aria-hidden="true"
/>
{item.name}
</Link>
)
})}
</nav>
</div>
<div className="group shrink-0 flex items-center px-2 py-2 text-base font-medium rounded-md text-gray-600 hover:bg-gray-50 hover:text-gray-900">
<Form action="/logout" method="post">
<button
type="submit"
className="group border-l-4 border-transparent py-2 px-3 flex items-center text-sm font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-50"
>
<LogoutIcon
className="text-gray-400 group-hover:text-gray-500 mr-4 shrink-0 h-6 w-6"
aria-hidden="true"
/>
Keluar
</button>
</Form>
</div>
<div className="shrink-0 flex border-t border-gray-200 p-4">
<Link
to="/dashboard/profile"
className="shrink-0 w-full group block"
onClick={() => setSidebarOpen(false)}
>
<div className="flex items-center">
<div>
<UserCircleIcon
className="h-10 w-10 text-gray-500"
aria-hidden="true"
/>
</div>
<div className="ml-3">
<p className="text-sm font-medium text-gray-700 group-hover:text-gray-900">
{user.name}
</p>
<p className="text-xs font-medium text-gray-500 group-hover:text-gray-700">
View profile
</p>
</div>
</div>
</Link>
</div>
</div>
</div>
<div className="lg:pl-64 flex flex-col h-screen">
<div className="sticky top-0 z-20 lg:hidden pl-1 pt-1 sm:pl-3 sm:pt-2 bg-white">
<button
type="button"
className="-ml-0.5 -mt-0.5 h-12 w-12 inline-flex items-center justify-center rounded-md text-gray-500 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500"
onClick={() => setSidebarOpen(true)}
>
<span className="sr-only">Open sidebar</span>
<MenuIcon className="h-6 w-6" aria-hidden="true" />
</button>
<Breadcrumbs
matches={matches}
searchParams={searchParams}
className="-translate-y-1"
/>
</div>
<Outlet />
</div>
</div>
</>
)
} | the_stack |
import * as json from 'vs/base/common/json';
import { ResourceMap, getOrSet } from 'vs/base/common/map';
import * as arrays from 'vs/base/common/arrays';
import * as types from 'vs/base/common/types';
import * as objects from 'vs/base/common/objects';
import { URI, UriComponents } from 'vs/base/common/uri';
import { OVERRIDE_PROPERTY_PATTERN, ConfigurationScope, IConfigurationRegistry, Extensions, IConfigurationPropertySchema, overrideIdentifierFromKey } from 'vs/platform/configuration/common/configurationRegistry';
import { IOverrides, addToValueTree, toValuesTree, IConfigurationModel, getConfigurationValue, IConfigurationOverrides, IConfigurationData, getDefaultValues, getConfigurationKeys, removeFromValueTree, toOverrides, IConfigurationValue, ConfigurationTarget, compare, IConfigurationChangeEvent, IConfigurationChange } from 'vs/platform/configuration/common/configuration';
import { Workspace } from 'vs/platform/workspace/common/workspace';
import { Registry } from 'vs/platform/registry/common/platform';
import { Disposable } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { IFileService } from 'vs/platform/files/common/files';
import { IExtUri } from 'vs/base/common/resources';
export class ConfigurationModel implements IConfigurationModel {
private isFrozen: boolean = false;
constructor(
private _contents: any = {},
private _keys: string[] = [],
private _overrides: IOverrides[] = []
) {
}
get contents(): any {
return this.checkAndFreeze(this._contents);
}
get overrides(): IOverrides[] {
return this.checkAndFreeze(this._overrides);
}
get keys(): string[] {
return this.checkAndFreeze(this._keys);
}
isEmpty(): boolean {
return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
}
getValue<V>(section: string | undefined): V {
return section ? getConfigurationValue<any>(this.contents, section) : this.contents;
}
getOverrideValue<V>(section: string | undefined, overrideIdentifier: string): V | undefined {
const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
return overrideContents
? section ? getConfigurationValue<any>(overrideContents, section) : overrideContents
: undefined;
}
getKeysForOverrideIdentifier(identifier: string): string[] {
for (const override of this.overrides) {
if (override.identifiers.indexOf(identifier) !== -1) {
return override.keys;
}
}
return [];
}
override(identifier: string): ConfigurationModel {
const overrideContents = this.getContentsForOverrideIdentifer(identifier);
if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) {
// If there are no valid overrides, return self
return this;
}
let contents: any = {};
for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
let contentsForKey = this.contents[key];
let overrideContentsForKey = overrideContents[key];
// If there are override contents for the key, clone and merge otherwise use base contents
if (overrideContentsForKey) {
// Clone and merge only if base contents and override contents are of type object otherwise just override
if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') {
contentsForKey = objects.deepClone(contentsForKey);
this.mergeContents(contentsForKey, overrideContentsForKey);
} else {
contentsForKey = overrideContentsForKey;
}
}
contents[key] = contentsForKey;
}
return new ConfigurationModel(contents, this.keys, this.overrides);
}
merge(...others: ConfigurationModel[]): ConfigurationModel {
const contents = objects.deepClone(this.contents);
const overrides = objects.deepClone(this.overrides);
const keys = [...this.keys];
for (const other of others) {
this.mergeContents(contents, other.contents);
for (const otherOverride of other.overrides) {
const [override] = overrides.filter(o => arrays.equals(o.identifiers, otherOverride.identifiers));
if (override) {
this.mergeContents(override.contents, otherOverride.contents);
} else {
overrides.push(objects.deepClone(otherOverride));
}
}
for (const key of other.keys) {
if (keys.indexOf(key) === -1) {
keys.push(key);
}
}
}
return new ConfigurationModel(contents, keys, overrides);
}
freeze(): ConfigurationModel {
this.isFrozen = true;
return this;
}
private mergeContents(source: any, target: any): void {
for (const key of Object.keys(target)) {
if (key in source) {
if (types.isObject(source[key]) && types.isObject(target[key])) {
this.mergeContents(source[key], target[key]);
continue;
}
}
source[key] = objects.deepClone(target[key]);
}
}
private checkAndFreeze<T>(data: T): T {
if (this.isFrozen && !Object.isFrozen(data)) {
return objects.deepFreeze(data);
}
return data;
}
private getContentsForOverrideIdentifer(identifier: string): any {
for (const override of this.overrides) {
if (override.identifiers.indexOf(identifier) !== -1) {
return override.contents;
}
}
return null;
}
toJSON(): IConfigurationModel {
return {
contents: this.contents,
overrides: this.overrides,
keys: this.keys
};
}
// Update methods
public setValue(key: string, value: any) {
this.addKey(key);
addToValueTree(this.contents, key, value, e => { throw new Error(e); });
}
public removeValue(key: string): void {
if (this.removeKey(key)) {
removeFromValueTree(this.contents, key);
}
}
private addKey(key: string): void {
let index = this.keys.length;
for (let i = 0; i < index; i++) {
if (key.indexOf(this.keys[i]) === 0) {
index = i;
}
}
this.keys.splice(index, 1, key);
}
private removeKey(key: string): boolean {
let index = this.keys.indexOf(key);
if (index !== -1) {
this.keys.splice(index, 1);
return true;
}
return false;
}
}
export class DefaultConfigurationModel extends ConfigurationModel {
constructor() {
const contents = getDefaultValues();
const keys = getConfigurationKeys();
const overrides: IOverrides[] = [];
for (const key of Object.keys(contents)) {
if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
overrides.push({
identifiers: [overrideIdentifierFromKey(key).trim()],
keys: Object.keys(contents[key]),
contents: toValuesTree(contents[key], message => console.error(`Conflict in default settings file: ${message}`)),
});
}
}
super(contents, keys, overrides);
}
}
export interface ConfigurationParseOptions {
scopes: ConfigurationScope[] | undefined;
skipRestricted?: boolean;
}
export class ConfigurationModelParser {
private _raw: any = null;
private _configurationModel: ConfigurationModel | null = null;
private _restrictedConfigurations: string[] = [];
private _parseErrors: any[] = [];
constructor(protected readonly _name: string) { }
get configurationModel(): ConfigurationModel {
return this._configurationModel || new ConfigurationModel();
}
get restrictedConfigurations(): string[] {
return this._restrictedConfigurations;
}
get errors(): any[] {
return this._parseErrors;
}
public parse(content: string | null | undefined, options?: ConfigurationParseOptions): void {
if (!types.isUndefinedOrNull(content)) {
const raw = this.doParseContent(content);
this.parseRaw(raw, options);
}
}
public reparse(options: ConfigurationParseOptions): void {
if (this._raw) {
this.parseRaw(this._raw, options);
}
}
public parseRaw(raw: any, options?: ConfigurationParseOptions): void {
this._raw = raw;
const { contents, keys, overrides, restricted } = this.doParseRaw(raw, options);
this._configurationModel = new ConfigurationModel(contents, keys, overrides);
this._restrictedConfigurations = restricted || [];
}
private doParseContent(content: string): any {
let raw: any = {};
let currentProperty: string | null = null;
let currentParent: any = [];
let previousParents: any[] = [];
let parseErrors: json.ParseError[] = [];
function onValue(value: any) {
if (Array.isArray(currentParent)) {
(<any[]>currentParent).push(value);
} else if (currentProperty) {
currentParent[currentProperty] = value;
}
}
let visitor: json.JSONVisitor = {
onObjectBegin: () => {
let object = {};
onValue(object);
previousParents.push(currentParent);
currentParent = object;
currentProperty = null;
},
onObjectProperty: (name: string) => {
currentProperty = name;
},
onObjectEnd: () => {
currentParent = previousParents.pop();
},
onArrayBegin: () => {
let array: any[] = [];
onValue(array);
previousParents.push(currentParent);
currentParent = array;
currentProperty = null;
},
onArrayEnd: () => {
currentParent = previousParents.pop();
},
onLiteralValue: onValue,
onError: (error: json.ParseErrorCode, offset: number, length: number) => {
parseErrors.push({ error, offset, length });
}
};
if (content) {
try {
json.visit(content, visitor);
raw = currentParent[0] || {};
} catch (e) {
console.error(`Error while parsing settings file ${this._name}: ${e}`);
this._parseErrors = [e];
}
}
return raw;
}
protected doParseRaw(raw: any, options?: ConfigurationParseOptions): IConfigurationModel & { restricted?: string[] } {
const configurationProperties = Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties();
const filtered = this.filter(raw, configurationProperties, true, options);
raw = filtered.raw;
const contents = toValuesTree(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
const keys = Object.keys(raw);
const overrides: IOverrides[] = toOverrides(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
return { contents, keys, overrides, restricted: filtered.restricted };
}
private filter(properties: any, configurationProperties: { [qualifiedKey: string]: IConfigurationPropertySchema | undefined }, filterOverriddenProperties: boolean, options?: ConfigurationParseOptions): { raw: {}, restricted: string[] } {
if (!options?.scopes && !options?.skipRestricted) {
return { raw: properties, restricted: [] };
}
const raw: any = {};
const restricted: string[] = [];
for (let key in properties) {
if (OVERRIDE_PROPERTY_PATTERN.test(key) && filterOverriddenProperties) {
const result = this.filter(properties[key], configurationProperties, false, options);
raw[key] = result.raw;
restricted.push(...result.restricted);
} else {
const propertySchema = configurationProperties[key];
const scope = propertySchema ? typeof propertySchema.scope !== 'undefined' ? propertySchema.scope : ConfigurationScope.WINDOW : undefined;
if (propertySchema?.restricted) {
restricted.push(key);
}
// Load unregistered configurations always.
if (scope === undefined || options.scopes === undefined || options.scopes.includes(scope)) {
if (!(options.skipRestricted && propertySchema?.restricted)) {
raw[key] = properties[key];
}
}
}
}
return { raw, restricted };
}
}
export class UserSettings extends Disposable {
private readonly parser: ConfigurationModelParser;
private readonly parseOptions: ConfigurationParseOptions;
protected readonly _onDidChange: Emitter<void> = this._register(new Emitter<void>());
readonly onDidChange: Event<void> = this._onDidChange.event;
constructor(
private readonly userSettingsResource: URI,
private readonly scopes: ConfigurationScope[] | undefined,
extUri: IExtUri,
private readonly fileService: IFileService
) {
super();
this.parser = new ConfigurationModelParser(this.userSettingsResource.toString());
this.parseOptions = { scopes: this.scopes };
this._register(this.fileService.watch(extUri.dirname(this.userSettingsResource)));
// Also listen to the resource incase the resource is a symlink - https://github.com/microsoft/vscode/issues/118134
this._register(this.fileService.watch(this.userSettingsResource));
this._register(Event.filter(this.fileService.onDidFilesChange, e => e.contains(this.userSettingsResource))(() => this._onDidChange.fire()));
}
async loadConfiguration(): Promise<ConfigurationModel> {
try {
const content = await this.fileService.readFile(this.userSettingsResource);
this.parser.parse(content.value.toString() || '{}', this.parseOptions);
return this.parser.configurationModel;
} catch (e) {
return new ConfigurationModel();
}
}
reparse(): ConfigurationModel {
this.parser.reparse(this.parseOptions);
return this.parser.configurationModel;
}
getRestrictedSettings(): string[] {
return this.parser.restrictedConfigurations;
}
}
export class Configuration {
private _workspaceConsolidatedConfiguration: ConfigurationModel | null = null;
private _foldersConsolidatedConfigurations: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>();
constructor(
private _defaultConfiguration: ConfigurationModel,
private _localUserConfiguration: ConfigurationModel,
private _remoteUserConfiguration: ConfigurationModel = new ConfigurationModel(),
private _workspaceConfiguration: ConfigurationModel = new ConfigurationModel(),
private _folderConfigurations: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>(),
private _memoryConfiguration: ConfigurationModel = new ConfigurationModel(),
private _memoryConfigurationByResource: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>(),
private _freeze: boolean = true) {
}
getValue(section: string | undefined, overrides: IConfigurationOverrides, workspace: Workspace | undefined): any {
const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
return consolidateConfigurationModel.getValue(section);
}
updateValue(key: string, value: any, overrides: IConfigurationOverrides = {}): void {
let memoryConfiguration: ConfigurationModel | undefined;
if (overrides.resource) {
memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
if (!memoryConfiguration) {
memoryConfiguration = new ConfigurationModel();
this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
}
} else {
memoryConfiguration = this._memoryConfiguration;
}
if (value === undefined) {
memoryConfiguration.removeValue(key);
} else {
memoryConfiguration.setValue(key, value);
}
if (!overrides.resource) {
this._workspaceConsolidatedConfiguration = null;
}
}
inspect<C>(key: string, overrides: IConfigurationOverrides, workspace: Workspace | undefined): IConfigurationValue<C> {
const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
const defaultValue = overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : this._defaultConfiguration.freeze().getValue<C>(key);
const userValue = overrides.overrideIdentifier ? this.userConfiguration.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : this.userConfiguration.freeze().getValue<C>(key);
const userLocalValue = overrides.overrideIdentifier ? this.localUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : this.localUserConfiguration.freeze().getValue<C>(key);
const userRemoteValue = overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : this.remoteUserConfiguration.freeze().getValue<C>(key);
const workspaceValue = workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : this._workspaceConfiguration.freeze().getValue<C>(key) : undefined; //Check on workspace exists or not because _workspaceConfiguration is never null
const workspaceFolderValue = folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue<C>(key) : folderConfigurationModel.freeze().getValue<C>(key) : undefined;
const memoryValue = overrides.overrideIdentifier ? memoryConfigurationModel.override(overrides.overrideIdentifier).getValue<C>(key) : memoryConfigurationModel.getValue<C>(key);
const value = consolidateConfigurationModel.getValue<C>(key);
const overrideIdentifiers: string[] = arrays.distinct(arrays.flatten(consolidateConfigurationModel.overrides.map(override => override.identifiers))).filter(overrideIdentifier => consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== undefined);
return {
defaultValue: defaultValue,
userValue: userValue,
userLocalValue: userLocalValue,
userRemoteValue: userRemoteValue,
workspaceValue: workspaceValue,
workspaceFolderValue: workspaceFolderValue,
memoryValue: memoryValue,
value,
default: defaultValue !== undefined ? { value: this._defaultConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
user: userValue !== undefined ? { value: this.userConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.userConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
userLocal: userLocalValue !== undefined ? { value: this.localUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.localUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
userRemote: userRemoteValue !== undefined ? { value: this.remoteUserConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this.remoteUserConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
workspace: workspaceValue !== undefined ? { value: this._workspaceConfiguration.freeze().getValue(key), override: overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
workspaceFolder: workspaceFolderValue !== undefined ? { value: folderConfigurationModel?.freeze().getValue(key), override: overrides.overrideIdentifier ? folderConfigurationModel?.freeze().getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
memory: memoryValue !== undefined ? { value: memoryConfigurationModel.getValue(key), override: overrides.overrideIdentifier ? memoryConfigurationModel.getOverrideValue(key, overrides.overrideIdentifier) : undefined } : undefined,
overrideIdentifiers: overrideIdentifiers.length ? overrideIdentifiers : undefined
};
}
keys(workspace: Workspace | undefined): {
default: string[];
user: string[];
workspace: string[];
workspaceFolder: string[];
} {
const folderConfigurationModel = this.getFolderConfigurationModelForResource(undefined, workspace);
return {
default: this._defaultConfiguration.freeze().keys,
user: this.userConfiguration.freeze().keys,
workspace: this._workspaceConfiguration.freeze().keys,
workspaceFolder: folderConfigurationModel ? folderConfigurationModel.freeze().keys : []
};
}
updateDefaultConfiguration(defaultConfiguration: ConfigurationModel): void {
this._defaultConfiguration = defaultConfiguration;
this._workspaceConsolidatedConfiguration = null;
this._foldersConsolidatedConfigurations.clear();
}
updateLocalUserConfiguration(localUserConfiguration: ConfigurationModel): void {
this._localUserConfiguration = localUserConfiguration;
this._userConfiguration = null;
this._workspaceConsolidatedConfiguration = null;
this._foldersConsolidatedConfigurations.clear();
}
updateRemoteUserConfiguration(remoteUserConfiguration: ConfigurationModel): void {
this._remoteUserConfiguration = remoteUserConfiguration;
this._userConfiguration = null;
this._workspaceConsolidatedConfiguration = null;
this._foldersConsolidatedConfigurations.clear();
}
updateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): void {
this._workspaceConfiguration = workspaceConfiguration;
this._workspaceConsolidatedConfiguration = null;
this._foldersConsolidatedConfigurations.clear();
}
updateFolderConfiguration(resource: URI, configuration: ConfigurationModel): void {
this._folderConfigurations.set(resource, configuration);
this._foldersConsolidatedConfigurations.delete(resource);
}
deleteFolderConfiguration(resource: URI): void {
this.folderConfigurations.delete(resource);
this._foldersConsolidatedConfigurations.delete(resource);
}
compareAndUpdateDefaultConfiguration(defaults: ConfigurationModel, keys: string[]): IConfigurationChange {
const overrides: [string, string[]][] = keys
.filter(key => OVERRIDE_PROPERTY_PATTERN.test(key))
.map(key => {
const overrideIdentifier = overrideIdentifierFromKey(key);
const fromKeys = this._defaultConfiguration.getKeysForOverrideIdentifier(overrideIdentifier);
const toKeys = defaults.getKeysForOverrideIdentifier(overrideIdentifier);
const keys = [
...toKeys.filter(key => fromKeys.indexOf(key) === -1),
...fromKeys.filter(key => toKeys.indexOf(key) === -1),
...fromKeys.filter(key => !objects.equals(this._defaultConfiguration.override(overrideIdentifier).getValue(key), defaults.override(overrideIdentifier).getValue(key)))
];
return [overrideIdentifier, keys];
});
this.updateDefaultConfiguration(defaults);
return { keys, overrides };
}
compareAndUpdateLocalUserConfiguration(user: ConfigurationModel): IConfigurationChange {
const { added, updated, removed, overrides } = compare(this.localUserConfiguration, user);
const keys = [...added, ...updated, ...removed];
if (keys.length) {
this.updateLocalUserConfiguration(user);
}
return { keys, overrides };
}
compareAndUpdateRemoteUserConfiguration(user: ConfigurationModel): IConfigurationChange {
const { added, updated, removed, overrides } = compare(this.remoteUserConfiguration, user);
let keys = [...added, ...updated, ...removed];
if (keys.length) {
this.updateRemoteUserConfiguration(user);
}
return { keys, overrides };
}
compareAndUpdateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): IConfigurationChange {
const { added, updated, removed, overrides } = compare(this.workspaceConfiguration, workspaceConfiguration);
let keys = [...added, ...updated, ...removed];
if (keys.length) {
this.updateWorkspaceConfiguration(workspaceConfiguration);
}
return { keys, overrides };
}
compareAndUpdateFolderConfiguration(resource: URI, folderConfiguration: ConfigurationModel): IConfigurationChange {
const currentFolderConfiguration = this.folderConfigurations.get(resource);
const { added, updated, removed, overrides } = compare(currentFolderConfiguration, folderConfiguration);
let keys = [...added, ...updated, ...removed];
if (keys.length || !currentFolderConfiguration) {
this.updateFolderConfiguration(resource, folderConfiguration);
}
return { keys, overrides };
}
compareAndDeleteFolderConfiguration(folder: URI): IConfigurationChange {
const folderConfig = this.folderConfigurations.get(folder);
if (!folderConfig) {
throw new Error('Unknown folder');
}
this.deleteFolderConfiguration(folder);
const { added, updated, removed, overrides } = compare(folderConfig, undefined);
return { keys: [...added, ...updated, ...removed], overrides };
}
get defaults(): ConfigurationModel {
return this._defaultConfiguration;
}
private _userConfiguration: ConfigurationModel | null = null;
get userConfiguration(): ConfigurationModel {
if (!this._userConfiguration) {
this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
if (this._freeze) {
this._userConfiguration.freeze();
}
}
return this._userConfiguration;
}
get localUserConfiguration(): ConfigurationModel {
return this._localUserConfiguration;
}
get remoteUserConfiguration(): ConfigurationModel {
return this._remoteUserConfiguration;
}
get workspaceConfiguration(): ConfigurationModel {
return this._workspaceConfiguration;
}
protected get folderConfigurations(): ResourceMap<ConfigurationModel> {
return this._folderConfigurations;
}
private getConsolidateConfigurationModel(overrides: IConfigurationOverrides, workspace: Workspace | undefined): ConfigurationModel {
let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel;
}
private getConsolidatedConfigurationModelForResource({ resource }: IConfigurationOverrides, workspace: Workspace | undefined): ConfigurationModel {
let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
if (workspace && resource) {
const root = workspace.getFolder(resource);
if (root) {
consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
}
const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
if (memoryConfigurationForResource) {
consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
}
}
return consolidateConfiguration;
}
private getWorkspaceConsolidatedConfiguration(): ConfigurationModel {
if (!this._workspaceConsolidatedConfiguration) {
this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
if (this._freeze) {
this._workspaceConfiguration = this._workspaceConfiguration.freeze();
}
}
return this._workspaceConsolidatedConfiguration;
}
private getFolderConsolidatedConfiguration(folder: URI): ConfigurationModel {
let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
if (!folderConsolidatedConfiguration) {
const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
const folderConfiguration = this._folderConfigurations.get(folder);
if (folderConfiguration) {
folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
if (this._freeze) {
folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
}
this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
} else {
folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
}
}
return folderConsolidatedConfiguration;
}
private getFolderConfigurationModelForResource(resource: URI | null | undefined, workspace: Workspace | undefined): ConfigurationModel | undefined {
if (workspace && resource) {
const root = workspace.getFolder(resource);
if (root) {
return this._folderConfigurations.get(root.uri);
}
}
return undefined;
}
toData(): IConfigurationData {
return {
defaults: {
contents: this._defaultConfiguration.contents,
overrides: this._defaultConfiguration.overrides,
keys: this._defaultConfiguration.keys
},
user: {
contents: this.userConfiguration.contents,
overrides: this.userConfiguration.overrides,
keys: this.userConfiguration.keys
},
workspace: {
contents: this._workspaceConfiguration.contents,
overrides: this._workspaceConfiguration.overrides,
keys: this._workspaceConfiguration.keys
},
folders: [...this._folderConfigurations.keys()].reduce<[UriComponents, IConfigurationModel][]>((result, folder) => {
const { contents, overrides, keys } = this._folderConfigurations.get(folder)!;
result.push([folder, { contents, overrides, keys }]);
return result;
}, [])
};
}
allKeys(): string[] {
const keys: Set<string> = new Set<string>();
this._defaultConfiguration.freeze().keys.forEach(key => keys.add(key));
this.userConfiguration.freeze().keys.forEach(key => keys.add(key));
this._workspaceConfiguration.freeze().keys.forEach(key => keys.add(key));
this._folderConfigurations.forEach(folderConfiguraiton => folderConfiguraiton.freeze().keys.forEach(key => keys.add(key)));
return [...keys.values()];
}
protected getAllKeysForOverrideIdentifier(overrideIdentifier: string): string[] {
const keys: Set<string> = new Set<string>();
this._defaultConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach(key => keys.add(key));
this.userConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach(key => keys.add(key));
this._workspaceConfiguration.getKeysForOverrideIdentifier(overrideIdentifier).forEach(key => keys.add(key));
this._folderConfigurations.forEach(folderConfiguraiton => folderConfiguraiton.getKeysForOverrideIdentifier(overrideIdentifier).forEach(key => keys.add(key)));
return [...keys.values()];
}
static parse(data: IConfigurationData): Configuration {
const defaultConfiguration = this.parseConfigurationModel(data.defaults);
const userConfiguration = this.parseConfigurationModel(data.user);
const workspaceConfiguration = this.parseConfigurationModel(data.workspace);
const folders: ResourceMap<ConfigurationModel> = data.folders.reduce((result, value) => {
result.set(URI.revive(value[0]), this.parseConfigurationModel(value[1]));
return result;
}, new ResourceMap<ConfigurationModel>());
return new Configuration(defaultConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new ResourceMap<ConfigurationModel>(), false);
}
private static parseConfigurationModel(model: IConfigurationModel): ConfigurationModel {
return new ConfigurationModel(model.contents, model.keys, model.overrides).freeze();
}
}
export function mergeChanges(...changes: IConfigurationChange[]): IConfigurationChange {
if (changes.length === 0) {
return { keys: [], overrides: [] };
}
if (changes.length === 1) {
return changes[0];
}
const keysSet = new Set<string>();
const overridesMap = new Map<string, Set<string>>();
for (const change of changes) {
change.keys.forEach(key => keysSet.add(key));
change.overrides.forEach(([identifier, keys]) => {
const result = getOrSet(overridesMap, identifier, new Set<string>());
keys.forEach(key => result.add(key));
});
}
const overrides: [string, string[]][] = [];
overridesMap.forEach((keys, identifier) => overrides.push([identifier, [...keys.values()]]));
return { keys: [...keysSet.values()], overrides };
}
export class ConfigurationChangeEvent implements IConfigurationChangeEvent {
private readonly affectedKeysTree: any;
readonly affectedKeys: string[];
source!: ConfigurationTarget;
sourceConfig: any;
constructor(readonly change: IConfigurationChange, private readonly previous: { workspace?: Workspace, data: IConfigurationData } | undefined, private readonly currentConfiguraiton: Configuration, private readonly currentWorkspace?: Workspace) {
const keysSet = new Set<string>();
change.keys.forEach(key => keysSet.add(key));
change.overrides.forEach(([, keys]) => keys.forEach(key => keysSet.add(key)));
this.affectedKeys = [...keysSet.values()];
const configurationModel = new ConfigurationModel();
this.affectedKeys.forEach(key => configurationModel.setValue(key, {}));
this.affectedKeysTree = configurationModel.contents;
}
private _previousConfiguration: Configuration | undefined = undefined;
get previousConfiguration(): Configuration | undefined {
if (!this._previousConfiguration && this.previous) {
this._previousConfiguration = Configuration.parse(this.previous.data);
}
return this._previousConfiguration;
}
affectsConfiguration(section: string, overrides?: IConfigurationOverrides): boolean {
if (this.doesAffectedKeysTreeContains(this.affectedKeysTree, section)) {
if (overrides) {
const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, this.previous?.workspace) : undefined;
const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
return !objects.equals(value1, value2);
}
return true;
}
return false;
}
private doesAffectedKeysTreeContains(affectedKeysTree: any, section: string): boolean {
let requestedTree = toValuesTree({ [section]: true }, () => { });
let key;
while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property
affectedKeysTree = affectedKeysTree[key];
if (!affectedKeysTree) {
return false; // Requested tree is not found
}
requestedTree = requestedTree[key];
}
return true;
}
}
export class AllKeysConfigurationChangeEvent extends ConfigurationChangeEvent {
constructor(configuration: Configuration, workspace: Workspace, source: ConfigurationTarget, sourceConfig: any) {
super({ keys: configuration.allKeys(), overrides: [] }, undefined, configuration, workspace);
this.source = source;
this.sourceConfig = sourceConfig;
}
} | the_stack |
import {Color, Cursor, SignalRef, Text} from 'vega';
import {isNumber, isObject} from 'vega-util';
import {NormalizedSpec} from '.';
import {Data} from '../data';
import {ExprRef} from '../expr';
import {MarkConfig} from '../mark';
import {Resolve} from '../resolve';
import {TitleParams} from '../title';
import {Transform} from '../transform';
import {Flag, keys} from '../util';
import {LayoutAlign, RowCol} from '../vega.schema';
import {isConcatSpec, isVConcatSpec} from './concat';
import {isFacetMapping, isFacetSpec} from './facet';
export {TopLevel} from './toplevel';
/**
* Common properties for all types of specification
*/
export interface BaseSpec {
/**
* Title for the plot.
*/
title?: Text | TitleParams<ExprRef | SignalRef>;
/**
* Name of the visualization for later reference.
*/
name?: string;
/**
* Description of this mark for commenting purpose.
*/
description?: string;
/**
* An object describing the data source. Set to `null` to ignore the parent's data source. If no data is set, it is derived from the parent.
*/
data?: Data | null;
/**
* An array of data transformations such as filter and new field calculation.
*/
transform?: Transform[];
}
export interface DataMixins {
/**
* An object describing the data source.
*/
data: Data;
}
export type StepFor = 'position' | 'offset';
export interface Step {
/**
* The size (width/height) per discrete step.
*/
step: number;
/**
* Whether to apply the step to position scale or offset scale when there are both `x` and `xOffset` or both `y` and `yOffset` encodings.
*/
for?: StepFor;
}
export function getStepFor({step, offsetIsDiscrete}: {step: Step; offsetIsDiscrete: boolean}): StepFor {
if (offsetIsDiscrete) {
return step.for ?? 'offset';
} else {
return 'position';
}
}
export function isStep(size: number | Step | 'container' | 'merged'): size is Step {
return isObject(size) && size['step'] !== undefined;
}
// TODO(https://github.com/vega/vega-lite/issues/2503): Make this generic so we can support some form of top-down sizing.
/**
* Common properties for specifying width and height of unit and layer specifications.
*/
export interface LayoutSizeMixins {
/**
* The width of a visualization.
*
* - For a plot with a continuous x-field, width should be a number.
* - For a plot with either a discrete x-field or no x-field, width can be either a number indicating a fixed width or an object in the form of `{step: number}` defining the width per discrete step. (No x-field is equivalent to having one discrete step.)
* - To enable responsive sizing on width, it should be set to `"container"`.
*
* __Default value:__
* Based on `config.view.continuousWidth` for a plot with a continuous x-field and `config.view.discreteWidth` otherwise.
*
* __Note:__ For plots with [`row` and `column` channels](https://vega.github.io/vega-lite/docs/encoding.html#facet), this represents the width of a single view and the `"container"` option cannot be used.
*
* __See also:__ [`width`](https://vega.github.io/vega-lite/docs/size.html) documentation.
*/
width?: number | 'container' | Step; // Vega also supports SignalRef for width and height. However, we need to know if width is a step or not in VL and it's very difficult to check this at runtime, so we intentionally do not support SignalRef here.
/**
* The height of a visualization.
*
* - For a plot with a continuous y-field, height should be a number.
* - For a plot with either a discrete y-field or no y-field, height can be either a number indicating a fixed height or an object in the form of `{step: number}` defining the height per discrete step. (No y-field is equivalent to having one discrete step.)
* - To enable responsive sizing on height, it should be set to `"container"`.
*
* __Default value:__ Based on `config.view.continuousHeight` for a plot with a continuous y-field and `config.view.discreteHeight` otherwise.
*
* __Note:__ For plots with [`row` and `column` channels](https://vega.github.io/vega-lite/docs/encoding.html#facet), this represents the height of a single view and the `"container"` option cannot be used.
*
* __See also:__ [`height`](https://vega.github.io/vega-lite/docs/size.html) documentation.
*/
height?: number | 'container' | Step; // Vega also supports SignalRef for width and height. However, we need to know if width is a step or not in VL and it's very difficult to check this at runtime, so we intentionally do not support SignalRef here.
}
export function isFrameMixins(o: any): o is FrameMixins<any> {
return o['view'] || o['width'] || o['height'];
}
export interface FrameMixins<ES extends ExprRef | SignalRef = ExprRef | SignalRef> extends LayoutSizeMixins {
/**
* An object defining the view background's fill and stroke.
*
* __Default value:__ none (transparent)
*/
view?: ViewBackground<ES>;
}
export interface ResolveMixins {
/**
* Scale, axis, and legend resolutions for view composition specifications.
*/
resolve?: Resolve;
}
export interface BaseViewBackground<ES extends ExprRef | SignalRef>
extends Partial<
Pick<
MarkConfig<ES>,
| 'cornerRadius'
| 'fillOpacity'
| 'opacity'
| 'strokeCap'
| 'strokeDash'
| 'strokeDashOffset'
| 'strokeJoin'
| 'strokeMiterLimit'
| 'strokeOpacity'
| 'strokeWidth'
>
> {
// Override documentations for fill, stroke, and cursor
/**
* The fill color.
*
* __Default value:__ `undefined`
*/
fill?: Color | null | ES;
/**
* The stroke color.
*
* __Default value:__ `"#ddd"`
*/
stroke?: Color | null | ES;
/**
* The mouse cursor used over the view. Any valid [CSS cursor type](https://developer.mozilla.org/en-US/docs/Web/CSS/cursor#Values) can be used.
*/
cursor?: Cursor;
}
export interface ViewBackground<ES extends ExprRef | SignalRef> extends BaseViewBackground<ES> {
/**
* A string or array of strings indicating the name of custom styles to apply to the view background. A style is a named collection of mark property defaults defined within the [style configuration](https://vega.github.io/vega-lite/docs/mark.html#style-config). If style is an array, later styles will override earlier styles.
*
* __Default value:__ `"cell"`
* __Note:__ Any specified view background properties will augment the default style.
*/
style?: string | string[];
}
export interface BoundsMixins {
/**
* The bounds calculation method to use for determining the extent of a sub-plot. One of `full` (the default) or `flush`.
*
* - If set to `full`, the entire calculated bounds (including axes, title, and legend) will be used.
* - If set to `flush`, only the specified width and height values for the sub-view will be used. The `flush` setting can be useful when attempting to place sub-plots without axes or legends into a uniform grid structure.
*
* __Default value:__ `"full"`
*/
bounds?: 'full' | 'flush';
}
/**
* Base layout for FacetSpec and RepeatSpec.
* This is named "GenericComposition" layout as ConcatLayout is a GenericCompositionLayout too
* (but _not_ vice versa).
*/
export interface GenericCompositionLayout extends BoundsMixins {
/**
* The alignment to apply to grid rows and columns.
* The supported string values are `"all"`, `"each"`, and `"none"`.
*
* - For `"none"`, a flow layout will be used, in which adjacent subviews are simply placed one after the other.
* - For `"each"`, subviews will be aligned into a clean grid structure, but each row or column may be of variable size.
* - For `"all"`, subviews will be aligned and each row or column will be sized identically based on the maximum observed size. String values for this property will be applied to both grid rows and columns.
*
* Alternatively, an object value of the form `{"row": string, "column": string}` can be used to supply different alignments for rows and columns.
*
* __Default value:__ `"all"`.
*/
align?: LayoutAlign | RowCol<LayoutAlign>;
/**
* Boolean flag indicating if subviews should be centered relative to their respective rows or columns.
*
* An object value of the form `{"row": boolean, "column": boolean}` can be used to supply different centering values for rows and columns.
*
* __Default value:__ `false`
*/
center?: boolean | RowCol<boolean>;
/**
* The spacing in pixels between sub-views of the composition operator.
* An object of the form `{"row": number, "column": number}` can be used to set
* different spacing values for rows and columns.
*
* __Default value__: Depends on `"spacing"` property of [the view composition configuration](https://vega.github.io/vega-lite/docs/config.html#view-config) (`20` by default)
*/
spacing?: number | RowCol<number>;
}
export const DEFAULT_SPACING = 20;
export interface ColumnMixins {
/**
* The number of columns to include in the view composition layout.
*
* __Default value__: `undefined` -- An infinite number of columns (a single row) will be assumed. This is equivalent to
* `hconcat` (for `concat`) and to using the `column` channel (for `facet` and `repeat`).
*
* __Note__:
*
* 1) This property is only for:
* - the general (wrappable) `concat` operator (not `hconcat`/`vconcat`)
* - the `facet` and `repeat` operator with one field/repetition definition (without row/column nesting)
*
* 2) Setting the `columns` to `1` is equivalent to `vconcat` (for `concat`) and to using the `row` channel (for `facet` and `repeat`).
*/
columns?: number;
}
export type GenericCompositionLayoutWithColumns = GenericCompositionLayout & ColumnMixins;
export type CompositionConfig = ColumnMixins & {
/**
* The default spacing in pixels between composed sub-views.
*
* __Default value__: `20`
*/
spacing?: number;
};
export interface CompositionConfigMixins {
/** Default configuration for the `facet` view composition operator */
facet?: CompositionConfig;
/** Default configuration for all concatenation and repeat view composition operators (`concat`, `hconcat`, `vconcat`, and `repeat`) */
concat?: CompositionConfig;
}
const COMPOSITION_LAYOUT_INDEX: Flag<keyof GenericCompositionLayoutWithColumns> = {
align: 1,
bounds: 1,
center: 1,
columns: 1,
spacing: 1
};
const COMPOSITION_LAYOUT_PROPERTIES = keys(COMPOSITION_LAYOUT_INDEX);
export type SpecType = 'unit' | 'facet' | 'layer' | 'concat';
export function extractCompositionLayout(
spec: NormalizedSpec,
specType: keyof CompositionConfigMixins,
config: CompositionConfigMixins
): GenericCompositionLayoutWithColumns {
const compositionConfig = config[specType];
const layout: GenericCompositionLayoutWithColumns = {};
// Apply config first
const {spacing: spacingConfig, columns} = compositionConfig;
if (spacingConfig !== undefined) {
layout.spacing = spacingConfig;
}
if (columns !== undefined) {
if ((isFacetSpec(spec) && !isFacetMapping(spec.facet)) || isConcatSpec(spec)) {
layout.columns = columns;
}
}
if (isVConcatSpec(spec)) {
layout.columns = 1;
}
// Then copy properties from the spec
for (const prop of COMPOSITION_LAYOUT_PROPERTIES) {
if (spec[prop] !== undefined) {
if (prop === 'spacing') {
const spacing: number | RowCol<number> = spec[prop];
layout[prop] = isNumber(spacing)
? spacing
: {
row: spacing.row ?? spacingConfig,
column: spacing.column ?? spacingConfig
};
} else {
(layout[prop] as any) = spec[prop];
}
}
}
return layout;
} | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { UsersAPIClientInterface } from './users-api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, UsersAPIClient } from './users-api-client.service';
import { DefaultHttpOptions, HttpOptions } from '../../types';
import * as models from '../../models';
import * as guards from '../../guards';
@Injectable()
export class GuardedUsersAPIClient extends UsersAPIClient implements UsersAPIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* Get all users.
* This provides a dump of every user, in the order that they signed up for GitHub.
* Note: Pagination is powered exclusively by the since parameter. Use the Link
* header to get the URL for the next page of users.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUsers(
args?: UsersAPIClientInterface['getUsersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getUsers(
args?: UsersAPIClientInterface['getUsersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getUsers(
args?: UsersAPIClientInterface['getUsersParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getUsers(
args: UsersAPIClientInterface['getUsersParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
return super.getUsers(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res)));
}
/**
* Get a single user.
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsername(
args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getUsersUsername(
args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getUsersUsername(
args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getUsersUsername(
args: Exclude<UsersAPIClientInterface['getUsersUsernameParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
return super.getUsersUsername(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res)));
}
/**
* If you are authenticated as the given user, you will see your private events. Otherwise, you'll only see public events.
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameEvents(args, requestHttpOptions, observe);
}
/**
* This is the user's organization dashboard. You must be authenticated as the user to view this.
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameEventsOrg(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameEventsOrg(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameEventsOrg(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameEventsOrg(
args: Exclude<UsersAPIClientInterface['getUsersUsernameEventsOrgParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameEventsOrg(args, requestHttpOptions, observe);
}
/**
* List a user's followers
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsernameFollowers(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Users>;
getUsersUsernameFollowers(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Users>>;
getUsersUsernameFollowers(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Users>>;
getUsersUsernameFollowers(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowersParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Users | HttpResponse<models.Users> | HttpEvent<models.Users>> {
return super.getUsersUsernameFollowers(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUsers(res) || console.error(`TypeGuard for response 'models.Users' caught inconsistency.`, res)));
}
/**
* Check if one user follows another.
* Response generated for [ 204 ] HTTP response code.
*/
getUsersUsernameFollowingTargetUser(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameFollowingTargetUser(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameFollowingTargetUser(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameFollowingTargetUser(
args: Exclude<UsersAPIClientInterface['getUsersUsernameFollowingTargetUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameFollowingTargetUser(args, requestHttpOptions, observe);
}
/**
* List a users gists.
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsernameGists(
args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gists>;
getUsersUsernameGists(
args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gists>>;
getUsersUsernameGists(
args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gists>>;
getUsersUsernameGists(
args: Exclude<UsersAPIClientInterface['getUsersUsernameGistsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gists | HttpResponse<models.Gists> | HttpEvent<models.Gists>> {
return super.getUsersUsernameGists(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGists(res) || console.error(`TypeGuard for response 'models.Gists' caught inconsistency.`, res)));
}
/**
* List public keys for a user.
* Lists the verified public keys for a user. This is accessible by anyone.
*
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsernameKeys(
args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gitignore>;
getUsersUsernameKeys(
args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gitignore>>;
getUsersUsernameKeys(
args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gitignore>>;
getUsersUsernameKeys(
args: Exclude<UsersAPIClientInterface['getUsersUsernameKeysParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> {
return super.getUsersUsernameKeys(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGitignore(res) || console.error(`TypeGuard for response 'models.Gitignore' caught inconsistency.`, res)));
}
/**
* List all public organizations for a user.
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsernameOrgs(
args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Gitignore>;
getUsersUsernameOrgs(
args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Gitignore>>;
getUsersUsernameOrgs(
args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Gitignore>>;
getUsersUsernameOrgs(
args: Exclude<UsersAPIClientInterface['getUsersUsernameOrgsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Gitignore | HttpResponse<models.Gitignore> | HttpEvent<models.Gitignore>> {
return super.getUsersUsernameOrgs(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isGitignore(res) || console.error(`TypeGuard for response 'models.Gitignore' caught inconsistency.`, res)));
}
/**
* These are events that you'll only see public events.
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameReceivedEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameReceivedEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameReceivedEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameReceivedEvents(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameReceivedEvents(args, requestHttpOptions, observe);
}
/**
* List public events that a user has received
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameReceivedEventsPublic(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameReceivedEventsPublic(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameReceivedEventsPublic(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameReceivedEventsPublic(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReceivedEventsPublicParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameReceivedEventsPublic(args, requestHttpOptions, observe);
}
/**
* List public repositories for the specified user.
* Response generated for [ 200 ] HTTP response code.
*/
getUsersUsernameRepos(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Repos>;
getUsersUsernameRepos(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Repos>>;
getUsersUsernameRepos(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Repos>>;
getUsersUsernameRepos(
args: Exclude<UsersAPIClientInterface['getUsersUsernameReposParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Repos | HttpResponse<models.Repos> | HttpEvent<models.Repos>> {
return super.getUsersUsernameRepos(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isRepos(res) || console.error(`TypeGuard for response 'models.Repos' caught inconsistency.`, res)));
}
/**
* List repositories being starred by a user.
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameStarred(
args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameStarred(
args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameStarred(
args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameStarred(
args: Exclude<UsersAPIClientInterface['getUsersUsernameStarredParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameStarred(args, requestHttpOptions, observe);
}
/**
* List repositories being watched by a user.
* Response generated for [ default ] HTTP response code.
*/
getUsersUsernameSubscriptions(
args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
getUsersUsernameSubscriptions(
args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
getUsersUsernameSubscriptions(
args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
getUsersUsernameSubscriptions(
args: Exclude<UsersAPIClientInterface['getUsersUsernameSubscriptionsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.getUsersUsernameSubscriptions(args, requestHttpOptions, observe);
}
} | the_stack |
import { DisposableStore } from 'vs/base/common/lifecycle';
import { URI as uri, UriComponents } from 'vs/base/common/uri';
import { IDebugService, IConfig, IDebugConfigurationProvider, IBreakpoint, IFunctionBreakpoint, IBreakpointData, IDebugAdapter, IDebugAdapterDescriptorFactory, IDebugSession, IDebugAdapterFactory, IDataBreakpoint, IDebugSessionOptions, IInstructionBreakpoint } from 'vs/workbench/contrib/debug/common/debug';
import {
ExtHostContext, ExtHostDebugServiceShape, MainThreadDebugServiceShape, DebugSessionUUID, MainContext,
IExtHostContext, IBreakpointsDeltaDto, ISourceMultiBreakpointDto, ISourceBreakpointDto, IFunctionBreakpointDto, IDebugSessionDto, IDataBreakpointDto, IStartDebuggingOptions, IDebugConfiguration
} from 'vs/workbench/api/common/extHost.protocol';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import severity from 'vs/base/common/severity';
import { AbstractDebugAdapter } from 'vs/workbench/contrib/debug/common/abstractDebugAdapter';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { convertToVSCPaths, convertToDAPaths } from 'vs/workbench/contrib/debug/common/debugUtils';
import { DebugConfigurationProviderTriggerKind } from 'vs/workbench/api/common/extHostTypes';
@extHostNamedCustomer(MainContext.MainThreadDebugService)
export class MainThreadDebugService implements MainThreadDebugServiceShape, IDebugAdapterFactory {
private readonly _proxy: ExtHostDebugServiceShape;
private readonly _toDispose = new DisposableStore();
private _breakpointEventsActive: boolean | undefined;
private readonly _debugAdapters: Map<number, ExtensionHostDebugAdapter>;
private _debugAdaptersHandleCounter = 1;
private readonly _debugConfigurationProviders: Map<number, IDebugConfigurationProvider>;
private readonly _debugAdapterDescriptorFactories: Map<number, IDebugAdapterDescriptorFactory>;
private readonly _sessions: Set<DebugSessionUUID>;
constructor(
extHostContext: IExtHostContext,
@IDebugService private readonly debugService: IDebugService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostDebugService);
this._toDispose.add(debugService.onDidNewSession(session => {
this._proxy.$acceptDebugSessionStarted(this.getSessionDto(session));
this._toDispose.add(session.onDidChangeName(name => {
this._proxy.$acceptDebugSessionNameChanged(this.getSessionDto(session), name);
}));
}));
// Need to start listening early to new session events because a custom event can come while a session is initialising
this._toDispose.add(debugService.onWillNewSession(session => {
this._toDispose.add(session.onDidCustomEvent(event => this._proxy.$acceptDebugSessionCustomEvent(this.getSessionDto(session), event)));
}));
this._toDispose.add(debugService.onDidEndSession(session => {
this._proxy.$acceptDebugSessionTerminated(this.getSessionDto(session));
this._sessions.delete(session.getId());
}));
this._toDispose.add(debugService.getViewModel().onDidFocusSession(session => {
this._proxy.$acceptDebugSessionActiveChanged(this.getSessionDto(session));
}));
this._debugAdapters = new Map();
this._debugConfigurationProviders = new Map();
this._debugAdapterDescriptorFactories = new Map();
this._sessions = new Set();
}
public dispose(): void {
this._toDispose.dispose();
}
// interface IDebugAdapterProvider
createDebugAdapter(session: IDebugSession): IDebugAdapter {
const handle = this._debugAdaptersHandleCounter++;
const da = new ExtensionHostDebugAdapter(this, handle, this._proxy, session);
this._debugAdapters.set(handle, da);
return da;
}
substituteVariables(folder: IWorkspaceFolder | undefined, config: IConfig): Promise<IConfig> {
return Promise.resolve(this._proxy.$substituteVariables(folder ? folder.uri : undefined, config));
}
runInTerminal(args: DebugProtocol.RunInTerminalRequestArguments, sessionId: string): Promise<number | undefined> {
return this._proxy.$runInTerminal(args, sessionId);
}
// RPC methods (MainThreadDebugServiceShape)
public $registerDebugTypes(debugTypes: string[]) {
this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterFactory(debugTypes, this));
}
public $startBreakpointEvents(): void {
if (!this._breakpointEventsActive) {
this._breakpointEventsActive = true;
// set up a handler to send more
this._toDispose.add(this.debugService.getModel().onDidChangeBreakpoints(e => {
// Ignore session only breakpoint events since they should only reflect in the UI
if (e && !e.sessionOnly) {
const delta: IBreakpointsDeltaDto = {};
if (e.added) {
delta.added = this.convertToDto(e.added);
}
if (e.removed) {
delta.removed = e.removed.map(x => x.getId());
}
if (e.changed) {
delta.changed = this.convertToDto(e.changed);
}
if (delta.added || delta.removed || delta.changed) {
this._proxy.$acceptBreakpointsDelta(delta);
}
}
}));
// send all breakpoints
const bps = this.debugService.getModel().getBreakpoints();
const fbps = this.debugService.getModel().getFunctionBreakpoints();
const dbps = this.debugService.getModel().getDataBreakpoints();
if (bps.length > 0 || fbps.length > 0) {
this._proxy.$acceptBreakpointsDelta({
added: this.convertToDto(bps).concat(this.convertToDto(fbps)).concat(this.convertToDto(dbps))
});
}
}
}
public $registerBreakpoints(DTOs: Array<ISourceMultiBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto>): Promise<void> {
for (let dto of DTOs) {
if (dto.type === 'sourceMulti') {
const rawbps = dto.lines.map(l =>
<IBreakpointData>{
id: l.id,
enabled: l.enabled,
lineNumber: l.line + 1,
column: l.character > 0 ? l.character + 1 : undefined, // a column value of 0 results in an omitted column attribute; see #46784
condition: l.condition,
hitCondition: l.hitCondition,
logMessage: l.logMessage
}
);
this.debugService.addBreakpoints(uri.revive(dto.uri), rawbps);
} else if (dto.type === 'function') {
this.debugService.addFunctionBreakpoint(dto.functionName, dto.id);
} else if (dto.type === 'data') {
this.debugService.addDataBreakpoint(dto.label, dto.dataId, dto.canPersist, dto.accessTypes, dto.accessType);
}
}
return Promise.resolve();
}
public $unregisterBreakpoints(breakpointIds: string[], functionBreakpointIds: string[], dataBreakpointIds: string[]): Promise<void> {
breakpointIds.forEach(id => this.debugService.removeBreakpoints(id));
functionBreakpointIds.forEach(id => this.debugService.removeFunctionBreakpoints(id));
dataBreakpointIds.forEach(id => this.debugService.removeDataBreakpoints(id));
return Promise.resolve();
}
public $registerDebugConfigurationProvider(debugType: string, providerTriggerKind: DebugConfigurationProviderTriggerKind, hasProvide: boolean, hasResolve: boolean, hasResolve2: boolean, handle: number): Promise<void> {
const provider = <IDebugConfigurationProvider>{
type: debugType,
triggerKind: providerTriggerKind
};
if (hasProvide) {
provider.provideDebugConfigurations = (folder, token) => {
return this._proxy.$provideDebugConfigurations(handle, folder, token);
};
}
if (hasResolve) {
provider.resolveDebugConfiguration = (folder, config, token) => {
return this._proxy.$resolveDebugConfiguration(handle, folder, config, token);
};
}
if (hasResolve2) {
provider.resolveDebugConfigurationWithSubstitutedVariables = (folder, config, token) => {
return this._proxy.$resolveDebugConfigurationWithSubstitutedVariables(handle, folder, config, token);
};
}
this._debugConfigurationProviders.set(handle, provider);
this._toDispose.add(this.debugService.getConfigurationManager().registerDebugConfigurationProvider(provider));
return Promise.resolve(undefined);
}
public $unregisterDebugConfigurationProvider(handle: number): void {
const provider = this._debugConfigurationProviders.get(handle);
if (provider) {
this._debugConfigurationProviders.delete(handle);
this.debugService.getConfigurationManager().unregisterDebugConfigurationProvider(provider);
}
}
public $registerDebugAdapterDescriptorFactory(debugType: string, handle: number): Promise<void> {
const provider = <IDebugAdapterDescriptorFactory>{
type: debugType,
createDebugAdapterDescriptor: session => {
return Promise.resolve(this._proxy.$provideDebugAdapter(handle, this.getSessionDto(session)));
}
};
this._debugAdapterDescriptorFactories.set(handle, provider);
this._toDispose.add(this.debugService.getAdapterManager().registerDebugAdapterDescriptorFactory(provider));
return Promise.resolve(undefined);
}
public $unregisterDebugAdapterDescriptorFactory(handle: number): void {
const provider = this._debugAdapterDescriptorFactories.get(handle);
if (provider) {
this._debugAdapterDescriptorFactories.delete(handle);
this.debugService.getAdapterManager().unregisterDebugAdapterDescriptorFactory(provider);
}
}
private getSession(sessionId: DebugSessionUUID | undefined): IDebugSession | undefined {
if (sessionId) {
return this.debugService.getModel().getSession(sessionId, true);
}
return undefined;
}
public async $startDebugging(folder: UriComponents | undefined, nameOrConfig: string | IDebugConfiguration, options: IStartDebuggingOptions): Promise<boolean> {
const folderUri = folder ? uri.revive(folder) : undefined;
const launch = this.debugService.getConfigurationManager().getLaunch(folderUri);
const parentSession = this.getSession(options.parentSessionID);
const debugOptions: IDebugSessionOptions = {
noDebug: options.noDebug,
parentSession,
lifecycleManagedByParent: options.lifecycleManagedByParent,
repl: options.repl,
compact: options.compact,
debugUI: options.debugUI,
compoundRoot: parentSession?.compoundRoot
};
try {
const saveBeforeStart = typeof options.suppressSaveBeforeStart === 'boolean' ? !options.suppressSaveBeforeStart : undefined;
return this.debugService.startDebugging(launch, nameOrConfig, debugOptions, saveBeforeStart);
} catch (err) {
throw new Error(err && err.message ? err.message : 'cannot start debugging');
}
}
public $setDebugSessionName(sessionId: DebugSessionUUID, name: string): void {
const session = this.debugService.getModel().getSession(sessionId);
if (session) {
session.setName(name);
}
}
public $customDebugAdapterRequest(sessionId: DebugSessionUUID, request: string, args: any): Promise<any> {
const session = this.debugService.getModel().getSession(sessionId, true);
if (session) {
return session.customRequest(request, args).then(response => {
if (response && response.success) {
return response.body;
} else {
return Promise.reject(new Error(response ? response.message : 'custom request failed'));
}
});
}
return Promise.reject(new Error('debug session not found'));
}
public $getDebugProtocolBreakpoint(sessionId: DebugSessionUUID, breakpoinId: string): Promise<DebugProtocol.Breakpoint | undefined> {
const session = this.debugService.getModel().getSession(sessionId, true);
if (session) {
return Promise.resolve(session.getDebugProtocolBreakpoint(breakpoinId));
}
return Promise.reject(new Error('debug session not found'));
}
public $stopDebugging(sessionId: DebugSessionUUID | undefined): Promise<void> {
if (sessionId) {
const session = this.debugService.getModel().getSession(sessionId, true);
if (session) {
return this.debugService.stopSession(session);
}
} else { // stop all
return this.debugService.stopSession(undefined);
}
return Promise.reject(new Error('debug session not found'));
}
public $appendDebugConsole(value: string): void {
// Use warning as severity to get the orange color for messages coming from the debug extension
const session = this.debugService.getViewModel().focusedSession;
if (session) {
session.appendToRepl(value, severity.Warning);
}
}
public $acceptDAMessage(handle: number, message: DebugProtocol.ProtocolMessage) {
this.getDebugAdapter(handle).acceptMessage(convertToVSCPaths(message, false));
}
public $acceptDAError(handle: number, name: string, message: string, stack: string) {
this.getDebugAdapter(handle).fireError(handle, new Error(`${name}: ${message}\n${stack}`));
}
public $acceptDAExit(handle: number, code: number, signal: string) {
this.getDebugAdapter(handle).fireExit(handle, code, signal);
}
private getDebugAdapter(handle: number): ExtensionHostDebugAdapter {
const adapter = this._debugAdapters.get(handle);
if (!adapter) {
throw new Error('Invalid debug adapter');
}
return adapter;
}
// dto helpers
public $sessionCached(sessionID: string) {
// remember that the EH has cached the session and we do not have to send it again
this._sessions.add(sessionID);
}
getSessionDto(session: undefined): undefined;
getSessionDto(session: IDebugSession): IDebugSessionDto;
getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined;
getSessionDto(session: IDebugSession | undefined): IDebugSessionDto | undefined {
if (session) {
const sessionID = <DebugSessionUUID>session.getId();
if (this._sessions.has(sessionID)) {
return sessionID;
} else {
// this._sessions.add(sessionID); // #69534: see $sessionCached above
return {
id: sessionID,
type: session.configuration.type,
name: session.name,
folderUri: session.root ? session.root.uri : undefined,
configuration: session.configuration,
parent: session.parentSession?.getId(),
};
}
}
return undefined;
}
private convertToDto(bps: (ReadonlyArray<IBreakpoint | IFunctionBreakpoint | IDataBreakpoint | IInstructionBreakpoint>)): Array<ISourceBreakpointDto | IFunctionBreakpointDto | IDataBreakpointDto> {
return bps.map(bp => {
if ('name' in bp) {
const fbp = <IFunctionBreakpoint>bp;
return <IFunctionBreakpointDto>{
type: 'function',
id: fbp.getId(),
enabled: fbp.enabled,
condition: fbp.condition,
hitCondition: fbp.hitCondition,
logMessage: fbp.logMessage,
functionName: fbp.name
};
} else if ('dataId' in bp) {
const dbp = <IDataBreakpoint>bp;
return <IDataBreakpointDto>{
type: 'data',
id: dbp.getId(),
dataId: dbp.dataId,
enabled: dbp.enabled,
condition: dbp.condition,
hitCondition: dbp.hitCondition,
logMessage: dbp.logMessage,
label: dbp.description,
canPersist: dbp.canPersist
};
} else {
const sbp = <IBreakpoint>bp;
return <ISourceBreakpointDto>{
type: 'source',
id: sbp.getId(),
enabled: sbp.enabled,
condition: sbp.condition,
hitCondition: sbp.hitCondition,
logMessage: sbp.logMessage,
uri: sbp.uri,
line: sbp.lineNumber > 0 ? sbp.lineNumber - 1 : 0,
character: (typeof sbp.column === 'number' && sbp.column > 0) ? sbp.column - 1 : 0,
};
}
});
}
}
/**
* DebugAdapter that communicates via extension protocol with another debug adapter.
*/
class ExtensionHostDebugAdapter extends AbstractDebugAdapter {
constructor(private readonly _ds: MainThreadDebugService, private _handle: number, private _proxy: ExtHostDebugServiceShape, private _session: IDebugSession) {
super();
}
fireError(handle: number, err: Error) {
this._onError.fire(err);
}
fireExit(handle: number, code: number, signal: string) {
this._onExit.fire(code);
}
startSession(): Promise<void> {
return Promise.resolve(this._proxy.$startDASession(this._handle, this._ds.getSessionDto(this._session)));
}
sendMessage(message: DebugProtocol.ProtocolMessage): void {
this._proxy.$sendDAMessage(this._handle, convertToDAPaths(message, true));
}
async stopSession(): Promise<void> {
await this.cancelPendingRequests();
return Promise.resolve(this._proxy.$stopDASession(this._handle));
}
} | the_stack |
import * as ko from "knockout";
import * as _ from "underscore";
import * as Constants from "../Constants";
import * as ViewModels from "../../../Contracts/ViewModels";
import * as DataTableBuilder from "./DataTableBuilder";
import DataTableOperationManager from "./DataTableOperationManager";
import * as DataTableOperations from "./DataTableOperations";
import QueryTablesTab from "../../Tabs/QueryTablesTab";
import TableEntityListViewModel from "./TableEntityListViewModel";
import * as Utilities from "../Utilities";
import * as Entities from "../Entities";
/**
* Custom binding manager of datatable
*/
var tableEntityListViewModelMap: {
[key: string]: {
tableViewModel: TableEntityListViewModel;
operationManager: DataTableOperationManager;
$dataTable: JQuery;
};
} = {};
function bindDataTable(element: any, valueAccessor: any, allBindings: any, viewModel: any, bindingContext: any) {
var tableEntityListViewModel = bindingContext.$data;
tableEntityListViewModel.notifyColumnChanges = onTableColumnChange;
var $dataTable = $(element);
var queryTablesTab = bindingContext.$parent;
var operationManager = new DataTableOperationManager(
$dataTable,
tableEntityListViewModel,
queryTablesTab.tableCommands
);
tableEntityListViewModelMap[queryTablesTab.tabId] = {
tableViewModel: tableEntityListViewModel,
operationManager: operationManager,
$dataTable: $dataTable,
};
createDataTable(0, tableEntityListViewModel, queryTablesTab); // Fake a DataTable to start.
$(window).resize(updateTableScrollableRegionMetrics);
operationManager.focusTable(); // Also selects the first row if needed.
}
function onTableColumnChange(enablePrompt: boolean = true, queryTablesTab: QueryTablesTab) {
var columnsFilter: boolean[] = null;
var tableEntityListViewModel = tableEntityListViewModelMap[queryTablesTab.tabId].tableViewModel;
if (queryTablesTab.queryViewModel()) {
queryTablesTab.queryViewModel().queryBuilderViewModel().updateColumnOptions();
}
createDataTable(
tableEntityListViewModel.tablePageStartIndex,
tableEntityListViewModel,
queryTablesTab,
true,
columnsFilter
);
}
function createDataTable(
startIndex: number,
tableEntityListViewModel: TableEntityListViewModel,
queryTablesTab: QueryTablesTab,
destroy: boolean = false,
columnsFilter: boolean[] = null
): void {
var $dataTable = tableEntityListViewModelMap[queryTablesTab.tabId].$dataTable;
if (destroy) {
// Find currently displayed columns.
var currentColumns: string[] = tableEntityListViewModel.headers;
// Calculate how many more columns need to added to the current table.
var columnsToAdd: number = _.difference(tableEntityListViewModel.headers, currentColumns).length;
// This is needed as current solution of adding column is more like a workaround
// The official support for dynamically add column is not yet there
// Please track github issue https://github.com/DataTables/DataTables/issues/273 for its offical support
for (var i = 0; i < columnsToAdd; i++) {
$(".dataTables_scrollHead table thead tr th").eq(0).after("<th></th>");
}
tableEntityListViewModel.table.destroy();
$dataTable.empty();
}
var jsonColTable = [];
for (var i = 0; i < tableEntityListViewModel.headers.length; i++) {
jsonColTable.push({
sTitle: tableEntityListViewModel.headers[i],
data: tableEntityListViewModel.headers[i],
aTargets: [i],
mRender: bindColumn,
visible: !!columnsFilter ? columnsFilter[i] : true,
});
}
tableEntityListViewModel.table = DataTableBuilder.createDataTable($dataTable, <DataTables.Settings>{
// WARNING!!! SECURITY: If you add new columns, make sure you encode them if they are user strings from Azure (see encodeText)
// so that they don't get interpreted as HTML in our page.
colReorder: true,
aoColumnDefs: jsonColTable,
stateSave: false,
dom: "RZlfrtip",
oColReorder: {
iFixedColumns: 1,
},
displayStart: startIndex,
bPaginate: true,
pagingType: "full_numbers",
bProcessing: true,
oLanguage: {
sInfo: "Results _START_ - _END_ of _TOTAL_",
oPaginate: {
sFirst: "<<",
sNext: ">",
sPrevious: "<",
sLast: ">>",
},
sProcessing: '<img style="width: 28px; height: 6px; " src="images/LoadingIndicator_3Squares.gif">',
oAria: {
sSortAscending: "",
sSortDescending: "",
},
},
destroy: destroy,
bInfo: true,
bLength: false,
bLengthChange: false,
scrollX: true,
scrollCollapse: true,
iDisplayLength: 100,
serverSide: true,
ajax: queryTablesTab.tabId, // Using this settings to make sure for getServerData we update the table based on the appropriate tab
fnServerData: getServerData,
fnRowCallback: bindClientId,
fnInitComplete: initializeTable,
fnDrawCallback: updateSelectionStatus,
});
(tableEntityListViewModel.table.table(0).container() as Element)
.querySelectorAll(Constants.htmlSelectors.dataTableHeaderTableSelector)
.forEach((table) => {
table.setAttribute(
"summary",
`Header for sorting results for container ${tableEntityListViewModel.queryTablesTab.collection.id()}`
);
});
(tableEntityListViewModel.table.table(0).container() as Element)
.querySelectorAll(Constants.htmlSelectors.dataTableBodyTableSelector)
.forEach((table) => {
table.setAttribute("summary", `Results for container ${tableEntityListViewModel.queryTablesTab.collection.id()}`);
});
}
function bindColumn(data: any, type: string, full: any) {
var displayedValue: any = null;
if (data) {
displayedValue = data._;
// SECURITY: Make sure we don't allow cross-site scripting by interpreting the values as HTML
displayedValue = Utilities.htmlEncode(displayedValue);
// Css' empty psuedo class can only tell the difference of whether a cell has values.
// A cell has no values no matter it's empty or it has no such a property.
// To distinguish between an empty cell and a non-existing property cell,
// we add a whitespace to the empty cell so that css will treat it as a cell with values.
if (displayedValue === "" && data.$ === Constants.TableType.String) {
displayedValue = " ";
}
}
return displayedValue;
}
function getServerData(sSource: any, aoData: any, fnCallback: any, oSettings: any) {
tableEntityListViewModelMap[oSettings.ajax].tableViewModel.renderNextPageAndupdateCache(
sSource,
aoData,
fnCallback,
oSettings
);
}
/**
* Bind table data information to row element so that we can track back to the table data
* from UI elements.
*/
function bindClientId(nRow: Node, aData: Entities.ITableEntity) {
$(nRow).attr(Constants.htmlAttributeNames.dataTableRowKeyAttr, aData.RowKey._);
return nRow;
}
function selectionChanged(element: any, valueAccessor: any, allBindings: any, viewModel: any, bindingContext: any) {
$(".dataTable tr.selected").attr("tabindex", "-1").removeClass("selected");
const selected =
bindingContext && bindingContext.$data && bindingContext.$data.selected && bindingContext.$data.selected();
selected &&
selected.forEach((b: Entities.ITableEntity) => {
var sel = DataTableOperations.getRowSelector([
{
key: Constants.htmlAttributeNames.dataTableRowKeyAttr,
value: b.RowKey && b.RowKey._ && b.RowKey._.toString(),
},
]);
$(sel).attr("tabindex", "0").focus().addClass("selected");
});
//selected = bindingContext.$data.selected();
}
function dataChanged(element: any, valueAccessor: any, allBindings: any, viewModel: any, bindingContext: any) {
// do nothing for now
}
function initializeTable(): void {
updateTableScrollableRegionMetrics();
initializeEventHandlers();
}
function updateTableScrollableRegionMetrics(): void {
updateTableScrollableRegionHeight();
updateTableScrollableRegionWidth();
}
/*
* Update the table's scrollable region height. So the pagination control is always shown at the bottom of the page.
*/
function updateTableScrollableRegionHeight(): void {
$(".tab-pane").each(function (index, tabElement) {
if (!$(tabElement).hasClass("tableContainer")) {
return;
}
// Add some padding to the table so it doesn't get too close to the container border.
var dataTablePaddingBottom = 10;
var bodyHeight = $(window).height();
var dataTablesScrollBodyPosY = $(tabElement).find(Constants.htmlSelectors.dataTableScrollBodySelector).offset().top;
var dataTablesInfoElem = $(tabElement).find(".dataTables_info");
var dataTablesPaginateElem = $(tabElement).find(".dataTables_paginate");
const notificationConsoleHeight = 32; /** Header height **/
var scrollHeight =
bodyHeight -
dataTablesScrollBodyPosY -
dataTablesPaginateElem.outerHeight(true) -
dataTablePaddingBottom -
notificationConsoleHeight;
//info and paginate control are stacked
if (dataTablesInfoElem.offset().top < dataTablesPaginateElem.offset().top) {
scrollHeight -= dataTablesInfoElem.outerHeight(true);
}
// TODO This is a work around for setting the outerheight since we don't have access to the JQuery.outerheight(numberValue)
// in the current version of JQuery we are using. Ideally, we would upgrade JQuery and use this line instead:
// $(Constants.htmlSelectors.dataTableScrollBodySelector).outerHeight(scrollHeight);
var element = $(tabElement).find(Constants.htmlSelectors.dataTableScrollBodySelector)[0];
var style = getComputedStyle(element);
var actualHeight = parseInt(style.height);
var change = element.offsetHeight - scrollHeight;
$(tabElement)
.find(Constants.htmlSelectors.dataTableScrollBodySelector)
.height(actualHeight - change);
});
}
/*
* Update the table's scrollable region width to make efficient use of the remaining space.
*/
function updateTableScrollableRegionWidth(): void {
$(".tab-pane").each(function (index, tabElement) {
if (!$(tabElement).hasClass("tableContainer")) {
return;
}
var bodyWidth = $(window).width();
var dataTablesScrollBodyPosLeft = $(tabElement).find(Constants.htmlSelectors.dataTableScrollBodySelector).offset()
.left;
var scrollWidth = bodyWidth - dataTablesScrollBodyPosLeft;
// jquery datatables automatically sets width:100% to both the header and the body when we use it's column autoWidth feature.
// We work around that by setting the height for it's container instead.
$(tabElement).find(Constants.htmlSelectors.dataTableScrollContainerSelector).width(scrollWidth);
});
}
function initializeEventHandlers(): void {
var $headers: JQuery = $(Constants.htmlSelectors.dataTableHeaderTypeSelector);
var $firstHeader: JQuery = $headers.first();
var firstIndex: string = $firstHeader.attr(Constants.htmlAttributeNames.dataTableHeaderIndex);
$headers
.on("keydown", (event: JQueryEventObject) => {
Utilities.onEnter(event, ($sourceElement: JQuery) => {
$sourceElement.css("background-color", Constants.cssColors.commonControlsButtonActive);
});
// Bind shift+tab from first header back to search input field
Utilities.onTab(
event,
($sourceElement: JQuery) => {
var sourceIndex: string = $sourceElement.attr(Constants.htmlAttributeNames.dataTableHeaderIndex);
if (sourceIndex === firstIndex) {
event.preventDefault();
}
},
/* metaKey */ null,
/* shiftKey */ true,
/* altKey */ null
);
// Also reset color if [shift-] tabbing away from button while holding down 'enter'
Utilities.onTab(event, ($sourceElement: JQuery) => {
$sourceElement.css("background-color", "");
});
})
.on("keyup", (event: JQueryEventObject) => {
Utilities.onEnter(event, ($sourceElement: JQuery) => {
$sourceElement.css("background-color", "");
});
});
}
function updateSelectionStatus(oSettings: any): void {
var $dataTableRows: JQuery = $(Constants.htmlSelectors.dataTableAllRowsSelector);
if ($dataTableRows) {
for (var i = 0; i < $dataTableRows.length; i++) {
var $row: JQuery = $dataTableRows.eq(i);
var rowKey: string = $row.attr(Constants.htmlAttributeNames.dataTableRowKeyAttr);
var table = tableEntityListViewModelMap[oSettings.ajax].tableViewModel;
if (table.isItemSelected(table.getTableEntityKeys(rowKey))) {
$row.attr("tabindex", "0");
}
}
}
updateDataTableFocus(oSettings.ajax);
DataTableOperations.setPaginationButtonEventHandlers();
}
// TODO consider centralizing this "post-command" logic into some sort of Command Manager entity.
// See VSO:166520: "[Storage Explorer] Consider adding a 'command manager' to track command post-effects."
function updateDataTableFocus(queryTablesTabId: string): void {
var $activeElement: JQuery = $(document.activeElement);
var isFocusLost: boolean = $activeElement.is("body"); // When focus is lost, "body" becomes the active element.
var storageExplorerFrameHasFocus: boolean = document.hasFocus();
var operationManager = tableEntityListViewModelMap[queryTablesTabId].operationManager;
if (operationManager) {
if (isFocusLost && storageExplorerFrameHasFocus) {
// We get here when no control is active, meaning that the table update was triggered
// from a dialog, the context menu or by clicking on a toolbar control or header.
// Note that giving focus to the table also selects the first row if needed.
// The document.hasFocus() ensures that the table will only get focus when the
// focus was lost (i.e. "body has the focus") within the Storage Explorer frame
// i.e. not when the focus is lost because it is in another frame
// e.g. a daytona dialog or in the Activity Log.
operationManager.focusTable();
}
if ($activeElement.is(".sorting_asc") || $activeElement.is(".sorting_desc")) {
// If table header is selected, focus is shifted to the selected element as part of accessibility
$activeElement && $activeElement.focus();
} else {
// If some control is active, we don't give focus back to the table,
// just select the first row if needed (empty selection).
operationManager.selectFirstIfNeeded();
}
}
}
(<any>ko.bindingHandlers).tableSource = {
init: bindDataTable,
update: dataChanged,
};
(<any>ko.bindingHandlers).tableSelection = {
update: selectionChanged,
};
(<any>ko.bindingHandlers).readOnly = {
update: function (element: any, valueAccessor: any) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (value) {
element.setAttribute("readOnly", true);
} else {
element.removeAttribute("readOnly");
}
},
}; | the_stack |
import { LanguageCode, Result } from '@inlang/common';
import { remove } from 'lodash-es';
import { Attribute, Identifier, Message, Resource } from '@fluent/syntax';
import { isValidMessageId } from './utils/isValidMessageId';
import { parsePattern } from './utils/parsePattern';
/**
* The API of this class could be improved.
*
* Most methods require a `languageCode` and act only on one resource.
* Intead of defining functions like `getMessage` on all resources,
* single resources could be extended to include those functions.
* Getting a message from a resource could then be `resources.en.deleteMessage()`.
* Functions that act on all resources would be called like `resources.deleteMessage()`.
*
* However:
* a) could lead to confusion e.g. single deletion, delete for all resources (see example above)?
* b) works only if resources always use languageCodes as ids. Maybe as on object it's possible:
* ```
* type Resources = {
* [resourceId: string] : SingleResource | undefined
* messageIds (of all resources)
* deleteMessage (for all resources)
* ...
* }
* ```
*/
/**
* Utility type for consistency throughout the resources class.
*/
type RecordOfResources = Record<string, Resource | undefined>;
/**
* Allows to parse files (as resources), act on those resources and serialize back to files.
*
* All messages, terms etc. are saved as files (resources) either in the local source code,
* or the inlang database. In order to act on those files, they need to be parsed.
* The parsed format is `Resource`. This class acts as wrapper around multiple `Resource`s
* to act on all those resources at once.
*/
export class Resources {
/**
* Holds all resources as object accesible via a `languageCode`.
*
*
* @example:
*
* const x: RecordOfResources = {
* en: Resource,
* de: Resource
* }
* console.log(x.en)
* >> Resource
*
*
*/
resources: RecordOfResources;
constructor(args: { resources: RecordOfResources }) {
this.resources = args.resources;
}
/**
* The language codes contained in the resources.
*
* Example:
* The resources contain "en", "de" and "fr".
*/
containedLanguageCodes(): LanguageCode[] {
return Object.entries(this.resources).map(([languageCode]) => languageCode as LanguageCode);
}
messageExist(args: { id: Message['id']['name']; languageCode: LanguageCode }): boolean {
for (const entry of this.resources[args.languageCode]?.body ?? []) {
if (entry.type === 'Message' && entry.id.name === args.id) {
return true;
}
}
return false;
}
/**
* Whether or not an attribute exists.
*/
attributeExists(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
languageCode: LanguageCode;
}): boolean {
for (const entry of this.resources[args.languageCode]?.body ?? []) {
if (entry.type === 'Message' && entry.id.name === args.messageId) {
for (const attribute of entry.attributes) {
if (attribute.id.name === args.id) {
return true;
}
}
}
}
return false;
}
getMessage(args: { id: Message['id']['name']; languageCode: LanguageCode }): Message | undefined {
for (const entry of this.resources[args.languageCode]?.body ?? []) {
if (entry.type === 'Message' && entry.id.name === args.id) {
return entry;
}
}
}
/**
* Retrieves all messages with the given id of all resources.
*
* @returns A record holding the messages accessible via the languageCode.
*
* @example
* {
* "en": "Hello World",
* "de": "Hallo Welt"
* }
*/
getMessageForAllResources(args: { id: Message['id']['name'] }): Record<string, Message | undefined> {
const result: ReturnType<typeof this.getMessageForAllResources> = {};
for (const [languageCode] of Object.entries(this.resources)) {
const message = this.getMessage({ id: args.id, languageCode: languageCode as LanguageCode });
result[languageCode] = message;
}
return result;
}
// overloading: empty pattern requires attributes
createMessage(args: {
id: Message['id']['name'];
pattern?: string;
languageCode: LanguageCode;
attributes: Attribute[];
}): Result<void, Error>;
// overloading: defined pattern does not require attributes
createMessage(args: {
id: Message['id']['name'];
pattern: string;
languageCode: LanguageCode;
attributes?: Attribute[];
}): Result<void, Error>;
/**
* Creates a message.
*
* Note: Attributes can not be passed in the `pattern`.
*/
createMessage(args: {
id: Message['id']['name'];
pattern?: string;
languageCode: LanguageCode;
attributes?: Attribute[];
}): Result<void, Error> {
if (
(args.pattern === undefined || args.pattern.trim() === '') &&
(args.attributes === undefined || args.attributes.length === 0)
) {
return Result.err(Error('The message has no pattern. Thus, at least one attribute is required.'));
}
if (this.messageExist({ id: args.id, languageCode: args.languageCode })) {
return Result.err(
Error(`Message id ${args.id} already exists for the language code ${args.languageCode}.`)
);
} else if (isValidMessageId(args.id) === false) {
return Result.err(Error(`Message id ${args.id} is not a valid id.`));
} else if (this.resources[args.languageCode] === undefined) {
return Result.err(Error(`No resource for the language code ${args.languageCode} exits.`));
}
const message = new Message(new Identifier(args.id));
if (args.pattern) {
const parsed = parsePattern(args.pattern);
if (parsed.isErr) {
return Result.err(parsed.error);
}
message.value = parsed.value;
}
if (args.attributes) {
message.attributes = args.attributes;
}
this.resources[args.languageCode]?.body.push(message);
return Result.ok(undefined);
}
deleteMessage(args: { id: Message['id']['name']; languageCode: LanguageCode }): Result<void, Error> {
const removed = remove(
this.resources[args.languageCode]?.body ?? [],
(resource) => (resource.type === 'Message' || resource.type === 'Term') && resource.id.name === args.id
);
if (removed.length === 0) {
return Result.err(Error(`Message with id ${args.id} does not exist in resource ${args.languageCode}`));
}
return Result.ok(undefined);
}
deleteMessageForAllResources(args: { id: Message['id']['name'] }): Result<void, Error> {
for (const [languageCode] of Object.entries(this.resources)) {
if (this.messageExist({ id: args.id, languageCode: languageCode as LanguageCode })) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const deletion = this.deleteMessage({ id: args.id, languageCode: languageCode as LanguageCode });
// dont return an error (if a message does not exist for this language code)
// if (deletion.isErr) {
// return Result.err(deletion.error);
// }
}
}
return Result.ok(undefined);
}
getMessageIds(args: { languageCode: LanguageCode }): Set<Message['id']['name']> {
const result: Set<string> = new Set();
for (const entry of this.resources[args.languageCode]?.body ?? []) {
if (entry.type === 'Message') {
result.add(entry.id.name);
}
}
return result;
}
getMessageIdsForAllResources(): Set<Message['id']['name']> {
let result: Set<string> = new Set();
for (const languageCode of this.containedLanguageCodes()) {
// concating both sets
result = new Set([...result, ...this.getMessageIds({ languageCode })]);
}
return result;
}
updateMessage(args: { id: Message['id']['name']; languageCode: LanguageCode; with: Message }): Result<void, Error> {
if (args.id !== args.with.id.name) {
return Result.err(Error('The given id does not match the with.id'));
}
const resource = this.resources[args.languageCode];
if (resource === undefined) {
return Result.err(Error(`Resource for language code ${args.languageCode} does not exist.`));
}
const indexOfMessage = resource.body.findIndex(
(entry) => entry.type === 'Message' && entry.id.name === args.id
);
if (indexOfMessage === -1) {
return Result.err(
Error(`Message with id '${args.id}' does not exist for the language code ${args.languageCode}.`)
);
}
resource.body[indexOfMessage] = args.with;
return Result.ok(undefined);
}
// ----------- attributes -------------
/**
* Creates an attribute of a message.
*
* If the message does not exist, the message is created too.
*/
createAttribute(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
pattern: string;
languageCode: LanguageCode;
}): Result<void, Error> {
const message = this.getMessage({ id: args.messageId, languageCode: args.languageCode });
if (message?.attributes.some((attribute) => attribute.id.name === args.id)) {
return Result.err(
Error(`Attribute with id ${args.id} exists already for language "${args.languageCode}".`)
);
}
const parsedPattern = parsePattern(args.pattern);
if (parsedPattern.isErr) {
return Result.err(parsedPattern.error);
}
const attribute = new Attribute(new Identifier(args.id), parsedPattern.value);
if (message) {
message.attributes.push(attribute);
return this.updateMessage({ id: args.messageId, languageCode: args.languageCode, with: message });
} else {
return this.createMessage({ id: args.messageId, languageCode: args.languageCode, attributes: [attribute] });
}
}
/**
* Get an attribute of a message.
*
* Returns undefined if the message, or the attribute itself does not exist.
*/
getAttribute(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
languageCode: LanguageCode;
}): Attribute | undefined {
const message = this.getMessage({ id: args.messageId, languageCode: args.languageCode });
const attribute = message?.attributes.find((attribute) => attribute.id.name === args.id);
return attribute;
}
/**
* Retrieves all attributes with the given ids for all resources.
*
* @returns A record holding the messages accessible via the languageCode.
*
* @example
* {
* "en": Attribute
* "de": Attribute
* }
*/
getAttributeForAllResources(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
}): Record<string, Attribute | undefined> {
const result: ReturnType<typeof this.getAttributeForAllResources> = {};
for (const [languageCode] of Object.entries(this.resources)) {
const attribute = this.getAttribute({
messageId: args.messageId,
id: args.id,
languageCode: languageCode as LanguageCode,
});
result[languageCode] = attribute;
}
return result;
}
/**
* Updates an attribute of a message.
*/
updateAttribute(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
languageCode: LanguageCode;
with: Attribute;
}): Result<void, Error> {
const message = this.getMessage({ id: args.messageId, languageCode: args.languageCode });
if (message === undefined) {
return Result.err(
Error(`The message "${args.messageId}" does not exist for the language ${args.languageCode}`)
);
}
const indexOfAttribute = message.attributes.findIndex((attribute) => attribute.id.name === args.id);
if (indexOfAttribute === -1) {
return Result.err(
Error(
`Attribute with id '${args.id}' does not exist for the message ${args.messageId} with language ${args.languageCode}.`
)
);
}
// replace existent attribute at that index
message.attributes[indexOfAttribute] = args.with;
return this.updateMessage({ id: args.messageId, languageCode: args.languageCode, with: message });
}
/**
* Deletes an attribute of a message.
*/
deleteAttribute(args: {
messageId: Message['id']['name'];
id: Attribute['id']['name'];
languageCode: LanguageCode;
}): Result<void, Error> {
const message = this.getMessage({ id: args.messageId, languageCode: args.languageCode });
if (message === undefined) {
return Result.err(
Error(`The message "${args.messageId}" does not exist for the language ${args.languageCode}`)
);
}
const removed = remove(message.attributes, (attribute) => attribute.id.name === args.id);
if (removed.length === 0) {
return Result.err(
Error(
`Attribute with id '${args.id}' does not exist for the message ${args.messageId} with language ${args.languageCode}.`
)
);
}
return Result.ok(undefined);
}
/**
* Deletes the attribute with the given id for all resources.
*/
deleteAttributeForAllResources(args: { messageId: Message['id']['name']; id: string }): Result<void, Error> {
for (const [languageCode] of Object.entries(this.resources)) {
if (this.messageExist({ id: args.messageId, languageCode: languageCode as LanguageCode })) {
const deletion = this.deleteAttribute({
messageId: args.messageId,
id: args.id,
languageCode: languageCode as LanguageCode,
});
if (deletion.isErr) {
return Result.err(deletion.error);
}
}
}
return Result.ok(undefined);
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides an AppSync GraphQL API.
*
* ## Example Usage
* ### API Key Authentication
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* authenticationType: "API_KEY",
* });
* ```
* ### AWS Cognito User Pool Authentication
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* authenticationType: "AMAZON_COGNITO_USER_POOLS",
* userPoolConfig: {
* awsRegion: data.aws_region.current.name,
* defaultAction: "DENY",
* userPoolId: aws_cognito_user_pool.example.id,
* },
* });
* ```
* ### AWS IAM Authentication
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* authenticationType: "AWS_IAM",
* });
* ```
* ### With Schema
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* authenticationType: "AWS_IAM",
* schema: `schema {
* query: Query
* }
* type Query {
* test: Int
* }
* `,
* });
* ```
* ### OpenID Connect Authentication
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* authenticationType: "OPENID_CONNECT",
* openidConnectConfig: {
* issuer: "https://example.com",
* },
* });
* ```
* ### With Multiple Authentication Providers
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const example = new aws.appsync.GraphQLApi("example", {
* additionalAuthenticationProviders: [{
* authenticationType: "AWS_IAM",
* }],
* authenticationType: "API_KEY",
* });
* ```
* ### Enabling Logging
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const exampleRole = new aws.iam.Role("exampleRole", {assumeRolePolicy: `{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Effect": "Allow",
* "Principal": {
* "Service": "appsync.amazonaws.com"
* },
* "Action": "sts:AssumeRole"
* }
* ]
* }
* `});
* const exampleRolePolicyAttachment = new aws.iam.RolePolicyAttachment("exampleRolePolicyAttachment", {
* policyArn: "arn:aws:iam::aws:policy/service-role/AWSAppSyncPushToCloudWatchLogs",
* role: exampleRole.name,
* });
* // ... other configuration ...
* const exampleGraphQLApi = new aws.appsync.GraphQLApi("exampleGraphQLApi", {logConfig: {
* cloudwatchLogsRoleArn: exampleRole.arn,
* fieldLogLevel: "ERROR",
* }});
* ```
* ### Associate Web ACL (v2)
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const exampleGraphQLApi = new aws.appsync.GraphQLApi("exampleGraphQLApi", {authenticationType: "API_KEY"});
* const exampleWebAcl = new aws.wafv2.WebAcl("exampleWebAcl", {
* description: "Example of a managed rule.",
* scope: "REGIONAL",
* defaultAction: {
* allow: {},
* },
* rules: [{
* name: "rule-1",
* priority: 1,
* overrideAction: {
* block: [{}],
* },
* statement: {
* managedRuleGroupStatement: {
* name: "AWSManagedRulesCommonRuleSet",
* vendorName: "AWS",
* },
* },
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-rule-metric-name",
* sampledRequestsEnabled: false,
* },
* }],
* visibilityConfig: {
* cloudwatchMetricsEnabled: false,
* metricName: "friendly-metric-name",
* sampledRequestsEnabled: false,
* },
* });
* const exampleWebAclAssociation = new aws.wafv2.WebAclAssociation("exampleWebAclAssociation", {
* resourceArn: exampleGraphQLApi.arn,
* webAclArn: exampleWebAcl.arn,
* });
* ```
*
* ## Import
*
* AppSync GraphQL API can be imported using the GraphQL API ID, e.g.
*
* ```sh
* $ pulumi import aws:appsync/graphQLApi:GraphQLApi example 0123456789
* ```
*/
export class GraphQLApi extends pulumi.CustomResource {
/**
* Get an existing GraphQLApi resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: GraphQLApiState, opts?: pulumi.CustomResourceOptions): GraphQLApi {
return new GraphQLApi(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:appsync/graphQLApi:GraphQLApi';
/**
* Returns true if the given object is an instance of GraphQLApi. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is GraphQLApi {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === GraphQLApi.__pulumiType;
}
/**
* One or more additional authentication providers for the GraphqlApi. Defined below.
*/
public readonly additionalAuthenticationProviders!: pulumi.Output<outputs.appsync.GraphQLApiAdditionalAuthenticationProvider[] | undefined>;
/**
* The ARN
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* The authentication type. Valid values: `API_KEY`, `AWS_IAM`, `AMAZON_COGNITO_USER_POOLS`, `OPENID_CONNECT`
*/
public readonly authenticationType!: pulumi.Output<string>;
/**
* Nested argument containing logging configuration. Defined below.
*/
public readonly logConfig!: pulumi.Output<outputs.appsync.GraphQLApiLogConfig | undefined>;
/**
* A user-supplied name for the GraphqlApi.
*/
public readonly name!: pulumi.Output<string>;
/**
* Nested argument containing OpenID Connect configuration. Defined below.
*/
public readonly openidConnectConfig!: pulumi.Output<outputs.appsync.GraphQLApiOpenidConnectConfig | undefined>;
/**
* The schema definition, in GraphQL schema language format. This provider cannot perform drift detection of this configuration.
*/
public readonly schema!: pulumi.Output<string | undefined>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* Map of URIs associated with the API. e.g. `uris["GRAPHQL"] = https://ID.appsync-api.REGION.amazonaws.com/graphql`
*/
public /*out*/ readonly uris!: pulumi.Output<{[key: string]: string}>;
/**
* The Amazon Cognito User Pool configuration. Defined below.
*/
public readonly userPoolConfig!: pulumi.Output<outputs.appsync.GraphQLApiUserPoolConfig | undefined>;
/**
* Whether tracing with X-ray is enabled. Defaults to false.
*/
public readonly xrayEnabled!: pulumi.Output<boolean | undefined>;
/**
* Create a GraphQLApi resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: GraphQLApiArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: GraphQLApiArgs | GraphQLApiState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as GraphQLApiState | undefined;
inputs["additionalAuthenticationProviders"] = state ? state.additionalAuthenticationProviders : undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["authenticationType"] = state ? state.authenticationType : undefined;
inputs["logConfig"] = state ? state.logConfig : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["openidConnectConfig"] = state ? state.openidConnectConfig : undefined;
inputs["schema"] = state ? state.schema : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["uris"] = state ? state.uris : undefined;
inputs["userPoolConfig"] = state ? state.userPoolConfig : undefined;
inputs["xrayEnabled"] = state ? state.xrayEnabled : undefined;
} else {
const args = argsOrState as GraphQLApiArgs | undefined;
if ((!args || args.authenticationType === undefined) && !opts.urn) {
throw new Error("Missing required property 'authenticationType'");
}
inputs["additionalAuthenticationProviders"] = args ? args.additionalAuthenticationProviders : undefined;
inputs["authenticationType"] = args ? args.authenticationType : undefined;
inputs["logConfig"] = args ? args.logConfig : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["openidConnectConfig"] = args ? args.openidConnectConfig : undefined;
inputs["schema"] = args ? args.schema : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["userPoolConfig"] = args ? args.userPoolConfig : undefined;
inputs["xrayEnabled"] = args ? args.xrayEnabled : undefined;
inputs["arn"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
inputs["uris"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(GraphQLApi.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering GraphQLApi resources.
*/
export interface GraphQLApiState {
/**
* One or more additional authentication providers for the GraphqlApi. Defined below.
*/
additionalAuthenticationProviders?: pulumi.Input<pulumi.Input<inputs.appsync.GraphQLApiAdditionalAuthenticationProvider>[]>;
/**
* The ARN
*/
arn?: pulumi.Input<string>;
/**
* The authentication type. Valid values: `API_KEY`, `AWS_IAM`, `AMAZON_COGNITO_USER_POOLS`, `OPENID_CONNECT`
*/
authenticationType?: pulumi.Input<string>;
/**
* Nested argument containing logging configuration. Defined below.
*/
logConfig?: pulumi.Input<inputs.appsync.GraphQLApiLogConfig>;
/**
* A user-supplied name for the GraphqlApi.
*/
name?: pulumi.Input<string>;
/**
* Nested argument containing OpenID Connect configuration. Defined below.
*/
openidConnectConfig?: pulumi.Input<inputs.appsync.GraphQLApiOpenidConnectConfig>;
/**
* The schema definition, in GraphQL schema language format. This provider cannot perform drift detection of this configuration.
*/
schema?: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Map of URIs associated with the API. e.g. `uris["GRAPHQL"] = https://ID.appsync-api.REGION.amazonaws.com/graphql`
*/
uris?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The Amazon Cognito User Pool configuration. Defined below.
*/
userPoolConfig?: pulumi.Input<inputs.appsync.GraphQLApiUserPoolConfig>;
/**
* Whether tracing with X-ray is enabled. Defaults to false.
*/
xrayEnabled?: pulumi.Input<boolean>;
}
/**
* The set of arguments for constructing a GraphQLApi resource.
*/
export interface GraphQLApiArgs {
/**
* One or more additional authentication providers for the GraphqlApi. Defined below.
*/
additionalAuthenticationProviders?: pulumi.Input<pulumi.Input<inputs.appsync.GraphQLApiAdditionalAuthenticationProvider>[]>;
/**
* The authentication type. Valid values: `API_KEY`, `AWS_IAM`, `AMAZON_COGNITO_USER_POOLS`, `OPENID_CONNECT`
*/
authenticationType: pulumi.Input<string>;
/**
* Nested argument containing logging configuration. Defined below.
*/
logConfig?: pulumi.Input<inputs.appsync.GraphQLApiLogConfig>;
/**
* A user-supplied name for the GraphqlApi.
*/
name?: pulumi.Input<string>;
/**
* Nested argument containing OpenID Connect configuration. Defined below.
*/
openidConnectConfig?: pulumi.Input<inputs.appsync.GraphQLApiOpenidConnectConfig>;
/**
* The schema definition, in GraphQL schema language format. This provider cannot perform drift detection of this configuration.
*/
schema?: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The Amazon Cognito User Pool configuration. Defined below.
*/
userPoolConfig?: pulumi.Input<inputs.appsync.GraphQLApiUserPoolConfig>;
/**
* Whether tracing with X-ray is enabled. Defaults to false.
*/
xrayEnabled?: pulumi.Input<boolean>;
} | the_stack |
"use strict";
import { assert } from "chai";
import * as path from "path";
import { Delete } from "../../../src/tfvc/commands/delete";
import { TfvcError } from "../../../src/tfvc/tfvcerror";
import { IExecutionResult } from "../../../src/tfvc/interfaces";
import { TeamServerContext } from "../../../src/contexts/servercontext";
import { CredentialInfo } from "../../../src/info/credentialinfo";
import { RepositoryInfo } from "../../../src/info/repositoryinfo";
describe("Tfvc-DeleteCommand", function() {
const serverUrl: string = "http://server:8080/tfs";
const repoUrl: string = "http://server:8080/tfs/collection1/_git/repo1";
const collectionUrl: string = "http://server:8080/tfs/collection1";
const user: string = "user1";
const pass: string = "pass1";
let context: TeamServerContext;
beforeEach(function() {
context = new TeamServerContext(repoUrl);
context.CredentialInfo = new CredentialInfo(user, pass);
context.RepoInfo = new RepositoryInfo({
serverUrl: serverUrl,
collection: {
name: "collection1",
id: ""
},
repository: {
remoteUrl: repoUrl,
id: "",
name: "",
project: {
name: "project1"
}
}
});
});
it("should verify constructor - windows", function() {
const localPaths: string[] = ["c:\\repos\\Tfvc.L2VSCodeExtension.RC\\README.md"];
new Delete(undefined, localPaths);
});
it("should verify constructor - mac/linux", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
new Delete(undefined, localPaths);
});
it("should verify constructor with context", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
new Delete(context, localPaths);
});
it("should verify constructor - undefined args", function() {
assert.throws(() => new Delete(undefined, undefined), TfvcError, /Argument is required/);
});
it("should verify GetOptions", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
assert.deepEqual(cmd.GetOptions(), {});
});
it("should verify GetExeOptions", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
assert.deepEqual(cmd.GetExeOptions(), {});
});
it("should verify arguments", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "delete -noprompt " + localPaths[0]);
});
it("should verify Exe arguments", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "delete -noprompt " + localPaths[0]);
});
it("should verify arguments with context", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(context, localPaths);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "delete -noprompt -collection:" + collectionUrl + " ******** " + localPaths[0]);
});
it("should verify Exe arguments with context", function() {
const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"];
const cmd: Delete = new Delete(context, localPaths);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "delete -noprompt ******** " + localPaths[0]);
});
it("should verify parse output - single file - no errors", async function() {
const localPaths: string[] = ["README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "README.md\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], "README.md");
});
it("should verify parse output - single empty folder - no errors", async function() {
const localPaths: string[] = ["empty-folder"];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "empty-folder:\n" +
"empty-folder\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.equal(filesDeleted.length, 1);
//In this case, the CLC returns:
//empty-folder:
//empty-folder
//So we will have to return empty-folder\empty-folder. Not ideal but let's ensure we're getting that.
assert.equal(filesDeleted[0], path.join(localPaths[0], localPaths[0]));
});
it("should verify parse output - single folder+file - no errors", async function() {
const localPaths: string[] = [path.join("folder1", "file1.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "folder1:\n" +
"file1.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse output - single subfolder+file - no errors", async function() {
const localPaths: string[] = [path.join("folder1", "folder2", "file2.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: path.join("folder1", "folder2") + ":\n" +
"file2.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse output - single folder+file - spaces - no errors", async function() {
const localPaths: string[] = [path.join("fold er1", "file1.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "fold er1:\n" +
"file1.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse output - multiple files", async function() {
const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")];
const localPaths: string[] = noChangesPaths;
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: path.join("folder1", "file1.txt") + ":\n" +
"file1.txt\n" +
path.join("folder2", "file2.txt") + ":\n" +
"file2.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseOutput(executionResult);
assert.isDefined(filesDeleted);
assert.equal(filesDeleted.length, 2);
});
//
//
//
//
it("should verify parse Exe output - single file - no errors", async function() {
const localPaths: string[] = ["README.md"];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "README.md\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], "README.md");
});
it("should verify parse Exe output - single empty folder - no errors", async function() {
const localPaths: string[] = ["empty-folder"];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "empty-folder:\n" +
"empty-folder\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.equal(filesDeleted.length, 1);
//In this case, the CLC returns:
//empty-folder:
//empty-folder
//So we will have to return empty-folder\empty-folder. Not ideal but let's ensure we're getting that.
assert.equal(filesDeleted[0], path.join(localPaths[0], localPaths[0]));
});
it("should verify parse Exe output - single folder+file - no errors", async function() {
const localPaths: string[] = [path.join("folder1", "file1.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "folder1:\n" +
"file1.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse Exe output - single subfolder+file - no errors", async function() {
const localPaths: string[] = [path.join("folder1", "folder2", "file2.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: path.join("folder1", "folder2") + ":\n" +
"file2.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse Exe output - single folder+file - spaces - no errors", async function() {
const localPaths: string[] = [path.join("fold er1", "file1.txt")];
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "fold er1:\n" +
"file1.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.equal(filesDeleted.length, 1);
assert.equal(filesDeleted[0], localPaths[0]);
});
it("should verify parse Exe output - multiple files", async function() {
const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")];
const localPaths: string[] = noChangesPaths;
const cmd: Delete = new Delete(undefined, localPaths);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: path.join("folder1", "file1.txt") + ":\n" +
"file1.txt\n" +
path.join("folder2", "file2.txt") + ":\n" +
"file2.txt\n",
stderr: undefined
};
const filesDeleted: string[] = await cmd.ParseExeOutput(executionResult);
assert.isDefined(filesDeleted);
assert.equal(filesDeleted.length, 2);
});
}); | the_stack |
var browser: Browser = browser || chrome;
const PENDING_SUBMISSIONS = ':PENDING_SUBMISSIONS'
const MIGRATION = ':MIGRATION'
const CURRENT_VERSION = 100029;
const badIdentifiersReasons: { [id: string]: BadIdentifierReason } = {};
const badIdentifiers: { [id: string]: true } = {};
// If a user labels one of these URLs, they're making a mistake. Ignore the label.
// This list includes:
// * Social networks that are not supported (SN)
// * System pages of supported social networks
// * Archival and link shortening sites. (AR)
// * Reddit bots.
const badIdentifiersArray = [
'a.co',
'about.me=SN',
'amzn.to',
'archive.is=AR',
'archive.org=AR',
'ask.fm=SN',
'assets.tumblr.com',
'bing.com',
'bit.ly',
'blogspot.com',
'buymeacoffee.com=SN',
'cash.app=SN',
'cash.me=SN',
'change.org',
'chrome.google.com',
'curiouscat.me=SN',
'curiouscat.qa=SN',
'deviantart.com=SN',
'discord.gg=SN',
'discordapp.com=SN',
'discord-store.com=SN',
'disqus.com',
'docs.google.com',
'drive.google.com',
'duckduckgo.com',
'en.wikipedia.org',
'en.wikiquote.org',
'etsy.com=SN',
'facebook.com',
'facebook.com/a',
'facebook.com/about',
'facebook.com/ad_campaign',
'facebook.com/ads',
'facebook.com/advertising',
'facebook.com/ajax',
'facebook.com/bookmarks',
'facebook.com/browse',
'facebook.com/buddylist.php',
'facebook.com/bugnub',
'facebook.com/business',
'facebook.com/c',
'facebook.com/comment',
'facebook.com/composer',
'facebook.com/connect',
'facebook.com/dialog',
'facebook.com/docs',
'facebook.com/donate',
'facebook.com/events',
'facebook.com/findfriends',
'facebook.com/friends',
'facebook.com/fundraisers',
'facebook.com/games',
'facebook.com/groups',
'facebook.com/hashtag',
'facebook.com/help',
'facebook.com/home.php',
'facebook.com/instantgames',
'facebook.com/intl',
'facebook.com/jobs',
'facebook.com/l.php',
'facebook.com/language.php',
'facebook.com/latest',
'facebook.com/legal',
'facebook.com/like.php',
'facebook.com/local_surface',
'facebook.com/logout.php',
'facebook.com/marketplace',
'facebook.com/mbasic',
'facebook.com/me',
'facebook.com/media',
'facebook.com/memories',
'facebook.com/menu',
'facebook.com/messages',
'facebook.com/nfx',
'facebook.com/notes',
'facebook.com/notifications',
'facebook.com/notifications.php',
'facebook.com/nt',
'facebook.com/page',
'facebook.com/pages',
'facebook.com/people',
'facebook.com/permalink.php',
'facebook.com/pg',
'facebook.com/photo',
'facebook.com/photo.php',
'facebook.com/places',
'facebook.com/policies',
'facebook.com/privacy',
'facebook.com/profile',
'facebook.com/profile.php',
'facebook.com/public',
'facebook.com/rapid_report',
'facebook.com/reactions',
'facebook.com/salegroups',
'facebook.com/search',
'facebook.com/settings',
'facebook.com/share',
'facebook.com/share.php',
'facebook.com/sharer.php',
'facebook.com/shares',
'facebook.com/stories',
'facebook.com/story.php',
'facebook.com/support',
'facebook.com/timeline',
'facebook.com/ufi',
'facebook.com/video',
'facebook.com/watch',
'fb.me',
'flickr.com=SN',
'gofundme.com=SN',
'goo.gl',
'google.com',
'googleusercontent.com',
'http',
'https',
'i.imgur.com',
'i.reddituploads.com',
'imdb.com=SN',
'imgur.com',
'indiegogo.com=SN',
'instagram.com=SN',
'itunes.apple.com=SN',
'ko-fi.com=SN',
'last.fm=SN',
'linkedin.com=SN',
'linktr.ee=SN',
'mail.google.com',
'media.tumblr.com',
'medium.com',
'news.google.com',
'onlyfans.com=SN',
'open.spotify.com=SN',
'patreon.com=SN',
'paypal.com=SN',
'paypal.me=SN',
'pinterest.com=SN',
'play.google.com',
'plus.google.com=SN',
'podcasts.apple.com=SN',
'poshmark.com=SN',
'rationalwiki.org',
'reddit.com',
'reddit.com/r/all',
'reddit.com/r/popular',
'reddit.com/user/_youtubot_',
'reddit.com/user/animalfactsbot',
'reddit.com/user/anti-gif-bot',
'reddit.com/user/areyoudeaf',
'reddit.com/user/automoderator',
'reddit.com/user/autotldr',
'reddit.com/user/auto-xkcd37',
'reddit.com/user/biglebowskibot',
'reddit.com/user/bots_rise_up',
'reddit.com/user/cheer_up_bot',
'reddit.com/user/cheer-bot',
'reddit.com/user/clickablelinkbot',
'reddit.com/user/colorizethis',
'reddit.com/user/darnit_bot',
'reddit.com/user/darthplagueisbot',
'reddit.com/user/deepfrybot',
'reddit.com/user/dreamprocessor',
'reddit.com/user/drunkanimalfactbot',
'reddit.com/user/election_info_bot',
'reddit.com/user/eyebleachbot',
'reddit.com/user/factorial-bot',
'reddit.com/user/friendly-bot',
'reddit.com/user/garlicbot',
'reddit.com/user/gfycat_details_fixer',
'reddit.com/user/gifv-bot',
'reddit.com/user/good_good_gb_bb',
'reddit.com/user/goodbot_badbot',
'reddit.com/user/goodmod_badmod',
'reddit.com/user/gyazo_bot',
'reddit.com/user/haikubot-1911',
'reddit.com/user/haiku-detector',
'reddit.com/user/helperbot_',
'reddit.com/user/hug-bot',
'reddit.com/user/i_am_a_haiku_bot',
'reddit.com/user/ilinknsfwsubreddits',
'reddit.com/user/image_linker_bot',
'reddit.com/user/imdb_preview',
'reddit.com/user/imguralbumbot',
'reddit.com/user/jacksfilmsbot',
'reddit.com/user/jiffierbot',
'reddit.com/user/livetwitchclips',
'reddit.com/user/lyrics-matcher-bot',
'reddit.com/user/mailmygovnnbot',
'reddit.com/user/massdropbot',
'reddit.com/user/mentioned_videos',
'reddit.com/user/metric_units',
'reddit.com/user/mlbvideoconverterbot',
'reddit.com/user/morejpeg_auto',
'reddit.com/user/movieguide',
'reddit.com/user/multiusebot',
'reddit.com/user/news-summary',
'reddit.com/user/nflvideoconverterbot',
'reddit.com/user/octopusfunfacts',
'reddit.com/user/octupusfunfacts',
'reddit.com/user/opfeels',
'reddit.com/user/payrespects-bot',
'reddit.com/user/perrycohen',
'reddit.com/user/phonebatterylevelbot',
'reddit.com/user/picdescriptionbot',
'reddit.com/user/portmanteau-bot',
'reddit.com/user/quoteme-bot',
'reddit.com/user/redditsilverbot',
'reddit.com/user/redditstreamable',
'reddit.com/user/remindmebot',
'reddit.com/user/riskyclickerbot',
'reddit.com/user/rosey-the-bot',
'reddit.com/user/seriouslywhenishl3',
'reddit.com/user/shhbot',
'reddit.com/user/smallsubbot',
'reddit.com/user/snapshillbot',
'reddit.com/user/sneakpeekbot',
'reddit.com/user/stabbot',
'reddit.com/user/stabbot_crop',
'reddit.com/user/steamnewsbot',
'reddit.com/user/subjunctive__bot',
'reddit.com/user/table_it_bot',
'reddit.com/user/thehelperdroid',
'reddit.com/user/the-paranoid-android',
'reddit.com/user/thiscatmightcheeryou',
'reddit.com/user/timestamp_bot',
'reddit.com/user/timezone_bot',
'reddit.com/user/tiny_smile_bot',
'reddit.com/user/tipjarbot',
'reddit.com/user/tippr',
'reddit.com/user/totes_meta_bot',
'reddit.com/user/totesmessenger',
'reddit.com/user/tumblrdirect',
'reddit.com/user/tweetsincommentsbot',
'reddit.com/user/twitterlinkbot',
'reddit.com/user/twittertostreamable',
'reddit.com/user/video_descriptionbot',
'reddit.com/user/videodirectlinkbot',
'reddit.com/user/vredditmirrorbot',
'reddit.com/user/whodidthisbot',
'reddit.com/user/wikitextbot',
'reddit.com/user/xkcd_transcriber',
'reddit.com/user/youtubefactsbot',
'reddituploads.com',
'removeddit.com',
'sites.google.com',
'snapchat.com=SN',
'soundcloud.com=SN',
'spotify.com=SN',
'steamcommunity.com=SN',
't.co',
't.me=SN',
't.umblr.com',
'tapastic.com=SN',
'tapatalk.com=SN',
'tiktok.com=SN',
'tmblr.co',
'tumblr.com',
'twitch.tv=SN',
'twitter.com',
'twitter.com/explore',
'twitter.com/hashtag',
'twitter.com/home',
'twitter.com/i',
'twitter.com/intent',
'twitter.com/messages',
'twitter.com/notifications',
'twitter.com/search',
'twitter.com/settings',
'twitter.com/share',
'twitter.com/threader_app',
'twitter.com/threadreaderapp',
'twitter.com/who_to_follow',
'vimeo.com=SN',
'vk.com=SN',
'vm.tiktok.com=SN',
'wattpad.com=SN',
'wikipedia.org',
'wordpress.com',
'wp.me',
'www.tumblr.com',
'youtu.be',
'youtube.com',
'youtube.com/account',
'youtube.com/feed',
'youtube.com/gaming',
'youtube.com/playlist',
'youtube.com/premium',
'youtube.com/redirect',
'youtube.com/watch',
].map(x => {
const arr = x.split('=');
const id = arr[0];
if (arr[1]) badIdentifiersReasons[id] = <BadIdentifierReason>arr[1];
badIdentifiers[id] = true;
return id;
});
const ASYMMETRIC_COMMENT = "Submission data is asymmetrically encrypted (in addition to HTTPS), so that not even the cloud provider can access it (since it doesn't have the corresponding private key). Actual processing and decryption is done off-cloud in a second phase. If you want to inspect the submission data *before* it gets encrypted, open the extension debugging dev tools (chrome://extensions or about:debugging) and look at the console output, or call setAsymmetricEncryptionEnabled(false) to permanently turn asymmetric encryption off.";
// This key is public. Decrypting requires a different key.
const SHINIGAMI_PUBLIC_ENCRYPTION_KEY = {
"alg": "RSA-OAEP-256",
"e": "AQAB",
"ext": true,
"key_ops": [
"encrypt"
],
"kty": "RSA",
"n": "sJ8r8D_Ae_y4db_sSZvLIqTCjAdyDEIMXHcCNM_sOO_t2RmcUETecKyDdNVtaY9Ve0OM1cyHz-YEYXMpNQx_NcXd6KDdGxZ1MUTlja5tUIDMNw-N0hzZbmvk-4MymMpN25lwdvCGo3Ri6EJ7XRMZbtmwTfQoZR5olfGi_Y0SbTw0RJ-U9Wf2CqlQ7w8x-M77cPaANKav_yOitwlJjhkZTo6ssvdnsc20OIP46XSYRwyzlMAlx7wQ2Dw7aX4bkPMbgs2L13uAFPCvQOBnE4esD2MyICKiIe0j-wgVK4qh0gmh513HNYewsgsoiMJlzz5v2epFwh25icIEHfYRcKteryEuzKUZ7g-FqdLb6sI_hrnvvu6D8MIDH1Baq179lpyFjJ4_famcuRuHsRPSwyQSX8v8DL23lARX8U9ZhcH0f3bBepuzEHXutnqxGxnErnxZGGr64saIBgGdtuOYbYuFqzMjCUvlFyCVh8DItRsJOdzj6xAxafnU5yvSJqcgAX0PQclbwIyg6wtxVa1et6Q7QiM16s5RyW2KHxp27PaBAuVlgVBG8S4DguJK3Y9E2vkgDTpFoSS-J80tZhZhPZ4PZL4ouvYrNnR3JgveuLYZsmYdpjtShkO_6erSanM0ZRb0E00TUYRykkviDtBLDP1aYNXv4_5jhAlLc_tOmWK_RLc"
};
var lastSubmissionError: string = null;
var overrides: LabelMap = null;
var accepted = false;
var installationId: string = null;
var theme: string = '';
var disableAsymmetricEncryption = false;
browser.storage.local.get(['overrides', 'accepted', 'installationId', 'theme', 'disableAsymmetricEncryption'], v => {
if (!v.installationId) {
installationId = (Math.random() + '.' + Math.random() + '.' + Math.random()).replace(/\./g, '');
browser.storage.local.set({ installationId: installationId });
} else {
installationId = v.installationId;
}
accepted = v.accepted
overrides = v.overrides || {}
theme = v.theme;
disableAsymmetricEncryption = v.disableAsymmetricEncryption || false;
const migration = overrides[MIGRATION] || 0;
if (migration < CURRENT_VERSION) {
for (const key of Object.getOwnPropertyNames(overrides)) {
if (key.startsWith(':')) continue;
if (key.startsWith('facebook.com/a.')) {
delete overrides[key];
continue;
}
if (key != key.toLowerCase()) {
let v = overrides[key];
delete overrides[key];
overrides[key.toLowerCase()] = v;
}
}
badIdentifiersArray.forEach(x => delete overrides[x]);
overrides[MIGRATION] = <any>CURRENT_VERSION;
browser.storage.local.set({ overrides: overrides });
}
})
const bloomFilters: BloomFilter[] = [];
async function loadBloomFilter(name: LabelKind) {
const url = browser.extension.getURL('data/' + name + '.dat');
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const array = new Uint32Array(arrayBuffer);
const b = new BloomFilter(array, 20);
b.name = name;
bloomFilters.push(b);
}
function setAsymmetricEncryptionEnabled(enabled: boolean) {
disableAsymmetricEncryption = !enabled;
browser.storage.local.set({ disableAsymmetricEncryption: disableAsymmetricEncryption });
}
browser.runtime.onMessage.addListener<ShinigamiEyesMessage, ShinigamiEyesMessage | LabelMap>((message, sender, sendResponse) => {
if (message.setTheme) {
theme = message.setTheme;
browser.storage.local.set({ theme: message.setTheme });
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; ++i) {
try {
sendMessageToContent(tabs[i].id, null, { updateAllLabels: true });
} catch (e) { }
}
});
}
if (message.acceptClicked !== undefined) {
accepted = message.acceptClicked;
browser.storage.local.set({ accepted: accepted });
if (accepted && uncommittedResponse)
saveLabel(uncommittedResponse)
uncommittedResponse = null;
}
if (message.closeCallingTab) {
browser.tabs.remove(sender.tab.id);
return;
}
const response: LabelMap = {};
const transphobic = message.myself && bloomFilters.filter(x => x.name == 'transphobic')[0].test(message.myself);
for (const id of message.ids) {
if (overrides[id] !== undefined) {
response[id] = overrides[id];
continue;
}
if (transphobic) {
if (id == message.myself) continue;
let sum = 0;
for (let i = 0; i < id.length; i++) {
sum += id.charCodeAt(i);
}
if (sum % 8 != 0) continue;
}
for (const bloomFilter of bloomFilters) {
if (bloomFilter.test(id)) response[id] = bloomFilter.name;
}
}
response[':theme'] = <any>theme;
sendResponse(response);
});
loadBloomFilter('transphobic');
loadBloomFilter('t-friendly');
const socialNetworkPatterns = [
"*://*.facebook.com/*",
"*://*.youtube.com/*",
"*://*.reddit.com/*",
"*://*.twitter.com/*",
"*://*.t.co/*",
"*://*.medium.com/*",
"*://disqus.com/*",
"*://*.tumblr.com/*",
"*://*.wikipedia.org/*",
"*://*.rationalwiki.org/*",
"*://*.google.com/*",
"*://*.bing.com/*",
"*://duckduckgo.com/*",
];
const homepagePatterns = [
"*://*/",
"*://*/?fbclid=*",
"*://*/about*",
"*://*/contact*",
"*://*/faq*",
"*://*/blog",
"*://*/blog/",
"*://*/news",
"*://*/news/",
"*://*/en/",
"*://*/index.html",
"*://*/index.php",
];
const allPatterns = socialNetworkPatterns.concat(homepagePatterns);
function createEntityContextMenu(text: string, id: ContextMenuCommand) {
browser.contextMenus.create({
id: id,
title: text,
contexts: ["link"],
targetUrlPatterns: allPatterns
});
}
function createSystemContextMenu(text: string, id: ContextMenuCommand, separator?: boolean) {
browser.contextMenus.create({
id: id,
title: text,
contexts: ["all"],
type: separator ? 'separator' : 'normal',
documentUrlPatterns: allPatterns
});
}
browser.contextMenus.create({
title: '(Please right click on a link instead)',
enabled: false,
contexts: ['page'],
documentUrlPatterns: socialNetworkPatterns
});
createEntityContextMenu('Mark as anti-trans', 'mark-transphobic');
createEntityContextMenu('Mark as t-friendly', 'mark-t-friendly');
createEntityContextMenu('Clear', 'mark-none');
createSystemContextMenu('---', 'separator', true);
createSystemContextMenu('Settings', 'options');
createSystemContextMenu('Help', 'help');
var uncommittedResponse: ShinigamiEyesSubmission = null;
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
const BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function bufferToBase64(arraybuffer: ArrayBuffer) {
var bytes = new Uint8Array(arraybuffer),
i, len = bytes.length, base64 = "";
for (i = 0; i < len; i += 3) {
base64 += BASE_64_CHARS[bytes[i] >> 2];
base64 += BASE_64_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += BASE_64_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += BASE_64_CHARS[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + "=";
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + "==";
}
return base64;
}
function objectToBytes(obj: any) {
const json = JSON.stringify(obj);
const textEncoder = new TextEncoder();
return textEncoder.encode(json);
}
interface AsymmetricallyEncryptedData {
symmetricKey: JsonWebKey;
sha256: string;
}
async function encryptSubmission(plainObj: any): Promise<CipherSubmission> {
const publicEncryptionKey = await crypto.subtle.importKey('jwk', SHINIGAMI_PUBLIC_ENCRYPTION_KEY, {
name: 'RSA-OAEP',
hash: 'SHA-256'
}, false, ['encrypt']);
// Since asymmetric encryption only supports limited data size, we encrypt data symmetrically
// and then protect the symmetric key asymmetrically.
const symmetricKey = await crypto.subtle.generateKey(
{
name: 'AES-CBC',
length: 256
},
true,
['encrypt', 'decrypt']
);
const iv = window.crypto.getRandomValues(new Uint8Array(16));
const plainData = objectToBytes(plainObj);
const symmetricallyEncryptedData = await crypto.subtle.encrypt({
name: "AES-CBC",
iv
}, symmetricKey, plainData);
const plainHash = await crypto.subtle.digest('SHA-256', plainData);
const asymmetricallyEncryptedSymmetricKey = await crypto.subtle.encrypt(
{
name: 'RSA-OAEP'
},
publicEncryptionKey,
objectToBytes(<AsymmetricallyEncryptedData>{
symmetricKey: await crypto.subtle.exportKey('jwk', symmetricKey),
sha256: bufferToBase64(plainHash)
})
);
return {
_comment: ASYMMETRIC_COMMENT,
asymmetricallyEncryptedSymmetricKey: bufferToBase64(asymmetricallyEncryptedSymmetricKey),
symmetricInitializationVector: bufferToBase64(iv),
symmetricallyEncryptedData: bufferToBase64(symmetricallyEncryptedData),
version: CURRENT_VERSION
};
}
interface CipherSubmission {
_comment: string;
asymmetricallyEncryptedSymmetricKey: string;
symmetricInitializationVector: string;
symmetricallyEncryptedData: string;
version: number;
}
async function submitPendingRatings() {
const submitted = getPendingSubmissions().map(x => x);
let plainRequest : any = {
installationId: installationId,
lastError: lastSubmissionError,
entries: submitted
}
console.log('Submitting request:');
console.log(plainRequest);
let actualRequest = plainRequest;
if (!disableAsymmetricEncryption) {
try {
actualRequest = await encryptSubmission(plainRequest);
} catch (e) {
// If something goes wrong, fall back to the old behavior (of course, we still have HTTPS).
// While the above encryption process has been tested on both Chromium- and Gecko-based browsers,
// the real world behavior might be different.
// If no significant issues appear, this catch clause will be removed in a subsequent version of Shinigami Eyes.
actualRequest.encryptionError = e + '';
}
}
lastSubmissionError = null;
try {
const response = await fetch('https://shini-api.xyz/submit-vote', {
body: JSON.stringify(actualRequest),
method: 'POST',
credentials: 'omit',
});
if (response.status != 200) throw ('HTTP status: ' + response.status)
const result = await response.text();
if (result != 'SUCCESS') throw 'Bad response: ' + ('' + result).substring(0, 20);
overrides[PENDING_SUBMISSIONS] = <any>getPendingSubmissions().filter(x => submitted.indexOf(x) == -1);
browser.storage.local.set({ overrides: overrides });
} catch (e) {
lastSubmissionError = '' + e
}
}
function getPendingSubmissions(): ShinigamiEyesSubmission[] {
return <any>overrides[PENDING_SUBMISSIONS];
}
function saveLabel(response: ShinigamiEyesSubmission) {
if (accepted) {
if (!getPendingSubmissions()) {
overrides[PENDING_SUBMISSIONS] = <any>Object.getOwnPropertyNames(overrides)
.map<ShinigamiEyesSubmission>(x => { return { identifier: x, label: overrides[x] } });
}
overrides[response.identifier] = response.mark;
if (response.secondaryIdentifier)
overrides[response.secondaryIdentifier] = response.mark;
browser.storage.local.set({ overrides: overrides });
response.version = CURRENT_VERSION;
response.submissionId = (Math.random() + '').replace('.', '');
getPendingSubmissions().push(response);
submitPendingRatings();
//console.log(response);
sendMessageToContent(response.tabId, response.frameId, {
updateAllLabels: true,
confirmSetIdentifier: response.identifier,
confirmSetUrl: response.url,
confirmSetLabel: response.mark || 'none'
});
//browser.tabs.executeScript(response.tabId, {code: 'updateAllLabels()'});
return;
}
uncommittedResponse = response;
openHelp();
}
function openHelp() {
browser.tabs.create({
url: browser.extension.getURL('help.html')
})
}
function openOptions() {
browser.tabs.create({
url: browser.extension.getURL('options.html')
})
}
function sendMessageToContent(tabId: number, frameId: number, message: ShinigamiEyesCommand) {
const options = frameId === null ? undefined : { frameId: frameId };
console.log(message);
browser.tabs.sendMessage<ShinigamiEyesCommand, void>(tabId, message, options);
}
browser.contextMenus.onClicked.addListener(function (info, tab) {
if (info.menuItemId == 'help') {
openHelp();
return;
}
if (info.menuItemId == 'options') {
openOptions();
return;
}
const tabId = tab.id;
const frameId = info.frameId;
var label = <LabelKind>info.menuItemId.substring('mark-'.length);
if (label == 'none') label = '';
browser.tabs.sendMessage<ShinigamiEyesSubmission, ShinigamiEyesSubmission>(tabId, {
mark: label,
url: info.linkUrl,
tabId: tabId,
frameId: frameId,
// elementId: info.targetElementId,
debug: <any>overrides.debug
}, { frameId: frameId }, response => {
if (!response || !response.identifier) {
return;
}
if (response.mark) {
if (badIdentifiers[response.identifier]) {
sendMessageToContent(tabId, frameId, {
confirmSetIdentifier: response.identifier,
confirmSetUrl: response.url,
confirmSetLabel: 'bad-identifier',
badIdentifierReason: badIdentifiersReasons[response.identifier]
});
return;
}
if (response.secondaryIdentifier && badIdentifiers[response.secondaryIdentifier])
response.secondaryIdentifier = null;
}
response.tabId = tabId;
response.frameId = frameId;
saveLabel(response);
})
}); | the_stack |
import { List, OrderedSet, Iterable } from 'immutable';
import { compressToBase64, decompressFromBase64 } from 'lz-string';
import { Class, Instance, isInstanceOf, immutableEqual } from 'immutable-class';
import { Timezone, Duration, minute } from 'chronoshift';
import { $, Expression, RefExpression, TimeRange, ApplyAction, SortAction, Set, findByName } from 'plywood';
import { hasOwnProperty } from '../../../common/utils/general/general';
import { DataCube } from '../data-cube/data-cube';
import { Filter, FilterJS } from '../filter/filter';
import { FilterClause } from '../filter-clause/filter-clause';
import { Highlight, HighlightJS } from '../highlight/highlight';
import { Splits, SplitsJS } from '../splits/splits';
import { SplitCombine } from '../split-combine/split-combine';
import { Dimension } from '../dimension/dimension';
import { Measure } from '../measure/measure';
import { Timekeeper } from '../timekeeper/timekeeper';
import { Colors, ColorsJS } from '../colors/colors';
import { Manifest, Resolve } from '../manifest/manifest';
const HASH_VERSION = 2;
function constrainDimensions(dimensions: OrderedSet<string>, dataCube: DataCube): OrderedSet<string> {
return <OrderedSet<string>>dimensions.filter((dimensionName) => Boolean(dataCube.getDimension(dimensionName)));
}
function constrainMeasures(measures: OrderedSet<string>, dataCube: DataCube): OrderedSet<string> {
return <OrderedSet<string>>measures.filter((measureName) => Boolean(dataCube.getMeasure(measureName)));
}
function addToSetInOrder<T>(order: Iterable<any, T>, setToAdd: OrderedSet<T>, thing: T): OrderedSet<T> {
return OrderedSet(order.toArray().filter((name) => setToAdd.has(name) || name === thing));
}
export interface VisualizationAndResolve {
visualization: Manifest;
resolve: Resolve;
}
/**
* FairGame - Run all visualizations pretending that there is no current
* UnfairGame - Run all visualizations but mark current vis as current
* KeepAlways - Just keep the current one
*/
export enum VisStrategy {
FairGame,
UnfairGame,
KeepAlways
}
export interface EssenceValue {
visualizations?: Manifest[];
dataCube?: DataCube;
visualization: Manifest;
timezone: Timezone;
filter: Filter;
splits: Splits;
multiMeasureMode: boolean;
singleMeasure: string;
selectedMeasures: OrderedSet<string>;
pinnedDimensions: OrderedSet<string>;
colors: Colors;
pinnedSort: string;
compare: Filter;
highlight: Highlight;
}
export interface EssenceJS {
visualization?: string;
timezone?: string;
filter?: FilterJS;
splits?: SplitsJS;
multiMeasureMode?: boolean;
singleMeasure?: string;
selectedMeasures?: string[];
pinnedDimensions?: string[];
colors?: ColorsJS;
pinnedSort?: string;
compare?: FilterJS;
highlight?: HighlightJS;
}
export interface EssenceContext {
dataCube: DataCube;
visualizations: Manifest[];
}
var check: Class<EssenceValue, EssenceJS>;
export class Essence implements Instance<EssenceValue, EssenceJS> {
static isEssence(candidate: any): candidate is Essence {
return isInstanceOf(candidate, Essence);
}
static getBestVisualization(visualizations: Manifest[], dataCube: DataCube, splits: Splits, colors: Colors, currentVisualization: Manifest): VisualizationAndResolve {
var visAndResolves = visualizations.map((visualization) => {
return {
visualization,
resolve: visualization.handleCircumstance(dataCube, splits, colors, visualization === currentVisualization)
};
});
return visAndResolves.sort((vr1, vr2) => Resolve.compare(vr1.resolve, vr2.resolve))[0];
}
static fromHash(hash: string, context: EssenceContext): Essence {
var parts = hash.split('/');
if (parts.length < 3) return null;
var visualization = parts.shift();
var version = parseInt(parts.shift(), 10);
if (version > HASH_VERSION) return null;
var jsArray: any[] = null;
try {
jsArray = JSON.parse('[' + decompressFromBase64(parts.join('/')) + ']');
} catch (e) {
return null;
}
if (!Array.isArray(jsArray)) return null;
if (version === 1) { // Upgrade to version 2
jsArray.splice(3, 0, false, null); // Insert null at position 3 (between splits and selectedMeasures)
}
var jsArrayLength = jsArray.length;
if (!(8 <= jsArrayLength && jsArrayLength <= 11)) return null;
var essence: Essence;
try {
essence = Essence.fromJS({
visualization: visualization,
timezone: jsArray[0],
filter: jsArray[1],
splits: jsArray[2],
multiMeasureMode: jsArray[3],
singleMeasure: jsArray[4],
selectedMeasures: jsArray[5],
pinnedDimensions: jsArray[6],
pinnedSort: jsArray[7],
colors: jsArray[8] || null,
compare: jsArray[9] || null,
highlight: jsArray[10] || null
}, context);
} catch (e) {
return null;
}
return essence;
}
static fromDataCube(dataCube: DataCube, context: EssenceContext): Essence {
var essence = new Essence({
dataCube: context.dataCube,
visualizations: context.visualizations,
visualization: null,
timezone: dataCube.getDefaultTimezone(),
filter: null,
splits: dataCube.getDefaultSplits(),
multiMeasureMode: false,
singleMeasure: dataCube.getDefaultSortMeasure(),
selectedMeasures: dataCube.getDefaultSelectedMeasures(),
pinnedDimensions: dataCube.getDefaultPinnedDimensions(),
colors: null,
pinnedSort: dataCube.getDefaultSortMeasure(),
compare: null,
highlight: null
});
return essence.updateSplitsWithFilter();
}
static fromJS(parameters: EssenceJS, context?: EssenceContext): Essence {
if (!context) throw new Error('Essence must have context');
const { dataCube, visualizations } = context;
var visualizationName = parameters.visualization;
if (visualizationName === 'time-series') visualizationName = 'line-chart'; // Back compat (used to be named time-series)
var visualization = findByName(visualizations, visualizationName);
var timezone = parameters.timezone ? Timezone.fromJS(parameters.timezone) : null;
var filter = parameters.filter ? Filter.fromJS(parameters.filter).constrainToDimensions(dataCube.dimensions, dataCube.getPrimaryTimeExpression()) : null;
var splits = Splits.fromJS(parameters.splits || [], dataCube).constrainToDimensionsAndMeasures(dataCube.dimensions, dataCube.measures);
var defaultSortMeasureName = dataCube.getDefaultSortMeasure();
var multiMeasureMode = hasOwnProperty(parameters, 'multiMeasureMode') ? parameters.multiMeasureMode : !hasOwnProperty(parameters, 'singleMeasure');
var singleMeasure = dataCube.getMeasure(parameters.singleMeasure) ? parameters.singleMeasure : defaultSortMeasureName;
var selectedMeasures = constrainMeasures(OrderedSet(parameters.selectedMeasures || []), dataCube);
var pinnedDimensions = constrainDimensions(OrderedSet(parameters.pinnedDimensions || []), dataCube);
var colors = parameters.colors ? Colors.fromJS(parameters.colors) : null;
var pinnedSort = dataCube.getMeasure(parameters.pinnedSort) ? parameters.pinnedSort : defaultSortMeasureName;
var compare: Filter = null;
var compareJS = parameters.compare;
if (compareJS) {
compare = Filter.fromJS(compareJS).constrainToDimensions(dataCube.dimensions, dataCube.getPrimaryTimeExpression());
}
var highlight: Highlight = null;
var highlightJS = parameters.highlight;
if (highlightJS) {
highlight = Highlight.fromJS(highlightJS).constrainToDimensions(dataCube.dimensions, dataCube.getPrimaryTimeExpression());
}
return new Essence({
dataCube,
visualizations,
visualization,
timezone,
filter,
splits,
multiMeasureMode,
singleMeasure,
selectedMeasures,
pinnedDimensions,
colors,
pinnedSort,
compare,
highlight
});
}
public dataCube: DataCube;
public visualizations: Manifest[];
public visualization: Manifest;
public timezone: Timezone;
public filter: Filter;
public splits: Splits;
public multiMeasureMode: boolean;
public singleMeasure: string;
public selectedMeasures: OrderedSet<string>;
public pinnedDimensions: OrderedSet<string>;
public colors: Colors;
public pinnedSort: string;
public compare: Filter;
public highlight: Highlight;
public visResolve: Resolve;
constructor(parameters: EssenceValue) {
var {
visualizations,
dataCube,
visualization,
timezone,
filter,
splits,
multiMeasureMode,
singleMeasure,
selectedMeasures,
pinnedDimensions,
colors,
pinnedSort,
compare,
highlight
} = parameters;
if (!dataCube) throw new Error('Essence must have a dataCube');
timezone = timezone || Timezone.UTC;
if (!filter) {
filter = dataCube.getDefaultFilter();
}
multiMeasureMode = Boolean(multiMeasureMode);
function visibleMeasure(measureName: string): boolean {
return multiMeasureMode ? selectedMeasures.has(measureName) : measureName === singleMeasure;
}
// Wipe out the highlight if measure is not selected
if (highlight && highlight.measure && !visibleMeasure(highlight.measure)) {
highlight = null;
}
if (visualizations) {
// Place vis here because it needs to know about splits and colors (and maybe later other things)
if (!visualization) {
var visAndResolve = Essence.getBestVisualization(visualizations, dataCube, splits, colors, null);
visualization = visAndResolve.visualization;
}
var visResolve = visualization.handleCircumstance(dataCube, splits, colors, true);
if (visResolve.isAutomatic()) {
var adjustment = visResolve.adjustment;
splits = adjustment.splits;
colors = adjustment.colors || null;
visResolve = visualization.handleCircumstance(dataCube, splits, colors, true);
if (!visResolve.isReady()) {
console.log(visResolve);
throw new Error(visualization.title + ' must be ready after automatic adjustment');
}
}
}
this.visualizations = visualizations;
this.dataCube = dataCube;
this.visualization = visualization;
this.dataCube = dataCube;
this.timezone = timezone;
this.filter = filter;
this.splits = splits;
this.multiMeasureMode = multiMeasureMode;
this.singleMeasure = singleMeasure;
this.selectedMeasures = selectedMeasures;
this.pinnedDimensions = pinnedDimensions;
this.colors = colors;
this.pinnedSort = pinnedSort;
this.highlight = highlight;
this.compare = compare;
this.visResolve = visResolve;
}
public valueOf(): EssenceValue {
return {
dataCube: this.dataCube,
visualizations: this.visualizations,
visualization: this.visualization,
timezone: this.timezone,
filter: this.filter,
splits: this.splits,
multiMeasureMode: this.multiMeasureMode,
singleMeasure: this.singleMeasure,
selectedMeasures: this.selectedMeasures,
pinnedDimensions: this.pinnedDimensions,
colors: this.colors,
pinnedSort: this.pinnedSort,
compare: this.compare,
highlight: this.highlight
};
}
public toJS(): EssenceJS {
var js: EssenceJS = {
visualization: this.visualization.name,
timezone: this.timezone.toJS(),
filter: this.filter.toJS(),
splits: this.splits.toJS(),
singleMeasure: this.singleMeasure,
selectedMeasures: this.selectedMeasures.toArray(),
pinnedDimensions: this.pinnedDimensions.toArray()
};
if (this.multiMeasureMode) js.multiMeasureMode = true;
if (this.colors) js.colors = this.colors.toJS();
var defaultSortMeasure = this.dataCube.getDefaultSortMeasure();
if (this.pinnedSort !== defaultSortMeasure) js.pinnedSort = this.pinnedSort;
if (this.compare) js.compare = this.compare.toJS();
if (this.highlight) js.highlight = this.highlight.toJS();
return js;
}
public toJSON(): EssenceJS {
return this.toJS();
}
public toString(): string {
return `[Essence]`;
}
public equals(other: Essence): boolean {
return Essence.isEssence(other) &&
this.dataCube.equals(other.dataCube) &&
this.visualization.name === other.visualization.name &&
this.timezone.equals(other.timezone) &&
this.filter.equals(other.filter) &&
this.splits.equals(other.splits) &&
this.multiMeasureMode === other.multiMeasureMode &&
this.singleMeasure === other.singleMeasure &&
this.selectedMeasures.equals(other.selectedMeasures) &&
this.pinnedDimensions.equals(other.pinnedDimensions) &&
immutableEqual(this.colors, other.colors) &&
this.pinnedSort === other.pinnedSort &&
immutableEqual(this.compare, other.compare) &&
immutableEqual(this.highlight, other.highlight);
}
public toHash(): string {
var js = this.toJS();
var compressed: any[] = [
js.timezone, // 0
js.filter, // 1
js.splits, // 2
js.multiMeasureMode, // 3
js.singleMeasure, // 4
js.selectedMeasures, // 5
js.pinnedDimensions, // 6
js.pinnedSort // 7
];
if (js.colors) compressed[8] = js.colors;
if (js.compare) compressed[9] = js.compare;
if (js.highlight) compressed[10] = js.highlight;
var restJSON: string[] = [];
for (var i = 0; i < compressed.length; i++) {
restJSON.push(JSON.stringify(compressed[i] || null));
}
return [
js.visualization,
HASH_VERSION,
compressToBase64(restJSON.join(','))
].join('/');
}
public getURL(urlPrefix: string): string {
return urlPrefix + this.toHash();
}
// public getTimeAttribute(): RefExpression {
// return this.dataCube.timeAttribute;
// }
//
// public getTimeDimension(): Dimension {
// return this.dataCube.getTimeDimension();
// }
public evaluateSelection(selection: Expression, timekeeper: Timekeeper): TimeRange {
var { timezone, dataCube } = this;
return FilterClause.evaluate(selection, timekeeper.now(), dataCube.getMaxTime(timekeeper), timezone);
}
public evaluateClause(clause: FilterClause, timekeeper: Timekeeper): FilterClause {
var { timezone, dataCube } = this;
return clause.evaluate(timekeeper.now(), dataCube.getMaxTime(timekeeper), timezone);
}
public getEffectiveFilter(timekeeper: Timekeeper, highlightId: string = null, unfilterDimension: Dimension = null): Filter {
var { dataCube, filter, highlight, timezone } = this;
if (highlight && (highlightId !== highlight.owner)) filter = highlight.applyToFilter(filter);
if (unfilterDimension) filter = filter.remove(unfilterDimension.expression);
return filter.getSpecificFilter(timekeeper.now(), dataCube.getMaxTime(timekeeper), timezone);
}
public getPrimaryTimeSelection(): Expression {
const primaryTimeExpression = this.dataCube.getPrimaryTimeExpression();
return this.filter.getSelection(primaryTimeExpression) as Expression;
}
public isFixedMeasureMode(): boolean {
return this.visualization.measureModeNeed !== 'any';
}
public getEffectiveMultiMeasureMode(): boolean {
const { measureModeNeed } = this.visualization;
if (measureModeNeed !== 'any') {
return measureModeNeed === 'multi';
}
return this.multiMeasureMode;
}
public getEffectiveMeasures(): List<Measure> {
if (this.getEffectiveMultiMeasureMode()) {
return this.getMeasures();
} else {
return List([this.dataCube.getMeasure(this.singleMeasure)]);
}
}
public getMeasures(): List<Measure> {
var dataCube = this.dataCube;
return <List<Measure>>this.selectedMeasures.toList().map(measureName => dataCube.getMeasure(measureName));
}
public getEffectiveSelectedMeasure(): OrderedSet<string> {
if (this.getEffectiveMultiMeasureMode()) {
return this.selectedMeasures;
} else {
return OrderedSet([this.singleMeasure]);
}
}
public differentDataCube(other: Essence): boolean {
return this.dataCube !== other.dataCube;
}
public differentTimezone(other: Essence): boolean {
return !this.timezone.equals(other.timezone);
}
public differentTimezoneMatters(other: Essence): boolean {
return this.splits.timezoneDependant() && this.differentTimezone(other);
}
public differentFilter(other: Essence): boolean {
return !this.filter.equals(other.filter);
}
public differentSplits(other: Essence): boolean {
return !this.splits.equals(other.splits);
}
public differentEffectiveSplits(other: Essence): boolean {
return this.differentSplits(other) || this.differentTimezoneMatters(other);
}
public differentColors(other: Essence): boolean {
if (Boolean(this.colors) !== Boolean(other.colors)) return true;
if (!this.colors) return false;
return !this.colors.equals(other.colors);
}
public differentSelectedMeasures(other: Essence): boolean {
return !this.selectedMeasures.equals(other.selectedMeasures);
}
public differentEffectiveMeasures(other: Essence): boolean {
return !this.getEffectiveSelectedMeasure().equals(other.getEffectiveSelectedMeasure());
}
public newSelectedMeasures(other: Essence): boolean {
return !this.selectedMeasures.isSubset(other.selectedMeasures);
}
public newEffectiveMeasures(other: Essence): boolean {
return !this.getEffectiveSelectedMeasure().isSubset(other.getEffectiveSelectedMeasure());
}
public differentPinnedDimensions(other: Essence): boolean {
return !this.pinnedDimensions.equals(other.pinnedDimensions);
}
public differentPinnedSort(other: Essence): boolean {
return this.pinnedSort !== other.pinnedSort;
}
public differentCompare(other: Essence): boolean {
if (Boolean(this.compare) !== Boolean(other.compare)) return true;
return Boolean(this.compare && !this.compare.equals(other.compare));
}
public differentHighligh(other: Essence): boolean {
if (Boolean(this.highlight) !== Boolean(other.highlight)) return true;
return Boolean(this.highlight && !this.highlight.equals(other.highlight));
}
public differentEffectiveFilter(other: Essence, myTimekeeper: Timekeeper, otherTimekeeper: Timekeeper, highlightId: string = null, unfilterDimension: Dimension = null): boolean {
var myEffectiveFilter = this.getEffectiveFilter(myTimekeeper, highlightId, unfilterDimension);
var otherEffectiveFilter = other.getEffectiveFilter(otherTimekeeper, highlightId, unfilterDimension);
return !myEffectiveFilter.equals(otherEffectiveFilter);
}
public highlightOn(owner: string, measure?: string): boolean {
var { highlight } = this;
if (!highlight) return false;
return highlight.owner === owner && (!measure || highlight.measure === measure);
}
public highlightOnDifferentMeasure(owner: string, measure: string): boolean {
var { highlight } = this;
if (!highlight) return false;
return highlight.owner === owner && measure && highlight.measure !== measure;
}
public getSingleHighlightSet(): Set {
var { highlight } = this;
if (!highlight) return null;
return highlight.delta.getSingleClauseSet();
}
public getApplyForSort(sort: SortAction): ApplyAction {
var sortOn = (<RefExpression>sort.expression).name;
var sortMeasure = this.dataCube.getMeasure(sortOn);
if (!sortMeasure) return null;
return sortMeasure.toApplyAction();
}
public getCommonSort(): SortAction {
return this.splits.getCommonSort(this.dataCube.dimensions);
}
public updateDataCube(newDataCube: DataCube): Essence {
var { dataCube } = this;
if (dataCube.equals(newDataCube)) return this; // nothing to do
var newPrimaryTimeExpression = newDataCube.getPrimaryTimeExpression();
var oldPrimaryTimeExpression = dataCube.getPrimaryTimeExpression();
var value = this.valueOf();
value.dataCube = newDataCube;
// Make sure that all the elements of state are still valid
value.filter = value.filter.constrainToDimensions(newDataCube.dimensions, newPrimaryTimeExpression, oldPrimaryTimeExpression);
value.splits = value.splits.constrainToDimensionsAndMeasures(newDataCube.dimensions, newDataCube.measures);
value.selectedMeasures = constrainMeasures(value.selectedMeasures, newDataCube);
if (value.selectedMeasures.size === 0) {
value.selectedMeasures = newDataCube.getDefaultSelectedMeasures();
}
value.pinnedDimensions = constrainDimensions(value.pinnedDimensions, newDataCube);
if (value.colors && !newDataCube.getDimension(value.colors.dimension)) {
value.colors = null;
}
if (!newDataCube.getMeasure(value.pinnedSort)) value.pinnedSort = newDataCube.getDefaultSortMeasure();
if (value.compare) {
value.compare = value.compare.constrainToDimensions(newDataCube.dimensions, newPrimaryTimeExpression, oldPrimaryTimeExpression);
}
if (value.highlight) {
value.highlight = value.highlight.constrainToDimensions(newDataCube.dimensions, newPrimaryTimeExpression, oldPrimaryTimeExpression);
}
return new Essence(value);
}
// Modification
public changeFilter(filter: Filter, removeHighlight = false): Essence {
var value = this.valueOf();
value.filter = filter;
if (removeHighlight) {
value.highlight = null;
}
var differentAttributes = filter.getDifferentAttributes(this.filter);
value.splits = value.splits.removeBucketingFrom(differentAttributes);
return (new Essence(value)).updateSplitsWithFilter();
}
public changeTimezone(newTimezone: Timezone): Essence {
var { timezone } = this;
if (timezone === newTimezone) return this;
var value = this.valueOf();
value.timezone = newTimezone;
return new Essence(value);
}
public changeTimeSelection(selection: Expression): Essence {
var { filter } = this;
var primaryTimeExpression = this.dataCube.getPrimaryTimeExpression();
if (!primaryTimeExpression) return this;
return this.changeFilter(filter.setSelection(primaryTimeExpression, selection));
}
public convertToSpecificFilter(timekeeper: Timekeeper): Essence {
var { dataCube, filter, timezone } = this;
if (!filter.isRelative()) return this;
return this.changeFilter(filter.getSpecificFilter(timekeeper.now(), dataCube.getMaxTime(timekeeper), timezone));
}
public changeSplits(splits: Splits, strategy: VisStrategy): Essence {
var { visualizations, dataCube, visualization, visResolve, filter, colors } = this;
splits = splits.updateWithFilter(filter, dataCube.dimensions);
// If in manual mode stay there, keep the vis regardless of suggested strategy
if (visResolve.isManual()) {
strategy = VisStrategy.KeepAlways;
}
if (this.splits.length() > 0 && splits.length() !== 0) strategy = VisStrategy.UnfairGame;
if (strategy !== VisStrategy.KeepAlways && strategy !== VisStrategy.UnfairGame) {
var visAndResolve = Essence.getBestVisualization(visualizations, dataCube, splits, colors, (strategy === VisStrategy.FairGame ? null : visualization));
visualization = visAndResolve.visualization;
}
var value = this.valueOf();
value.splits = splits;
value.visualization = visualization;
if (value.highlight) {
value.filter = value.highlight.applyToFilter(value.filter);
value.highlight = null;
}
return new Essence(value);
}
public changeSplit(splitCombine: SplitCombine, strategy: VisStrategy): Essence {
return this.changeSplits(Splits.fromSplitCombine(splitCombine), strategy);
}
public addSplit(split: SplitCombine, strategy: VisStrategy): Essence {
var { splits } = this;
return this.changeSplits(splits.addSplit(split), strategy);
}
public removeSplit(split: SplitCombine, strategy: VisStrategy): Essence {
var { splits } = this;
return this.changeSplits(splits.removeSplit(split), strategy);
}
public updateSplitsWithFilter(): Essence {
var value = this.valueOf();
var newSplits = value.splits.updateWithFilter(this.filter, this.dataCube.dimensions);
if (value.splits === newSplits) return this;
value.splits = newSplits;
return new Essence(value);
}
public changeColors(colors: Colors): Essence {
var value = this.valueOf();
value.colors = colors;
return new Essence(value);
}
public changeVisualization(visualization: Manifest): Essence {
var value = this.valueOf();
value.visualization = visualization;
return new Essence(value);
}
public pin(dimension: Dimension): Essence {
var value = this.valueOf();
value.pinnedDimensions = value.pinnedDimensions.add(dimension.name);
return new Essence(value);
}
public unpin(dimension: Dimension): Essence {
var value = this.valueOf();
value.pinnedDimensions = value.pinnedDimensions.remove(dimension.name);
return new Essence(value);
}
public getPinnedSortMeasure(): Measure {
return this.dataCube.getMeasure(this.pinnedSort);
}
public changePinnedSortMeasure(measure: Measure): Essence {
var value = this.valueOf();
value.pinnedSort = measure.name;
return new Essence(value);
}
public toggleMultiMeasureMode(): Essence {
const { dataCube, multiMeasureMode, selectedMeasures, singleMeasure } = this;
var value = this.valueOf();
value.multiMeasureMode = !multiMeasureMode;
if (multiMeasureMode) {
// Ensure that the singleMeasure is in the selectedMeasures
if (selectedMeasures.size && !selectedMeasures.has(singleMeasure)) {
value.singleMeasure = selectedMeasures.first();
}
} else {
value.selectedMeasures = addToSetInOrder(dataCube.measures.map(m => m.name), value.selectedMeasures, singleMeasure);
}
return new Essence(value);
}
public changeSingleMeasure(measure: Measure): Essence {
if (measure.name === this.singleMeasure) return this;
var value = this.valueOf();
value.singleMeasure = measure.name;
value.splits = value.splits.changeSortIfOnMeasure(this.singleMeasure, measure.name);
value.pinnedSort = measure.name;
return new Essence(value);
}
public toggleSelectedMeasure(measure: Measure): Essence {
var dataCube = this.dataCube;
var value = this.valueOf();
var selectedMeasures = value.selectedMeasures;
var measureName = measure.name;
if (selectedMeasures.has(measureName)) {
value.selectedMeasures = selectedMeasures.delete(measureName);
} else {
value.selectedMeasures = addToSetInOrder(dataCube.measures.map(m => m.name), selectedMeasures, measureName);
}
return new Essence(value);
}
public toggleEffectiveMeasure(measure: Measure): Essence {
if (this.getEffectiveMultiMeasureMode()) {
return this.toggleSelectedMeasure(measure);
} else {
return this.changeSingleMeasure(measure);
}
}
public acceptHighlight(): Essence {
var { highlight } = this;
if (!highlight) return this;
return this.changeFilter(highlight.applyToFilter(this.filter), true);
}
public changeHighlight(owner: string, measure: string, delta: Filter): Essence {
var { highlight } = this;
// If there is already a highlight from someone else accept it
var value: EssenceValue;
if (highlight && highlight.owner !== owner) {
value = this.changeFilter(highlight.applyToFilter(this.filter)).valueOf();
} else {
value = this.valueOf();
}
value.highlight = new Highlight({
owner,
delta,
measure
});
return new Essence(value);
}
public dropHighlight(): Essence {
var value = this.valueOf();
value.highlight = null;
return new Essence(value);
}
}
check = Essence; | the_stack |
import {noUpdate, ObjectStateHandler, setProperty, setValue} from ".";
import {ProxyStateView} from "./state_handler";
import {deepCopy} from "../util/helpers";
interface TestState {
str: string
num: number
maybeNum?: number
obj: {
inner: {
innerStr: string
maybeInnerStr?: string
innerNum: number
}
objStr: string
objNum: number
maybeObjStr?: string
}
}
const initialState: TestState = {
str: "hello",
num: 1,
maybeNum: 2,
obj: {
inner: {
innerStr: "inner",
maybeInnerStr: "present",
innerNum: 3
},
objStr: "yup",
objNum: 4
}
}
let handler: ObjectStateHandler<TestState>;
describe("ObjectStateHandler", () => {
beforeEach(() => {
handler = new ObjectStateHandler<TestState>(deepCopy(initialState));
})
afterEach(() => {
handler.dispose()
})
describe("addObserver", () => {
it("is triggered by state update", () => {
const listener = jest.fn()
const obs = handler.addObserver(listener)
handler.updateField("num", () => 2)
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith({...initialState, num: 2}, expect.anything(), expect.anything())
obs.dispose()
})
it("is not triggered by noop", () => {
const listener = jest.fn()
const obs = handler.addObserver(listener)
handler.update(() => noUpdate())
expect(listener).toHaveBeenCalledTimes(0)
obs.dispose()
})
it("doesn't break when state is updated inside an observer", () => {
const numListener = jest.fn()
const updater = handler.observeKey("str", (newValue) => handler.updateField("num", () => newValue.length))
const numObs = handler.observeKey("num", numListener)
handler.update(() => ({str: "goober", num: 44}))
expect(handler.state.num).toEqual("goober".length)
expect(numListener).toHaveBeenCalledTimes(2)
expect(numListener).toHaveBeenNthCalledWith(1, 44, expect.anything(), expect.anything())
expect(numListener).toHaveBeenNthCalledWith(2, "goober".length, expect.anything(), expect.anything())
})
it("disposes", done => {
const listener = jest.fn()
const obs = handler.addObserver(listener)
const disposed = jest.fn()
obs.onDispose.then(disposed).then(done).then(() => expect(disposed).toHaveBeenCalledTimes(1))
obs.dispose()
})
})
describe("observeKey", () => {
it("is triggered by update to that key", () => {
const listener = jest.fn()
const obs = handler.observeKey("str", listener)
handler.updateField("str", () => "goodbye")
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith("goodbye", expect.anything(), expect.anything())
obs.dispose()
})
it("is not triggered by updates to siblings", () => {
const listener = jest.fn()
const obs = handler.observeKey("num", listener)
handler.updateField("str", () => "goodbye")
expect(listener).toHaveBeenCalledTimes(0)
obs.dispose()
})
it("is not triggered when the value is equal", () => {
const listener = jest.fn()
const obs = handler.observeKey("num", listener)
handler.updateField("num", num => num)
expect(listener).toHaveBeenCalledTimes(0)
obs.dispose()
})
})
describe("view", () => {
it("observes changes to the key and disposes listeners", done => {
const view = handler.view("num")
const listener = jest.fn()
const obs = view.addObserver(listener)
const disposed = jest.fn()
obs.onDispose.then(disposed).then(done).then(() => {
expect(disposed).toHaveBeenCalledTimes(1)
expect(handler.observerCount).toEqual(0)
})
const oldNum = handler.state.num
handler.updateField("num", () => setValue(42))
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith(42, {newValue: 42, oldValue: initialState.num, update: setValue(42)}, expect.anything())
view.dispose()
})
it("observes deep changes to the key", () => {
const view = handler.view("obj")
const listener = jest.fn()
const obs = view.observeKey("objStr", listener)
handler.update(() => ({
obj: {
objStr: setValue("nope")
}
}));
expect(listener).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledWith("nope", {newValue: "nope", oldValue: "yup", update: setValue("nope")}, expect.anything())
view.dispose()
})
it("doesn't get spuriously triggered", () => {
const view = handler.view("num")
const listener = jest.fn()
const obs = view.addObserver(listener)
handler.update(() => ({
str: "shabba"
}))
expect(listener).toHaveBeenCalledTimes(0)
view.dispose()
})
})
describe("updateWith", () => {
it("updates multiple fields and triggers listeners everywhere", () => {
const listenStr = jest.fn()
const obsStr = handler.observeKey("str", listenStr)
const viewObj = handler.view("obj")
const listenObjStr = jest.fn()
const obsObjStr = viewObj.observeKey("objStr", listenObjStr)
const viewInner = viewObj.view("inner")
const listenInnerNum = jest.fn()
const obsInnerNum = viewInner.observeKey("innerNum", listenInnerNum)
// test that observers aren't triggered if their thing isn't updated
const listenNum = jest.fn()
const obsNum = handler.observeKey("num", listenNum);
handler.update(() => ({
str: "hellogoodbye",
obj: {
objStr: "yupper",
inner: {
innerNum: 123
}
}
}))
expect(handler.state.str).toEqual("hellogoodbye")
expect(handler.state.obj.objStr).toEqual("yupper")
expect(handler.state.obj.inner.innerNum).toEqual(123)
expect(listenStr).toHaveBeenCalledWith("hellogoodbye", expect.anything(), expect.anything())
expect(listenNum).toHaveBeenCalledTimes(0)
expect(listenObjStr).toHaveBeenCalledWith("yupper", expect.anything(), expect.anything())
expect(listenInnerNum).toHaveBeenCalledWith(123, expect.anything(), expect.anything())
})
})
describe("lens", () => {
describe("lens of value", () => {
describe("update", () => {
it("updates the value", () => {
const lens = handler.lens("num")
const numListener = jest.fn()
const obsNum = handler.observeKey("num", numListener)
const lensListener = jest.fn()
const obsLens = lens.addObserver(lensListener)
lens.update(() => 67)
expect(numListener).toHaveBeenCalledWith(67, expect.anything(), expect.anything())
expect(lensListener).toHaveBeenCalledWith(67, expect.anything(), expect.anything())
expect(handler.state.num).toEqual(67)
})
})
})
describe("lens of object", () => {
describe("update", () => {
it("updates fields", () => {
const lens = handler.lens("obj")
const objListener = jest.fn()
const strListener = jest.fn()
handler.observeKey("obj", objListener)
lens.observeKey("objStr", strListener)
lens.updateField("objStr", () => setValue("nope"))
expect(objListener).toHaveBeenCalledTimes(1)
expect(strListener).toHaveBeenCalledTimes(1)
expect(strListener).toHaveBeenCalledWith("nope", expect.anything(), expect.anything())
expect(objListener).toHaveBeenCalledWith({...initialState.obj, objStr: "nope"}, expect.anything(), expect.anything())
})
})
})
})
})
describe("ProxyStateView", () => {
const initialState2: TestState = {
...initialState,
str: "goodbye",
maybeNum: undefined,
obj: {
...initialState.obj,
inner: {
...initialState.obj.inner,
innerNum: 32
},
objNum: 42
}
}
let handler2: ObjectStateHandler<TestState>;
beforeEach(() => {
handler = new ObjectStateHandler<TestState>(deepCopy(initialState))
handler2 = new ObjectStateHandler<TestState>(deepCopy(initialState2))
})
afterEach(() => {
handler.dispose()
handler2.dispose()
})
it ("notifies observers of new values when parent handler is changed", () => {
const proxy = new ProxyStateView(handler)
// verify that observers on the proxy get notified
const obsStr = jest.fn()
const obsNum = jest.fn()
const obsMaybeNum = jest.fn()
const obsObjNum = jest.fn()
const obsInnerNum = jest.fn()
proxy.observeKey("str", obsStr)
proxy.observeKey("num", obsNum)
proxy.observeKey("maybeNum", obsMaybeNum)
proxy.view("obj").observeKey("objNum", obsObjNum)
proxy.view("obj").view("inner").observeKey("innerNum", obsInnerNum)
proxy.setParent(handler2)
// verify that observers on the proxy get notified about changes to the new parent
handler2.lens("obj").updateField("objNum", () => 88)
// verify that observers on the proxy don't get notified about changes on the old parent
handler.updateField("str", () => setValue("hello and goodbye"))
expect(obsStr).toHaveBeenCalledTimes(1)
expect(obsStr).toHaveBeenCalledWith(initialState2.str, expect.anything(), expect.anything())
expect(obsNum).toHaveBeenCalledTimes(0)
expect(obsMaybeNum).toHaveBeenCalledTimes(1)
expect(obsMaybeNum).toHaveBeenCalledWith(initialState2.maybeNum, expect.anything(), expect.anything())
expect(obsObjNum).toHaveBeenCalledTimes(2)
expect(obsObjNum).toHaveBeenCalledWith(initialState2.obj.objNum, expect.anything(), expect.anything())
expect(obsObjNum).toHaveBeenCalledWith(88, expect.anything(), expect.anything())
expect(obsInnerNum).toHaveBeenCalledTimes(1)
expect(obsInnerNum).toHaveBeenCalledWith(initialState2.obj.inner.innerNum, expect.anything(), expect.anything())
})
it ("notifies pre-observers of new values when parent handler is changed", () => {
const proxy = new ProxyStateView(handler)
// verify that observers on the proxy get notified
const obsStr = jest.fn()
const obsNum = jest.fn()
const obsMaybeNum = jest.fn()
const obsObjNum = jest.fn()
const obsInnerNum = jest.fn()
const preObsStr = jest.fn(() => obsStr)
const preObsNum = jest.fn(() => obsNum)
const preObsMaybeNum = jest.fn(() => obsMaybeNum)
const preObsObjNum = jest.fn(() => obsObjNum)
const preObsInnerNum = jest.fn(() => obsInnerNum)
proxy.preObserveKey("str", preObsStr)
proxy.preObserveKey("num", preObsNum)
proxy.preObserveKey("maybeNum", preObsMaybeNum)
proxy.view("obj").preObserveKey("objNum", preObsObjNum)
proxy.view("obj").view("inner").preObserveKey("innerNum", preObsInnerNum)
proxy.setParent(handler2)
// verify that observers on the proxy get notified about changes to the new parent
handler2.lens("obj").updateField("objNum", () => 88)
// verify that observers on the proxy don't get notified about changes on the old parent
handler.updateField("str", () => setValue("hello and goodbye"))
expect(preObsStr).toHaveBeenCalledTimes(1)
expect(preObsStr).toHaveBeenCalledWith(initialState.str)
expect(obsStr).toHaveBeenCalledTimes(1)
expect(obsStr).toHaveBeenCalledWith(initialState2.str, expect.anything(), expect.anything())
expect(obsNum).toHaveBeenCalledTimes(0)
expect(preObsMaybeNum).toHaveBeenCalledTimes(1)
expect(preObsMaybeNum).toHaveBeenCalledWith(initialState.maybeNum)
expect(obsMaybeNum).toHaveBeenCalledTimes(1)
expect(obsMaybeNum).toHaveBeenCalledWith(initialState2.maybeNum, expect.anything(), expect.anything())
expect(preObsObjNum).toHaveBeenCalledTimes(2)
expect(preObsObjNum).toHaveBeenCalledWith(initialState.obj.objNum)
expect(preObsObjNum).toHaveBeenCalledWith(initialState2.obj.objNum)
expect(obsObjNum).toHaveBeenCalledTimes(2)
expect(obsObjNum).toHaveBeenCalledWith(initialState2.obj.objNum, expect.anything(), expect.anything())
expect(obsObjNum).toHaveBeenCalledWith(88, expect.anything(), expect.anything())
expect(preObsInnerNum).toHaveBeenCalledTimes(1)
expect(preObsInnerNum).toHaveBeenCalledWith(initialState.obj.inner.innerNum)
expect(obsInnerNum).toHaveBeenCalledTimes(1)
expect(obsInnerNum).toHaveBeenCalledWith(initialState2.obj.inner.innerNum, expect.anything(), expect.anything())
})
})
//
// // Old state handler tests – Keeping this around in case we want to reuse these tests
//
// describe("StateHandler", () => {
// it("holds some state value that can be updated", () => {
// const s = StateHandler.from(1)
// expect(s.state).toEqual(1)
// s.update(() => 2)
// expect(s.state).toEqual(2)
// })
// it("allows observation of state changes", done => {
// const s = StateHandler.from(1)
// s.addObserver((newState: number, oldState: number) => {
// expect(newState).toEqual(2)
// expect(oldState).toEqual(1)
// done()
// }, s)
// s.update(() => 2)
// })
// it("doesn't call observers when the state isn't changed", () => {
// const s = StateHandler.from(1)
// s.addObserver(() => {
// throw new Error("you better not change the state!!")
// }, s)
// expect(() => s.update(() => 2)).toThrow()
// expect(s.state).toEqual(2)
// expect(() => s.update(() => 2)).not.toThrow()
// })
// test("observers can be removed / cleared", () => {
// const s = StateHandler.from(1)
// let obsStateChange = false;
// const obs = s.addObserver(() => {
// if (obsStateChange) {
// throw new Error("error from obs")
// }
// obsStateChange = true;
// }, s)
// let anonStateChange = false;
// s.addObserver(() => {
// if (anonStateChange) {
// throw new Error("error from anonymous")
// }
// anonStateChange = true;
// }, s)
// s.update(() => 2)
// expect(s.state).toEqual(2)
// expect(() => s.update(() => 3)).toThrowError("error from obs")
// expect(s.state).toEqual(3)
// s.removeObserver(obs)
// expect(() => s.update(() => 4)).toThrowError("error from anonymous")
// s.clearObservers()
// s.update(() => 5)
// expect(s.state).toEqual(5)
// })
// it("can be disposed", async () => {
// const s = StateHandler.from(1)
// const obFn = jest.fn()
// s.addObserver(obFn, s)
// s.update(() => 2)
// expect(obFn).toHaveBeenCalledTimes(1)
// expect(obFn).toHaveBeenCalledWith(2, 1, undefined)
// s.dispose()
// s.onDispose.then(() => {
// expect(obFn).toHaveBeenCalledTimes(1)
// })
// })
// it("can be linked to the lifecycle of another Disposable", done => {
// const d = new Disposable()
// const s = StateHandler.from(1)
// d.onDispose.then(() => s.dispose())
// const obFn = jest.fn()
// s.addObserver(obFn, s)
// s.update(() => 2)
// expect(obFn).toHaveBeenCalledTimes(1)
// expect(obFn).toHaveBeenCalledWith(2, 1, undefined)
// d.dispose() // disposed `d`, now expect `s` to also be disposed
// s.onDispose.then(() => {
// expect(obFn).toHaveBeenCalledTimes(1)
// done()
// })
// })
// it("supports views of object states", () => {
// const sh = StateHandler.from<{a?: number, b?: number}>({a: undefined, b: 2})
// const view = sh.view("a")
// expect(sh.state).toEqual({a: undefined, b: 2})
// expect(view.state).toEqual(undefined)
//
// const obState = jest.fn()
// sh.addObserver(obState, sh)
//
// const obA = jest.fn()
// view.addObserver(obA, sh)
//
// sh.update(s => ({...s, a: 1}))
// expect(view.state).toEqual(1)
//
// sh.update(s => ({...s, a: 2}))
// expect(view.state).toEqual(2)
//
// sh.update(s => ({...s, b: 100}))
// expect(view.state).toEqual(2) // stays the same
//
// sh.update(s => ({...s, a: undefined}))
// expect(view.state).toEqual(undefined)
//
// sh.update(s => ({...s, a: 100}))
// expect(view.state).toEqual(100)
//
// expect(obState).toHaveBeenCalledTimes(5)
// expect(obA).toHaveBeenCalledTimes(4)
// })
// it("supports nested views", () => {
// const sh = StateHandler.from<{s: {a: Record<string, number>}, c: number}>({
// s: {
// a: {
// b: 1
// },
// },
// c: 2
// })
// const sView = sh.view("s")
// const obS = jest.fn()
// sView.addObserver(obS, sh)
// const aView = sView.view("a")
// const obA = jest.fn()
// aView.addObserver(obA, sh)
// sh.update(state => ({...state, s: {...state.s, a: {...state.s.a, b: 2}}}))
//
// expect(obS).toHaveBeenCalledWith({a: {b: 2}}, {a: {b: 1}}, undefined)
// expect(obA).toHaveBeenCalledWith({b: 2}, {b: 1}, undefined)
//
// sh.update(state => ({...state, s: {...state.s, a: {...state.s.a, b: 2, foo: 100}}}))
// expect(obA).toHaveBeenCalledWith({b: 2, foo: 100}, {b: 2}, undefined)
//
// const fooView = sView.view("a").view("foo")
// const obFoo = jest.fn()
// fooView.addObserver(obFoo, sh)
// expect(fooView["_state"]).toEqual(100)
//
// sh.update(state => ({...state, s: {...state.s, a: {...state.s.a, b: 2, foo: 200, bar: 1000}}}))
// expect(obFoo).toHaveBeenCalledWith(200, 100, undefined)
//
// const barView = sView.view("a").view("bar")
// const obBar = jest.fn()
// barView.addObserver(obBar, sh)
// expect(barView["_state"]).toEqual(1000)
//
// })
// it("supports mapViews", () => {
// const sh = StateHandler.from<{a?: number, b?: number}>({a: undefined, b: 2})
// const view = sh.mapView("a", a => a?.toString())
//
// expect(sh.state).toEqual({a: undefined, b: 2})
// expect(view.state).toEqual(undefined)
//
// const obState = jest.fn()
// sh.addObserver(obState, sh)
//
// const obA = jest.fn()
// view.addObserver(obA, sh)
//
// sh.update(s => ({...s, a: 1}))
// expect(view.state).toEqual("1")
//
// sh.update(s => ({...s, a: 2}))
// expect(view.state).toEqual("2")
//
// sh.update(s => ({...s, b: 100}))
// expect(view.state).toEqual("2") // stays the same
//
// sh.update(s => ({...s, a: undefined}))
// expect(view.state).toEqual(undefined)
//
// sh.update(s => ({...s, a: 100}))
// expect(view.state).toEqual("100")
//
// expect(obState).toHaveBeenCalledTimes(5)
// expect(obA).toHaveBeenCalledTimes(4)
// })
// test("views can also synchronize with another Disposable", () => {
// const d = new Disposable()
// const parent = StateHandler.from({a: 1, b: 2})
// const view = parent.view("a");
// const obFn = jest.fn()
// view.addObserver(obFn, d)
// parent.update(s => ({...s, a: 2}))
// expect(obFn).toHaveBeenCalledTimes(1)
// expect(obFn).toHaveBeenCalledWith(2, 1, undefined)
// d.dispose()
// d.onDispose.then(() => {
// expect(obFn).toHaveBeenCalledTimes(1)
// })
// })
// test("view stop updating after their key is removed", done => {
// const d = new Disposable()
// const parent = StateHandler.from({a: 1, b: 2})
// const view = parent.view("a");
// const obFn = jest.fn()
// view.addObserver(obFn, d)
// parent.update(s => ({...s, a: 2}))
// expect(obFn).toHaveBeenCalledTimes(1)
// parent.update(s => {
// const st = {...s}
// delete st["a"]
// return st
// })
// // to ensure that the view promise settles
// setTimeout(() => {
// expect(obFn).toHaveBeenCalledTimes(1)
// parent.update(s => ({...s, a: 3}))
// parent.update(s => ({...s, a: 4}))
// parent.update(s => ({...s, a: 5}))
// expect(obFn).toHaveBeenCalledTimes(1)
// done()
// }, 0)
//
// })
// test("views can be wrapped", () => {
// const parent = StateHandler.from({a: 1, b: 2});
//
// const view = parent.view("a")
// const viewObs = jest.fn()
// view.addObserver(viewObs, parent)
//
// class AddingStorageHandler extends StateWrapper<number> {
// readonly someProperty: number = 100;
// constructor(view: StateView<number>) {
// super(view)
// }
//
// setState(newState: number) {
// super.setState(newState + 10);
// }
// }
// const addingView = new AddingStorageHandler(parent.view("a"));
// expect(addingView.state).toEqual(11)
// expect(addingView.someProperty).toEqual(100);
// expect(addingView instanceof AddingStorageHandler).toBeTruthy();
//
// const addingViewObs = jest.fn()
// addingView.addObserver(addingViewObs, addingView)
// parent.update(() => ({a: 2, b: 2}));
// expect(viewObs).toHaveBeenCalledWith(2, 1, undefined)
// expect(addingViewObs).toHaveBeenCalledWith(12, 11, undefined)
//
// expect(view.state).toEqual(2)
// expect(addingView.state).toEqual(12)
// });
// test("equality comparison can be extended", () => {
// const state = () => ({a: 1, b: 2})
// const stringyState = {a: "1", b: "2"} as any
// const sh = StateHandler.from(state())
// sh.addObserver(() => {
// throw new Error("you better not change the state!!")
// }, sh)
// expect(() => sh.update(() => stringyState)).toThrow() // since state is a new object, this throws because equality is not deep.
//
// const stringy = class<S> extends StateHandler<S> {
// protected compare(s1?: any, s2?: any): boolean {
// return s1?.toString() === s2?.toString()
// }
// }.from({a: 1, b: 2})
// stringy.addObserver(() => {
// throw new Error("you better not change the state!!")
// }, sh)
// expect(() => stringy.update(() => stringyState)).not.toThrow()
// })
// }) | the_stack |
import React from "react";
import Matter from "../../../common/model/matter/Matter";
import TankComponent from "../../../common/component/TankComponent";
import Director from "./Director";
import "./MatterPanel.less";
import Sun from "../../../common/model/global/Sun";
import StringUtil from "../../../common/util/StringUtil";
import DateUtil from "../../../common/util/DateUtil";
import AnimateUtil from "../../../common/util/AnimateUtil";
import MessageBoxUtil from "../../../common/util/MessageBoxUtil";
import Expanding from "../../widget/Expanding";
import {
LockOutlined,
UnlockOutlined,
DownloadOutlined,
ExclamationCircleFilled,
LinkOutlined,
DeleteOutlined,
EditOutlined,
InfoCircleOutlined,
EllipsisOutlined,
RedoOutlined,
CloseCircleOutlined,
} from "@ant-design/icons";
import { Modal, Checkbox, Tooltip } from "antd";
import { CheckboxChangeEvent } from "antd/es/checkbox";
import SafeUtil from "../../../common/util/SafeUtil";
import ClipboardUtil from "../../../common/util/ClipboardUtil";
import Lang from "../../../common/model/global/Lang";
import MatterDeleteModal from "./MatterDeleteModal";
interface IProps {
matter: Matter;
recycleMode?: boolean; // 回收站模式,默认false,简化相关操作,不可进入文件夹里
director?: Director;
onCreateDirectoryCallback?: () => any;
onDeleteSuccess?: () => any;
onRecoverySuccess?: () => any;
onCheckMatter?: (matter?: Matter) => any;
onPreviewImage?: (matter: Matter) => any;
onGoToDirectory?: (id: string) => any;
}
interface IState {}
export default class MatterPanel extends TankComponent<IProps, IState> {
// 正在重命名的临时字段
renameMatterName: string = "";
// 正在向服务器提交rename的请求
renamingLoading: boolean = false;
// 小屏幕下操作栏
showMore: boolean = false;
inputRef = React.createRef<HTMLInputElement>();
constructor(props: IProps) {
super(props);
this.state = {};
}
prepareRename() {
const { matter, director } = this.props;
if (director!.isEditing()) {
console.error("导演正忙着,不予执行");
return;
}
//告诉导演,自己正在编辑
director!.renameMode = true;
matter.editMode = true;
this.renameMatterName = matter.name!;
this.updateUI();
setTimeout(() => {
if (!this.inputRef.current) return;
//如果是文件夹,全选中
let dotIndex = matter.name!.lastIndexOf(".");
if (dotIndex === -1) {
AnimateUtil.setInputSelection(
this.inputRef.current,
0,
this.renameMatterName.length
);
} else {
AnimateUtil.setInputSelection(this.inputRef.current, 0, dotIndex);
}
});
};
clipboard() {
let textToCopy = this.props.matter.getDownloadUrl();
ClipboardUtil.copy(textToCopy, () => {
MessageBoxUtil.success(Lang.t("operationSuccess"));
});
};
deleteMatter() {
MatterDeleteModal.open(
() => {
this.props.matter.httpSoftDelete(() => {
MessageBoxUtil.success(Lang.t("operationSuccess"));
this.props.onDeleteSuccess!();
});
},
() => {
this.props.matter.httpDelete(() => {
MessageBoxUtil.success(Lang.t("operationSuccess"));
this.props.onDeleteSuccess!();
});
}
);
};
hardDeleteMatter() {
Modal.confirm({
title: Lang.t("actionCanNotRevertConfirm"),
icon: <ExclamationCircleFilled twoToneColor="#FFDC00" />,
onOk: () => {
this.props.matter.httpDelete(() => {
MessageBoxUtil.success(Lang.t("operationSuccess"));
this.props.onDeleteSuccess!();
});
},
});
};
recoveryMatter() {
Modal.confirm({
title: Lang.t("actionRecoveryConfirm"),
icon: <ExclamationCircleFilled twoToneColor="#FFDC00" />,
onOk: () => {
this.props.matter.httpRecovery(() => {
MessageBoxUtil.success(Lang.t("operationSuccess"));
this.props.onRecoverySuccess!();
});
},
});
};
changeMatterName(e: any) {
this.renameMatterName = e.currentTarget.value;
this.updateUI();
};
finishRename() {
//有可能按enter的时候和blur同时了。
if (this.renamingLoading) {
return;
}
const { matter, director } = this.props;
this.renamingLoading = true;
matter.httpRename(
this.renameMatterName,
() => {
this.renamingLoading = false;
MessageBoxUtil.success(Lang.t("operationSuccess"));
//告诉导演,自己编辑完毕
director!.renameMode = false;
matter.editMode = false;
},
(msg: string) => {
this.renamingLoading = false;
MessageBoxUtil.error(msg);
//告诉导演,自己编辑完毕
director!.renameMode = false;
matter.editMode = false;
},
() => this.updateUI()
);
};
finishCreateDirectory() {
const { matter, director, onCreateDirectoryCallback } = this.props;
matter.name = this.renameMatterName;
matter.httpCreateDirectory(
() => {
director!.createMode = false;
matter.editMode = false;
matter.assign(new Matter());
},
(msg: string) => {
director!.createMode = false;
matter.editMode = false;
MessageBoxUtil.error(msg);
},
() => onCreateDirectoryCallback!()
);
};
blurTrigger() {
const { matter, director } = this.props;
if (matter.editMode) {
if (director!.createMode) {
this.finishCreateDirectory();
} else if (director!.renameMode) {
this.finishRename();
}
}
};
enterTrigger(e: any) {
if (e.key.toLowerCase() === "enter") {
this.inputRef.current!.blur();
}
};
changePrivacy(privacy: boolean) {
this.props.matter.httpChangePrivacy(privacy, () => {
this.updateUI();
});
};
checkToggle(e: CheckboxChangeEvent) {
this.props.matter.check = e.target.checked;
this.props.onCheckMatter!(this.props.matter);
};
highLight() {
this.inputRef.current!.select();
};
clickRow() {
const {
matter,
recycleMode = false,
director,
onGoToDirectory,
onPreviewImage,
} = this.props;
if (director && director.isEditing()) {
console.error("导演正忙着,不予执行");
return;
}
if (matter.dir) {
if (recycleMode) return;
onGoToDirectory!(matter.uuid!);
} else {
//图片进行预览操作
if (matter.isImage()) {
onPreviewImage!(matter);
} else {
matter.preview();
}
}
};
toggleHandles() {
this.showMore = !this.showMore;
this.updateUI();
};
renderPcOperation() {
const { matter, recycleMode = false } = this.props;
// 文件操作在正常模式 or 回收站模式下不同,其中回收站模式只保留查看信息与彻底删除操作
const handles = recycleMode ? (
<>
<Tooltip title={Lang.t("matter.recovery")}>
<RedoOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.recoveryMatter())
}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.fileDetail")}>
<InfoCircleOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(
Sun.navigateTo("/matter/detail/" + matter.uuid)
)
}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.hardDelete")}>
<CloseCircleOutlined
className="btn-action text-danger"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.hardDeleteMatter())
}
/>
</Tooltip>
</>
) : (
<>
{!matter.dir && matter.privacy && (
<Tooltip title={Lang.t("matter.setPublic")}>
<UnlockOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.changePrivacy(false))
}
/>
</Tooltip>
)}
{!matter.dir && !matter.privacy && (
<Tooltip title={Lang.t("matter.setPrivate")}>
<LockOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.changePrivacy(true))
}
/>
</Tooltip>
)}
<Tooltip title={Lang.t("matter.fileDetail")}>
<InfoCircleOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(
Sun.navigateTo("/matter/detail/" + matter.uuid)
)
}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.rename")}>
<EditOutlined
className="btn-action"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.prepareRename())
}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.copyPath")}>
<LinkOutlined
className="btn-action"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(this.clipboard())}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.download")}>
<DownloadOutlined
className="btn-action"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(matter.download())}
/>
</Tooltip>
<Tooltip title={Lang.t("matter.delete")}>
<DeleteOutlined
className="btn-action text-danger"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.deleteMatter())
}
/>
</Tooltip>
</>
);
return (
<div className="right-part">
<span className="matter-operation text-theme">{handles}</span>
<Tooltip title={Lang.t("matter.size")}>
<span className="matter-size">
{StringUtil.humanFileSize(matter.size)}
</span>
</Tooltip>
{recycleMode ? (
<Tooltip title={Lang.t("matter.deleteTime")}>
<span className="matter-date mr10">
{DateUtil.simpleDateHourMinute(matter.deleteTime)}
</span>
</Tooltip>
) : (
<Tooltip title={Lang.t("matter.updateTime")}>
<span className="matter-date mr10">
{DateUtil.simpleDateHourMinute(matter.updateTime)}
</span>
</Tooltip>
)}
</div>
);
};
renderMobileOperation() {
const { matter, recycleMode = false } = this.props;
// 文件操作在正常模式 or 回收站模式下不同,其中回收站模式只保留查看信息与彻底删除操作
const handles = recycleMode ? (
<>
<div
className="cell-btn navy"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(
Sun.navigateTo("/matter/detail/" + matter.uuid)
)
}
>
<InfoCircleOutlined className="btn-action mr5" />
{Lang.t("matter.fileDetail")}
</div>
<div
className="cell-btn navy"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.recoveryMatter())
}
>
<RedoOutlined className="btn-action mr5" />
{Lang.t("matter.recovery")}
</div>
<div
className="cell-btn text-danger"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.hardDeleteMatter())
}
>
<CloseCircleOutlined className="btn-action mr5" />
{Lang.t("matter.hardDelete")}
</div>
</>
) : (
<>
{!matter.dir && matter.privacy && (
<div
className="cell-btn navy"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.changePrivacy(false))
}
>
<UnlockOutlined className="btn-action mr5" />
{Lang.t("matter.setPublic")}
</div>
)}
{!matter.dir && !matter.privacy && (
<div
className="cell-btn navy"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.changePrivacy(true))
}
>
<LockOutlined className="btn-action mr5" />
{Lang.t("matter.setPrivate")}
</div>
)}
<div
className="cell-btn navy"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(
Sun.navigateTo("/matter/detail/" + matter.uuid)
)
}
>
<InfoCircleOutlined className="btn-action mr5" />
{Lang.t("matter.fileDetail")}
</div>
<div
className="cell-btn navy"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(this.prepareRename())}
>
<EditOutlined className="btn-action mr5" />
{Lang.t("matter.rename")}
</div>
<div
className="cell-btn navy"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(this.clipboard())}
>
<LinkOutlined className="btn-action mr5" />
{Lang.t("matter.copyLink")}
</div>
<div
className="cell-btn navy"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(matter.download())}
>
<DownloadOutlined className="btn-action mr5" />
{Lang.t("matter.download")}
</div>
<div
className="cell-btn text-danger"
onClick={(e) => SafeUtil.stopPropagationWrap(e)(this.deleteMatter())}
>
<DeleteOutlined className="btn-action mr5" />
{Lang.t("matter.delete")}
</div>
</>
);
return (
<div className="more-panel">
<div className="cell-btn navy text">
<span>
{DateUtil.simpleDateHourMinute(
recycleMode ? matter.deleteTime : matter.updateTime
)}
</span>
<span className="matter-size">
{StringUtil.humanFileSize(matter.size)}
</span>
</div>
{handles}
</div>
);
};
render() {
const { matter } = this.props;
return (
<div className="widget-matter-panel">
<div onClick={(e) => SafeUtil.stopPropagationWrap(e)(this.clickRow())}>
<div className="media clearfix">
<div className="pull-left">
<div className="left-part">
<span
className="cell cell-hot"
onClick={(e) => SafeUtil.stopPropagationWrap(e)}
>
<Checkbox
checked={matter.check}
onChange={e => this.checkToggle(e)}
/>
</span>
<span className="cell">
<img className="matter-icon" src={matter.getIcon()} />
</span>
</div>
</div>
{/*在大屏幕下的操作栏*/}
<div className="pull-right visible-pc">
{matter.uuid && this.renderPcOperation()}
</div>
<div className="pull-right visible-mobile">
<span
className="more-btn"
onClick={(e) =>
SafeUtil.stopPropagationWrap(e)(this.toggleHandles())
}
>
<EllipsisOutlined className="btn-action navy f18" />
</span>
</div>
<div className="media-body">
<div className="middle-part">
{matter.editMode ? (
<span className="matter-name-edit">
<input
ref={this.inputRef}
className={matter.uuid!}
value={this.renameMatterName}
onChange={e => this.changeMatterName(e)}
placeholder={Lang.t("matter.enterName")}
onBlur={() => this.blurTrigger()}
onKeyUp={e => this.enterTrigger(e)}
/>
</span>
) : (
<span className="matter-name">
{matter.name}
{!matter.dir && !matter.privacy && (
<Tooltip
title={Lang.t("matter.publicFileEveryoneCanVisit")}
>
<UnlockOutlined className="icon" />
</Tooltip>
)}
</span>
)}
</div>
</div>
</div>
</div>
<Expanding>
{this.showMore ? this.renderMobileOperation() : null}
</Expanding>
</div>
);
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { visualizationSavedObjectTypeMigrations } from './visualization_migrations';
import { SavedObjectMigrationContext, SavedObjectMigrationFn } from 'opensearch-dashboards/server';
const savedObjectMigrationContext = (null as unknown) as SavedObjectMigrationContext;
const testMigrateMatchAllQuery = (migrate: Function) => {
it('should migrate obsolete match_all query', () => {
const migratedDoc = migrate({
type: 'area',
attributes: {
kibanaSavedObjectMeta: {
searchSourceJSON: JSON.stringify({
query: {
match_all: {},
},
}),
},
},
});
const migratedSearchSource = JSON.parse(
migratedDoc.attributes.kibanaSavedObjectMeta.searchSourceJSON
);
expect(migratedSearchSource).toEqual({
query: {
query: '',
language: 'kuery',
},
});
});
it('should return original doc if searchSourceJSON cannot be parsed', () => {
const migratedDoc = migrate({
type: 'area',
attributes: {
kibanaSavedObjectMeta: 'kibanaSavedObjectMeta',
},
});
expect(migratedDoc).toEqual({
type: 'area',
attributes: {
kibanaSavedObjectMeta: 'kibanaSavedObjectMeta',
},
});
});
};
describe('migration visualization', () => {
describe('6.7.2', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['6.7.2'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
let doc: any;
describe('migrateMatchAllQuery', () => {
testMigrateMatchAllQuery(migrate);
});
describe('date histogram time zone removal', () => {
beforeEach(() => {
doc = {
attributes: {
visState: JSON.stringify({
aggs: [
{
enabled: true,
id: '1',
params: {
// Doesn't make much sense but we want to test it's not removing it from anything else
time_zone: 'Europe/Berlin',
},
schema: 'metric',
type: 'count',
},
{
enabled: true,
id: '2',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
time_zone: 'Europe/Berlin',
interval: 'auto',
min_doc_count: 1,
useNormalizedOpenSearchInterval: true,
},
schema: 'segment',
type: 'date_histogram',
},
{
enabled: true,
id: '4',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
interval: 'auto',
min_doc_count: 1,
useNormalizedOpenSearchInterval: true,
},
schema: 'segment',
type: 'date_histogram',
},
{
enabled: true,
id: '3',
params: {
customBucket: {
enabled: true,
id: '1-bucket',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
interval: 'auto',
min_doc_count: 1,
time_zone: 'Europe/Berlin',
useNormalizedOpenSearchInterval: true,
},
type: 'date_histogram',
},
customMetric: {
enabled: true,
id: '1-metric',
params: {},
type: 'count',
},
},
schema: 'metric',
type: 'max_bucket',
},
],
}),
},
} as Parameters<SavedObjectMigrationFn>[0];
});
it('should remove time_zone from date_histogram aggregations', () => {
const migratedDoc = migrate(doc);
const aggs = JSON.parse(migratedDoc.attributes.visState).aggs;
expect(aggs[1]).not.toHaveProperty('params.time_zone');
});
it('should not remove time_zone from non date_histogram aggregations', () => {
const migratedDoc = migrate(doc);
const aggs = JSON.parse(migratedDoc.attributes.visState).aggs;
expect(aggs[0]).toHaveProperty('params.time_zone');
});
it('should remove time_zone from nested aggregations', () => {
const migratedDoc = migrate(doc);
const aggs = JSON.parse(migratedDoc.attributes.visState).aggs;
expect(aggs[3]).not.toHaveProperty('params.customBucket.params.time_zone');
});
it('should not fail on date histograms without a time_zone', () => {
const migratedDoc = migrate(doc);
const aggs = JSON.parse(migratedDoc.attributes.visState).aggs;
expect(aggs[2]).not.toHaveProperty('params.time_zone');
});
it('should be able to apply the migration twice, since we need it for 6.7.2 and 7.0.1', () => {
const migratedDoc = migrate(doc);
const aggs = JSON.parse(migratedDoc.attributes.visState).aggs;
expect(aggs[1]).not.toHaveProperty('params.time_zone');
expect(aggs[0]).toHaveProperty('params.time_zone');
expect(aggs[3]).not.toHaveProperty('params.customBucket.params.time_zone');
expect(aggs[2]).not.toHaveProperty('params.time_zone');
});
});
});
describe('7.0.0', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.0.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (type: any, aggs: any) => ({
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: JSON.stringify({ type, aggs }),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
references: [],
});
it('does not throw error on empty object', () => {
const migratedDoc = migrate({
attributes: {
visState: '{}',
},
});
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"visState": "{}",
},
"references": Array [],
}
`);
});
it('skips errors when searchSourceJSON is null', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: null,
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": null,
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('skips errors when searchSourceJSON is undefined', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: undefined,
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": undefined,
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('skips error when searchSourceJSON is not a string', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: 123,
},
savedSearchId: '123',
},
};
expect(migrate(doc)).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": 123,
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('skips error when searchSourceJSON is invalid json', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: '{abc123}',
},
savedSearchId: '123',
},
};
expect(migrate(doc)).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{abc123}",
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('skips error when "index" and "filter" is missing from searchSourceJSON', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: JSON.stringify({ bar: true }),
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{\\"bar\\":true}",
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('extracts "index" attribute from doc', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: JSON.stringify({ bar: true, index: 'pattern*' }),
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{\\"bar\\":true,\\"indexRefName\\":\\"kibanaSavedObjectMeta.searchSourceJSON.index\\"}",
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "pattern*",
"name": "kibanaSavedObjectMeta.searchSourceJSON.index",
"type": "index-pattern",
},
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('extracts index patterns from the filter', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: JSON.stringify({
bar: true,
filter: [
{
meta: { index: 'my-index', foo: true },
},
],
}),
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{\\"bar\\":true,\\"filter\\":[{\\"meta\\":{\\"foo\\":true,\\"indexRefName\\":\\"kibanaSavedObjectMeta.searchSourceJSON.filter[0].meta.index\\"}}]}",
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "my-index",
"name": "kibanaSavedObjectMeta.searchSourceJSON.filter[0].meta.index",
"type": "index-pattern",
},
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
"type": "visualization",
}
`);
});
it('extracts index patterns from controls', () => {
const doc = {
id: '1',
type: 'visualization',
attributes: {
foo: true,
visState: JSON.stringify({
bar: false,
params: {
controls: [
{
bar: true,
indexPattern: 'pattern*',
},
{
foo: true,
},
],
},
}),
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"foo": true,
"visState": "{\\"bar\\":false,\\"params\\":{\\"controls\\":[{\\"bar\\":true,\\"indexPatternRefName\\":\\"control_0_index_pattern\\"},{\\"foo\\":true}]}}",
},
"id": "1",
"references": Array [
Object {
"id": "pattern*",
"name": "control_0_index_pattern",
"type": "index-pattern",
},
],
"type": "visualization",
}
`);
});
it('skips extracting savedSearchId when missing', () => {
const doc = {
id: '1',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{}",
},
"visState": "{}",
},
"id": "1",
"references": Array [],
}
`);
});
it('extract savedSearchId from doc', () => {
const doc = {
id: '1',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
savedSearchId: '123',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{}",
},
"savedSearchRefName": "search_0",
"visState": "{}",
},
"id": "1",
"references": Array [
Object {
"id": "123",
"name": "search_0",
"type": "search",
},
],
}
`);
});
it('delete savedSearchId when empty string in doc', () => {
const doc = {
id: '1',
attributes: {
visState: '{}',
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
savedSearchId: '',
},
};
const migratedDoc = migrate(doc);
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"kibanaSavedObjectMeta": Object {
"searchSourceJSON": "{}",
},
"visState": "{}",
},
"id": "1",
"references": Array [],
}
`);
});
it('should return a new object if vis is table and has multiple split aggs', () => {
const aggs = [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
schema: 'split',
params: { foo: 'bar' },
},
{
id: '3',
schema: 'split',
params: { hey: 'ya' },
},
];
const tableDoc = generateDoc('table', aggs);
const expected = tableDoc;
const actual = migrate(tableDoc);
expect(actual).not.toEqual(expected);
});
it('should not touch any vis that is not table', () => {
const pieDoc = generateDoc('pie', []);
const expected = pieDoc;
const actual = migrate(pieDoc);
expect(actual).toEqual(expected);
});
it('should not change values in any vis that is not table', () => {
const aggs = [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
schema: 'split',
params: { foo: 'bar' },
},
{
id: '3',
schema: 'segment',
params: { hey: 'ya' },
},
];
const pieDoc = generateDoc('pie', aggs);
const expected = pieDoc;
const actual = migrate(pieDoc);
expect(actual).toEqual(expected);
});
it('should not touch table vis if there are not multiple split aggs', () => {
const aggs = [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
schema: 'split',
params: { foo: 'bar' },
},
];
const tableDoc = generateDoc('table', aggs);
const expected = tableDoc;
const actual = migrate(tableDoc);
expect(actual).toEqual(expected);
});
it('should change all split aggs to `bucket` except the first', () => {
const aggs = [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
schema: 'split',
params: { foo: 'bar' },
},
{
id: '3',
schema: 'split',
params: { hey: 'ya' },
},
{
id: '4',
schema: 'bucket',
params: { heyyy: 'yaaa' },
},
];
const expected = ['metric', 'split', 'bucket', 'bucket'];
const migrated = migrate(generateDoc('table', aggs));
const actual = JSON.parse(migrated.attributes.visState);
expect(actual.aggs.map((agg: any) => agg.schema)).toEqual(expected);
});
it('should remove `rows` param from any aggs that are not `split`', () => {
const aggs = [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
schema: 'split',
params: { foo: 'bar' },
},
{
id: '3',
schema: 'split',
params: { hey: 'ya' },
},
];
const expected = [{}, { foo: 'bar' }, { hey: 'ya' }];
const migrated = migrate(generateDoc('table', aggs));
const actual = JSON.parse(migrated.attributes.visState);
expect(actual.aggs.map((agg: any) => agg.params)).toEqual(expected);
});
it('should throw with a reference to the doc name if something goes wrong', () => {
const doc = {
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: '!/// Intentionally malformed JSON ///!',
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
};
expect(() => migrate(doc)).toThrowError(/My Vis/);
});
});
describe('7.2.0', () => {
describe('date histogram custom interval removal', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.2.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
let doc: any;
beforeEach(() => {
doc = {
attributes: {
visState: JSON.stringify({
aggs: [
{
enabled: true,
id: '1',
params: {
customInterval: '1h',
},
schema: 'metric',
type: 'count',
},
{
enabled: true,
id: '2',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
interval: 'auto',
min_doc_count: 1,
useNormalizedOpenSearchInterval: true,
},
schema: 'segment',
type: 'date_histogram',
},
{
enabled: true,
id: '4',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
interval: 'custom',
min_doc_count: 1,
useNormalizedOpenSearchInterval: true,
},
schema: 'segment',
type: 'date_histogram',
},
{
enabled: true,
id: '3',
params: {
customBucket: {
enabled: true,
id: '1-bucket',
params: {
customInterval: '2h',
drop_partials: false,
extended_bounds: {},
field: 'timestamp',
interval: 'custom',
min_doc_count: 1,
useNormalizedOpenSearchInterval: true,
},
type: 'date_histogram',
},
customMetric: {
enabled: true,
id: '1-metric',
params: {},
type: 'count',
},
},
schema: 'metric',
type: 'max_bucket',
},
],
}),
},
};
});
it('should remove customInterval from date_histogram aggregations', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[1]).not.toHaveProperty('params.customInterval');
});
it('should not change interval from date_histogram aggregations', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[1].params.interval).toBe(
JSON.parse(doc.attributes.visState).aggs[1].params.interval
);
});
it('should not remove customInterval from non date_histogram aggregations', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[0]).toHaveProperty('params.customInterval');
});
it('should set interval with customInterval value and remove customInterval when interval equals "custom"', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[2].params.interval).toBe(
JSON.parse(doc.attributes.visState).aggs[2].params.customInterval
);
expect(aggs[2]).not.toHaveProperty('params.customInterval');
});
it('should remove customInterval from nested aggregations', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[3]).not.toHaveProperty('params.customBucket.params.customInterval');
});
it('should remove customInterval from nested aggregations and set interval with customInterval value', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[3].params.customBucket.params.interval).toBe(
JSON.parse(doc.attributes.visState).aggs[3].params.customBucket.params.customInterval
);
expect(aggs[3]).not.toHaveProperty('params.customBucket.params.customInterval');
});
it('should not fail on date histograms without a customInterval', () => {
const migratedDoc = migrate(doc);
const { aggs } = JSON.parse(migratedDoc.attributes.visState);
expect(aggs[3]).not.toHaveProperty('params.customInterval');
});
});
});
describe('7.3.0', () => {
const logMsgArr: string[] = [];
const logger = ({
log: {
warn: (msg: string) => logMsgArr.push(msg),
},
} as unknown) as SavedObjectMigrationContext;
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.3.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
logger
);
it('migrates type = gauge verticalSplit: false to alignment: vertical', () => {
const migratedDoc = migrate({
attributes: {
visState: JSON.stringify({ type: 'gauge', params: { gauge: { verticalSplit: false } } }),
},
});
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"visState": "{\\"type\\":\\"gauge\\",\\"params\\":{\\"gauge\\":{\\"alignment\\":\\"horizontal\\"}}}",
},
}
`);
});
it('migrates type = gauge verticalSplit: false to alignment: horizontal', () => {
const migratedDoc = migrate({
attributes: {
visState: JSON.stringify({ type: 'gauge', params: { gauge: { verticalSplit: true } } }),
},
});
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"visState": "{\\"type\\":\\"gauge\\",\\"params\\":{\\"gauge\\":{\\"alignment\\":\\"vertical\\"}}}",
},
}
`);
});
it('doesnt migrate type = gauge containing invalid visState object, adds message to log', () => {
const migratedDoc = migrate({
attributes: {
visState: JSON.stringify({ type: 'gauge' }),
},
});
expect(migratedDoc).toMatchInlineSnapshot(`
Object {
"attributes": Object {
"visState": "{\\"type\\":\\"gauge\\"}",
},
}
`);
expect(logMsgArr).toMatchInlineSnapshot(`
Array [
"Exception @ migrateGaugeVerticalSplitToAlignment! TypeError: Cannot read property 'gauge' of undefined",
"Exception @ migrateGaugeVerticalSplitToAlignment! Payload: {\\"type\\":\\"gauge\\"}",
]
`);
});
describe('filters agg query migration', () => {
const doc = {
attributes: {
visState: JSON.stringify({
aggs: [
{
type: 'filters',
params: {
filters: [
{
input: {
query: 'response:200',
},
label: '',
},
{
input: {
query: 'response:404',
},
label: 'bad response',
},
{
input: {
query: {
exists: {
field: 'phpmemory',
},
},
},
label: '',
},
],
},
},
],
}),
},
};
it('should add language property to filters without one, assuming lucene', () => {
const migrationResult = migrate(doc);
expect(migrationResult).toEqual({
attributes: {
visState: JSON.stringify({
aggs: [
{
type: 'filters',
params: {
filters: [
{
input: {
query: 'response:200',
language: 'lucene',
},
label: '',
},
{
input: {
query: 'response:404',
language: 'lucene',
},
label: 'bad response',
},
{
input: {
query: {
exists: {
field: 'phpmemory',
},
},
language: 'lucene',
},
label: '',
},
],
},
},
],
}),
},
});
});
});
describe('replaceMovAvgToMovFn()', () => {
let doc: any;
beforeEach(() => {
doc = {
attributes: {
title: 'VIS',
visState: `{"title":"VIS","type":"metrics","params":{"id":"61ca57f0-469d-11e7-af02-69e470af7417",
"type":"timeseries","series":[{"id":"61ca57f1-469d-11e7-af02-69e470af7417","color":"rgba(0,156,224,1)",
"split_mode":"terms","metrics":[{"id":"61ca57f2-469d-11e7-af02-69e470af7417","type":"count",
"numerator":"FlightDelay:true"},{"settings":"","minimize":0,"window":5,"model":
"holt_winters","id":"23054fe0-8915-11e9-9b86-d3f94982620f","type":"moving_average","field":
"61ca57f2-469d-11e7-af02-69e470af7417","predict":1}],"separate_axis":0,"axis_position":"right",
"formatter":"number","chart_type":"line","line_width":"2","point_size":"0","fill":0.5,"stacked":"none",
"label":"Percent Delays","terms_size":"2","terms_field":"OriginCityName"}],"time_field":"timestamp",
"index_pattern":"opensearch_dashboards_sample_data_flights","interval":">=12h","axis_position":"left","axis_formatter":
"number","show_legend":1,"show_grid":1,"annotations":[{"fields":"FlightDelay,Cancelled,Carrier",
"template":"{{Carrier}}: Flight Delayed and Cancelled!","index_pattern":"opensearch_dashboards_sample_data_flights",
"query_string":"FlightDelay:true AND Cancelled:true","id":"53b7dff0-4c89-11e8-a66a-6989ad5a0a39",
"color":"rgba(0,98,177,1)","time_field":"timestamp","icon":"fa-exclamation-triangle",
"ignore_global_filters":1,"ignore_panel_filters":1,"hidden":true}],"legend_position":"bottom",
"axis_scale":"normal","default_index_pattern":"opensearch_dashboards_sample_data_flights","default_timefield":"timestamp"},
"aggs":[]}`,
},
migrationVersion: {
visualization: '7.2.0',
},
type: 'visualization',
};
});
test('should add some necessary moving_fn fields', () => {
const migratedDoc = migrate(doc);
const visState = JSON.parse(migratedDoc.attributes.visState);
const metric = visState.params.series[0].metrics[1];
expect(metric).toHaveProperty('model_type');
expect(metric).toHaveProperty('alpha');
expect(metric).toHaveProperty('beta');
expect(metric).toHaveProperty('gamma');
expect(metric).toHaveProperty('period');
expect(metric).toHaveProperty('multiplicative');
});
});
});
describe('7.3.0 tsvb', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.3.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (params: any) => ({
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: JSON.stringify({ params }),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
});
it('should change series item filters from a string into an object', () => {
const params = { type: 'metric', series: [{ filter: 'Filter Bytes Test:>1000' }] };
const testDoc1 = generateDoc(params);
const migratedTestDoc1 = migrate(testDoc1);
const series = JSON.parse(migratedTestDoc1.attributes.visState).params.series;
expect(series[0].filter).toHaveProperty('query');
expect(series[0].filter).toHaveProperty('language');
});
it('should not change a series item filter string in the object after migration', () => {
const markdownParams = {
type: 'markdown',
series: [
{
filter: 'Filter Bytes Test:>1000',
split_filters: [{ filter: 'bytes:>1000' }],
},
],
};
const markdownDoc = generateDoc(markdownParams);
const migratedMarkdownDoc = migrate(markdownDoc);
const markdownSeries = JSON.parse(migratedMarkdownDoc.attributes.visState).params.series;
expect(markdownSeries[0].filter.query).toBe(
JSON.parse(markdownDoc.attributes.visState).params.series[0].filter
);
expect(markdownSeries[0].split_filters[0].filter.query).toBe(
JSON.parse(markdownDoc.attributes.visState).params.series[0].split_filters[0].filter
);
});
it('should change series item filters from a string into an object for all filters', () => {
const params = {
type: 'timeseries',
filter: 'bytes:>1000',
series: [
{
filter: 'Filter Bytes Test:>1000',
split_filters: [{ filter: 'bytes:>1000' }],
},
],
annotations: [{ query_string: 'bytes:>1000' }],
};
const timeSeriesDoc = generateDoc(params);
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const timeSeriesParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(Object.keys(timeSeriesParams.series[0].filter)).toEqual(
expect.arrayContaining(['query', 'language'])
);
expect(Object.keys(timeSeriesParams.series[0].split_filters[0].filter)).toEqual(
expect.arrayContaining(['query', 'language'])
);
expect(Object.keys(timeSeriesParams.annotations[0].query_string)).toEqual(
expect.arrayContaining(['query', 'language'])
);
});
it('should not fail on a metric visualization without a filter in a series item', () => {
const params = { type: 'metric', series: [{}, {}, {}] };
const testDoc1 = generateDoc(params);
const migratedTestDoc1 = migrate(testDoc1);
const series = JSON.parse(migratedTestDoc1.attributes.visState).params.series;
expect(series[2]).not.toHaveProperty('filter.query');
});
it('should not migrate a visualization of unknown type', () => {
const params = { type: 'unknown', series: [{ filter: 'foo:bar' }] };
const doc = generateDoc(params);
const migratedDoc = migrate(doc);
const series = JSON.parse(migratedDoc.attributes.visState).params.series;
expect(series[0].filter).toEqual(params.series[0].filter);
});
});
describe('7.3.1', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.3.1'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
it('should migrate filters agg query string queries', () => {
const state = {
aggs: [
{ type: 'count', params: {} },
{
type: 'filters',
params: {
filters: [
{
input: {
query: {
query_string: { query: 'machine.os.keyword:"win 8"' },
},
},
},
],
},
},
],
};
const expected = {
aggs: [
{ type: 'count', params: {} },
{
type: 'filters',
params: {
filters: [{ input: { query: 'machine.os.keyword:"win 8"' } }],
},
},
],
};
const migratedDoc = migrate({ attributes: { visState: JSON.stringify(state) } });
expect(migratedDoc).toEqual({ attributes: { visState: JSON.stringify(expected) } });
});
});
describe('7.4.2 tsvb split_filters migration', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.4.2'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (params: any) => ({
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: JSON.stringify({ params }),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
});
it('should change series item filters from a string into an object for all filters', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [
{
split_filters: [{ filter: 'bytes:>1000' }],
},
],
};
const timeSeriesDoc = generateDoc(params);
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const timeSeriesParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(Object.keys(timeSeriesParams.filter)).toEqual(
expect.arrayContaining(['query', 'language'])
);
expect(timeSeriesParams.series[0].split_filters[0].filter).toEqual({
query: 'bytes:>1000',
language: 'lucene',
});
});
it('should change series item split filters when there is no filter item', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [
{
split_filters: [{ filter: 'bytes:>1000' }],
},
],
annotations: [
{
query_string: {
query: 'bytes:>1000',
language: 'lucene',
},
},
],
};
const timeSeriesDoc = generateDoc(params);
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const timeSeriesParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(timeSeriesParams.series[0].split_filters[0].filter).toEqual({
query: 'bytes:>1000',
language: 'lucene',
});
});
it('should not convert split_filters to objects if there are no split filter filters', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [
{
split_filters: [],
},
],
};
const timeSeriesDoc = generateDoc(params);
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const timeSeriesParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(timeSeriesParams.series[0].split_filters).not.toHaveProperty('query');
});
it('should do nothing if a split_filter is already a query:language object', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [
{
split_filters: [
{
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
},
],
},
],
annotations: [
{
query_string: {
query: 'bytes:>1000',
language: 'lucene',
},
},
],
};
const timeSeriesDoc = generateDoc(params);
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const timeSeriesParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(timeSeriesParams.series[0].split_filters[0].filter.query).toEqual('bytes:>1000');
expect(timeSeriesParams.series[0].split_filters[0].filter.language).toEqual('lucene');
});
});
describe('7.7.0 tsvb opperator typo migration', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.7.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (visState: any) => ({
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: JSON.stringify(visState),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
});
it('should remove the misspelled opperator key if it exists', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [],
gauge_color_rules: [
{
value: 0,
id: '020e3d50-75a6-11ea-8f61-71579ff7f64d',
gauge: 'rgba(69,39,217,1)',
opperator: 'lt',
},
],
};
const timeSeriesDoc = generateDoc({ params });
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const migratedParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(migratedParams.gauge_color_rules[0]).toMatchInlineSnapshot(`
Object {
"gauge": "rgba(69,39,217,1)",
"id": "020e3d50-75a6-11ea-8f61-71579ff7f64d",
"opperator": "lt",
"value": 0,
}
`);
});
it('should not change color rules with the correct spelling', () => {
const params = {
type: 'timeseries',
filter: {
query: 'bytes:>1000',
language: 'lucene',
},
series: [],
gauge_color_rules: [
{
value: 0,
id: '020e3d50-75a6-11ea-8f61-71579ff7f64d',
gauge: 'rgba(69,39,217,1)',
opperator: 'lt',
},
{
value: 0,
id: '020e3d50-75a6-11ea-8f61-71579ff7f64d',
gauge: 'rgba(69,39,217,1)',
operator: 'lt',
},
],
};
const timeSeriesDoc = generateDoc({ params });
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
const migratedParams = JSON.parse(migratedtimeSeriesDoc.attributes.visState).params;
expect(migratedParams.gauge_color_rules[1]).toEqual(params.gauge_color_rules[1]);
});
it('should move "row" field on split chart by a row or column to vis.params', () => {
const visData = {
type: 'area',
aggs: [
{
id: '1',
schema: 'metric',
params: {},
},
{
id: '2',
type: 'terms',
schema: 'split',
params: { foo: 'bar', row: true },
},
],
params: {},
};
const migrated = migrate(generateDoc(visData));
const actual = JSON.parse(migrated.attributes.visState);
expect(actual.aggs.filter((agg: any) => 'row' in agg.params)).toEqual([]);
expect(actual.params.row).toBeTruthy();
});
});
describe('7.9.3', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.9.3'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
describe('migrateMatchAllQuery', () => {
testMigrateMatchAllQuery(migrate);
});
});
describe('7.8.0 tsvb split_color_mode', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.8.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (params: any) => ({
attributes: {
title: 'My Vis',
type: 'visualization',
description: 'This is my super cool vis.',
visState: JSON.stringify(params),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: '{}',
},
},
});
it('should change a missing split_color_mode to gradient', () => {
const params = { type: 'metrics', params: { series: [{}] } };
const testDoc1 = generateDoc(params);
const migratedTestDoc1 = migrate(testDoc1);
const series = JSON.parse(migratedTestDoc1.attributes.visState).params.series;
expect(series[0].split_color_mode).toEqual('gradient');
});
it('should not change the color mode if it is set', () => {
const params = { type: 'metrics', params: { series: [{ split_color_mode: 'gradient' }] } };
const testDoc1 = generateDoc(params);
const migratedTestDoc1 = migrate(testDoc1);
const series = JSON.parse(migratedTestDoc1.attributes.visState).params.series;
expect(series[0].split_color_mode).toEqual('gradient');
});
it('should not change the color mode if it is non-default', () => {
const params = { type: 'metrics', params: { series: [{ split_color_mode: 'rainbow' }] } };
const testDoc1 = generateDoc(params);
const migratedTestDoc1 = migrate(testDoc1);
const series = JSON.parse(migratedTestDoc1.attributes.visState).params.series;
expect(series[0].split_color_mode).toEqual('rainbow');
});
it('should not migrate a visualization of unknown type', () => {
const params = { type: 'unknown', params: { series: [{}] } };
const doc = generateDoc(params);
const migratedDoc = migrate(doc);
const series = JSON.parse(migratedDoc.attributes.visState).params.series;
expect(series[0].split_color_mode).toBeUndefined();
});
});
describe('7.10.0 tsvb filter_ratio migration', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.10.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const testDoc1 = {
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: `{"type":"metrics","params":{"id":"61ca57f0-469d-11e7-af02-69e470af7417","type":"timeseries",
"series":[{"id":"61ca57f1-469d-11e7-af02-69e470af7417","metrics":[{"id":"61ca57f2-469d-11e7-af02-69e470af7417",
"type":"filter_ratio","numerator":"Filter Bytes Test:>1000","denominator":"Filter Bytes Test:<1000"}]}]}}`,
},
};
it('should replace numerator string with a query object', () => {
const migratedTestDoc1 = migrate(testDoc1);
const metric = JSON.parse(migratedTestDoc1.attributes.visState).params.series[0].metrics[0];
expect(metric.numerator).toHaveProperty('query');
expect(metric.numerator).toHaveProperty('language');
});
it('should replace denominator string with a query object', () => {
const migratedTestDoc1 = migrate(testDoc1);
const metric = JSON.parse(migratedTestDoc1.attributes.visState).params.series[0].metrics[0];
expect(metric.denominator).toHaveProperty('query');
expect(metric.denominator).toHaveProperty('language');
});
});
describe('7.10.0 remove tsvb search source', () => {
const migrate = (doc: any) =>
visualizationSavedObjectTypeMigrations['7.10.0'](
doc as Parameters<SavedObjectMigrationFn>[0],
savedObjectMigrationContext
);
const generateDoc = (visState: any) => ({
attributes: {
title: 'My Vis',
description: 'This is my super cool vis.',
visState: JSON.stringify(visState),
uiStateJSON: '{}',
version: 1,
kibanaSavedObjectMeta: {
searchSourceJSON: JSON.stringify({
filter: [],
query: {
query: {
query_string: {
query: '*',
},
},
language: 'lucene',
},
}),
},
},
});
it('should remove the search source JSON', () => {
const timeSeriesDoc = generateDoc({ type: 'metrics' });
const migratedtimeSeriesDoc = migrate(timeSeriesDoc);
expect(migratedtimeSeriesDoc.attributes.kibanaSavedObjectMeta.searchSourceJSON).toEqual('{}');
const { kibanaSavedObjectMeta, ...attributes } = migratedtimeSeriesDoc.attributes;
const {
kibanaSavedObjectMeta: oldOpenSearchDashboardsSavedObjectMeta,
...oldAttributes
} = migratedtimeSeriesDoc.attributes;
expect(attributes).toEqual(oldAttributes);
});
});
}); | the_stack |
import { assertEqual, assertNull, assertThrows, assertNotNull, assert } from '../../tk-unit';
import { Button, Builder, Page, Color, _setResolver, ModuleNameResolver, PlatformContext } from '@nativescript/core';
import { navigate } from '../../ui-helper';
const testPrefix = 'bundle-file-qualifiers-tests';
let modulesToCleanup: string[] = [];
function registerTestModule(name, loader: (name: string) => void) {
modulesToCleanup.push(name);
global.registerModule(name, loader);
}
export function setUp() {
_setResolver(
new ModuleNameResolver({
width: 640,
height: 360,
os: 'android',
deviceType: 'phone',
})
);
}
export function tearDown() {
modulesToCleanup.forEach(global._unregisterModule);
modulesToCleanup = [];
_setResolver(undefined);
}
function createViewFromEntryAndNavigate(): Page {
const page = <Page>Builder.createViewFromEntry({
moduleName: `${testPrefix}/test`,
});
navigate(() => page);
return page;
}
function loadRightCss() {
return `.test-class { color: green }`;
}
function loadRightXml() {
return `
<Page>
<Button id="test-id" class="test-class" text="right" tap="testEvent"/>
</Page>`;
}
let testEventCalled = false;
function loadRightJS() {
return {
testEvent: () => {
testEventCalled = true;
},
};
}
function loadRightJS_CreatePage() {
return {
createPage: () => {
const page = new Page();
const btn = new Button();
btn.id = 'test-id';
btn.className = 'test-class';
btn.text = 'right';
btn.on('tap', () => {
testEventCalled = true;
});
page.content = btn;
return page;
},
};
}
function loadWrongCss(name: string) {
throw new Error(`Loading wrong CSS module: ${name}`);
}
function loadWrongXml(name: string) {
throw new Error(`Loading wrong XML module: ${name}`);
}
function loadWrongJS(name: string) {
throw new Error(`Loading wrong JS module: ${name}`);
}
function assertXmlCss(btn: Button) {
assertNotNull(btn, 'Test button not found');
assertEqual(btn.text, 'right', 'Wrong XML loaded');
assertNotNull(btn.style.color, 'Wrong CSS loaded');
assertEqual(btn.style.color.hex, new Color('green').hex, 'Wrong CSS loaded');
}
function assertXmlCssJs(btn: Button) {
assertXmlCss(btn);
testEventCalled = false;
btn._emit('tap');
assert(testEventCalled, 'Wrong JS loaded');
}
export function testPageWithXmlCssJs_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithJsCss_NoXML_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test`, loadRightJS_CreatePage);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCss_NoJS_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCss(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_CssQualifier() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadWrongCss);
registerTestModule(`${testPrefix}/test.land.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_XmlQualifier() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadWrongXml);
registerTestModule(`${testPrefix}/test.land.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_JsQualifier() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadWrongJS);
registerTestModule(`${testPrefix}/test.land`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_XmlCssJsQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadWrongXml);
registerTestModule(`${testPrefix}/test.land.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadWrongCss);
registerTestModule(`${testPrefix}/test.land.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadWrongJS);
registerTestModule(`${testPrefix}/test.land`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCss_NoJS_XmlQualifier() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadWrongXml);
registerTestModule(`${testPrefix}/test.land.xml`, loadRightXml);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCss(page.getViewById('test-id'));
}
export function testPageWithJsCss_NoXML_JsQualifier() {
// Arrange
registerTestModule(`${testPrefix}/test`, loadWrongJS);
registerTestModule(`${testPrefix}/test.land`, loadRightJS_CreatePage);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
function loadPageXmlWithCssFile() {
return `
<Page cssFile="${testPrefix}/custom-test.css">
<Button id="test-id" class="test-class" text="right" tap="testEvent"/>
</Page>`;
}
export function testPageWithXmlCssJs_WithCssFile_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithCssFile);
registerTestModule(`${testPrefix}/test.css`, loadWrongCss);
registerTestModule(`${testPrefix}/custom-test.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_WithCssFile_WithQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithCssFile);
registerTestModule(`${testPrefix}/test.css`, loadWrongCss);
registerTestModule(`${testPrefix}/custom-test.css`, loadWrongCss);
registerTestModule(`${testPrefix}/custom-test.land.css`, loadRightCss);
registerTestModule(`${testPrefix}/test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
function loadPageXmlWithCodeFile() {
return `
<Page codeFile="${testPrefix}/custom-test.js">
<Button id="test-id" class="test-class" text="right" tap="testEvent"/>
</Page>`;
}
export function testPageWithXmlCssJs_WithCodeFile_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithCodeFile);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
registerTestModule(`${testPrefix}/custom-test`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testPageWithXmlCssJs_WithCodeFile_WithQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithCodeFile);
registerTestModule(`${testPrefix}/test.css`, loadRightCss);
registerTestModule(`${testPrefix}/custom-test`, loadWrongJS);
registerTestModule(`${testPrefix}/custom-test.land`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
// --------------------------------------------------------------
// ----------------- Custom Component Tests ---------------------
// --------------------------------------------------------------
function loadPageXmlWithComponent() {
return `
<Page xmlns:cc="${testPrefix}/component">
<cc:MyComponent/>
</Page>`;
}
function loadRightComponentXml() {
return `<Button id="test-id" class="test-class" text="right" tap="testEvent"/>`;
}
export function testCustomComponentWithXmlCssJs_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadRightComponentXml);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadRightCss);
registerTestModule(`${testPrefix}/component/MyComponent`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponentWithXmlCssJs_JsQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadRightComponentXml);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadRightCss);
registerTestModule(`${testPrefix}/component/MyComponent`, loadWrongJS);
registerTestModule(`${testPrefix}/component/MyComponent.land`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponentWithXmlCssJs_CssQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadRightComponentXml);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component/MyComponent.land.css`, loadRightCss);
registerTestModule(`${testPrefix}/component/MyComponent`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponentWithXmlCssJs_XmlQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadWrongXml);
registerTestModule(`${testPrefix}/component/MyComponent.land.xml`, loadRightComponentXml);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadRightCss);
registerTestModule(`${testPrefix}/component/MyComponent`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponentWithXmlCssJs_XmlCssJsQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadWrongXml);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component/MyComponent`, loadWrongJS);
registerTestModule(`${testPrefix}/component/MyComponent.land.xml`, loadRightComponentXml);
registerTestModule(`${testPrefix}/component/MyComponent.land.css`, loadRightCss);
registerTestModule(`${testPrefix}/component/MyComponent.land`, loadRightJS);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
function loadCodeCustomComponentJS() {
class MyComponent extends Button {
constructor() {
super();
this.id = 'test-id';
this.className = 'test-class';
this.text = 'right';
this.on('tap', () => {
testEventCalled = true;
});
}
}
return { MyComponent };
}
export function testCustomComponentWithCode_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component`, loadCodeCustomComponentJS);
registerTestModule(`${testPrefix}/component.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponentWithCode_JsCssQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component`, loadWrongJS);
registerTestModule(`${testPrefix}/component.land`, loadCodeCustomComponentJS);
registerTestModule(`${testPrefix}/component.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component.land.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
function loadRightComponentXmlWithCodeFileAndCssFile() {
return `<Button
codeFile="${testPrefix}/component/custom-code-component.js"
cssFile="${testPrefix}/component/custom-code-component.css"
id="test-id" class="test-class" text="right" tap="testEvent"/>`;
}
export function testCustomComponent_WithCodeFileAndCssFile_NoQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadRightComponentXmlWithCodeFileAndCssFile);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component/custom-code-component`, loadRightJS);
registerTestModule(`${testPrefix}/component/custom-code-component.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
}
export function testCustomComponent_WithCodeFileAndCssFile_WithQualifiers() {
// Arrange
registerTestModule(`${testPrefix}/test.xml`, loadPageXmlWithComponent);
registerTestModule(`${testPrefix}/component/MyComponent.xml`, loadRightComponentXmlWithCodeFileAndCssFile);
registerTestModule(`${testPrefix}/component/MyComponent.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component/custom-code-component`, loadWrongJS);
registerTestModule(`${testPrefix}/component/custom-code-component.css`, loadWrongCss);
registerTestModule(`${testPrefix}/component/custom-code-component.land`, loadRightJS);
registerTestModule(`${testPrefix}/component/custom-code-component.land.css`, loadRightCss);
// Act
const page = createViewFromEntryAndNavigate();
// Assert
assertXmlCssJs(page.getViewById('test-id'));
} | the_stack |
import * as jssm from '../jssm';
test('build-set version number is present', () =>
expect(typeof jssm.version)
.toBe('string'));
describe('Stochastic weather', () => {
new jssm.Machine({
start_states: ['breezy'],
transitions: [
{ from: 'breezy', to: 'breezy', probability: 0.4, kind: 'legal', forced_only: false, main_path: false },
{ from: 'breezy', to: 'sunny', probability: 0.3, kind: 'legal', forced_only: false, main_path: false },
{ from: 'breezy', to: 'cloudy', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'breezy', to: 'windy', probability: 0.1, kind: 'legal', forced_only: false, main_path: false },
{ from: 'breezy', to: 'rain', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'sunny', to: 'sunny', probability: 0.5, kind: 'legal', forced_only: false, main_path: false },
{ from: 'sunny', to: 'hot', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'sunny', to: 'breezy', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'sunny', to: 'cloudy', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'sunny', to: 'rain', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'hot', to: 'hot', probability: 0.75, kind: 'legal', forced_only: false, main_path: false },
{ from: 'hot', to: 'breezy', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'hot', to: 'sunny', probability: 0.2, kind: 'legal', forced_only: false, main_path: false },
{ from: 'cloudy', to: 'cloudy', probability: 0.6, kind: 'legal', forced_only: false, main_path: false },
{ from: 'cloudy', to: 'sunny', probability: 0.2, kind: 'legal', forced_only: false, main_path: false },
{ from: 'cloudy', to: 'rain', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'cloudy', to: 'breezy', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'windy', to: 'windy', probability: 0.3, kind: 'legal', forced_only: false, main_path: false },
{ from: 'windy', to: 'gale', probability: 0.1, kind: 'legal', forced_only: false, main_path: false },
{ from: 'windy', to: 'breezy', probability: 0.4, kind: 'legal', forced_only: false, main_path: false },
{ from: 'windy', to: 'rain', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'windy', to: 'sunny', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'gale', to: 'gale', probability: 0.65, kind: 'legal', forced_only: false, main_path: false },
{ from: 'gale', to: 'windy', probability: 0.25, kind: 'legal', forced_only: false, main_path: false },
{ from: 'gale', to: 'torrent', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'gale', to: 'hot', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'rain', probability: 0.3, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'torrent', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'windy', probability: 0.1, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'breezy', probability: 0.15, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'sunny', probability: 0.1, kind: 'legal', forced_only: false, main_path: false },
{ from: 'rain', to: 'cloudy', probability: 0.3, kind: 'legal', forced_only: false, main_path: false },
{ from: 'torrent', to: 'torrent', probability: 0.65, kind: 'legal', forced_only: false, main_path: false },
{ from: 'torrent', to: 'rain', probability: 0.25, kind: 'legal', forced_only: false, main_path: false },
{ from: 'torrent', to: 'cloudy', probability: 0.05, kind: 'legal', forced_only: false, main_path: false },
{ from: 'torrent', to: 'gale', probability: 0.05, kind: 'legal', forced_only: false, main_path: false }
]
});
test.todo('Unfinished test case in general spec');
});
describe('list exit actions', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from:'off', to:'red', action:'on', kind: 'legal', forced_only: false, main_path: false },
{ from:'red', to:'off', action:'off', kind: 'legal', forced_only: false, main_path: false }
]
});
test('shows "on" from off as default', () =>
expect(machine.list_exit_actions()[0])
.toBe('on') );
test('shows "on" from off', () =>
expect(machine.list_exit_actions('off')[0])
.toBe('on') );
test('shows "off" from red', () =>
expect(machine.list_exit_actions('red')[0])
.toBe('off') );
});
describe('probable exits for', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[ { from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false } ]
});
test('probable exits are an array', () =>
expect(Array.isArray(machine.probable_exits_for('off')) )
.toBe(true) );
test('one probable exit in example', () =>
expect(machine.probable_exits_for('off').length)
.toBe(1) );
test('exit is an object', () =>
expect(typeof machine.probable_exits_for('off')[0])
.toBe('object') );
test('exit 0 has a string from property', () =>
expect(typeof machine.probable_exits_for('off')[0].from)
.toBe('string') );
});
describe('probable action exits', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from:'off', to:'red', action:'on', kind: 'legal', forced_only: false, main_path: false },
{ from:'red', to:'off', action:'off', kind: 'legal', forced_only: false, main_path: false }
]
});
test('probable action exits are an array', () =>
expect(Array.isArray(machine.probable_action_exits()) )
.toBe(true) );
test('probable action exit 1 is on', () =>
expect(machine.probable_action_exits()[0].action)
.toBe('on') );
test('probable action exits are an array 2', () =>
expect(Array.isArray(machine.probable_action_exits('off')) )
.toBe(true) );
test('probable action exit 1 is on 2', () =>
expect(machine.probable_action_exits('off')[0].action)
.toBe('on') );
test('probable action exits are an array 3', () =>
expect(Array.isArray(machine.probable_action_exits('red')) )
.toBe(true) );
test('probable action exit 1 is on 3', () =>
expect(machine.probable_action_exits('red')[0].action)
.toBe('off') );
});
describe('probabilistic_transition', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [ { from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false } ]
});
machine.probabilistic_transition();
test('solo after probabilistic is red', () =>
expect(machine.state())
.toBe('red') );
});
describe('probabilistic_walk', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false },
{ from: 'red', to: 'off', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.probabilistic_walk(3);
test('solo after probabilistic walk 3 is red', () =>
expect(machine.state())
.toBe('red') );
});
describe('probabilistic_histo_walk', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false },
{ from: 'red', to: 'off', kind: 'legal', forced_only: false, main_path: false }
]
});
const histo = machine.probabilistic_histo_walk(3);
test('histo is a Map', () =>
expect(histo instanceof Map)
.toBe(true) );
test('histo red is 2', () =>
expect(histo.get('red'))
.toBe(2) );
test('histo off is 2', () =>
expect(histo.get('off'))
.toBe(2) );
});
describe('reports state_is_final', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[
{ from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false },
{ from: 'off', to: 'mid', kind: 'legal', forced_only: false, main_path: false },
{ from: 'mid', to: 'fin', kind: 'legal', forced_only: false, main_path: false }
],
complete:['red', 'mid']
});
test('final false for neither', () =>
expect(machine.state_is_final('off') )
.toBe(false) );
test('final false for just terminal', () =>
expect(machine.state_is_final('mid') )
.toBe(false) );
test('final false for just complete', () =>
expect(machine.state_is_final('fin') )
.toBe(false) );
test('final true', () =>
expect(machine.state_is_final('red') )
.toBe(true) );
});
describe('reports is_final', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[
{ from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false }
],
complete:['red']
});
const init_final = machine.is_final();
machine.transition('red');
const fin_final = machine.is_final();
test('final false', () =>
expect(init_final)
.toBe(false) );
test('final true', () =>
expect(fin_final)
.toBe(true) );
// why is this written this way?
/* todo whargarbl needs another two tests for is_changing once reintroduced */
});
describe('reports state_is_terminal', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [ { name: 'turn_on', action: 'power_on', from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false } ]
});
test('terminal false', () =>
expect(machine.state_is_terminal('off') )
.toBe(false) );
test('terminal true', () =>
expect(machine.state_is_terminal('red') )
.toBe(true) );
test('terminal on missing state throws', () =>
expect( () => machine.state_is_terminal('notARealState') )
.toThrow() );
});
describe('reports is_terminal', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [ { name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false} ]
});
const first = machine.is_terminal();
machine.transition('red');
const second = machine.is_terminal();
const terms = machine.has_terminals();
// why is this written this way?
test('terminal false', () =>
expect(first)
.toBe(false) );
test('terminal true', () =>
expect(second)
.toBe(true) );
test('has_terminals', () =>
expect(terms)
.toBe(true) );
});
describe('reports state_is_complete', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[ { name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false} ],
complete:['off'] // huhu
});
test('state_is_complete false', () =>
expect(machine.state_is_complete('off') )
.toBe(true) );
test('state_is_complete true', () =>
expect(machine.state_is_complete('red') )
.toBe(false) );
test('throws on nonexisting state', () =>
expect( () => machine.state_is_complete('thisStateDoesNotExist') )
.toThrow() );
});
describe('reports is_complete', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[ { name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false} ],
complete:['off'] // huhu
});
const first = machine.is_complete();
machine.transition('red');
const second = machine.is_complete();
const terms = machine.has_completes();
// why is this written this way?
test('is_complete false', () =>
expect(first)
.toBe(true) );
test('is_complete true', () =>
expect(second)
.toBe(false) );
test('has_completes', () =>
expect(terms)
.toBe(true) );
});
describe('reports on actions', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[ { name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false} ]
});
const a = machine.list_actions(); // todo comeback
test('that it has', () =>
expect(typeof machine.current_action_for('power_on') )
.toBe('number') );
test('that it doesn\'t have', () =>
expect(typeof machine.current_action_for('power_left') )
.toBe('undefined') );
test('correct list type', () =>
expect(Array.isArray(a))
.toBe(true) );
test('correct list size', () =>
expect(a.length)
.toBe(1) );
});
describe('actions', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from:'off', to:'red', action:'on', kind: 'legal', forced_only: false, main_path: false },
{ from:'red', to:'off', action:'off', kind: 'legal', forced_only: false, main_path: false }
]
});
test('red has actions().length 1', () =>
expect(machine.actions().length)
.toBe(1) );
test('red has actions()[0] "on"', () =>
expect(machine.actions()[0])
.toBe('on') );
test('red has actions().length 1 again', () =>
expect(machine.actions('off').length)
.toBe(1) );
test('red has actions()[0] "on" again', () =>
expect(machine.actions('off')[0])
.toBe('on') );
test('red has actions().length 1 re-again', () =>
expect(machine.actions('red').length)
.toBe(1) );
test('red has actions()[0] "off" re-again',
() => expect(machine.actions('red')[0])
.toBe('off') );
});
describe('states having action', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ from:'off', to: 'red', action: 'on', kind: 'legal', forced_only: false, main_path: false },
{ from:'red', to: 'off', action: 'off', kind: 'legal', forced_only: false, main_path: false }
]
});
test('one action has on', () =>
expect(machine.list_states_having_action('on').length)
.toBe(1) );
test('on is had by off', () =>
expect(machine.list_states_having_action('on')[0])
.toBe('off') );
});
describe('unenterables', () => {
const machine = new jssm.Machine({
start_states: ['off'],
transitions:[ { name:'turn_on', action: 'power_on', from: 'off', to: 'red', kind: 'legal', forced_only: false, main_path: false } ]
});
test('off isn\'t enterable', () =>
expect(machine.is_unenterable('off') )
.toBe(true) );
test('red is enterable', () =>
expect(machine.is_unenterable('red') )
.toBe(false) );
test('machine has unenterables', () =>
expect(machine.has_unenterables() )
.toBe(true) );
test('unenterable test on missing state throws', () =>
expect( () => machine.is_unenterable('notARealState') )
.toThrow() );
});
describe('reports on action edges', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false }
]
});
test('that it has', () =>
expect(typeof machine.current_action_edge_for('power_on'))
.toBe('object') );
test('that it doesn\'t have', () =>
expect(() => { machine.current_action_edge_for('power_west'); })
.toThrow() );
});
describe('reports on states', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false }
]
});
test('that it has', () =>
expect(typeof machine.state_for('off') )
.toBe('object') );
test('that it doesn\'t have', () =>
expect(() => { machine.state_for('no such state'); })
.toThrow() );
});
describe('returns states', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false }
]
});
test('that it has', () =>
expect(typeof machine.machine_state() )
.toBe('object') );
});
describe('reports on transitions', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [
{ name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false }
]
});
test('unspecified transition return type', () =>
expect(typeof machine.list_transitions() )
.toBe('object') );
test('unspecified transition correct entrance count', () =>
expect(machine.list_transitions().entrances.length)
.toBe(0) );
test('unspecified transition correct exit count', () =>
expect(machine.list_transitions().exits.length)
.toBe(1) );
test('specified transition return type', () =>
expect(typeof machine.list_transitions('off') )
.toBe('object') );
test('specified transition correct entrance count', () =>
expect(machine.list_transitions('off').entrances.length)
.toBe(0) );
test('specified transition correct exit count', () =>
expect(machine.list_transitions('off').exits.length)
.toBe(1) );
test('no such spec trans return type', () =>
expect(typeof machine.list_transitions('moot') )
.toBe('object') );
test('no such spec trans correct entrance count', () =>
expect(machine.list_transitions('moot').entrances.length)
.toBe(0) );
test('no such spec trans correct exit count', () =>
expect(machine.list_transitions('moot').exits.length)
.toBe(0) );
test('unspecified entrance return type', () =>
expect(Array.isArray( machine.list_entrances() ))
.toBe(true) );
test('unspecified entrance correct count', () =>
expect(machine.list_entrances().length)
.toBe(0) );
test('specified entrance return type', () =>
expect(Array.isArray( machine.list_entrances('off') ))
.toBe(true) );
test('specified entrance correct count', () =>
expect(machine.list_entrances('off').length)
.toBe(0) );
test('no such specified entrance return type', () =>
expect(Array.isArray( machine.list_entrances('moot') ))
.toBe(true) ); // todo whargarbl should these throw?
test('no such specified entrance correct count', () =>
expect(machine.list_entrances('moot').length)
.toBe(0) );
test('unspecified exit return type', () =>
expect(Array.isArray( machine.list_exits() ))
.toBe(true) );
test('unspecified exit correct count', () =>
expect(machine.list_exits().length)
.toBe(1) );
test('specified exit return type', () =>
expect(Array.isArray( machine.list_exits('off') ))
.toBe(true) );
test('specified exit correct count', () =>
expect(machine.list_exits('off').length)
.toBe(1) );
test('no such specified exit return type', () =>
expect(Array.isArray( machine.list_exits('moot') ))
.toBe(true) );
test('no such specified exit correct count', () =>
expect(machine.list_exits('moot').length)
.toBe(0) );
test('edge list return type', () =>
expect(Array.isArray( machine.list_edges() ))
.toBe(true) );
test('edge list correct count', () =>
expect(machine.list_edges().length)
.toBe(1) );
});
describe('transition by state names', () => {
const machine = new jssm.Machine({
start_states : ['off'],
transitions : [ { name:'turn_on', action:'power_on', from:'off', to:'red', kind: 'legal', forced_only: false, main_path: false } ]
});
test('finds off -> red', () =>
expect(machine.get_transition_by_state_names('off', 'red') )
.toBe(0) );
test('does not find off -> blue', () =>
expect(machine.get_transition_by_state_names('off', 'blue') )
.toBe(undefined) );
test('does not find blue -> red', () =>
expect(machine.get_transition_by_state_names('blue', 'red') )
.toBe(undefined) );
});
describe('Illegal machines', () => {
test('catch repeated names', () => expect( () => {
new jssm.Machine({
start_states: ['moot'],
transitions:[
{ name: 'identical', from: '1', to: '2', kind: 'legal', forced_only: false, main_path: false },
{ name: 'identical', from: '2', to: '3', kind: 'legal', forced_only: false, main_path: false }
]
});
}).toThrow() );
test('must define from', () => expect( () => {
new jssm.Machine({
start_states: ['moot'],
transitions:[
{ name:'identical', to:'2', kind: 'legal', forced_only: false, main_path: false }
]
} as any);
}).toThrow() );
test('must define to', () => expect( () => {
new jssm.Machine({
start_states: ['moot'],
transitions:[
{ name:'identical', from:'1', kind: 'legal', forced_only: false, main_path: false }
]
} as any);
}).toThrow() );
test('must not have two identical edges', () => expect( () => {
new jssm.Machine({
start_states: ['moot'],
transitions:[
{ name:'id1', from:'1', to:'2', kind: 'legal', forced_only: false, main_path: false },
{ name:'id2', from:'1', to:'2', kind: 'legal', forced_only: false, main_path: false }
]
});
}).toThrow() );
test('must not have two of the same action from the same source', () => expect( () => {
new jssm.Machine({
start_states: ['moot'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false },
{ name:'id2', from:'1', to:'3', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
}).toThrow() );
test.todo('Does is_complete need an argument?');
// test('must not have completion of non-state', () => expect( () => {
// const machine = new jssm.Machine({
// start_states: ['moot'],
// transitions:[
// { name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
// ]
// });
// machine.is_complete('no such state');
// }).toThrow() );
test.todo('is the _new_state api misunderstood in these tests?')
// test('internal state helper must not accept double states', () => expect( () => {
// const machine = new jssm.Machine({
// start_states: ['moot'],
// transitions:[
// { name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
// ]
// });
// machine._new_state({from: '1', name:'id1', to:'2', complete:false});
// machine._new_state({from: '1', name:'id1', to:'2', complete:false});
// }).toThrow() );
test('can\'t get actions of non-state', () => expect( () => {
const machine = new jssm.Machine({
start_states: ['1'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.actions('three');
}).toThrow() );
test('can\'t get states having non-action', () => expect( () => {
const machine = new jssm.Machine({
start_states: ['1'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.list_states_having_action('no such action');
}).toThrow() );
test('can\'t list exit states of non-action', () => expect( () => {
const machine = new jssm.Machine({
start_states: ['1'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.list_exit_actions('no such action');
}).toThrow() );
test('probable exits for throws on non-state', () => expect( () => {
const machine = new jssm.Machine({
start_states: ['1'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.probable_exits_for('3');
}).toThrow() );
test('no probable action exits of non-action', () => expect( () => {
const machine = new jssm.Machine({
start_states: ['1'],
transitions:[
{ name:'id1', from:'1', to:'2', action:'identical', kind: 'legal', forced_only: false, main_path: false }
]
});
machine.probable_action_exits('no such action');
}).toThrow() );
}); | the_stack |
import { bySport, isSport, PHASE, PLAYER } from "../../common";
import { idb } from "../db";
import { defaultGameAttributes, g, helpers } from "../util";
import type { UpdateEvents, ViewInput } from "../../common/types";
const getCategoriesAndStats = () => {
const categories = bySport<
{
name: string;
stat: string;
statProp: string;
title: string;
data: any[];
minStats: string[];
minValue: number[];
sortAscending?: true;
filter?: (p: any) => boolean;
}[]
>({
basketball: [
{
name: "Points",
stat: "PTS",
statProp: "pts",
title: "Points Per Game",
data: [],
minStats: ["gp", "pts"],
minValue: [70, 1400],
},
{
name: "Rebounds",
stat: "TRB",
statProp: "trb",
title: "Rebounds Per Game",
data: [],
minStats: ["gp", "trb"],
minValue: [70, 800],
},
{
name: "Assists",
stat: "AST",
statProp: "ast",
title: "Assists Per Game",
data: [],
minStats: ["gp", "ast"],
minValue: [70, 400],
},
{
name: "Field Goal Percentage",
stat: "FG%",
statProp: "fgp",
title: "Field Goal Percentage",
data: [],
minStats: ["fg"],
minValue: [300 * g.get("twoPointAccuracyFactor")],
},
{
name: "Three-Pointer Percentage",
stat: "3PT%",
statProp: "tpp",
title: "Three-Pointer Percentage",
data: [],
minStats: ["tp"],
minValue: [Math.max(55 * g.get("threePointTendencyFactor"), 12)],
},
{
name: "Free Throw Percentage",
stat: "FT%",
statProp: "ftp",
title: "Free Throw Percentage",
data: [],
minStats: ["ft"],
minValue: [125],
},
{
name: "Blocks",
stat: "BLK",
statProp: "blk",
title: "Blocks Per Game",
data: [],
minStats: ["gp", "blk"],
minValue: [70, 100],
},
{
name: "Steals",
stat: "STL",
statProp: "stl",
title: "Steals Per Game",
data: [],
minStats: ["gp", "stl"],
minValue: [70, 125],
},
{
name: "Minutes",
stat: "MP",
statProp: "min",
title: "Minutes Per Game",
data: [],
minStats: ["gp", "min"],
minValue: [70, 2000],
},
{
name: "Player Efficiency Rating",
stat: "PER",
statProp: "per",
title: "Player Efficiency Rating",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Estimated Wins Added",
stat: "EWA",
statProp: "ewa",
title: "Estimated Wins Added",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Win Shares / 48 Mins",
stat: "WS/48",
statProp: "ws48",
title: "Win Shares Per 48 Minutes",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Offensive Win Shares",
stat: "OWS",
statProp: "ows",
title: "Offensive Win Shares",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Defensive Win Shares",
stat: "DWS",
statProp: "dws",
title: "Defensive Win Shares",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Win Shares",
stat: "WS",
statProp: "ws",
title: "Win Shares",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Offensive Box Plus-Minus",
stat: "OBPM",
statProp: "obpm",
title: "Offensive Box Plus-Minus",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Defensive Box Plus-Minus",
stat: "DBPM",
statProp: "dbpm",
title: "Defensive Box Plus-Minus",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Box Plus-Minus",
stat: "BPM",
statProp: "bpm",
title: "Box Plus-Minus",
data: [],
minStats: ["min"],
minValue: [2000],
},
{
name: "Value Over Replacement Player",
stat: "VORP",
statProp: "vorp",
title: "Value Over Replacement Player",
data: [],
minStats: ["min"],
minValue: [2000],
},
],
football: [
{
name: "Passing Yards",
stat: "Yds",
statProp: "pssYds",
title: "Passing Yards",
data: [],
minStats: [],
minValue: [],
},
{
name: "Passing Yards Per Attempt",
stat: "Y/A",
statProp: "pssYdsPerAtt",
title: "Passing Yards Per Attempt",
data: [],
minStats: ["pss"],
minValue: [14 * 16],
},
{
name: "Completion Percentage",
stat: "%",
statProp: "cmpPct",
title: "Completion Percentage",
data: [],
minStats: ["pss"],
minValue: [14 * 16],
},
{
name: "Passing TDs",
stat: "TD",
statProp: "pssTD",
title: "Passing Touchdowns",
data: [],
minStats: [],
minValue: [],
},
{
name: "Passing Interceptions",
stat: "Int",
statProp: "pssInt",
title: "Passing Interceptions",
data: [],
minStats: [],
minValue: [],
},
{
name: "Quarterback Rating",
stat: "QBRat",
statProp: "qbRat",
title: "Quarterback Rating",
data: [],
minStats: ["pss"],
minValue: [14 * 16],
},
{
name: "Rushing Yards",
stat: "Yds",
statProp: "rusYds",
title: "Rushing Yards",
data: [],
minStats: [],
minValue: [],
},
{
name: "Rushing Yards Per Attempt",
stat: "Y/A",
statProp: "rusYdsPerAtt",
title: "Rushing Yards Per Attempt",
data: [],
minStats: ["rus"],
minValue: [6.25 * 16],
},
{
name: "Rushing TDs",
stat: "TD",
statProp: "rusTD",
title: "Rushing Touchdowns",
data: [],
minStats: [],
minValue: [],
},
{
name: "Receiving Yards",
stat: "Yds",
statProp: "recYds",
title: "Receiving Yards",
data: [],
minStats: [],
minValue: [],
},
{
name: "Receiving Yards Per Attempt",
stat: "Y/A",
statProp: "recYdsPerAtt",
title: "Receiving Yards Per Attempt",
data: [],
minStats: ["rec"],
minValue: [1.875 * 16],
},
{
name: "Receiving TDs",
stat: "TD",
statProp: "recTD",
title: "Receiving Touchdowns",
data: [],
minStats: [],
minValue: [],
},
{
name: "Yards From Scrimmage",
stat: "Yds",
statProp: "ydsFromScrimmage",
title: "Total Rushing and Receiving Yards From Scrimmage",
data: [],
minStats: [],
minValue: [],
},
{
name: "Rushing and Receiving TDs",
stat: "TD",
statProp: "rusRecTD",
title: "Total Rushing and Receiving Touchdowns",
data: [],
minStats: [],
minValue: [],
},
{
name: "Tackles",
stat: "Tck",
statProp: "defTck",
title: "Tackles",
data: [],
minStats: [],
minValue: [],
},
{
name: "Sacks",
stat: "Sk",
statProp: "defSk",
title: "Sacks",
data: [],
minStats: [],
minValue: [],
},
{
name: "Defensive Interceptions",
stat: "Int",
statProp: "defInt",
title: "Defensive Interceptions",
data: [],
minStats: [],
minValue: [],
},
{
name: "Forced Fumbles",
stat: "FF",
statProp: "defFmbFrc",
title: "Forced Fumbles",
data: [],
minStats: [],
minValue: [],
},
{
name: "Fumbles Recovered",
stat: "FR",
statProp: "defFmbRec",
title: "Fumbles Recovered",
data: [],
minStats: [],
minValue: [],
},
{
name: "Approximate Value",
stat: "AV",
statProp: "av",
title: "Approximate Value",
data: [],
minStats: [],
minValue: [],
},
],
hockey: [
{
name: "Goals",
stat: "G",
statProp: "g",
title: "Goals",
data: [],
minStats: [],
minValue: [],
},
{
name: "Assists",
stat: "A",
statProp: "a",
title: "Assists",
data: [],
minStats: [],
minValue: [],
},
{
name: "Points",
stat: "PTS",
statProp: "pts",
title: "Points",
data: [],
minStats: [],
minValue: [],
},
{
name: "Plus/Minus",
stat: "+/-",
statProp: "pm",
title: "Plus/Minus",
data: [],
minStats: [],
minValue: [],
filter: p => p.ratings.pos !== "G",
},
{
name: "Penalty Minutes",
stat: "PIM",
statProp: "pim",
title: "Penalty Minutes",
data: [],
minStats: [],
minValue: [],
},
{
name: "Time On Ice",
stat: "TOI",
statProp: "min",
title: "Time On Ice",
data: [],
minStats: [],
minValue: [],
filter: p => p.ratings.pos !== "G",
},
{
name: "Blocks",
stat: "BLK",
statProp: "blk",
title: "Blocks",
data: [],
minStats: [],
minValue: [],
},
{
name: "Hits",
stat: "HIT",
statProp: "hit",
title: "Hits",
data: [],
minStats: [],
minValue: [],
},
{
name: "Takeaways",
stat: "TK",
statProp: "tk",
title: "Takeaways",
data: [],
minStats: [],
minValue: [],
},
{
name: "Giveaways",
stat: "GV",
statProp: "gv",
title: "Giveaways",
data: [],
minStats: [],
minValue: [],
},
{
name: "Save Percentage",
stat: "SV%",
statProp: "svPct",
title: "Save Percentage",
data: [],
minStats: ["sv"],
minValue: [800],
},
{
name: "Goals Against Average",
stat: "GAA",
statProp: "gaa",
title: "Goals Against Average",
data: [],
minStats: ["sv"],
minValue: [800],
sortAscending: true,
},
{
name: "Shutouts",
stat: "SO",
statProp: "so",
title: "Shutouts",
data: [],
minStats: [],
minValue: [],
},
{
name: "Goals Created",
stat: "GC",
statProp: "gc",
title: "Goals Created",
data: [],
minStats: [],
minValue: [],
},
{
name: "Offensive Point Shares",
stat: "OPS",
statProp: "ops",
title: "Offensive Point Shares",
data: [],
minStats: [],
minValue: [],
},
{
name: "Defensive Point Shares",
stat: "DPS",
statProp: "dps",
title: "Defensive Point Shares",
data: [],
minStats: [],
minValue: [],
},
{
name: "Goalie Point Shares",
stat: "GPS",
statProp: "gps",
title: "Goalie Point Shares",
data: [],
minStats: [],
minValue: [],
},
{
name: "Point Shares",
stat: "PS",
statProp: "ps",
title: "Point Shares",
data: [],
minStats: [],
minValue: [],
},
],
});
const statsSet = new Set<string>();
for (const { minStats, statProp } of categories) {
statsSet.add(statProp);
for (const stat of minStats) {
statsSet.add(stat);
}
}
const stats = Array.from(statsSet);
return {
categories,
stats,
};
};
const updateLeaders = async (
inputs: ViewInput<"leaders">,
updateEvents: UpdateEvents,
state: any,
) => {
// Respond to watchList in case players are listed twice in different categories
if (
updateEvents.includes("watchList") ||
(inputs.season === g.get("season") && updateEvents.includes("gameSim")) ||
inputs.season !== state.season ||
inputs.playoffs !== state.playoffs
) {
const { categories, stats } = getCategoriesAndStats(); // Calculate the number of games played for each team, which is used later to test if a player qualifies as a league leader
const teamSeasons = await idb.getCopies.teamSeasons({
season: inputs.season,
});
const gps: Record<number, number | undefined> = {};
for (const teamSeason of teamSeasons) {
if (inputs.playoffs === "playoffs") {
if (teamSeason.gp < g.get("numGames")) {
gps[teamSeason.tid] = 0;
} else {
gps[teamSeason.tid] = teamSeason.gp - g.get("numGames");
}
} else {
// Don't count playoff games
if (teamSeason.gp > g.get("numGames")) {
gps[teamSeason.tid] = g.get("numGames");
} else {
gps[teamSeason.tid] = teamSeason.gp;
}
}
}
let players;
if (g.get("season") === inputs.season && g.get("phase") <= PHASE.PLAYOFFS) {
players = await idb.cache.players.indexGetAll("playersByTid", [
PLAYER.FREE_AGENT,
Infinity,
]);
} else {
players = await idb.getCopies.players({
activeSeason: inputs.season,
});
}
players = await idb.getCopies.playersPlus(players, {
attrs: ["pid", "nameAbbrev", "injury", "watch", "jerseyNumber"],
ratings: ["skills", "pos"],
stats: ["abbrev", "tid", ...stats],
season: inputs.season,
playoffs: inputs.playoffs === "playoffs",
regularSeason: inputs.playoffs !== "playoffs",
mergeStats: true,
});
const userAbbrev = helpers.getAbbrev(g.get("userTid"));
// In theory this should be the same for all sports, like basketball. But for a while FBGM set it to the same value as basketball, which didn't matter since it doesn't influence game sim, but it would mess this up.
const numPlayersOnCourtFactor = bySport({
basketball:
defaultGameAttributes.numPlayersOnCourt / g.get("numPlayersOnCourt"),
football: 1,
hockey: 1,
});
// To handle changes in number of games, playing time, etc
const factor =
(g.get("numGames") / defaultGameAttributes.numGames) *
numPlayersOnCourtFactor *
helpers.quarterLengthFactor();
// minStats and minValues are the NBA requirements to be a league leader for each stat http://www.nba.com/leader_requirements.html. If any requirement is met, the player can appear in the league leaders
for (const cat of categories) {
if (cat.sortAscending) {
players.sort((a, b) => a.stats[cat.statProp] - b.stats[cat.statProp]);
} else {
players.sort((a, b) => b.stats[cat.statProp] - a.stats[cat.statProp]);
}
for (const p of players) {
// Test if the player meets the minimum statistical requirements for this category
let pass = cat.minStats.length === 0 && (!cat.filter || cat.filter(p));
if (!pass) {
for (let k = 0; k < cat.minStats.length; k++) {
// In basketball, everything except gp is a per-game average, so we need to scale them by games played
let playerValue;
if (!isSport("basketball") || cat.minStats[k] === "gp") {
playerValue = p.stats[cat.minStats[k]];
} else {
playerValue = p.stats[cat.minStats[k]] * p.stats.gp;
}
// Compare against value normalized for team games played
const gpTeam = gps[p.stats.tid];
if (gpTeam !== undefined) {
// Special case GP
if (cat.minStats[k] === "gp") {
if (
playerValue / gpTeam >=
cat.minValue[k] / g.get("numGames")
) {
pass = true;
break; // If one is true, don't need to check the others
}
}
// Other stats
if (
playerValue >=
Math.ceil(
(cat.minValue[k] * factor * gpTeam) / g.get("numGames"),
)
) {
pass = true;
break; // If one is true, don't need to check the others
}
}
}
}
if (pass) {
const leader = helpers.deepCopy(p);
leader.stat = leader.stats[cat.statProp];
leader.abbrev = leader.stats.abbrev;
leader.tid = leader.stats.tid;
// @ts-ignore
delete leader.stats;
leader.userTeam = userAbbrev === leader.abbrev;
cat.data.push(leader);
}
// Stop when we found 10
if (cat.data.length === 10) {
break;
}
}
// @ts-ignore
delete cat.minStats;
// @ts-ignore
delete cat.minValue;
delete cat.filter;
}
return {
categories,
playoffs: inputs.playoffs,
season: inputs.season,
};
}
};
export default updateLeaders; | the_stack |
declare const uni: Uni;
declare class Uni {
/**
* 将 Base64 字符串转成 ArrayBuffer 对象
*
* 参考: [http://uniapp.dcloud.io/api/base64ToArrayBuffer?id=base64toarraybuffer](http://uniapp.dcloud.io/api/base64ToArrayBuffer?id=base64toarraybuffer)
*/
base64ToArrayBuffer(base64?: string): ArrayBuffer;
/**
* 将 ArrayBuffer 对象转成 Base64 字符串
*
* 参考: [http://uniapp.dcloud.io/api/arrayBufferToBase64?id=arraybuffertobase64](http://uniapp.dcloud.io/api/arrayBufferToBase64?id=arraybuffertobase64)
*/
arrayBufferToBase64(arrayBuffer?: ArrayBuffer): string;
/**
* 监听自定义事件。事件可以由 uni.$emit 触发。回调函数会接收 uni.$emit 传递的参数。
*
* 参考: [http://uniapp.dcloud.io/api/window/communication?id=on](http://uniapp.dcloud.io/api/window/communication?id=on)
*/
$on(eventName?: string, callback?: () => void): void;
/**
* 触发自定义事件,附加的参数会传递给事件监听器。
*
* 参考: [http://uniapp.dcloud.io/api/window/communication?id=emit](http://uniapp.dcloud.io/api/window/communication?id=emit)
*/
$emit(eventName?: string, param?: any): void;
/**
* 监听一个自定义事件。事件只触发一次,在第一次触发之后移除事件监听器。
*
* 参考: [http://uniapp.dcloud.io/api/window/communication?id=once](http://uniapp.dcloud.io/api/window/communication?id=once)
*/
$once(eventName?: string, callback?: () => void): void;
/**
* 移除自定义事件监听器。如果没有指定事件名,则移除所有事件监听器。如果提供事件名,则移除该事件的所有监听器。如果提供了事件名和回调,则只移除这个回调的监听器。
*
* 参考: [http://uniapp.dcloud.io/api/window/communication?id=off](http://uniapp.dcloud.io/api/window/communication?id=off)
*/
$off(eventName?: string | any [], callback?: () => void): void;
/**
* 通过id 获取 subNVues 原生子窗体的实例
*
* 参考: [http://uniapp.dcloud.io/api/window/subNVues?id=app-getsubnvuebyid](http://uniapp.dcloud.io/api/window/subNVues?id=app-getsubnvuebyid)
*/
getSubNVueById(subNvueId?: string): SubNVue;
/**
* 获取当前 subNVues 原生子窗体的实例
*
* 参考: [http://uniapp.dcloud.io/api/window/subNVues?id=app-getsubnvuebyid](http://uniapp.dcloud.io/api/window/subNVues?id=app-getsubnvuebyid)
*/
getCurrentSubNVue(): SubNVue;
/**
* 发起网络请求
*
* 参考: [http://uniapp.dcloud.io/api/request/request?id=request](http://uniapp.dcloud.io/api/request/request?id=request)
*/
request(options?: RequestOptions): RequestTask;
/**
* 上传文件
*
* 参考: [http://uniapp.dcloud.io/api/request/network-file?id=uploadfile](http://uniapp.dcloud.io/api/request/network-file?id=uploadfile)
*/
uploadFile(options?: UploadFileOption): UploadTask;
/**
* 下载文件
*
* 参考: [http://uniapp.dcloud.io/api/request/network-file?id=downloadfile](http://uniapp.dcloud.io/api/request/network-file?id=downloadfile)
*/
downloadFile(options?: DownloadFileOption): DownloadTask;
/**
* 导入原生插件
*
* 参考: [http://uniapp.dcloud.io/api/request/network-file?id=downloadfile](http://uniapp.dcloud.io/api/request/network-file?id=downloadfile)
*/
requireNativePlugin(moduleName?: string): void;
/**
* upx 换算为 px
*
* 参考: [http://uniapp.dcloud.io/frame?id=upx2px](http://uniapp.dcloud.io/frame?id=upx2px)
*/
upx2px(upx?: number): number;
/**
* 创建一个 WebSocket 连接
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=connectsocket](http://uniapp.dcloud.io/api/request/websocket?id=connectsocket)
*/
connectSocket(options?: ConnectSocketOption): SocketTask;
/**
* 监听WebSocket连接打开事件
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketopen](http://uniapp.dcloud.io/api/request/websocket?id=onsocketopen)
*/
onSocketOpen(options?: (result: OnSocketOpenCallbackResult) => void): void;
/**
* 监听WebSocket错误
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketerror](http://uniapp.dcloud.io/api/request/websocket?id=onsocketerror)
*/
onSocketError(callback?: (result: GeneralCallbackResult) => void): void;
/**
* 通过 WebSocket 连接发送数据
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=sendsocketmessage](http://uniapp.dcloud.io/api/request/websocket?id=sendsocketmessage)
*/
sendSocketMessage(options?: SendSocketMessageOptions): void;
/**
* 监听WebSocket接受到服务器的消息事件
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketmessage](http://uniapp.dcloud.io/api/request/websocket?id=onsocketmessage)
*/
onSocketMessage(callback?: (result: OnSocketMessageCallbackResult) => void): void;
/**
* 关闭 WebSocket 连接
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=closesocket](http://uniapp.dcloud.io/api/request/websocket?id=closesocket)
*/
closeSocket(options?: CloseSocketOptions): void;
/**
* 监听WebSocket关闭
*
* 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketclose](http://uniapp.dcloud.io/api/request/websocket?id=onsocketclose)
*/
onSocketClose(callback?: (result: GeneralCallbackResult) => void): void;
/**
* 从本地相册选择图片或使用相机拍照
*
* 参考: [http://uniapp.dcloud.io/api/media/image?id=chooseimage](http://uniapp.dcloud.io/api/media/image?id=chooseimage)
*/
chooseImage(options?: ChooseImageOptions): void;
/**
* 预览图片
*
* 参考: [http://uniapp.dcloud.io/api/media/image?id=previewimage](http://uniapp.dcloud.io/api/media/image?id=previewimage)
*/
previewImage(options?: PreviewImageOptions): void;
/**
* 预览图片
*
* 参考: [http://uniapp.dcloud.io/api/media/image?id=getimageinfo](http://uniapp.dcloud.io/api/media/image?id=getimageinfo)
*/
getImageInfo(options?: GetImageInfoOptions): void;
/**
* 保存图片到系统相册
*
* 参考: [http://uniapp.dcloud.io/api/media/image?id=saveimagetophotosalbum](http://uniapp.dcloud.io/api/media/image?id=saveimagetophotosalbum)
*/
saveImageToPhotosAlbum(options?: SaveImageToPhotosAlbumOptions): void;
/**
* 压缩图片
*
* 参考: [http://uniapp.dcloud.io/api/media/image?id=compressimage](http://uniapp.dcloud.io/api/media/image?id=compressimage)
*/
compressImage(options?: CompressImageOptions): void;
/**
* 录音管理
*
* 参考: [http://uniapp.dcloud.io/api/media/record-manager?id=getrecordermanager](http://uniapp.dcloud.io/api/media/record-manager?id=getrecordermanager)
*/
getRecorderManager(): RecorderManager;
/**
* 获取全局唯一的背景音频管理器 backgroundAudioManager
*
* 参考: [http://uniapp.dcloud.io/api/media/background-audio-manager?id=getbackgroundaudiomanager](http://uniapp.dcloud.io/api/media/background-audio-manager?id=getbackgroundaudiomanager)
*/
getBackgroundAudioManager(): BackgroundAudioManager;
/**
* 创建并返回 audio 上下文 audioContext 对象
*
* 参考: [http://uniapp.dcloud.io/api/media/audio-context?id=createinneraudiocontext](http://uniapp.dcloud.io/api/media/audio-context?id=createinneraudiocontext)
*/
createInnerAudioContext(): CreateInnerAudioContext;
/**
* 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。
*
* 参考: [http://uniapp.dcloud.io/api/media/video?id=choosevideo](http://uniapp.dcloud.io/api/media/video?id=choosevideo)
*/
chooseVideo(options?: ChooseVideoOptions): void;
/**
* 保存视频到系统相册
*
* 参考: [http://uniapp.dcloud.io/api/media/video?id=savevideotophotosalbum](http://uniapp.dcloud.io/api/media/video?id=savevideotophotosalbum)
*/
saveVideoToPhotosAlbum(options?: SaveVideoToPhotosAlbumOptions): void;
/**
* 创建并返回 video 上下文 videoContext 对象
*
* 参考: [http://uniapp.dcloud.io/api/media/video-context?id=createvideocontext](http://uniapp.dcloud.io/api/media/video-context?id=createvideocontext)
*/
createVideoContext(videoId?: string, currentComponent?: any): VideoContext;
/**
* 创建并返回 camera 组件的上下文 cameraContext 对象
*
* 参考: [http://uniapp.dcloud.io/api/media/camera-context](http://uniapp.dcloud.io/api/media/camera-context)
*/
createCameraContext(): CameraContext;
/**
* 保存文件到本地
*
* 参考: [http://uniapp.dcloud.io/api/file/file?id=savefile](http://uniapp.dcloud.io/api/file/file?id=savefile)
*/
saveFile(options?: SaveFileOptions): void;
/**
* 获取文件信息
*/
getFileInfo(options?: GetFileInfoOptions): void;
/**
* 获取本地已保存的文件列表
*
* 参考: [http://uniapp.dcloud.io/api/file/file?id=getsavedfilelist](http://uniapp.dcloud.io/api/file/file?id=getsavedfilelist)
*/
getSavedFileList(options?: GetSavedFileListOptions): void;
/**
* 获取本地文件的文件信息
*
* 参考: [http://uniapp.dcloud.io/api/file/file?id=getsavedfileinfo](http://uniapp.dcloud.io/api/file/file?id=getsavedfileinfo)
*/
getSavedFileInfo(options?: GetSavedFileInfoOptions): void;
/**
* 删除本地存储的文件
*
* 参考: [http://uniapp.dcloud.io/api/file/file?id=removesavedfile](http://uniapp.dcloud.io/api/file/file?id=removesavedfile)
*/
removeSavedFile(options?: RemoveSavedFileOptions): void;
/**
* 新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx
*
* 参考: [http://uniapp.dcloud.io/api/file/file?id=opendocument](http://uniapp.dcloud.io/api/file/file?id=opendocument)
*/
openDocument(options?: OpenDocumentOptions): void;
/**
* 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=setstorage](http://uniapp.dcloud.io/api/storage/storage?id=setstorage)
*/
setStorage(options?: SetStorageOptions): void;
/**
* 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=setstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=setstoragesync)
*/
setStorageSync(key?: string, value?: any): void;
/**
* 从本地缓存中异步获取指定 key 对应的内容
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorage](http://uniapp.dcloud.io/api/storage/storage?id=getstorage)
*/
getStorage(options?: GetStorageOptions): void;
/**
* 从本地缓存中同步获取指定 key 对应的内容
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=getstoragesync)
*/
getStorageSync(key?: string): any;
/**
* 异步获取当前 storage 的相关信息
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfo](http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfo)
*/
getStorageInfo(options?: GetStorageInfoOptions): void;
/**
* 同步获取当前 storage 的相关信息
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfosync](http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfosync)
*/
getStorageInfoSync(): GetStorageInfoSuccess;
/**
* 从本地缓存中异步移除指定 key
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=removestorage](http://uniapp.dcloud.io/api/storage/storage?id=removestorage)
*/
removeStorage(options?: RemoveStorageOptions): void;
/**
* 从本地缓存中同步移除指定 key
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=removestoragesync](http://uniapp.dcloud.io/api/storage/storage?id=removestoragesync)
*/
removeStorageSync(key?: string): void;
/**
* 清理本地数据缓存
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=clearstorage](http://uniapp.dcloud.io/api/storage/storage?id=clearstorage)
*/
clearStorage(): void;
/**
* 同步清理本地数据缓存
*
* 参考: [http://uniapp.dcloud.io/api/storage/storage?id=clearstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=clearstoragesync)
*/
clearStorageSync(): void;
/**
* 获取当前的地理位置、速度
*
* 参考: [http://uniapp.dcloud.io/api/location/location?id=getlocation](http://uniapp.dcloud.io/api/location/location?id=getlocation)
*/
getLocation(options?: GetLocationOptions): void;
/**
* 打开地图选择位置。
*
* 参考: [http://uniapp.dcloud.io/api/location/location?id=chooselocation](http://uniapp.dcloud.io/api/location/location?id=chooselocation)
*/
chooseLocation(options?: ChooseLocationOptions): void;
/**
* 使用地图查看位置
*
* 参考: [http://uniapp.dcloud.io/api/location/open-location?id=openlocation](http://uniapp.dcloud.io/api/location/open-location?id=openlocation)
*/
openLocation(options?: OpenLocationOptions): void;
/**
* 创建并返回 map 上下文 mapContext 对象
*
* 参考: [http://uniapp.dcloud.io/api/location/map?id=createmapcontext](http://uniapp.dcloud.io/api/location/map?id=createmapcontext)
*/
createMapContext(mapId?: string, currentComponent?: any): MapContext;
/**
* 异步获取系统信息
*
* 参考: [http://uniapp.dcloud.io/api/system/info?id=getsysteminfo](http://uniapp.dcloud.io/api/system/info?id=getsysteminfo)
*/
getSystemInfo(options?: GetSystemInfoOptions): void;
/**
* 同步获取系统信息
*
* 参考: [http://uniapp.dcloud.io/api/system/info?id=getsysteminfosync](http://uniapp.dcloud.io/api/system/info?id=getsysteminfosync)
*/
getSystemInfoSync(): GetSystemInfoResult;
/**
* 判断uni-app的API,回调,参数,组件等是否在当前版本可用
*
* 参考: [http://uniapp.dcloud.io/api/system/info?id=caniuse](http://uniapp.dcloud.io/api/system/info?id=caniuse)
*/
canIUse(options?: string): boolean;
/**
* 获取网络类型
*
* 参考: [http://uniapp.dcloud.io/api/system/network?id=getnetworktype](http://uniapp.dcloud.io/api/system/network?id=getnetworktype)
*/
getNetworkType(options?: GetNetworkTypeOptions): void;
/**
* 监听网络状态变化
*
* 参考: [http://uniapp.dcloud.io/api/system/network?id=onnetworkstatuschange](http://uniapp.dcloud.io/api/system/network?id=onnetworkstatuschange)
*/
onNetworkStatusChange(callback?: (result: OnNetworkStatusChangeSuccess) => void): void;
/**
* 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 uni.stopAccelerometer 停止监听
*
* 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=onaccelerometerchange](http://uniapp.dcloud.io/api/system/accelerometer?id=onaccelerometerchange)
*/
onAccelerometerChange(callback?: (result: OnAccelerometerChangeSuccess) => void): void;
/**
* 开始监听加速度数据
*
* 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=startaccelerometer](http://uniapp.dcloud.io/api/system/accelerometer?id=startaccelerometer)
*/
startAccelerometer(options?: StartAccelerometerOptions): void;
/**
* 停止监听加速度数据
*
* 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=stopaccelerometer](http://uniapp.dcloud.io/api/system/accelerometer?id=stopaccelerometer)
*/
stopAccelerometer(options?: StopAccelerometerOptions): void;
/**
* 监听罗盘数据,频率:5次/秒,接口调用后会自动开始监听,可使用uni.stopCompass停止监听
*
* 参考: [http://uniapp.dcloud.io/api/system/compass?id=oncompasschange](http://uniapp.dcloud.io/api/system/compass?id=oncompasschange)
*/
onCompassChange(callback?: (result: OnCompassChangeSuccess) => void): void;
/**
* 开始监听罗盘数据
*
* 参考: [http://uniapp.dcloud.io/api/system/compass?id=startcompass](http://uniapp.dcloud.io/api/system/compass?id=startcompass)
*/
startCompass(options?: StartCompassOptions): void;
/**
* 停止监听罗盘数据
*
* 参考: [http://uniapp.dcloud.io/api/system/compass?id=stopcompass](http://uniapp.dcloud.io/api/system/compass?id=stopcompass)
*/
stopCompass(options?: StopCompassOptions): void;
/**
* 拨打电话
*
* 参考: [http://uniapp.dcloud.io/api/system/phone?id=makephonecall](http://uniapp.dcloud.io/api/system/phone?id=makephonecall)
*/
makePhoneCall(options?: MakePhoneCallOptions): void;
/**
* 调用扫码界面,扫码成功后返回对应的结果
*
* 参考: [http://uniapp.dcloud.io/api/system/barcode?id=scancode](http://uniapp.dcloud.io/api/system/barcode?id=scancode)
*/
scanCode(options?: ScanCodeOptions): void;
/**
* 设置系统剪贴板的内容
*
* 参考: [http://uniapp.dcloud.io/api/system/clipboard?id=setclipboarddata](http://uniapp.dcloud.io/api/system/clipboard?id=setclipboarddata)
*/
setClipboardData(options?: SetClipboardDataOptions): void;
/**
* 获得系统剪贴板的内容
*
* 参考: [http://uniapp.dcloud.io/api/system/clipboard?id=getclipboarddata](http://uniapp.dcloud.io/api/system/clipboard?id=getclipboarddata)
*/
getClipboardData(options?: GetClipboardDataOptions): void;
/**
* 隐藏软键盘
*
* 参考: [http://uniapp.dcloud.io/api/key?id=hidekeyboard](http://uniapp.dcloud.io/api/key?id=hidekeyboard)
*/
hideKeyboard(): void;
/**
* 监听键盘高度变化
*
* 参考: [http://uniapp.dcloud.io/api/key?id=onkeyboardheightchange](http://uniapp.dcloud.io/api/key?id=onkeyboardheightchange)
*/
onKeyboardHeightChange(callback?: (result: OnKeyboardHeightChangeResult) => void): void;
/**
* 设置屏幕亮度
*
* 参考: [http://uniapp.dcloud.io/api/system/brightness?id=setscreenbrightness](http://uniapp.dcloud.io/api/system/brightness?id=setscreenbrightness)
*/
setScreenBrightness(options?: SetScreenBrightnessOptions): void;
/**
* 获取屏幕亮度
*
* 参考: [http://uniapp.dcloud.io/api/system/brightness?id=getscreenbrightness](http://uniapp.dcloud.io/api/system/brightness?id=getscreenbrightness)
*/
getScreenBrightness(options?: GetScreenBrightnessOptions): void;
/**
* 设置是否保持常亮状态
*
* 参考: [http://uniapp.dcloud.io/api/system/brightness?id=setkeepscreenon](http://uniapp.dcloud.io/api/system/brightness?id=setkeepscreenon)
*/
setKeepScreenOn(options?: SetKeepScreenOnOptions): void;
/**
* 使手机发生较长时间的振动(400ms)
*
* 参考: [http://uniapp.dcloud.io/api/system/vibrate?id=vibratelong](http://uniapp.dcloud.io/api/system/vibrate?id=vibratelong)
*/
vibrateLong(options?: VibrateLongOptions): void;
/**
* 使手机发生较短时间的振动(15ms)
*
* 参考: [http://uniapp.dcloud.io/api/system/vibrate?id=vibrateshort](http://uniapp.dcloud.io/api/system/vibrate?id=vibrateshort)
*/
vibrateShort(options?: VibrateShortOptions): void;
/**
* 手机通讯录联系人和联系方式的增加
*
* 参考: [http://uniapp.dcloud.io/api/system/contact?id=addphonecontact](http://uniapp.dcloud.io/api/system/contact?id=addphonecontact)
*/
addPhoneContact(options?: AddPhoneContactOptions): void;
/**
* 获取已搜索到的iBeacon设备
*
* 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=getbeacons](http://uniapp.dcloud.io/api/system/ibeacon?id=getbeacons)
*/
getBeacons(options?: GetBeaconsOptions): void;
/**
* 开始搜索附近的iBeacon设备
*
* 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=startbeacondiscovery](http://uniapp.dcloud.io/api/system/ibeacon?id=startbeacondiscovery)
*/
startBeaconDiscovery(options?: StartBeaconDiscoveryOptions): void;
/**
* 停止搜索附近的iBeacon设备
*
* 参考: [http://uniapp.dcloud.io//api/system/ibeacon?id=stopbeacondiscovery](http://uniapp.dcloud.io//api/system/ibeacon?id=stopbeacondiscovery)
*/
stopBeaconDiscovery(options?: StopBeaconDiscoveryOptions): void;
/**
* 监听iBeacon设备更新
*
* 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconupdate](http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconupdate)
*/
onBeaconUpdate(callback?: (result: GetBeaconsRes) => void): void;
/**
* 监听iBeacon服务状态变化
*
* 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconservicechange](http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconservicechange)
*/
onBeaconServiceChange(callback?: (result: BeaconService) => void): void;
/**
* 关闭蓝牙模块
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=closebluetoothadapter](http://uniapp.dcloud.io/api/system/bluetooth?id=closebluetoothadapter)
*/
closeBluetoothAdapter(options?: CloseBluetoothAdapterOptions): void;
/**
* 获取本机蓝牙适配器状态
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothadapterstate](http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothadapterstate)
*/
getBluetoothAdapterState(options?: GetBluetoothAdapterStateOptions): void;
/**
* 获取已搜索到的蓝牙设备
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothdevices](http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothdevices)
*/
getBluetoothDevices(options?: GetBluetoothDevicesOptions): void;
/**
* 根据uuid获取处于已连接的设备
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getconnectedbluetoothdevices](http://uniapp.dcloud.io/api/system/bluetooth?id=getconnectedbluetoothdevices)
*/
getConnectedBluetoothDevices(options?: GetConnectedBluetoothDevicesOptions): void;
/**
* 监听蓝牙适配器状态变化事件
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothadapterstatechange](http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothadapterstatechange)
*/
onBluetoothAdapterStateChange(callback?: (result: OnBluetoothAdapterStateChangeResult) => void): void;
/**
* 监听搜索到新设备的事件
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothdevicefound](http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothdevicefound)
*/
onBluetoothDeviceFound(callback?: (result: OnBluetoothDeviceFoundResult) => void): void;
/**
* 初始化蓝牙模块
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter](http://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter)
*/
openBluetoothAdapter(options?: OpenBluetoothAdapterOptions): void;
/**
* 开始搜索附近的蓝牙设备
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=startbluetoothdevicesdiscovery](http://uniapp.dcloud.io/api/system/bluetooth?id=startbluetoothdevicesdiscovery)
*/
startBluetoothDevicesDiscovery(options?: StartBluetoothDevicesDiscoveryOptions): void;
/**
* 停止搜寻附近的蓝牙外围设备
*
* 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=stopbluetoothdevicesdiscovery](http://uniapp.dcloud.io/api/system/bluetooth?id=stopbluetoothdevicesdiscovery)
*/
stopBluetoothDevicesDiscovery(options?: StopBluetoothDevicesDiscoveryOptions): void;
/**
* 断开与低功耗蓝牙设备的连接
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=closebleconnection](http://uniapp.dcloud.io/api/system/ble?id=closebleconnection)
*/
closeBLEConnection(options?: CloseBLEConnectionOptions): void;
/**
* 连接低功耗蓝牙设备
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=createbleconnection](http://uniapp.dcloud.io/api/system/ble?id=createbleconnection)
*/
createBLEConnection(options?: CreateBLEConnectionOptions): void;
/**
* 获取蓝牙设备指定服务中所有特征值
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=getbledevicecharacteristics](http://uniapp.dcloud.io/api/system/ble?id=getbledevicecharacteristics)
*/
getBLEDeviceCharacteristics(options?: GetBLEDeviceCharacteristicsOptions): void;
/**
* 获取蓝牙设备的所有服务
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=getbledeviceservices](http://uniapp.dcloud.io/api/system/ble?id=getbledeviceservices)
*/
getBLEDeviceServices(options?: GetBLEDeviceServicesOptions): void;
/**
* 启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=notifyblecharacteristicvaluechange](http://uniapp.dcloud.io/api/system/ble?id=notifyblecharacteristicvaluechange)
*/
notifyBLECharacteristicValueChange(options?: NotifyBLECharacteristicValueChangeOptions): void;
/**
* 监听低功耗蓝牙设备的特征值变化事件
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=onblecharacteristicvaluechange](http://uniapp.dcloud.io/api/system/ble?id=onblecharacteristicvaluechange)
*/
onBLECharacteristicValueChange(callback?: (result: OnBLECharacteristicValueChangeSuccess) => void): void;
/**
* 监听低功耗蓝牙设备连接状态变化事件
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=onbleconnectionstatechange](http://uniapp.dcloud.io/api/system/ble?id=onbleconnectionstatechange)
*/
onBLEConnectionStateChange(callback?: (result: OnBLEConnectionStateChangeSuccess) => void): void;
/**
* 读取低功耗蓝牙设备指定特征值的二进制数据值
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=readblecharacteristicvalue](http://uniapp.dcloud.io/api/system/ble?id=readblecharacteristicvalue)
*/
readBLECharacteristicValue(options?: ReadBLECharacteristicValueOptions): void;
/**
* 向低功耗蓝牙设备指定特征值写入二进制数据
*
* 参考: [http://uniapp.dcloud.io/api/system/ble?id=writeblecharacteristicvalue](http://uniapp.dcloud.io/api/system/ble?id=writeblecharacteristicvalue)
*/
writeBLECharacteristicValue(options?: WriteBLECharacteristicValueOptions): void;
/**
* 显示消息提示框
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showtoast](http://uniapp.dcloud.io/api/ui/prompt?id=showtoast)
*/
showToast(options?: ShowToastOptions): void;
/**
* 显示 loading 提示框
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showloading](http://uniapp.dcloud.io/api/ui/prompt?id=showloading)
*/
showLoading(options?: ShowLoadingOptions): void;
/**
* 隐藏消息提示框
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=hidetoast](http://uniapp.dcloud.io/api/ui/prompt?id=hidetoast)
*/
hideToast(): void;
/**
* 隐藏 loading 提示框
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=hideloading](http://uniapp.dcloud.io/api/ui/prompt?id=hideloading)
*/
hideLoading(): void;
/**
* 显示模态弹窗
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showmodal](http://uniapp.dcloud.io/api/ui/prompt?id=showmodal)
*/
showModal(options?: ShowModalOptions): void;
/**
* 显示操作菜单
*
* 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showactionsheet](http://uniapp.dcloud.io/api/ui/prompt?id=showactionsheet)
*/
showActionSheet(options?: ShowActionSheetOptions): void;
/**
* 动态设置当前页面的标题
*
* 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle](http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle)
*/
setNavigationBarTitle(options?: SetNavigationBarTitleOptions): void;
/**
* 在当前页面显示导航条加载动画
*
* 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=shownavigationbarloading](http://uniapp.dcloud.io/api/ui/navigationbar?id=shownavigationbarloading)
*/
showNavigationBarLoading(): void;
/**
* 隐藏导航条加载动画
*
* 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=hidenavigationbarloading](http://uniapp.dcloud.io/api/ui/navigationbar?id=hidenavigationbarloading)
*/
hideNavigationBarLoading(): void;
/**
* 设置导航条颜色
*
* 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbarcolor](http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbarcolor)
*/
setNavigationBarColor(options?: SetNavigationbarColorOptions): void;
/**
* 动态设置 tabBar 某一项的内容
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbaritem](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbaritem)
*/
setTabBarItem(options?: SetTabBarItemOptions): void;
/**
* 动态设置 tabBar 的整体样式
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarstyle](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarstyle)
*/
setTabBarStyle(options?: SetTabBarStyleOptions): void;
/**
* 隐藏 tabBar
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbar](http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbar)
*/
hideTabBar(options?: HideTabBarOptions): void;
/**
* 显示 tabBar
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbar](http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbar)
*/
showTabBar(options?: ShowTabBarOptions): void;
/**
* 为 tabBar 某一项的右上角添加文本
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarbadge](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarbadge)
*/
setTabBarBadge(options?: SetTabBarBadgeOptions): void;
/**
* 移除 tabBar 某一项右上角的文本
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=removetabbarbadge](http://uniapp.dcloud.io/api/ui/tabbar?id=removetabbarbadge)
*/
removeTabBarBadge(options?: RemoveTabBarBadgeOptions): void;
/**
* 显示 tabBar 某一项的右上角的红点
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbarreddot](http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbarreddot)
*/
showTabBarRedDot(options?: ShowTabBarRedDotOptions): void;
/**
* 隐藏 tabBar 某一项的右上角的红点
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbarreddot](http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbarreddot)
*/
hideTabBarRedDot(options?: HideTabBarRedDotOptions): void;
/**
* 监听中间按钮的点击事件
*
* 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=ontabbarmidbuttontap](http://uniapp.dcloud.io/api/ui/tabbar?id=ontabbarmidbuttontap)
*/
onTabBarMidButtonTap(callback?: () => void): void;
/**
* 保留当前页面,跳转到应用内的某个页面
*
* 参考: [http://uniapp.dcloud.io/api/router?id=navigateto](http://uniapp.dcloud.io/api/router?id=navigateto)
*/
navigateTo(options?: NavigateToOptions): void;
/**
* 关闭当前页面,跳转到应用内的某个页面
*
* 参考: [http://uniapp.dcloud.io/api/router?id=redirectto](http://uniapp.dcloud.io/api/router?id=redirectto)
*/
redirectTo(options?: RedirectToOptions): void;
/**
* 关闭所有页面,打开到应用内的某个页面
*
* 参考: [http://uniapp.dcloud.io/api/router?id=relaunch](http://uniapp.dcloud.io/api/router?id=relaunch)
*/
reLaunch(options?: ReLaunchOptions): void;
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
*
* 参考: [http://uniapp.dcloud.io/api/router?id=switchtab](http://uniapp.dcloud.io/api/router?id=switchtab)
*/
switchTab(options?: SwitchTabOptions): void;
/**
* 关闭当前页面,返回上一页面或多级页面
*
* 参考: [http://uniapp.dcloud.io/api/router?id=navigateback](http://uniapp.dcloud.io/api/router?id=navigateback)
*/
navigateBack(options?: NavigateBackOptions): void;
/**
* 创建一个动画实例
*
* 参考: [http://uniapp.dcloud.io/api/ui/animation?id=createanimation](http://uniapp.dcloud.io/api/ui/animation?id=createanimation)
*/
createAnimation(options?: CreateAnimationOptions): Animation;
/**
* 将页面滚动到目标位置
*
* 参考: [http://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto](http://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto)
*/
pageScrollTo(options?: PageScrollToOptions): void;
/**
* 开始下拉刷新
*
* 参考: [http://uniapp.dcloud.io/api/ui/pulldown?id=startpulldownrefresh](http://uniapp.dcloud.io/api/ui/pulldown?id=startpulldownrefresh)
*/
startPullDownRefresh(options?: StartPullDownRefreshOptions): void;
/**
* 停止当前页面下拉刷新
*
* 参考: [http://uniapp.dcloud.io/api/ui/pulldown?id=stoppulldownrefresh](http://uniapp.dcloud.io/api/ui/pulldown?id=stoppulldownrefresh)
*/
stopPullDownRefresh(): void;
/**
* 返回一个SelectorQuery对象实例
*
* 参考: [http://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery](http://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery)
*/
createSelectorQuery(): SelectorQuery;
/**
* 创建并返回一个 IntersectionObserver 对象实例
*
* 参考: [http://uniapp.dcloud.io/api/ui/intersection-observer?id=createintersectionobserver](http://uniapp.dcloud.io/api/ui/intersection-observer?id=createintersectionobserver)
*/
createIntersectionObserver(options?: CreateIntersectionObserverOptions): IntersectionObserver;
/**
* 创建 canvas 绘图上下文
*
* 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=createcanvascontext](http://uniapp.dcloud.io/api/ui/canvas?id=createcanvascontext)
*/
createCanvasContext(canvasId?: string, componentInstance?: any): CanvasContext;
/**
* 把当前画布指定区域的内容导出生成指定大小的图片
*
* 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvastotempfilepath](http://uniapp.dcloud.io/api/ui/canvas?id=canvastotempfilepath)
*/
canvasToTempFilePath(options?: CanvasToTempFilePathOptions): void;
/**
* 描述 canvas 区域隐含的像素数据
*
* 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvasgetimagedata](http://uniapp.dcloud.io/api/ui/canvas?id=canvasgetimagedata)
*/
canvasGetImageData(options?: CanvasGetImageDataOptions): void;
/**
* 将像素数据绘制到画布
*
* 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvasputimagedata](http://uniapp.dcloud.io/api/ui/canvas?id=canvasputimagedata)
*/
canvasPutImageData(options?: CanvasPutImageDataOptions): void;
/**
* 监听窗口尺寸变化事件
*
* 参考: [http://uniapp.dcloud.io/api/ui/window?id=onwindowresize](http://uniapp.dcloud.io/api/ui/window?id=onwindowresize)
*/
onWindowResize(callback?: (result: WindowResizeResult) => void): void;
/**
* 取消监听窗口尺寸变化事件
*
* 参考: [http://uniapp.dcloud.io/api/ui/window?id=offwindowresize](http://uniapp.dcloud.io/api/ui/window?id=offwindowresize)
*/
offWindowResize(callback?: () => void): void;
/**
* 获取服务供应商
*
* 参考: [http://uniapp.dcloud.io/api/plugins/provider?id=getprovider](http://uniapp.dcloud.io/api/plugins/provider?id=getprovider)
*/
getProvider(options?: GetProviderOptions): void;
/**
* 登录
*
* 参考: [http://uniapp.dcloud.io/api/plugins/login?id=login](http://uniapp.dcloud.io/api/plugins/login?id=login)
*/
login(options?: LoginOptions): void;
/**
* 登录
*
* 参考: [http://uniapp.dcloud.io/api/plugins/login?id=unichecksession](http://uniapp.dcloud.io/api/plugins/login?id=unichecksession)
*/
checkSession(options?: CheckSessionOptions): void;
/**
* 获取用户信息
*
* 参考: [http://uniapp.dcloud.io/api/plugins/login?id=getuserinfo](http://uniapp.dcloud.io/api/plugins/login?id=getuserinfo)
*/
getUserInfo(options?: GetUserInfoOptions): void;
/**
* 分享
*
* 参考: [http://uniapp.dcloud.io/api/plugins/share?id=share](http://uniapp.dcloud.io/api/plugins/share?id=share)
*/
share(options?: ShareOptions): void;
/**
* 支付
*
* 参考: [http://uniapp.dcloud.io/api/plugins/payment?id=requestpayment](http://uniapp.dcloud.io/api/plugins/payment?id=requestpayment)
*/
requestPayment(options?: RequestPaymentOptions): void;
/**
* 提前向用户发起授权请求
*
* 参考: [http://uniapp.dcloud.io/api/other/authorize?id=authorize](http://uniapp.dcloud.io/api/other/authorize?id=authorize)
*/
authorize(options?: AuthorizeOptions): void;
/**
* 调起客户端小程序设置界面,返回用户设置的操作结果
*
* 参考: [http://uniapp.dcloud.io/api/other/authorize?id=opensetting](http://uniapp.dcloud.io/api/other/authorize?id=opensetting)
*/
openSetting(options?: OpenSettingOptions): void;
/**
* 获取用户的当前设置
*
* 参考: [http://uniapp.dcloud.io/api/other/setting?id=getsetting](http://uniapp.dcloud.io/api/other/setting?id=getsetting)
*/
getSetting(options?: GetSettingOptions): void;
/**
* 获取用户收货地址。调起用户编辑收货地址原生界面,并在编辑完成后返回用户选择的地址,需要用户授权 scope.address
*
* 参考: [http://uniapp.dcloud.io/api/other/choose-address?id=chooseaddress](http://uniapp.dcloud.io/api/other/choose-address?id=chooseaddress)
*/
chooseAddress(options?: ChooseAddressOptions): void;
/**
* 选择用户的发票抬头,需要用户授权 scope.invoiceTitle
*
* 参考: [http://uniapp.dcloud.io/api/other/invoice-title?id=chooseinvoicetitle](http://uniapp.dcloud.io/api/other/invoice-title?id=chooseinvoicetitle)
*/
chooseInvoiceTitle(options?: ChooseInvoiceTitleOptions): void;
/**
* 调起客户端小程序设置界面,返回用户设置的操作结果
*
* 参考: [http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatetominiprogram](http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatetominiprogram)
*/
navigateToMiniProgram(options?: NavigateToMiniProgramOptions): void;
/**
* 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功
*
* 参考: [http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatebackminiprogram](http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatebackminiprogram)
*/
navigateBackMiniProgram(options?: NavigateBackMiniProgramOptions): void;
/**
* 返回全局唯一的版本更新管理器对象: updateManager,用于管理小程序更新
*
* 参考: [http://uniapp.dcloud.io/api/other/update?id=getupdatemanager](http://uniapp.dcloud.io/api/other/update?id=getupdatemanager)
*/
getUpdateManager(): UpdateManager;
/**
* 设置是否打开调试开关。此开关对正式版也能生效
*
* 参考: [http://uniapp.dcloud.io/api/other/set-enable-debug?id=setenabledebug](http://uniapp.dcloud.io/api/other/set-enable-debug?id=setenabledebug)
*/
setEnableDebug(options?: SetEnableDebugOptions): void;
/**
* 获取第三方平台自定义的数据字段
*
* 参考: [http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfig](http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfig)
*/
getExtConfig(options?: GetExtConfigOptions): GetExtConfigRes;
/**
* uni.getExtConfig() 的同步版本
*
* 参考: [http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfigsync](http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfigsync)
*/
getExtConfigSync(): GetExtConfigSyncRes;
/**
* 隐藏分享按钮
*
* 参考: [http://uniapp.dcloud.io/api/plugins/share?id=hidesharemenu](http://uniapp.dcloud.io/api/plugins/share?id=hidesharemenu)
*/
hideShareMenu(options?: HideShareMenuOptions): void;
/**
* 动态设置窗口的背景色
*
* 参考: [http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundcolor](http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundcolor)
*/
setBackgroundColor(options?: SetBackgroundColorOptions): void;
/**
* 动态设置窗口的背景色
*
* 参考: [http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundtextstyle](http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundtextstyle)
*/
setBackgroundTextStyle(options?: SetBackgroundTextStyleOptions): void;
/**
* 监听陀螺仪数据变化事件
*
* 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=ongyroscopechange](http://uniapp.dcloud.io/api/system/gyroscope?id=ongyroscopechange)
*/
onGyroscopeChange(callback?: (result: OnGyroscopeChangeSuccess) => void): void;
/**
* 开始监听陀螺仪数据
*
* 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=startgyroscope](http://uniapp.dcloud.io/api/system/gyroscope?id=startgyroscope)
*/
startGyroscope(options?: StartGyroscopeOptions): void;
/**
* 停止监听陀螺仪数据
*
* 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=stopgyroscope](http://uniapp.dcloud.io/api/system/gyroscope?id=stopgyroscope)
*/
stopGyroscope(options?: StopGyroscopeOptions): void;
/**
* 动态加载网络字体
*
* 参考: [http://uniapp.dcloud.io/api/ui/font?id=loadfontface](http://uniapp.dcloud.io/api/ui/font?id=loadfontface)
*/
loadFontFace(options?: LoadFontFaceOptions): void;
/**
* 获取小程序下该菜单按钮的布局位置信息
*
* 参考: [http://uniapp.dcloud.io/api/ui/menuButton?id=getmenubuttonboundingclientrect](http://uniapp.dcloud.io/api/ui/menuButton?id=getmenubuttonboundingclientrect)
*/
getMenuButtonBoundingClientRect(): GetMenuButtonBoundingClientRectRes;
}
interface GeneralCallbackResult {
/**
* 错误信息
*/
errMsg?: string | undefined;
}
interface SubNVue {
/**
* 显示原生子窗体
*/
show(options?: 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' | 'fade-in' | 'zoom-out' | 'zoom-fade-out' | 'pop-in'): void;
/**
* 隐藏原生子窗体
*/
hide(options?: 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out'): void;
/**
* 设置原生子窗体的样式
*/
setStyle(options?: SubNVuesSetStyleOptions): void;
/**
* 发送消息
*/
postMessage(): void;
/**
* 监听消息
*/
onMessage(success?: () => void): void;
}
interface SubNVuesSetStyleOptions {
/**
* 原生子窗体的排版位置
* - static: 原生子窗体在页面中正常定位
* - absolute: 原生子窗体在页面中绝对定位
* - dock: 原生子窗体在页面中停靠
*/
position?: 'static' | 'absolute' | 'dock' | undefined;
/**
* 原生子窗体的停靠方式,仅当原生子窗体 "position" 属性值设置为 "dock" 时才生效
* - top: 原生子窗体停靠则页面顶部
* - bottom: 原生子窗体停靠在页面底部
* - left: 原生子窗体停靠在页面左侧
* - right: 原生子窗体停靠在页面右侧
*/
dock?: 'top' | 'bottom' | 'left' | 'right' | undefined;
/**
* 原生子窗体的内置样式
* - popup: 弹出层
* - navigationBar: 导航栏
*/
type?: 'popup' | 'navigationBar' | undefined;
/**
* 原生子窗体的遮罩层,仅当原生子窗体 "type" 属性值设置为 "popup" 时才生效
* - popup: 弹出层
* - navigationBar: 导航栏
*/
mask?: 'popup' | 'navigationBar' | undefined;
/**
* 原生子窗体的宽度
*/
width?: string | undefined;
/**
* 原生子窗体的高度
*/
height?: string | undefined;
/**
* 原生子窗体垂直向下的偏移量
*/
top?: string | undefined;
/**
* 原生子窗体垂直向上的偏移量
*/
bottom?: string | undefined;
/**
* 原生子窗体水平向左的偏移量
*/
left?: string | undefined;
/**
* 原生子窗体水平向右的偏移量
*/
right?: string | undefined;
/**
* 原生子窗体的边距
*/
margin?: string | undefined;
}
interface RequestPaymentOptions {
/**
* 支付服务提供商,通过 uni.getProvider 获取
* - alipay: 支付宝支付
* - wxpay: 微信支付
* - baidu: 百度收银台
* - appleiap: 苹果应用内支付
*/
provider?: 'alipay' | 'wxpay' | 'baidu' | 'appleiap' | undefined;
/**
* 订单数据
*/
orderInfo?: string | undefined;
/**
* 时间戳从1970年1月1日至今的秒数,即当前的时间,微信小程序独有
*/
timeStamp?: string | undefined;
/**
* 随机字符串,长度为32个字符以下,微信小程序独有 。
*/
nonceStr?: string | undefined;
/**
* 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=xx,微信小程序独有
*/
package?: string | undefined;
/**
* 签名算法,暂支持 MD5 ,微信小程序独有
*/
signType?: string | undefined;
/**
* 签名,具体签名方案参见小程序支付接口文档,微信小程序独有
*/
paySign?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface RequestOptions {
/**
* 资源url
*/
url?: string | undefined;
/**
* 请求的参数
*/
data?: string | object | ArrayBuffer | undefined;
/**
* 设置请求的 header,header 中不能设置 Referer。
*/
header?: any;
/**
* 默认为 GET
* 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
*/
method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' | undefined;
/**
* 如果设为json,会尝试对返回的数据做一次 JSON.parse
*/
dataType?: string | undefined;
/**
* 设置响应的数据类型。合法值:text、arraybuffer
*/
responseType?: string | undefined;
/**
* 成功返回的回调函数
*/
success?: ((result: RequestSuccessCallbackResult) => void) | undefined;
/**
* 失败的回调函数
*/
fail?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: ((result: GeneralCallbackResult) => void) | undefined;
}
interface RequestSuccessCallbackResult {
/**
* 开发者服务器返回的数据
*/
data?: string | undefined;
/**
* 开发者服务器返回的 HTTP 状态码
*/
statusCode?: number | undefined;
/**
* 开发者服务器返回的 HTTP Response Header
*/
header?: any;
}
interface RequestTask {
/**
* 中断请求任务
*/
abort(): void;
}
interface UploadFileOption {
/**
* 开发者服务器 url
*/
url?: string | undefined;
/**
* 文件类型,image/video/audio,仅支付宝小程序,且必填。
* - image: 图像
* - video: 视频
* - audio: 音频
*/
fileType?: 'image' | 'video' | 'audio' | undefined;
/**
* 要上传文件资源的路径
*/
filePath?: string | undefined;
/**
* 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
*/
name?: string | undefined;
/**
* 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。仅 5+App 支持
*/
files?: UploadFileOptionFiles [] | undefined;
/**
* HTTP 请求 Header, header 中不能设置 Referer
*/
header?: any;
/**
* HTTP 请求中其他额外的 form data
*/
formData?: any;
/**
* 成功返回的回调函数
*/
success?: ((result: UploadFileSuccessCallbackResult) => void) | undefined;
/**
* 失败的回调函数
*/
fail?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: ((result: GeneralCallbackResult) => void) | undefined;
}
interface UploadFileOptionFiles {
/**
* multipart 提交时,表单的项目名,默认为 file,如果 name 不填或填的值相同,可能导致服务端读取文件时只能读取到一个文件。
*/
name?: string | undefined;
/**
* 要上传文件资源的路径
*/
uri?: string | undefined;
}
interface UploadTask {
/**
* 监听上传进度变化
*/
onProgressUpdate(callback?: (result: OnProgressUpdateResult) => void): void;
/**
* 中断上传任务
*/
abort(): void;
}
interface OnProgressUpdateResult {
/**
* 上传进度百分比
*/
progress?: number | undefined;
/**
* 已经上传的数据长度,单位 Bytes
*/
totalBytesSent?: number | undefined;
/**
* 预期需要上传的数据总长度,单位 Bytes
*/
totalBytesExpectedToSend?: number | undefined;
}
interface DownloadFileOption {
/**
* 下载资源的 url
*/
url?: string | undefined;
/**
* HTTP 请求 Header,header 中不能设置 Referer
*/
header?: any;
/**
* 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'}
*/
success?: ((result: DownloadSuccessData) => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface DownloadTask {
/**
* 监听下载进度变化
*/
onProgressUpdate(callback?: (result: OnProgressDownloadResult) => void): void;
/**
* 中断下载任务
*/
abort(): void;
}
interface OnProgressDownloadResult {
/**
* 下载进度百分比
*/
progress?: number | undefined;
/**
* 已经下载的数据长度,单位 Bytes
*/
totalBytesWritten?: number | undefined;
/**
* 预期需要下载的数据总长度,单位 Bytes
*/
totalBytesExpectedToWrite?: number | undefined;
}
interface UploadFileSuccessCallbackResult {
/**
* 开发者服务器返回的数据
*/
data?: string | undefined;
/**
* 开发者服务器返回的 HTTP 状态码
*/
statusCode?: number | undefined;
}
interface DownloadSuccessData {
/**
* 临时文件路径,下载后的文件会存储到一个临时文件
*/
tempFilePath?: string | undefined;
/**
* 开发者服务器返回的 HTTP 状态码
*/
statusCode?: number | undefined;
}
interface ConnectSocketOption {
/**
* 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名
*/
url?: string | undefined;
/**
* HTTP 请求 Header,header 中不能设置 Referer
*/
header?: any;
/**
* 默认为 GET
* 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
*/
method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT' | undefined;
/**
* 子协议数组
*/
protocols?: string [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SendSocketMessageOptions {
/**
* 需要发送的内容
*/
data?: string | ArrayBuffer | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: ((result: GeneralCallbackResult) => void) | undefined;
}
interface CloseSocketOptions {
/**
* 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭)
*/
code?: number | undefined;
/**
* 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符)
*/
reason?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: ((result: GeneralCallbackResult) => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: ((result: GeneralCallbackResult) => void) | undefined;
}
interface SocketTask {
/**
* 通过 WebSocket 连接发送数据
*/
send(options?: SendSocketMessageOptions): void;
/**
* 关闭 WebSocket 连接
*/
close(options?: CloseSocketOptions): void;
/**
* 监听 WebSocket 连接打开事件
*/
onOpen(callback?: (result: OnSocketOpenCallbackResult) => void): void;
/**
* 监听 WebSocket 连接关闭事件
*/
onClose(callback?: () => void): void;
/**
* 监听 WebSocket 错误
*/
onError(callback?: (result: GeneralCallbackResult) => void): void;
/**
* 监听WebSocket接受到服务器的消息事件
*/
onMessage(callback?: (result: OnSocketMessageCallbackResult) => void): void;
}
interface OnSocketMessageCallbackResult {
/**
* 服务器返回的消息
*/
data?: string | ArrayBuffer | undefined;
}
interface OnSocketOpenCallbackResult {
/**
* 连接成功的 HTTP 响应 Header
*/
header?: any;
}
interface ChooseImageOptions {
/**
* 最多可以选择的图片张数,默认9
*/
count?: number | undefined;
/**
* original 原图,compressed 压缩图,默认二者都有
*/
sizeType?: string | string [] | undefined;
/**
* album 从相册选图,camera 使用相机,默认二者都有
*/
sourceType?: string | string [] | undefined;
/**
* 成功则返回图片的本地文件路径列表 tempFilePaths
*/
success?: ((result: ChooseImageSuccessCallbackResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseImageSuccessCallbackResult {
/**
* 图片的本地文件路径列表
*/
tempFilePaths?: string | any [] | undefined;
/**
* 图片的本地文件列表,每一项是一个 File 对象
*/
tempFiles?: ChooseImageSuccessCallbackResultFile | ChooseImageSuccessCallbackResultFile [] | undefined;
}
interface ChooseImageSuccessCallbackResultFile {
/**
* 本地文件路径
*/
path?: string | undefined;
/**
* 本地文件大小,单位:B
*/
size?: number | undefined;
}
interface PreviewImageOptions {
/**
* 当前显示图片的链接,不填则默认为 urls 的第一张
*/
count?: string | undefined;
/**
* current 为当前显示图片的链接/索引值,不填或填写的值无效则为 urls 的第一张。App平台在 1.9.5至1.9.8之间,current为必填。不填会报错
*/
current?: string | undefined;
/**
* 需要预览的图片链接列表
*/
urls?: string | any [] | undefined;
/**
* 图片指示器样式
* - default: 底部圆点指示器
* - number: 顶部数字指示器
* - none: 不显示指示器
*/
indicator?: 'default' | 'number' | 'none' | undefined;
/**
* 是否可循环预览
*/
loop?: boolean | undefined;
/**
* 长按图片显示操作菜单,如不填默认为保存相册,1.9.5 起支持。
*/
longPressActions?: LongPressActionsOptions | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LongPressActionsOptions {
/**
* 按钮的文字数组
*/
itemList?: string [] | undefined;
/**
* 按钮的文字颜色,字符串格式,默认为"#000000"
*/
itemColor?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: LongPressActionsSuccessData) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LongPressActionsSuccessData {
/**
* 接口调用失败的回调函数
*/
tapIndex?: number | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
index?: number | undefined;
}
interface GetImageInfoOptions {
/**
* 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径
*/
src?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetImageInfoSuccessData) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetImageInfoSuccessData {
/**
* 图片宽度,单位px
*/
width?: number | undefined;
/**
* 图片高度,单位px
*/
height?: number | undefined;
/**
* 返回图片的本地路径
*/
path?: string | undefined;
/**
* 返回图片的方向
*/
orientation?: string | undefined;
/**
* 返回图片的格式
*/
type?: string | undefined;
}
interface SaveImageToPhotosAlbumOptions {
/**
* 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径
*/
filePath?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CompressImageOptions {
/**
* 图片路径,图片的路径,可以是相对路径、临时文件路径、存储文件路径
*/
src?: string | undefined;
/**
* 压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)
*/
quality?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: ((result: CompressImageSuccessData) => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CompressImageSuccessData {
/**
* 压缩后图片的临时文件路径
*/
tempFilePath?: string | undefined;
}
interface StartRecordOptions {
/**
* 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'}
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface RecorderManager {
/**
* 开始录音
*/
start(options?: RecorderManagerStartOptions): void;
/**
* 暂停录音
*/
pause(): void;
/**
* 暂停录音
*/
resume(): void;
/**
* 停止录音
*/
stop(): void;
/**
* 录音开始事件
*/
onStart(options?: () => void): void;
/**
* 录音暂停事件
*/
onPause(options?: () => void): void;
/**
* 录音停止事件,会回调文件地址
*/
onStop(options?: () => void): void;
/**
* 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件
*/
onFrameRecorded(options?: () => void): void;
/**
* 录音错误事件, 会回调错误信息
*/
onError(options?: () => void): void;
}
interface RecorderManagerStartOptions {
/**
* 指定录音的时长,单位 ms ,如果传入了合法的 duration ,在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟)
*/
duration?: number | undefined;
/**
* 采样率,有效值 8000/16000/44100
*/
sampleRate?: number | undefined;
/**
* 录音通道数,有效值 1/2
*/
numberOfChannels?: number | undefined;
/**
* 编码码率,有效值见下表格
*/
encodeBitRate?: number | undefined;
/**
* 音频格式,有效值 aac/mp3
*/
format?: string | undefined;
/**
* 指定帧大小,单位 KB。传入 frameSize 后,每录制指定帧大小的内容后,会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。
*/
frameSize?: number | undefined;
}
interface PlayVoiceOptions {
/**
* 需要播放的语音文件的文件路径
*/
filePath?: string | undefined;
/**
* original 原图,compressed 压缩图,默认二者都有
*/
duration?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBackgroundAudioPlayerStateOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetBackgroundAudioPlayerStateSuccessData) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBackgroundAudioPlayerStateSuccessData {
/**
* 选定音频的长度(单位:s),只有在当前有音乐播放时返回
*/
duration?: number | undefined;
/**
* 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回
*/
currentPosition?: number | undefined;
/**
* 播放状态(2:没有音乐在播放,1:播放中,0:暂停中)
*/
status?: number | undefined;
/**
* 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回
*/
downloadPercent?: number | undefined;
/**
* 歌曲数据链接,只有在当前有音乐播放时返回
*/
dataUrl?: string | undefined;
}
interface GetBackgroundAudioOptions {
/**
* 音乐链接,目前支持的格式有 m4a, aac, mp3, wav
*/
dataUrl?: string | undefined;
/**
* 音乐标题
*/
title?: string | undefined;
/**
* 封面url
*/
coverImgUrl?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SeekBackgroundAudioOptions {
/**
* 音乐位置,单位:秒
*/
position?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface BackgroundAudioManager {
/**
* 当前音频的长度(单位:s),只有在当前有合法的 src 时返回
*/
duration?: number | undefined;
/**
* 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回
*/
currentTime?: number | undefined;
/**
* 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放
*/
paused?: boolean | undefined;
/**
* 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav
*/
src?: string | undefined;
/**
* 音频开始播放的位置(单位:s)
*/
startTime?: number | undefined;
/**
* 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲
*/
buffered?: number | undefined;
/**
* 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。
*/
title?: string | undefined;
/**
* 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值
*/
epname?: string | undefined;
/**
* 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值
*/
singer?: string | undefined;
/**
* 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。
*/
coverImgUrl?: string | undefined;
/**
* 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值
*/
webUrl?: string | undefined;
/**
* 音频协议。默认值为 'http',设置 'hls' 可以支持播放 HLS 协议的直播音频
*/
protocol?: string | undefined;
/**
* 播放
*/
play(): void;
/**
* 暂停
*/
pause(): void;
/**
* 跳转到指定位置,单位 s
*/
seek(): void;
/**
* 停止
*/
stop(): void;
/**
* 背景音频进入可以播放状态,但不保证后面可以流畅播放
*/
onCanplay(callback?: () => void): void;
/**
* 背景音频播放事件
*/
onPlay(callback?: () => void): void;
/**
* 背景音频暂停事件
*/
onPause(callback?: () => void): void;
/**
* 背景音频停止事件
*/
onStop(callback?: () => void): void;
/**
* 背景音频自然播放结束事件
*/
onEnded(callback?: () => void): void;
/**
* 背景音频播放进度更新事件
*/
onTimeUpdate(callback?: () => void): void;
/**
* 用户在系统音乐播放面板点击上一曲事件(iOS only)
*/
onPrev(callback?: () => void): void;
/**
* 用户在系统音乐播放面板点击下一曲事件(iOS only)
*/
onNext(callback?: () => void): void;
/**
* 背景音频播放错误事件
*/
onNext(callback?: () => void): void;
/**
* 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发
*/
onWaiting(callback?: () => void): void;
}
interface CreateAudioContext {
/**
* 音频的地址
*/
setSrc(): void;
/**
* 暂停
*/
pause(): void;
/**
* 播放
*/
play(): void;
/**
* 跳转到指定位置,单位 s
*/
seek(): void;
}
interface CreateInnerAudioContext {
/**
* 当前音频的长度(单位:s),只有在当前有合法的 src 时返回
*/
duration?: number | undefined;
/**
* 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回
*/
currentTime?: number | undefined;
/**
* 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放
*/
paused?: boolean | undefined;
/**
* 音频的数据链接,用于直接播放。
*/
src?: string | undefined;
/**
* 音频开始播放的位置(单位:s)
*/
startTime?: number | undefined;
/**
* 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲
*/
buffered?: number | undefined;
/**
* 是否自动开始播放,默认 false
*/
autoplay?: boolean | undefined;
/**
* 是否循环播放,默认 false
*/
loop?: boolean | undefined;
/**
* 是否遵循系统静音开关,当此参数为 false 时,即使用户打开了静音开关,也能继续发出声音,默认值 true
*/
obeyMuteSwitch?: boolean | undefined;
/**
* 音量。范围 0~1。
*/
volume?: number | undefined;
/**
* 暂停
*/
pause(): void;
/**
* 停止
*/
stop(): void;
/**
* 播放
*/
play(): void;
/**
* 跳转到指定位置,单位 s
*/
seek(): void;
/**
* 销毁当前实例
*/
destroy(): void;
/**
* 音频进入可以播放状态,但不保证后面可以流畅播放
*/
onCanplay(callback?: () => void): void;
/**
* 音频播放事件
*/
onPlay(callback?: () => void): void;
/**
* 音频暂停事件
*/
onPause(callback?: () => void): void;
/**
* 音频停止事件
*/
onStop(callback?: () => void): void;
/**
* 音频自然播放结束事件
*/
onEnded(callback?: () => void): void;
/**
* 音频播放进度更新事件
*/
onTimeUpdate(callback?: () => void): void;
/**
* 音频播放错误事件
*/
onError(callback?: () => void): void;
/**
* 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发
*/
onWaiting(callback?: () => void): void;
/**
* 音频进行 seek 操作事件
*/
onSeeking(callback?: () => void): void;
/**
* 音频完成 seek 操作事件
*/
onSeeked(callback?: () => void): void;
/**
* 取消监听 onCanplay 事件
*/
offCanplay(callback?: () => void): void;
/**
* 取消监听 onPlay 事件
*/
offPlay(callback?: () => void): void;
/**
* 取消监听 onPause 事件
*/
offPause(callback?: () => void): void;
/**
* 取消监听 onStop 事件
*/
offStop(callback?: () => void): void;
/**
* 取消监听 onEnded 事件
*/
offEnded(callback?: () => void): void;
/**
* 取消监听 onTimeUpdate 事件
*/
offTimeUpdate(callback?: () => void): void;
/**
* 取消监听 onWaiting 事件
*/
offError(callback?: () => void): void;
/**
* 取消监听 onWaiting 事件
*/
offWaiting(callback?: () => void): void;
/**
* 取消监听 onSeeking 事件
*/
offSeeking(callback?: () => void): void;
/**
* 取消监听 onSeeked 事件
*/
offSeeked(callback?: () => void): void;
}
interface ChooseVideoOptions {
/**
* album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera']
*/
sourceType?: string | any [] | undefined;
/**
* 是否压缩所选的视频源文件,默认值为true,需要压缩
*/
compressed?: boolean | undefined;
/**
* 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒
*/
maxDuration?: number | undefined;
/**
* 摄像切换
* - front: 前置摄像头
* - back: 后置摄像头
*/
camera?: 'front' | 'back' | undefined;
/**
* 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明
*/
success?: ((result: ChooseVideoSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SaveVideoToPhotosAlbumOptions {
/**
* 视频文件路径,可以是临时文件路径也可以是永久文件路径
*/
filePath?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseVideoSuccess {
/**
* 临时文件路径,下载后的文件会存储到一个临时文件
*/
tempFilePath?: string | undefined;
/**
* 选定视频的时间长度
*/
duration?: number | undefined;
/**
* 选定视频的数据量大小
*/
size?: number | undefined;
/**
* 返回选定视频的长
*/
height?: number | undefined;
/**
* 返回选定视频的宽
*/
width?: number | undefined;
}
interface VideoContext {
/**
* 暂停
*/
pause(): void;
/**
* 播放
*/
play(): void;
/**
* 跳转到指定位置,单位 s
*/
seek(): void;
/**
* 发送弹幕,danmu 包含两个属性 text, color。
*/
sendDanmu(): void;
/**
* 设置倍速播放,支持的倍率有 0.5/0.8/1.0/1.25/1.5
*/
playbackRate(): void;
/**
* 进入全屏,可传入{direction}参数(1.7.0起支持),详见video组件文档
*/
requestFullScreen(): void;
/**
* 退出全屏
*/
exitFullScreen(): void;
}
interface CameraContext {
/**
* 拍照,可指定质量,成功则返回图片
*/
takePhoto(options?: CameraContextTakePhotoOptions): void;
/**
* 开始录像
*/
startRecord(options?: CameraContextStartRecordOptions): void;
/**
* 结束录像,成功则返回封面与视频
*/
stopRecord(options?: CameraContextStopRecordOptions): void;
/**
* 结束录像,成功则返回封面与视频
*/
onCameraFrame(callback?: (result: CameraFrame) => void): void;
}
interface CameraContextTakePhotoOptions {
/**
* 成像质量,值为high, normal, low,默认normal
* - normal: 普通质量
* - high: 高质量
* - low: 低质量
*/
quality?: 'normal' | 'high' | 'low' | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: CameraContextTakePhotoResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CameraContextTakePhotoResult {
/**
* 照片文件的临时路径,安卓是jpg图片格式,ios是png
*/
tempImagePath?: string | undefined;
}
interface CameraContextStartRecordOptions {
/**
* 超过30s或页面onHide时会结束录像
*/
timeoutCallback?: ((result: CameraContextStopRecordResult) => void) | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CameraContextStopRecordOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: CameraContextStopRecordResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CameraContextStopRecordResult {
/**
* 封面图片文件的临时路径
*/
tempThumbPath?: string | undefined;
/**
* 视频的文件的临时路径
*/
tempVideoPath?: string | undefined;
}
interface CameraFrame {
/**
* 图像数据矩形的宽度
*/
width?: number | undefined;
/**
* 图像数据矩形的高度
*/
height?: number | undefined;
/**
* 图像像素点数据,一维数组,每四项表示一个像素点的 rgba
*/
data?: ArrayBuffer | undefined;
}
interface SaveFileOptions {
/**
* 需要保存的文件的临时路径
*/
tempFilePath?: string | undefined;
/**
* 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'}
*/
success?: ((result: SaveFileSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SaveFileSuccess {
/**
* 文件的保存路径
*/
savedFilePath?: string | undefined;
}
interface GetFileInfoOptions {
/**
* 本地路径
*/
filePath?: string | undefined;
/**
* 计算文件摘要的算法,默认值 md5,有效值:md5,sha1
*/
digestAlgorithm?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetFileInfoSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetFileInfoSuccess {
/**
* 文件大小,单位:B
*/
size?: number | undefined;
/**
* 按照传入的 digestAlgorithm 计算得出的的文件摘要
*/
digest?: string | undefined;
/**
* 调用结果
*/
errMsg?: string | undefined;
}
interface GetSavedFileListOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetSavedFileListSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetSavedFileListSuccess {
/**
* 接口调用结果
*/
errMsg?: number | undefined;
/**
* 文件列表
*/
fileList?: string | undefined;
}
interface GetSavedFileInfoOptions {
/**
* 文件路径
*/
filePath?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetSavedFileInfoSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetSavedFileInfoSuccess {
/**
* 接口调用结果
*/
errMsg?: string | undefined;
/**
* 文件大小,单位B
*/
size?: number | undefined;
/**
* 文件保存时的时间戳,从1970/01/01 08:00:00 到该时刻的秒数
*/
createTime?: number | undefined;
}
interface RemoveSavedFileOptions {
/**
* 文件路径
*/
filePath?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OpenDocumentOptions {
/**
* 文件路径
*/
filePath?: string | undefined;
/**
* 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx
*/
fileType?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetStorageOptions {
/**
* 本地缓存中的指定的 key
*/
key?: string | undefined;
/**
* 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象
*/
data?: any;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetStorageOptions {
/**
* 本地缓存中的指定的 key
*/
key?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: any) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetStorageInfoOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetStorageInfoSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetStorageInfoSuccess {
/**
* 当前storage中所有的 key
*/
keys?: string [] | undefined;
/**
* 当前占用的空间大小, 单位 kb
*/
currentSize?: number | undefined;
/**
* 限制的空间大小,单位kb
*/
limitSize?: number | undefined;
}
interface RemoveStorageOptions {
/**
* 本地缓存中的指定的 key
*/
key?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetLocationOptions {
/**
* 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于uni.openLocation的坐标
*/
type?: string | undefined;
/**
* 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度
*/
altitude?: boolean | undefined;
/**
* 传入 true 会解析地址
*/
geocode?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetLocationSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetLocationSuccess {
/**
* 纬度,浮点数,范围为-90~90,负数表示南纬
*/
latitude?: number | undefined;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude?: number | undefined;
/**
* 速度,浮点数,单位m/s
*/
speed?: number | undefined;
/**
* 位置的精确度
*/
accuracy?: string | undefined;
/**
* 高度,单位 m
*/
altitude?: number | undefined;
/**
* 垂直精度,单位 m(Android 无法获取,返回 0)
*/
verticalAccuracy?: number | undefined;
/**
* 水平精度,单位 m
*/
horizontalAccuracy?: number | undefined;
/**
* 地址信息
*/
address?: any;
}
interface ChooseLocationOptions {
/**
* 搜索关键字
*/
keyword?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: ChooseLocationSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseLocationSuccess {
/**
* 位置名称
*/
name?: string | undefined;
/**
* 详细地址
*/
address?: string | undefined;
/**
* 纬度,浮点数,范围为-90~90,负数表示南纬
*/
latitude?: number | undefined;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude?: number | undefined;
}
interface OpenLocationOptions {
/**
* 纬度,范围为-90~90,负数表示南纬
*/
latitude?: number | undefined;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude?: number | undefined;
/**
* 缩放比例,范围5~18,默认为18
*/
scale?: number | undefined;
/**
* 位置名称
*/
name?: string | undefined;
/**
* 地址的详细说明
*/
address?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface MapContext {
/**
* 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 uni.openLocation
*/
getCenterLocation(options?: MapContextGetCenterLocationOptions): void;
/**
* 将地图中心移动到当前定位点,需要配合map组件的show-location使用
*/
moveToLocation(): void;
/**
* 平移marker,带动画
*/
translateMarker(options?: MapContextTranslateMarkerOptions): void;
/**
* 缩放视野展示所有经纬度
*/
includePoints(options?: MapContextIncludePointsOptions): void;
/**
* 获取当前地图的视野范围
*/
getRegion(options?: MapContextGetRegionOptions): void;
/**
* 获取当前地图的缩放级别
*/
getScale(options?: MapContextGetScaleOptions): void;
/**
* 获取原生地图对象 plus.maps.Map
*/
$getAppMap(): any;
}
interface MapContextGetCenterLocationOptions {
/**
* 接口调用成功的回调函数 ,res = { longitude: "经度", latitude: "纬度"}
*/
success?: ((result: LocationObject) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LocationObject {
/**
* 纬度,浮点数,范围为-90~90,负数表示南纬
*/
latitude?: number | undefined;
/**
* 经度,范围为-180~180,负数表示西经
*/
longitude?: number | undefined;
}
interface MapContextTranslateMarkerOptions {
/**
* 指定marker
*/
markerId?: number | undefined;
/**
* 指定marker移动到的目标点
*/
destination?: LocationObject | undefined;
/**
* 移动过程中是否自动旋转marker
*/
autoRotate?: boolean | undefined;
/**
* marker的旋转角度
*/
rotate?: number | undefined;
/**
* 动画持续时长,默认值1000ms,平移与旋转分别计算
*/
duration?: number | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 动画结束回调函数
*/
animationEnd?: (() => void) | undefined;
}
interface MapContextIncludePointsOptions {
/**
* 要显示在可视区域内的坐标点列表,[{latitude, longitude}]
*/
points?: LocationObject [] | undefined;
/**
* 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左],安卓上只能识别数组第一项,上下左右的padding一致。开发者工具暂不支持padding参数。
*/
padding?: number [] | undefined;
}
interface MapContextGetRegionOptions {
/**
* 接口调用成功的回调函数,res = {southwest, northeast},西南角与东北角的经纬度
*/
success?: ((result: MapContextGetRegionResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface MapContextGetRegionResult {
/**
* 西南角的经纬度
*/
southwest?: LocationObject | undefined;
/**
* 东北角的经纬度
*/
northeast?: LocationObject | undefined;
}
interface MapContextGetScaleOptions {
/**
* 接口调用成功的回调函数,res = {scale}
*/
success?: ((result: MapContextGetScaleResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface MapContextGetScaleResult {
/**
* 地图缩放级别
*/
scale?: number | undefined;
}
interface GetSystemInfoOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetSystemInfoResult) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetSystemInfoResult {
/**
* 手机品牌
*/
brand?: string | undefined;
/**
* 手机型号
*/
model?: string | undefined;
/**
* 设备像素比
*/
pixelRatio?: number | undefined;
/**
* 屏幕宽度
*/
screenWidth?: number | undefined;
/**
* 屏幕高度
*/
screenHeight?: number | undefined;
/**
* 可使用窗口宽度
*/
windowWidth?: number | undefined;
/**
* 可使用窗口高度
*/
windowHeight?: number | undefined;
/**
* 状态栏的高度
*/
statusBarHeight?: number | undefined;
/**
* 导航栏的高度
*/
navigationBarHeight?: number | undefined;
/**
* 标题栏高度
*/
titleBarHeight?: number | undefined;
/**
* 程序设置的语言
*/
language?: string | undefined;
/**
* 引擎版本号
*/
version?: number | undefined;
/**
* 设备磁盘容量
*/
storage?: string | undefined;
/**
* 当前电量百分比
*/
currentBattery?: string | undefined;
/**
* 宿主APP名称
*/
appName?: string | undefined;
/**
* App平台
*/
AppPlatform?: string | undefined;
/**
* 宿主平台
*/
host?: string | undefined;
/**
* 当前运行的客户端
*/
app?: string | undefined;
/**
* 客户端基础库版本
*/
SDKVersion?: string | undefined;
/**
* 宿主平台版本号
*/
swanNativeVersion?: string | undefined;
/**
* 操作系统版本
*/
system?: string | undefined;
/**
* 客户端平台
*/
platform?: string | undefined;
/**
* 用户字体大小设置
*/
fontSizeSetting?: number | undefined;
/**
* 可使用窗口的顶部位置
*/
windowTop?: number | undefined;
/**
* 可使用窗口的底部位置
*/
windowBottom?: number | undefined;
/**
* 允许微信使用相册的开关(仅 iOS 有效)
*/
albumAuthorized?: boolean | undefined;
/**
* 允许微信使用摄像头的开关
*/
cameraAuthorized?: boolean | undefined;
/**
* 允许微信使用定位的开关
*/
locationAuthorized?: boolean | undefined;
/**
* 允许微信使用麦克风的开关
*/
microphoneAuthorized?: boolean | undefined;
/**
* 允许微信通知的开关
*/
notificationAuthorized?: boolean | undefined;
/**
* 允许微信通知带有提醒的开关(仅 iOS 有效)
*/
notificationAlertAuthorized?: boolean | undefined;
/**
* 允许微信通知带有标记的开关(仅 iOS 有效)
*/
notificationBadgeAuthorized?: boolean | undefined;
/**
* 允许微信通知带有声音的开关(仅 iOS 有效)
*/
notificationSoundAuthorized?: boolean | undefined;
/**
* 蓝牙的系统开关
*/
bluetoothEnabled?: boolean | undefined;
/**
* 地理位置的系统开关
*/
locationEnabled?: boolean | undefined;
/**
* Wi-Fi 的系统开关
*/
wifiEnabled?: boolean | undefined;
/**
* 在竖屏正方向下的安全区域
*/
safeArea?: SafeAreaResult | undefined;
/**
* 上一次缓存的位置信息
*/
cacheLocation?: any;
}
interface SafeAreaResult {
/**
* 安全区域左上角横坐标
*/
left?: number | undefined;
/**
* 安全区域右下角横坐标
*/
right?: number | undefined;
/**
* 安全区域左上角纵坐标
*/
top?: number | undefined;
/**
* 安全区域右下角纵坐标
*/
bottom?: number | undefined;
/**
* 安全区域的宽度,单位逻辑像素
*/
width?: number | undefined;
/**
* 安全区域的高度,单位逻辑像素
*/
height?: number | undefined;
}
interface GetNetworkTypeOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetNetworkTypeSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetNetworkTypeSuccess {
/**
* 网络类型
*/
networkType?: string | undefined;
}
interface OnNetworkStatusChangeSuccess {
/**
* 当前是否有网络连接
*/
isConnected?: number | undefined;
/**
* 网络类型
*/
networkType?: string | undefined;
}
interface OnKeyboardHeightChangeResult {
/**
* 键盘高度
*/
height?: number | undefined;
}
interface OnAccelerometerChangeSuccess {
/**
* X 轴
*/
x?: number | undefined;
/**
* Y 轴
*/
y?: number | undefined;
/**
* Z 轴
*/
z?: number | undefined;
}
interface StartAccelerometerOptions {
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopAccelerometerOptions {
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OnCompassChangeSuccess {
/**
* 面对的方向度数
*/
direction?: number | undefined;
}
interface StartCompassOptions {
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopCompassOptions {
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface MakePhoneCallOptions {
/**
* 需要拨打的电话号码
*/
phoneNumber?: string | undefined;
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ScanCodeOptions {
/**
* 是否只能从相机扫码,不允许从相册选择图片
*/
onlyFromCamera?: boolean | undefined;
/**
* 扫码类型,参数类型是数组,二维码是'qrCode',一维码是'barCode',DataMatrix是‘datamatrix’,pdf417是‘pdf417’。
*/
scanType?: any [] | undefined;
/**
* 成功返回的回调函数
*/
success?: ((result: ScanCodeSuccessRes) => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ScanCodeSuccessRes {
/**
* 所扫码的内容
*/
result?: string | undefined;
/**
* 所扫码的类型
*/
scanType?: string | undefined;
/**
* 所扫码的字符集
*/
charSet?: string | undefined;
/**
* 当所扫的码为当前应用的合法二维码时,会返回此字段,内容为二维码携带的 path。
*/
path?: string | undefined;
}
interface SetClipboardDataOptions {
/**
* 需要设置的内容
*/
data?: string | undefined;
/**
* 成功返回的回调函数
*/
success?: (() => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetClipboardDataOptions {
/**
* 成功返回的回调函数
*/
success?: ((result: GetClipboardDataSuccessRes) => void) | undefined;
/**
* 失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetClipboardDataSuccessRes {
/**
* 剪贴板的内容
*/
data?: string | undefined;
}
interface OpenBluetoothAdapterOptions {
/**
* 成功则返回成功初始化信息
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CloseBluetoothAdapterOptions {
/**
* 成功则返回成功关闭模块信息
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBluetoothAdapterStateOptions {
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: GetBluetoothAdapterStateSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBluetoothAdapterStateSuccess {
/**
* 是否正在搜索设备
*/
discovering?: boolean | undefined;
/**
* 蓝牙适配器是否可用
*/
available?: boolean | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface OnBluetoothAdapterStateChangeResult {
/**
* 是否正在搜索设备
*/
discovering?: boolean | undefined;
/**
* 蓝牙适配器是否可用
*/
available?: boolean | undefined;
}
interface OnBluetoothDeviceFoundResult {
/**
* 设备列表信息
*/
devices?: BluetoothDeviceInfo [] | undefined;
}
interface StartBluetoothDevicesDiscoveryOptions {
/**
* 蓝牙设备主 service 的 uuid 列表
*/
services?: any [] | undefined;
/**
* 是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同
*/
allowDuplicatesKey?: boolean | undefined;
/**
* 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报
*/
interval?: number | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopBluetoothDevicesDiscoveryOptions {
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: StopBluetoothDevicesDiscoverySuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopBluetoothDevicesDiscoverySuccess {
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface GetBluetoothDevicesOptions {
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: GetBluetoothDevicesSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBluetoothDevicesSuccess {
/**
* uuid 对应的的已连接设备列表
*/
devices?: BluetoothDeviceInfo [] | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface BluetoothDeviceInfo {
/**
* 蓝牙设备名称,某些设备可能没有
*/
name?: string | undefined;
/**
* 用于区分设备的 id
*/
deviceId?: string | undefined;
/**
* 当前蓝牙设备的信号强度
*/
RSSI?: number | undefined;
/**
* 当前蓝牙设备的广播数据段中的ManufacturerData数据段 (注意:vConsole 无法打印出 ArrayBuffer 类型数据)
*/
advertisData?: any [] | undefined;
/**
* 当前蓝牙设备的广播数据段中的ServiceUUIDs数据段
*/
advertisServiceUUIDs?: any [] | undefined;
/**
* 当前蓝牙设备的广播数据段中的LocalName数据段
*/
localName?: string | undefined;
/**
* 当前蓝牙设备的广播数据段中的ServiceData数据段
*/
serviceData?: any [] | undefined;
}
interface GetConnectedBluetoothDevicesOptions {
/**
* 蓝牙设备主 service 的 uuid 列表
*/
services?: any [] | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: GetConnectedBluetoothDevicesSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetConnectedBluetoothDevicesSuccess {
/**
* 搜索到的设备列表
*/
devices?: GetConnectedBluetoothDevicesSuccessData [] | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface GetConnectedBluetoothDevicesSuccessData {
/**
* 蓝牙设备名称,某些设备可能没有
*/
name?: string | undefined;
/**
* 用于区分设备的 id
*/
deviceId?: string | undefined;
}
interface CloseBLEConnectionOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
}
interface CreateBLEConnectionOptions {
/**
* 蓝牙设备 id,参考 getDevices 接口
*/
deviceId?: string | undefined;
/**
* 超时时间
*/
timeout?: number | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OnBLEConnectionStateChangeSuccess {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 连接目前的状态
*/
connected?: boolean | undefined;
}
interface GetBLEDeviceServicesOptions {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: GetBLEDeviceServicesSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBLEDeviceServicesSuccess {
/**
* 设备服务列表
*/
services?: GetBLEDeviceServicesSuccessData [] | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface GetBLEDeviceServicesSuccessData {
/**
* 蓝牙设备服务的 uuid
*/
uuid?: string | undefined;
/**
* 该服务是否为主服务
*/
isPrimary?: boolean | undefined;
}
interface GetBLEDeviceCharacteristicsOptions {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 蓝牙服务 uuid
*/
serviceId?: string | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: GetBLEDeviceCharacteristicsSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBLEDeviceCharacteristicsSuccess {
/**
* 设备特征值列表
*/
characteristics?: GetBLEDeviceCharacteristicsSuccessData [] | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface GetBLEDeviceCharacteristicsSuccessData {
/**
* 蓝牙设备服务的 uuid
*/
uuid?: string | undefined;
/**
* 该特征值支持的操作类型
*/
properties?: any;
}
interface ReadBLECharacteristicValueOptions {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId?: string | undefined;
/**
* 蓝牙特征值的 uuid
*/
characteristicId?: string | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: ReadBLECharacteristicValueSuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ReadBLECharacteristicValueSuccess {
/**
* 错误码
*/
errCode?: string | undefined;
/**
* 成功:ok,错误:详细信息
*/
errMsg?: string | undefined;
}
interface WriteBLECharacteristicValueOptions {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId?: string | undefined;
/**
* 蓝牙特征值的 uuid
*/
characteristicId?: string | undefined;
/**
* 蓝牙设备特征值对应的二进制值
*/
value?: any [] | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: StopBluetoothDevicesDiscoverySuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface NotifyBLECharacteristicValueChangeOptions {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId?: string | undefined;
/**
* 蓝牙特征值的 uuid
*/
characteristicId?: string | undefined;
/**
* true: 启用 notify; false: 停用 notify
*/
state?: boolean | undefined;
/**
* 成功则返回本机蓝牙适配器状态
*/
success?: ((result: StopBluetoothDevicesDiscoverySuccess) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OnBLECharacteristicValueChangeSuccess {
/**
* 蓝牙设备 id,参考 device 对象
*/
deviceId?: string | undefined;
/**
* 蓝牙特征值对应服务的 uuid
*/
serviceId?: string | undefined;
/**
* 蓝牙特征值的 uuid
*/
characteristicId?: string | undefined;
/**
* 特征值最新的值 (注意:vConsole 无法打印出 ArrayBuffer 类型数据)
*/
value?: any [] | undefined;
}
interface StartBeaconDiscoveryOptions {
/**
* iBeacon设备广播的 uuids
*/
uuids?: any [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopBeaconDiscoveryOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBeaconsOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetBeaconsRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetBeaconsRes {
/**
* 接口调用成功的回调函数
*/
beacons?: Beacon [] | undefined;
/**
* 调用结果
*/
errMsg?: string | undefined;
}
interface Beacon {
/**
* iBeacon 设备广播的 uuid
*/
uuid?: string | undefined;
/**
* iBeacon 设备的主 id
*/
major?: string | undefined;
/**
* iBeacon 设备的次 id
*/
minor?: string | undefined;
/**
* 表示设备距离的枚举值
*/
proximity?: number | undefined;
/**
* iBeacon 设备的距离
*/
accuracy?: number | undefined;
/**
* 表示设备的信号强度
*/
rssi?: number | undefined;
}
interface BeaconService {
/**
* 服务目前是否可用
*/
available?: boolean | undefined;
/**
* 目前是否处于搜索状态
*/
discovering?: boolean | undefined;
}
interface GetHCEStateOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StartHCEOptions {
/**
* 需要注册到系统的 AID 列表,每个 AID 为 String 类型
*/
aid_list?: any [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopHCEOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface HCEMessageRes {
/**
* 消息类型
*/
messageType?: number | undefined;
/**
* 客户端接收到 NFC 设备的指令
*/
data?: any [] | undefined;
/**
* 此参数当且仅当 messageType=2 时有效
*/
reason?: number | undefined;
}
interface SendHCEMessageOptions {
/**
* 二进制数据
*/
data?: any [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StartWifiOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopWifiOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ConnectWifiOptions {
/**
* Wi-Fi 设备ssid
*/
SSID?: string | undefined;
/**
* Wi-Fi 设备bssid
*/
BSSID?: string | undefined;
/**
* Wi-Fi 设备密码
*/
password?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetWifiListOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface WiFi {
/**
* Wi-Fi 的SSID
*/
SSID?: string | undefined;
/**
* Wi-Fi 的BSSID
*/
BSSID?: string | undefined;
/**
* Wi-Fi 是否安全
*/
secure?: boolean | undefined;
/**
* Wi-Fi 信号强度
*/
signalStrength?: number | undefined;
}
interface SetWifiListOptions {
/**
* Wi-Fi 的SSID
*/
wifiList?: WiFiItem [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface WiFiItem {
/**
* Wi-Fi 的SSID
*/
SSID?: string | undefined;
/**
* Wi-Fi 的BSSID
*/
BSSID?: string | undefined;
/**
* Wi-Fi 设备密码
*/
password?: string | undefined;
}
interface GetConnectedWifiOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetConnectedWifiRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetConnectedWifiRes {
/**
* 接口调用成功的回调函数
*/
wifi?: WiFi | undefined;
}
interface ShowToastOptions {
/**
* 提示的内容
*/
title?: string | undefined;
/**
* 图标
* - success: 显示成功图标
* - loading: 显示加载图标
* - none: 不显示图标
*/
icon?: 'success' | 'loading' | 'none' | undefined;
/**
* 自定义图标的本地路径,image 的优先级高于 icon
*/
image?: string | undefined;
/**
* 提示的延迟时间,单位毫秒,默认:1500
*/
duration?: number | undefined;
/**
* 是否显示透明蒙层,防止触摸穿透,默认:false
*/
mask?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowLoadingOptions {
/**
* 提示的内容
*/
title?: string | undefined;
/**
* 是否显示透明蒙层,防止触摸穿透,默认:false
*/
mask?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowModalOptions {
/**
* 提示的标题
*/
title?: string | undefined;
/**
* 提示的内容
*/
content?: string | undefined;
/**
* 是否显示取消按钮,默认为 true
*/
showCancel?: boolean | undefined;
/**
* 取消按钮的文字,默认为"取消"
*/
cancelText?: string | undefined;
/**
* 取消按钮的文字颜色,默认为"#000000"
*/
cancelColor?: string | undefined;
/**
* 确定按钮的文字,默认为"确定"
*/
confirmText?: string | undefined;
/**
* 确定按钮的文字颜色,默认为"#3CC51F"
*/
confirmColor?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: ShowModalRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowModalRes {
/**
* 为 true 时,表示用户点击了确定按钮
*/
confirm?: boolean | undefined;
/**
* 为 true 时,表示用户点击了取消
*/
cancel?: boolean | undefined;
}
interface ShowActionSheetOptions {
/**
* 按钮的文字数组
*/
itemList?: any [] | undefined;
/**
* 按钮的文字颜色,默认为"#000000"
*/
itemColor?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: ShowActionSheetRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowActionSheetRes {
/**
* 用户点击的按钮,从上到下的顺序,从0开始
*/
tapIndex?: number | undefined;
}
interface SetNavigationBarTitleOptions {
/**
* 页面标题
*/
title?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetNavigationbarColorOptions {
/**
* 前景颜色值,包括按钮、标题、状态栏的颜色
*/
frontColor?: string | undefined;
/**
* 背景颜色值,有效值为十六进制颜色
*/
backgroundColor?: string | undefined;
/**
* 动画效果
*/
animation?: NavigationBarAnimation | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetTabBarBadgeOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 显示的文本,不超过 3 个半角字符
*/
text?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface RemoveTabBarBadgeOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowTabBarRedDotOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface HideTabBarRedDotOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface NavigationBarAnimation {
/**
* 动画变化时间,默认0,单位:毫秒
*/
duration?: number | undefined;
/**
* 动画变化方式,默认 linear
* - linear: 动画从头到尾的速度是相同的
* - easeIn: 动画以低速开始
* - easeOut: 动画以低速结束
* - easeInOut: 动画以低速开始和结束
*/
timingFunc?: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut' | undefined;
}
interface WindowResizeResult {
/**
* 变化后的窗口宽度,单位 px
*/
windowWidth?: number | undefined;
/**
* 变化后的窗口高度,单位 px
*/
windowHeight?: number | undefined;
}
interface SetTabBarBadgeOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 显示的文本
*/
text?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface RemoveTabBarBadgeOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowTabBarRedDotOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface HideTabBarRedDotOptions {
/**
* tabBar的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetTabBarStyleOptions {
/**
* tab 上的文字默认颜色
*/
color?: string | undefined;
/**
* tab 上的文字选中时的颜色
*/
selectedColor?: string | undefined;
/**
* tab 的背景色
*/
backgroundColor?: string | undefined;
/**
* tabbar上边框的颜色
*/
borderStyle?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetTabBarItemOptions {
/**
* tabBar 的哪一项,从左边算起,索引从0开始
*/
index?: number | undefined;
/**
* tab 上按钮文字
*/
text?: string | undefined;
/**
* 图片路径
*/
iconPath?: string | undefined;
/**
* 选中时的图片路径
*/
selectedIconPath?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowTabBarOptions {
/**
* 是否需要动画效果
*/
animation?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface HideTabBarOptions {
/**
* 是否需要动画效果
*/
animation?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetTopBarTextOptions {
/**
* 置顶栏文字内容
*/
text?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface NavigateToOptions {
/**
* 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数
*/
url?: string | string | undefined;
/**
* 窗口显示的动画类型
* - auto: 自动选择动画效果
* - none: 无动画效果
* - slide-in-right: 从右侧横向滑动效果
* - slide-in-left: 左侧横向滑动效果
* - slide-in-top: 从上侧竖向滑动效果
* - slide-in-bottom: 从下侧竖向滑动效果
* - fade-in: 从透明到不透明逐渐显示效果
* - zoom-out: 从小到大逐渐放大显示效果
* - zoom-fade-out: 从小到大逐渐放大并且从透明到不透明逐渐显示效果
* - pop-in: 从右侧平移入栈动画效果
*/
animationType?: 'auto' | 'none' | 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' | 'fade-in' | 'zoom-out' | 'zoom-fade-out' | 'pop-in' | undefined;
/**
* 窗口显示动画的持续时间,单位为 ms
*/
animationDuration?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface RedirectToOptions {
/**
* 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数
*/
url?: string | string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ReLaunchOptions {
/**
* 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数
*/
url?: string | string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SwitchTabOptions {
/**
* 需要跳转的 tabBar 页面的路径,路径后不能带参数
*/
url?: string | string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CreateIntersectionObserverOptions {
/**
* 所有阈值
*/
thresholds?: any [] | undefined;
/**
* 初始的相交比例
*/
initialRatio?: number | undefined;
/**
* 是否同时观测多个参照节点(而非一个)
*/
selectAll?: boolean | undefined;
}
interface NavigateBackOptions {
/**
* 返回的页面数,如果 delta 大于现有页面数,则返回到首页
*/
delta?: number | undefined;
/**
* 窗口关闭的动画类型
* - auto: 自动选择动画效果
* - none: 无动画效果
* - slide-out-right: 横向向右侧滑出屏幕动画
* - slide-out-left: 横向向左侧滑出屏幕动画
* - slide-out-top: 竖向向上侧滑出屏幕动画
* - slide-out-bottom: 竖向向下侧滑出屏幕动画
* - fade-out: 从不透明到透明逐渐隐藏动画
* - zoom-in: 从大逐渐缩小关闭动画
* - zoom-fade-in: 从大逐渐缩小并且从不透明到透明逐渐隐藏关闭动画
* - pop-out: 从右侧平移出栈动画效果
*/
animationType?: 'auto' | 'none' | 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out' | undefined;
/**
* 窗口关闭动画的持续时间,单位为 ms
*/
animationDuration?: number | undefined;
}
interface CreateAnimationOptions {
/**
* 动画持续时间,单位ms
*/
duration?: number | undefined;
/**
* 定义动画的效果
* - linear: 动画从头到尾的速度是相同的
* - ease: 动画以低速开始,然后加快,在结束前变慢
* - ease-in: 动画以低速开始
* - ease-in-out: 动画以低速开始和结束
* - ease-out: 动画以低速结束
* - step-start: 动画第一帧就跳至结束状态直到结束
* - step-end: 动画一直保持开始状态,最后一帧跳到结束状态
*/
timingFunction?: 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end' | undefined;
/**
* 动画延迟时间,单位 ms
*/
delay?: number | undefined;
/**
* 设置transform-origin
*/
transformOrigin?: string | undefined;
}
interface PageScrollToOptions {
/**
* 滚动到页面的目标位置
*/
scrollTop?: number | undefined;
/**
* 滚动动画的时长
*/
duration?: number | undefined;
}
interface StartPullDownRefreshOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SelectorQuery {
/**
* 将选择器的选取范围更改为自定义组件component内
*/
in(component?: any): SelectorQuery;
/**
* 在当前页面下选择第一个匹配选择器selector的节点
*/
select(selector?: string): NodesRef;
/**
* 在当前页面下选择匹配选择器selector的所有节点
*/
selectAll(selector?: string): NodesRef;
/**
* 选择显示区域
*/
selectViewport(selector?: string): NodesRef;
/**
* 执行所有的请求
*/
exec(callback?: () => void): NodesRef;
}
interface NodesRef {
/**
* 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位
*/
boundingClientRect(callback?: (result: NodeInfo) => void): SelectorQuery;
/**
* 添加节点的滚动位置查询请求,以像素为单位
*/
scrollOffset(callback?: (result: NodeInfo) => void): SelectorQuery;
/**
* 获取节点的相关信息,需要获取的字段在fields中指定
*/
fields(fields?: NodeField, callback?: (result: NodeInfo) => void): SelectorQuery;
/**
* 添加节点的 Context 对象查询请求
*/
context(callback?: (result: NodeInfo) => void): SelectorQuery;
}
interface NodeInfo {
/**
* 节点的ID
*/
id?: string | undefined;
/**
* 节点的dataset
*/
dataset?: any;
/**
* 节点的左边界坐标
*/
left?: number | undefined;
/**
* 节点的右边界坐标
*/
right?: number | undefined;
/**
* 节点的上边界坐标
*/
top?: number | undefined;
/**
* 节点的下边界坐标
*/
bottom?: number | undefined;
/**
* 节点的宽度
*/
width?: number | undefined;
/**
* 节点的高度
*/
height?: number | undefined;
/**
* 节点的水平滚动位置
*/
scrollLeft?: number | undefined;
/**
* 节点的垂直滚动位置
*/
scrollTop?: number | undefined;
/**
* 节点对应的 Context 对象
*/
context?: MapContext | CanvasContext | VideoContext | EditorContext | undefined;
}
interface EditorContext {
/**
* 修改样式
*/
format(name?: string, value?: string): void;
/**
* 插入分割线
*/
insertDivider(): void;
/**
* 获取节点的相关信息,需要获取的字段在fields中指定
*/
insertImage(options?: EditorContextInsertImageOptions): void;
/**
* 添加节点的 Context 对象查询请求
*/
insertText(options?: EditorContextInsertTextOptions): void;
/**
* 初始化编辑器内容,hmlt和delta同时存在时仅delta生效
*/
setContents(options?: EditorContextSetContentsOptions): void;
/**
* 初始化编辑器内容,hmlt和delta同时存在时仅delta生效
*/
getContents(options?: EditorContextGetContentsOptions): void;
/**
* 初始化编辑器内容,hmlt和delta同时存在时仅delta生效
*/
clear(options?: EditorContextClearOptions): void;
/**
* 清除当前选区的样式
*/
removeFormat(options?: EditorContextRemoveFormatOptions): void;
/**
* 撤销
*/
undo(options?: EditorContextUndoOptions): void;
/**
* 撤销
*/
redo(options?: EditorContextRedoOptions): void;
}
interface EditorContextInsertImageOptions {
/**
* 图片地址
*/
src?: string | undefined;
/**
* 图像无法显示时的替代文本
*/
alt?: string | undefined;
/**
* data 被序列化为 name=value;name1=value2 的格式挂在属性 data-custom 上
*/
data?: any;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextInsertTextOptions {
/**
* 文本内容
*/
text?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextSetContentsOptions {
/**
* 带标签的HTML内容
*/
html?: string | undefined;
/**
* 表示内容的delta对象
*/
delta?: any;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextGetContentsOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextClearOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextRemoveFormatOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextUndoOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface EditorContextRedoOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface NodeField {
/**
* 是否返回节点 id
*/
id?: boolean | undefined;
/**
* 是否返回节点 dataset
*/
dataset?: boolean | undefined;
/**
* 是否返回节点布局位置(left right top bottom)
*/
rect?: boolean | undefined;
/**
* 是否返回节点尺寸(width height)
*/
size?: boolean | undefined;
/**
* 是否返回节点的 scrollLeft scrollTop,节点必须是 scroll-view 或者 viewport
*/
scrollOffset?: boolean | undefined;
/**
* 指定属性名列表,返回节点对应属性名的当前属性值(只能获得组件文档中标注的常规属性值,id class style 和事件绑定的属性值不可获取)
*/
properties?: string [] | undefined;
/**
* 指定样式名列表,返回节点对应样式名的当前值
*/
computedStyle?: string [] | undefined;
/**
* 是否返回节点对应的 Context 对象
*/
context?: boolean | undefined;
}
interface IntersectionObserver {
/**
* 使用选择器指定一个节点,作为参照区域之一
*/
relativeTo(selector?: string, margins?: any []): void;
/**
* 指定页面显示区域作为参照区域之一
*/
relativeToViewport(margins?: any []): void;
/**
* 指定目标节点并开始监听相交状态变化情况
*/
observe(targetSelector?: string, callback?: (result: ObserveResult) => void): void;
/**
* 停止监听
*/
disconnect(): void;
}
interface ObserveResult {
/**
* 相交比例
*/
intersectionRatio?: number | undefined;
/**
* 相交区域的边界
*/
intersectionRect?: any;
/**
* 目标节点布局区域的边界
*/
boundingClientRect?: ObserveNodeRect | undefined;
/**
* 参照区域的边界
*/
relativeRect?: ObserveNodeRect | undefined;
/**
* 相交检测时的时间戳
*/
time?: number | undefined;
}
interface ObserveNodeRect {
/**
* left
*/
left?: number | undefined;
/**
* right
*/
right?: number | undefined;
/**
* top
*/
top?: number | undefined;
/**
* bottom
*/
bottom?: number | undefined;
}
interface Animation {
/**
* 透明度
*/
opacity(value?: number): void;
/**
* 颜色值
*/
backgroundColor(color?: number): void;
/**
* 长度值
*/
width(length?: number): void;
/**
* 长度值
*/
height(length?: number): void;
/**
* 长度值
*/
top(length?: number): void;
/**
* 长度值
*/
left(length?: number): void;
/**
* 长度值
*/
bottom(length?: number): void;
/**
* 长度值
*/
right(length?: number): void;
/**
* 从原点顺时针旋转一个deg角度
*/
rotate(deg?: number): void;
/**
* 在X轴旋转一个deg角度
*/
rotateX(deg?: number): void;
/**
* 在Y轴旋转一个deg角度
*/
rotateY(deg?: number): void;
/**
* 在Z轴旋转一个deg角度
*/
rotateZ(deg?: number): void;
/**
* 同transform-function rotate3d
*/
rotate3d(x?: number, y?: number, z?: number, deg?: number): void;
/**
* 缩放
*/
scale(sx?: number, sy?: number): void;
/**
* 在X轴缩放sx倍数
*/
scaleX(sx?: number): void;
/**
* 在Y轴缩放sy倍数
*/
scaleY(sy?: number): void;
/**
* 在Z轴缩放sz倍数
*/
scaleZ(sz?: number): void;
/**
* 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数
*/
scale3d(sx?: number, sy?: number, sz?: number): void;
/**
* 偏移
*/
translate(tx?: number, ty?: number): void;
/**
* 在X轴偏移tx
*/
translateX(tx?: number): void;
/**
* 在Y轴偏移ty
*/
translateY(ty?: number): void;
/**
* 在Z轴偏移tx
*/
translateZ(tz?: number): void;
/**
* 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz
*/
translate3d(tx?: number, ty?: number, tz?: number): void;
/**
* 倾斜
*/
skew(ax?: number, ay?: number): void;
/**
* Y轴坐标不变,X轴坐标延顺时针倾斜ax度
*/
skewX(ax?: number): void;
/**
* X轴坐标不变,Y轴坐标延顺时针倾斜ay度
*/
skewY(ay?: number): void;
/**
* 矩阵变形
*/
matrix(a?: number, b?: number, c?: number, d?: number, tx?: number, ty?: number): void;
/**
* 矩阵变形
*/
matrix3d(): void;
}
interface CanvasContext {
/**
* 填充色
*/
fillStyle?: string | CanvasGradient | CanvasPattern | undefined;
/**
* 边框颜色
*/
strokeStyle?: string | CanvasGradient | CanvasPattern | undefined;
/**
* 阴影的模糊级别
*/
shadowBlur?: number | undefined;
/**
* 阴影的颜色
*/
shadowColor?: string | undefined;
/**
* 阴影相对于形状在水平方向的偏移
*/
shadowOffsetX?: number | undefined;
/**
* 阴影相对于形状在竖直方向的偏移
*/
shadowOffsetY?: number | undefined;
/**
* 线条的宽度
*/
lineWidth?: number | undefined;
/**
* 线条的端点样式
* - butt:
* - round:
* - square:
*/
lineCap?: 'butt' | 'round' | 'square' | undefined;
/**
* 线条的结束交点样式
* - bevel:
* - round:
* - miter:
*/
lineJoin?: 'bevel' | 'round' | 'miter' | undefined;
/**
* 最大斜接长度
*/
miterLimit?: number | undefined;
/**
* 透明度
*/
globalAlpha?: number | undefined;
/**
* 设置要在绘制新形状时应用的合成操作的类型
*/
globalCompositeOperation?: string | undefined;
/**
* 偏移量
*/
lineDashOffset?: number | undefined;
/**
* 字体样式
*/
font?: string | undefined;
/**
* 设置填充色
*/
setFillStyle(color?: string | CanvasGradient | CanvasPattern): void;
/**
* 设置边框颜色
*/
setStrokeStyle(color?: string | CanvasGradient | CanvasPattern): void;
/**
* 设置阴影样式
*/
setShadow(offsetX?: number, offsetY?: number, blur?: number, color?: string): void;
/**
* 创建一个线性的渐变颜色
*/
createLinearGradient(x0?: number, y0?: number, x1?: number, y1?: number): CanvasGradient;
/**
* 创建一个圆形的渐变颜色
*/
createCircularGradient(x?: number, y?: number, r?: number): CanvasGradient;
/**
* 设置线条的宽度
*/
setLineWidth(lineWidth?: number): void;
/**
* 设置线条的端点样式
*/
setLineCap(lineCap?: 'butt' | 'round' | 'square'): void;
/**
* 设置线条的交点样式
*/
setLineJoin(lineJoin?: 'bevel' | 'round' | 'miter'): void;
/**
* 设置线条的宽度
*/
setLineDash(pattern?: any [], offset?: number): void;
/**
* 设置最大斜接长度
*/
setMiterLimit(miterLimit?: number): void;
/**
* 创建一个矩形
*/
rect(x?: number, y?: number, width?: number, height?: number): void;
/**
* 填充一个矩形
*/
fillRect(x?: number, y?: number, width?: number, height?: number): void;
/**
* 画一个矩形(非填充)
*/
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, r?: number, sAngle?: number, eAngle?: number, counterclockwise?: boolean): void;
/**
* 创建三次方贝塞尔曲线路径
*/
bezierCurveTo(cp1x?: number, cp1y?: number, cp2x?: number, cp2y?: number, x?: number, y?: number): void;
/**
* 创建二次贝塞尔曲线路径
*/
quadraticCurveTo(cpx?: number, cpy?: number, x?: number, y?: number): void;
/**
* 横纵坐标缩放
*/
scale(scaleWidth?: number, scaleHeight?: number): void;
/**
* 顺时针旋转当前坐标轴
*/
rotate(rotate?: number): void;
/**
* 对当前坐标系的原点(0, 0)进行变换
*/
translate(x?: number, y?: number): void;
/**
* 从原始画布中剪切任意形状和尺寸
*/
clip(): void;
/**
* 设置字体的字号
*/
setFontSize(fontSize?: number): void;
/**
* 在画布上绘制被填充的文本
*/
fillText(text?: string, x?: number, y?: number, maxWidth?: number): void;
/**
* 设置文字的对齐
*/
setTextAlign(align?: 'left' | 'center' | 'right'): void;
/**
* 设置文字的水平对齐
*/
setTextBaseline(textBaseline?: 'top' | 'bottom' | 'middle' | 'normal'): void;
/**
* 绘制图像到画布
*/
drawImage(imageResource: string, dx: number, dy: number): void;
drawImage(imageResource: string, dx: number, dy: number, dWidth: number, dHeigt: number): void;
drawImage(imageResource: string, sx: number, sy: number, sWidth: number, sHeigt: number, dx: number, dy: number, dWidth: number, dHeight: number): void;
/**
* 设置全局画笔透明度
*/
setGlobalAlpha(alpha?: number): void;
/**
* 保存当前的绘图上下文
*/
save(): void;
/**
* 恢复之前保存的绘图上下文
*/
restore(): void;
/**
* 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中
*/
draw(reserve?: boolean, callback?: () => void): void;
/**
* 测量文本尺寸信息,目前仅返回文本宽度
*/
measureText(text?: string): CanvasTextMetrics;
/**
* 根据控制点和半径绘制圆弧路径
*/
arcTo(x1?: number, y1?: number, x2?: number, y2?: number, radius?: number): void;
/**
* 给定的 (x, y) 位置绘制文本描边的方法
*/
strokeText(text?: string, x?: number, y?: number, maxWidth?: number): void;
/**
* 对指定的图像创建模式的方法,可在指定的方向上重复元图像
*/
createPattern(image?: string, repetition?: 'repeat' | 'repeat-x' | 'repeat-y' | 'no-repeat'): CanvasPattern | null;
/**
* 使用矩阵重新设置(覆盖)当前变换的方法
*/
setTransform(scaleX?: number, skewX?: number, skewY?: number, scaleY?: number, translateX?: number, translateY?: number): void;
}
interface CanvasGradient {
/**
* 创建一个颜色的渐变点
*/
addColorStop(stop?: number, color?: string): void;
}
// tslint:disable-next-line no-empty-interface
interface CanvasPattern {
}
interface CanvasTextMetrics {
/**
* 文本的宽度
*/
width?: number | undefined;
}
interface CanvasToTempFilePathOptions {
/**
* 画布x轴起点(默认0)
*/
x?: number | undefined;
/**
* 画布y轴起点(默认0)
*/
y?: number | undefined;
/**
* 画布宽度(默认为canvas宽度-x)
*/
width?: number | undefined;
/**
* 画布高度(默认为canvas高度-y)
*/
height?: number | undefined;
/**
* 输出图片宽度(默认为 width * 屏幕像素密度)
*/
destWidth?: number | undefined;
/**
* 输出图片高度(默认为 height * 屏幕像素密度)
*/
destHeight?: number | undefined;
/**
* 画布标识,传入 <canvas/> 的 canvas-id
*/
canvasId?: string | undefined;
/**
* 目标文件的类型,默认为 'png'
*/
fileType?: string | undefined;
/**
* 图片的质量,取值范围为 (0, 1],不在范围内时当作1.0处理
*/
quality?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: CanvasToTempFilePathRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CanvasToTempFilePathRes {
/**
* 导出生成的图片路径
*/
tempFilePath?: string | undefined;
}
interface CanvasGetImageDataOptions {
/**
* 画布标识,传入 <canvas/> 的 canvas-id
*/
canvasId?: string | undefined;
/**
* 将要被提取的图像数据矩形区域的左上角 x 坐标
*/
x?: number | undefined;
/**
* 将要被提取的图像数据矩形区域的左上角 y 坐标
*/
y?: number | undefined;
/**
* 将要被提取的图像数据矩形区域的宽度
*/
width?: number | undefined;
/**
* 将要被提取的图像数据矩形区域的高度
*/
height?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: CanvasGetImageDataRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CanvasGetImageDataRes {
/**
* 回调信息
*/
errMsg?: string | undefined;
/**
* 图像数据矩形的宽度
*/
width?: number | undefined;
/**
* 图像数据矩形的高度
*/
height?: number | undefined;
/**
* 图像像素点数据,一维数组,每四项表示一个像素点的rgba
*/
data?: any [] | undefined;
}
interface CanvasPutImageDataOptions {
/**
* 画布标识,传入 <canvas/> 的 canvas-id
*/
canvasId?: string | undefined;
/**
* 图像像素点数据,一维数组,每四项表示一个像素点的rgba
*/
data?: any [] | undefined;
/**
* 源图像数据在目标画布中的位置偏移量(x 轴方向的偏移量)
*/
x?: number | undefined;
/**
* 源图像数据在目标画布中的位置偏移量(y 轴方向的偏移量)
*/
y?: number | undefined;
/**
* 源图像数据矩形区域的宽度
*/
width?: number | undefined;
/**
* 源图像数据矩形区域的高度
*/
height?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetScreenBrightnessOptions {
/**
* 屏幕亮度值,范围 0~1,0 最暗,1 最亮
*/
value?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetScreenBrightnessOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetScreenBrightnessSuccessRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetScreenBrightnessSuccessRes {
/**
* 屏幕亮度值,范围 0~1,0 最暗,1 最亮。
*/
value?: number | undefined;
}
interface SetKeepScreenOnOptions {
/**
* 是否保持屏幕常亮
*/
keepScreenOn?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface VibrateLongOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface VibrateShortOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface AddPhoneContactOptions {
/**
* 头像本地文件路径
*/
photoFilePath?: string | undefined;
/**
* 昵称
*/
nickName?: string | undefined;
/**
* 姓氏
*/
lastName?: string | undefined;
/**
* 中间名
*/
middleName?: string | undefined;
/**
* 名字
*/
firstName?: string | undefined;
/**
* 备注
*/
remark?: string | undefined;
/**
* 手机号
*/
mobilePhoneNumber?: string | undefined;
/**
* 微信号
*/
weChatNumber?: string | undefined;
/**
* 联系地址国家
*/
addressCountry?: string | undefined;
/**
* 联系地址省份
*/
addressState?: string | undefined;
/**
* 联系地址城市
*/
addressCity?: string | undefined;
/**
* 联系地址街道
*/
addressStreet?: string | undefined;
/**
* 联系地址邮政编码
*/
addressPostalCode?: string | undefined;
/**
* 公司
*/
organization?: string | undefined;
/**
* 职位
*/
title?: string | undefined;
/**
* 工作传真
*/
workFaxNumber?: string | undefined;
/**
* 工作电话
*/
workPhoneNumber?: string | undefined;
/**
* 公司电话
*/
hostNumber?: string | undefined;
/**
* 电子邮件
*/
email?: string | undefined;
/**
* 网站
*/
url?: string | undefined;
/**
* 工作地址国家
*/
workAddressCountry?: string | undefined;
/**
* 工作地址省份
*/
workAddressState?: string | undefined;
/**
* 工作地址城市
*/
workAddressCity?: string | undefined;
/**
* 工作地址街道
*/
workAddressStreet?: string | undefined;
/**
* 工作地址邮政编码
*/
workAddressPostalCode?: string | undefined;
/**
* 住宅传真
*/
homeFaxNumber?: string | undefined;
/**
* 住宅电话
*/
homePhoneNumber?: string | undefined;
/**
* 住宅地址国家
*/
homeAddressCountry?: string | undefined;
/**
* 住宅地址省份
*/
homeAddressState?: string | undefined;
/**
* 住宅地址城市
*/
homeAddressCity?: string | undefined;
/**
* 住宅地址街道
*/
homeAddressStreet?: string | undefined;
/**
* 住宅地址邮政编码
*/
homeAddressPostalCode?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetExtConfigOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetExtConfigRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetExtConfigRes {
/**
* 调用结果
*/
errMsg?: string | undefined;
/**
* 第三方平台自定义的数据
*/
extConfig?: any;
}
interface GetExtConfigSyncRes {
/**
* 第三方平台自定义的数据
*/
extConfig?: any;
}
interface GetMenuButtonBoundingClientRectRes {
/**
* 小程序胶囊菜单按钮的宽度
*/
width?: number | undefined;
/**
* 小程序胶囊菜单按钮的高度
*/
height?: number | undefined;
/**
* 小程序胶囊菜单按钮的上边界坐标
*/
top?: number | undefined;
/**
* 小程序胶囊菜单按钮的右边界坐标
*/
right?: number | undefined;
/**
* 小程序胶囊菜单按钮的下边界坐标
*/
bottom?: number | undefined;
/**
* 小程序胶囊菜单按钮的左边界坐标
*/
left?: number | undefined;
}
interface GetProviderOptions {
/**
* 服务类型,可取值“oauth”、“share”、“payment”、“push”
* - oauth: 授权登录
* - share: 分享
* - payment: 支付
* - push: 推送
*/
service?: 'oauth' | 'share' | 'payment' | 'push' | undefined;
/**
* 接口调用成功的回调
*/
success?: ((result: GetProviderRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetProviderRes {
/**
* 服务类型
* - oauth: 授权登录
* - share: 分享
* - payment: 支付
* - push: 推送
*/
service?: 'oauth' | 'share' | 'payment' | 'push' | undefined;
/**
* 得到的服务供应商
*/
provider?: any [] | undefined;
}
interface LoginOptions {
/**
* 授权登录服务提供商,通过uni.getProvider获取,如果不设置则弹出分享列表选择界面
* - weixin: 微信登录
* - qq: QQ登录
* - sinaweibo: 新浪微博登录
* - xiaomi: 小米登录
*/
provider?: 'weixin' | 'qq' | 'sinaweibo' | 'xiaomi' | undefined;
/**
* 超时时间,单位 ms
*/
timeout?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: LoginRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LoginRes {
/**
* 描述信息
*/
errMsg?: string | undefined;
/**
* 登录服务商提供的登录信息,服务商不同返回的结果不完全相同
*/
authResult?: string | undefined;
/**
* 小程序用户临时登录凭证
*/
code?: string | undefined;
/**
* 头条小程序当前设备标识
*/
anonymousCode?: string | undefined;
/**
* 支付宝小程序授权码
*/
authCode?: string | undefined;
/**
* 支付宝小程序登录失败的授权类型,key是授权失败的 scope,value 是对应的错误码
*/
authErrorScope?: any;
/**
* 支付宝小程序登录成功的授权 scope
*/
authSucessScope?: string [] | undefined;
}
interface CheckSessionOptions {
/**
* 接口调用成功的回调函数,session_key未过期
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数,session_key已过期
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface AuthorizeOptions {
/**
* 需要获取权限的scope
*/
scope?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetUserInfoOptions {
/**
* 授权登录服务提供商,通过uni.getProvider获取
* - weixin: 微信登录
* - qq: QQ登录
* - sinaweibo: 新浪微博登录
* - xiaomi: 小米登录
*/
provider?: 'weixin' | 'qq' | 'sinaweibo' | 'xiaomi' | undefined;
/**
* 是否带上登录态信息,仅微信小程序生效。
*/
withCredentials?: boolean | undefined;
/**
* 指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文。默认为en,仅微信小程序生效。
*/
lang?: string | undefined;
/**
* 超时时间,单位 ms
*/
timeout?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetUserInfoRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetUserInfoRes {
/**
* 用户信息对象,不包含 openid 等敏感信息
*/
userInfo?: UserInfo | undefined;
/**
* 不包括敏感信息的原始数据字符串,用于计算签名。
*/
rawData?: string | undefined;
/**
* 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,仅微信小程序生效。
*/
signature?: string | undefined;
/**
* 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法,仅微信小程序生效。
*/
encryptedData?: string | undefined;
/**
* 加密算法的初始向量,详细见加密数据解密算法,仅微信小程序生效。
*/
iv?: string | undefined;
/**
* 描述信息
*/
errMsg?: string | undefined;
}
interface UserInfo {
/**
* 用户昵称
*/
nickname?: string | undefined;
/**
* 该服务商唯一用户标识
*/
openid?: string | undefined;
/**
* 用户头像
*/
avatarUrl?: string | undefined;
}
interface ShareOptions {
/**
* 分享服务提供商,通过uni.getProvider获取,如果不设置则弹出分享列表选择界面
* - sinaweibo: 新浪微博分享
* - qq: 分享到QQ好友
* - weixin: 分享微信消息、朋友圈及微信小程序
*/
provider?: 'sinaweibo' | 'qq' | 'weixin' | undefined;
/**
* 分享类型。默认图文0,纯文字1,纯图片2,音乐3,视频4,小程序5。
* - 0: 图文
* - 1: 纯文字
* - 2: 纯图片
* - 3: 音乐
* - 4: 视频
* - 5: 小程序
*/
type?: '0' | '1' | '2' | '3' | '4' | '5' | undefined;
/**
* 标题
*/
title?: string | undefined;
/**
* 场景。可取值“WXSceneSession”分享到聊天界面,“WXSenceTimeline”分享到朋友圈,“WXSceneFavorite”分享到微信收藏
*/
scene?: string | undefined;
/**
* 摘要
*/
summary?: string | undefined;
/**
* 跳转链接
*/
href?: string | undefined;
/**
* 图片地址
*/
imageUrl?: string | undefined;
/**
* 音视频地址
*/
mediaUrl?: string | undefined;
/**
* 分享小程序
*/
miniProgram?: MiniProgramShareOptions | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface MiniProgramShareOptions {
/**
* 微信小程序原始id
*/
id?: string | undefined;
/**
* 点击链接进入的页面
*/
path?: string | undefined;
/**
* 微信小程序版本类型,默认为0。
* - 0: 正式版
* - 1: 测试版
* - 2: 体验版
*/
type?: '0' | '1' | '2' | undefined;
/**
* 兼容低版本的网页链接
*/
webUrl?: string | undefined;
}
interface SubscribePushOptions {
/**
* 推送服务提供商,通过uni.getProvider获取
* - unipush: UniPush
* - igexin: 个推
* - mipush: 小米推送
*/
provider?: 'unipush' | 'igexin' | 'mipush' | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface UnscribePushOptions {
/**
* 推送服务提供商,通过uni.getProvider获取
* - unipush: UniPush
* - igexin: 个推
* - mipush: 小米推送
*/
provider?: 'unipush' | 'igexin' | 'mipush' | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OnPushOptions {
/**
* 推送服务提供商,通过uni.getProvider获取
* - unipush: UniPush
* - igexin: 个推
* - mipush: 小米推送
*/
provider?: 'unipush' | 'igexin' | 'mipush' | undefined;
/**
* 接收到透传数据回调,回调参数(Object):messageId(消息id)、data(消息内容)
*/
callback?: (() => void) | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OffPushOptions {
/**
* 推送服务提供商,通过uni.getProvider获取
* - unipush: UniPush
* - igexin: 个推
* - mipush: 小米推送
*/
provider?: 'unipush' | 'igexin' | 'mipush' | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ShowShareMenuOptions {
/**
* 是否使用带 shareTicket 的转发
*/
withShareTicket?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface HideShareMenuOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface UpdateShareMenuOptions {
/**
* 是否使用带 shareTicket 的转发
*/
withShareTicket?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetShareInfoOptions {
/**
* shareTicket
*/
shareTicket?: string | undefined;
/**
* 超时时间,单位 ms
*/
timeout?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetShareInfoRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetShareInfoRes {
/**
* 错误信息
*/
errMsg?: string | undefined;
/**
* 包括敏感数据在内的完整转发信息的加密数据
*/
encryptedData?: string | undefined;
/**
* 加密算法的初始向量
*/
iv?: string | undefined;
}
interface ChooseAddressOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: ChooseAddressRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseAddressRes {
/**
* 调用结果
*/
errMsg?: string | undefined;
/**
* 收货人姓名
*/
userName?: string | undefined;
/**
* 邮编
*/
postalCode?: string | undefined;
/**
* 国标收货地址第一级地址
*/
provinceName?: string | undefined;
/**
* 国标收货地址第二级地址
*/
cityName?: string | undefined;
/**
* 国标收货地址第三级地址
*/
countyName?: string | undefined;
/**
* 详细收货地址信息
*/
detailInfo?: string | undefined;
/**
* 收货地址国家码
*/
nationalCode?: string | undefined;
/**
* 收货人手机号码
*/
telNumber?: string | undefined;
}
interface AddCardOptions {
/**
* 需要添加的卡券列表
*/
cardList?: AddCardData [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: AddCardRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface AddCardData {
/**
* 卡券 id
*/
cardId?: string | undefined;
/**
* 卡券的扩展参数
*/
cardExt?: string | undefined;
}
interface AddCardRes {
/**
* 卡券 id
*/
cardList?: CardData [] | undefined;
}
interface CardData {
/**
* 加密 code,为用户领取到卡券的code加密后的字符串
*/
code?: string | undefined;
/**
* 用户领取到卡券的id
*/
cardId?: string | undefined;
/**
* 用户领取到卡券的扩展参数,与调用时传入的参数相同
*/
cardExt?: string | undefined;
/**
* 是否成功
*/
isSuccess?: boolean | undefined;
}
interface OpenCardOptions {
/**
* 需要打开的卡券列表
*/
cardList?: OpenCardData [] | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OpenCardData {
/**
* 需要打开的卡券 Id
*/
cardId?: string | undefined;
/**
* 由 addCard 的返回对象中的加密 code 通过解密后得到
*/
code?: string | undefined;
}
interface OpenSettingOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetSettingOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: ((result: AuthSetting) => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface AuthSetting {
/**
* 是否授权用户信息
*/
'scope.userInfo'?: boolean | undefined;
/**
* 是否授权地理位置
*/
'scope.userLocation'?: boolean | undefined;
/**
* 是否授权通讯地址
*/
'scope.address'?: boolean | undefined;
/**
* 是否授权发票抬头
*/
'scope.invoiceTitle'?: boolean | undefined;
/**
* 是否授权获取发票
*/
'scope.invoice'?: boolean | undefined;
/**
* 是否授权微信运动步数
*/
'scope.werun'?: boolean | undefined;
/**
* 是否授权录音功能
*/
'scope.record'?: boolean | undefined;
/**
* 是否授权保存到相册
*/
'scope.writePhotosAlbum'?: boolean | undefined;
/**
* 是否授权摄像头
*/
'scope.camera'?: boolean | undefined;
}
interface GetWeRunDataOptions {
/**
* 超时时间,单位 ms
*/
timeout?: number | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: GetWeRunDataRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface GetWeRunDataRes {
/**
* 调用结果
*/
errMsg?: string | undefined;
/**
* 包括敏感数据在内的完整用户信息的加密数据
*/
encryptedData?: string | undefined;
/**
* 加密算法的初始向量
*/
iv?: string | undefined;
}
interface NavigateToMiniProgramOptions {
/**
* 要打开的uni-app appId
*/
appId?: string | undefined;
/**
* 打开的页面路径,如果为空则打开首页
*/
path?: string | undefined;
/**
* 需要传递给目标uni-app的数据
*/
extraData?: any;
/**
* 要打开的uni-app版本
*/
envVersion?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface NavigateBackMiniProgramOptions {
/**
* 需要返回给上一个uni-app的数据
*/
extraData?: any;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseInvoiceTitleOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: ChooseInvoiceTitleRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface ChooseInvoiceTitleRes {
/**
* 抬头类型(0:单位,1:个人)
*/
type?: string | undefined;
/**
* 抬头名称
*/
title?: string | undefined;
/**
* 抬头税号
*/
taxNumber?: string | undefined;
/**
* 单位地址
*/
companyAddress?: string | undefined;
/**
* 手机号码
*/
telephone?: string | undefined;
/**
* 银行名称
*/
bankName?: string | undefined;
/**
* 银行账号
*/
bankAccount?: string | undefined;
/**
* 接口调用结果
*/
errMsg?: string | undefined;
}
interface CheckIsSupportSoterAuthenticationOptions {
/**
* 接口调用成功的回调函数
*/
success?: ((result: CheckIsSupportSoterAuthenticationRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface CheckIsSupportSoterAuthenticationRes {
/**
* 接口调用成功的回调函数
*/
supportMode?: any [] | undefined;
/**
* 接口调用结果
*/
errMsg?: string | undefined;
}
interface StartSoterAuthenticationOptions {
/**
* 请求使用的可接受的生物认证方式
*/
requestAuthModes?: any [] | undefined;
/**
* 挑战因子
*/
challenge?: string | undefined;
/**
* 验证描述,即识别过程中显示在界面上的对话框提示内容
*/
authContent?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: ((result: StartSoterAuthenticationRes) => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StartSoterAuthenticationRes {
/**
* 错误码
*/
errCode?: number | undefined;
/**
* 生物认证方式
*/
authMode?: string | undefined;
/**
* 在设备安全区域(TEE)内获得的本机安全信息以及本次认证信息
*/
resultJSON?: string | undefined;
/**
* 接口调用结果
*/
errMsg?: string | undefined;
}
interface CheckIsSoterEnrolledInDeviceOptions {
/**
* 认证方式
* - fingerPrint: 指纹识别
* - facial: 人脸识别(暂未支持)
* - speech: 声纹识别(暂未支持)
*/
checkAuthMode?: 'fingerPrint' | 'facial' | 'speech' | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface UpdateManager {
/**
* 当向应用后台请求完新版本信息,会进行回调
*/
onCheckForUpdate(callback?: () => void): void;
/**
* 当新版本下载完成,会进行回调
*/
onUpdateReady(callback?: () => void): void;
/**
* 当新版本下载失败,会进行回调
*/
onUpdateFailed(callback?: () => void): void;
/**
* 当新版本下载完成,调用该方法会强制当前uni-app应用上新版本并重启
*/
applyUpdate(): void;
}
interface Worker {
/**
* 向 Worker 线程发送的消息。
*/
postMessage(message?: any): void;
/**
* 监听 Worker 线程向当前线程发送的消息
*/
onMessage(callback?: () => void): void;
/**
* 结束当前 Worker 线程,仅限在主线程 Worker 实例上调用。
*/
terminate(): void;
}
interface SetEnableDebugOptions {
/**
* 是否打开调试
*/
enableDebug?: boolean | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetBackgroundColorOptions {
/**
* 窗口的背景色,必须为十六进制颜色值
*/
backgroundColor?: string | undefined;
/**
* 顶部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持
*/
backgroundColorTop?: string | undefined;
/**
* 底部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持
*/
backgroundColorBottom?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface SetBackgroundTextStyleOptions {
/**
* 下拉背景字体、loading 图的样式,值为:dark、light
*/
textStyle?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface OnGyroscopeChangeSuccess {
/**
* x 轴方向角速度
*/
x?: number | undefined;
/**
* y 轴方向角速度
*/
y?: number | undefined;
/**
* z 轴方向角速度
*/
z?: number | undefined;
}
interface StartGyroscopeOptions {
/**
* 监听陀螺仪数据回调函数的执行频率:game(20ms/次)、ui(60ms/次)、normal (200ms/次)
*/
interval?: string | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopGyroscopeOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface StopGyroscopeOptions {
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LoadFontFaceOptions {
/**
* 定义的字体名称
*/
family?: string | undefined;
/**
* 字体资源的地址。建议格式为 TTF 和 WOFF,WOFF2 在低版本的iOS上会不兼容。
*/
source?: string | undefined;
/**
* 可选的字体描述符
*/
desc?: LoadFontFaceOptionsDesc | undefined;
/**
* 接口调用成功的回调函数
*/
success?: (() => void) | undefined;
/**
* 接口调用失败的回调函数
*/
fail?: (() => void) | undefined;
/**
* 接口调用结束的回调函数(调用成功、失败都会执行)
*/
complete?: (() => void) | undefined;
}
interface LoadFontFaceOptionsDesc {
/**
* 字体样式,可选值为 normal、italic、oblique
*/
style?: string | undefined;
/**
* 字体粗细,可选值为 normal、bold、100、200../ 900
*/
weight?: string | undefined;
/**
* 设置小型大写字母的字体显示文本,可选值为 normal、small-caps、inherit
*/
variant?: string | undefined;
} | the_stack |
import BigNumber from 'bignumber.js'
import { TestingGroup } from '@defichain/jellyfish-testing'
import { GenesisKeys, MasterNodeRegTestContainer } from '@defichain/testcontainers'
import { ListAuctionHistoryDetail } from '../../../src/category/loan'
describe('Loan listAuctionHistory', () => {
const tGroup = TestingGroup.create(2, i => new MasterNodeRegTestContainer(GenesisKeys[i]))
const alice = tGroup.get(0)
const bob = tGroup.get(1)
let aliceColAddr: string
let bobColAddr: string
let vaultId1: string // Alice 1st vault
let vaultId2: string // Alice 2nd vault
let vaultId3: string // Bob 1st vault
let vaultId4: string // Bob 2nd vault
beforeAll(async () => {
await tGroup.start()
await alice.container.waitForWalletCoinbaseMaturity()
aliceColAddr = await alice.generateAddress()
bobColAddr = await bob.generateAddress()
await alice.token.dfi({
address: aliceColAddr,
amount: 35000
})
await alice.generate(1)
await alice.token.create({
symbol: 'BTC',
collateralAddress: aliceColAddr
})
await alice.generate(1)
await alice.token.mint({
symbol: 'BTC',
amount: 50
})
await alice.generate(1)
await alice.rpc.account.sendTokensToAddress({}, { [bobColAddr]: ['25@BTC'] })
await alice.generate(1)
await tGroup.waitForSync()
await bob.token.dfi({
address: bobColAddr,
amount: 75000
})
await bob.generate(1)
await tGroup.waitForSync()
// Loan scheme
await alice.container.call('createloanscheme', [100, 1, 'default'])
await alice.generate(1)
// Price oracle
const addr = await alice.generateAddress()
const priceFeeds = [
{
token: 'DFI',
currency: 'USD'
},
{
token: 'BTC',
currency: 'USD'
},
{
token: 'AAPL',
currency: 'USD'
},
{
token: 'TSLA',
currency: 'USD'
},
{
token: 'MSFT',
currency: 'USD'
},
{
token: 'FB',
currency: 'USD'
}
]
const oracleId = await alice.rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 })
await alice.generate(1)
const timestamp = Math.floor(new Date().getTime() / 1000)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '1@DFI',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '10000@BTC',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2@AAPL',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2@TSLA',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2@MSFT',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2@FB',
currency: 'USD'
}]
})
await alice.generate(1)
// Collateral tokens
await alice.rpc.loan.setCollateralToken({
token: 'DFI',
factor: new BigNumber(1),
fixedIntervalPriceId: 'DFI/USD'
})
await alice.generate(1)
await alice.rpc.loan.setCollateralToken({
token: 'BTC',
factor: new BigNumber(1),
fixedIntervalPriceId: 'BTC/USD'
})
await alice.generate(1)
// Loan token
await alice.rpc.loan.setLoanToken({
symbol: 'AAPL',
fixedIntervalPriceId: 'AAPL/USD'
})
await alice.generate(1)
await alice.token.mint({
symbol: 'AAPL',
amount: 50000
})
await alice.generate(1)
await alice.rpc.loan.setLoanToken({
symbol: 'TSLA',
fixedIntervalPriceId: 'TSLA/USD'
})
await alice.generate(1)
await alice.token.mint({
symbol: 'TSLA',
amount: 50000
})
await alice.generate(1)
await alice.rpc.loan.setLoanToken({
symbol: 'MSFT',
fixedIntervalPriceId: 'MSFT/USD'
})
await alice.generate(1)
await alice.token.mint({
symbol: 'MSFT',
amount: 50000
})
await alice.generate(1)
await alice.rpc.loan.setLoanToken({
symbol: 'FB',
fixedIntervalPriceId: 'FB/USD'
})
await alice.generate(1)
await alice.token.mint({
symbol: 'FB',
amount: 50000
})
await alice.generate(1)
// Vault 1
vaultId1 = await alice.rpc.container.call('createvault', [await alice.generateAddress(), 'default'])
await alice.generate(1)
await alice.container.call('deposittovault', [vaultId1, aliceColAddr, '10000@DFI'])
await alice.generate(1)
await alice.container.call('deposittovault', [vaultId1, aliceColAddr, '0.5@BTC'])
await alice.generate(1)
await alice.container.call('takeloan', [{
vaultId: vaultId1,
amounts: '7500@AAPL'
}])
await alice.generate(1)
// Vault 2
vaultId2 = await alice.rpc.container.call('createvault', [await alice.generateAddress(), 'default'])
await alice.generate(1)
await alice.container.call('deposittovault', [vaultId2, aliceColAddr, '20000@0DFI'])
await alice.generate(1)
await alice.container.call('deposittovault', [vaultId2, aliceColAddr, '1@BTC'])
await alice.generate(1)
await alice.container.call('takeloan', [{
vaultId: vaultId2,
amounts: '15000@TSLA'
}])
await alice.generate(1)
// Vault 3
vaultId3 = await bob.rpc.container.call('createvault', [await bob.generateAddress(), 'default'])
await bob.generate(1)
await bob.container.call('deposittovault', [vaultId3, bobColAddr, '30000@DFI'])
await bob.generate(1)
await bob.container.call('deposittovault', [vaultId3, bobColAddr, '1.5@BTC'])
await bob.generate(1)
await bob.container.call('takeloan', [{
vaultId: vaultId3,
amounts: '22500@MSFT'
}])
await bob.generate(1)
// Vault 4
vaultId4 = await bob.rpc.container.call('createvault', [await bob.generateAddress(), 'default'])
await bob.generate(1)
await bob.container.call('deposittovault', [vaultId4, bobColAddr, '40000@DFI'])
await bob.generate(1)
await bob.container.call('deposittovault', [vaultId4, bobColAddr, '2@BTC'])
await bob.generate(1)
await bob.container.call('takeloan', [{
vaultId: vaultId4,
amounts: '30000@FB'
}])
await bob.generate(1)
{
// When there is no liquidation occurs
const data = await alice.container.call('listauctions', [])
expect(data).toStrictEqual([])
const vault1 = await alice.rpc.loan.getVault(vaultId1)
expect(vault1.state).toStrictEqual('active')
const vault2 = await alice.rpc.loan.getVault(vaultId2)
expect(vault2.state).toStrictEqual('active')
const vault3 = await alice.rpc.loan.getVault(vaultId3)
expect(vault3.state).toStrictEqual('active')
const vault4 = await alice.rpc.loan.getVault(vaultId4)
expect(vault4.state).toStrictEqual('active')
}
// Going to liquidate the vaults by price increase of the loan tokens
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2.2@AAPL',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.container.waitForActivePrice('AAPL/USD', '2.2')
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2.2@TSLA',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.container.waitForActivePrice('TSLA/USD', '2.2')
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2.2@MSFT',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.container.waitForActivePrice('MSFT/USD', '2.2')
await alice.rpc.oracle.setOracleData(oracleId, timestamp, {
prices: [{
tokenAmount: '2.2@FB',
currency: 'USD'
}]
})
await alice.generate(1)
await alice.container.waitForActivePrice('FB/USD', '2.2')
await alice.generate(1)
// When there is liquidation
const list = await alice.container.call('listauctions', [])
list.forEach((l: { state: any }) =>
expect(l.state).toStrictEqual('inLiquidation')
)
await alice.rpc.account.sendTokensToAddress({}, { [aliceColAddr]: ['7875@AAPL'] })
await alice.generate(1)
await alice.rpc.account.sendTokensToAddress({}, { [aliceColAddr]: ['15750@TSLA'] })
await alice.generate(1)
await alice.rpc.account.sendTokensToAddress({}, { [bobColAddr]: ['23625@MSFT'] })
await alice.generate(1)
await alice.rpc.account.sendTokensToAddress({}, { [bobColAddr]: ['31500@FB'] })
await alice.generate(1)
{
const txid = await alice.container.call('placeauctionbid', [vaultId1, 0, aliceColAddr, '7875@AAPL'])
expect(typeof txid).toStrictEqual('string')
expect(txid.length).toStrictEqual(64)
await alice.generate(1)
}
{
const txid = await alice.container.call('placeauctionbid', [vaultId2, 1, aliceColAddr, '15750@TSLA'])
expect(typeof txid).toStrictEqual('string')
expect(txid.length).toStrictEqual(64)
await alice.generate(1)
}
await tGroup.waitForSync()
{
const txid = await bob.container.call('placeauctionbid', [vaultId3, 0, bobColAddr, '23625@MSFT'])
expect(typeof txid).toStrictEqual('string')
expect(txid.length).toStrictEqual(64)
await bob.generate(1)
}
{
const txid = await bob.container.call('placeauctionbid', [vaultId4, 1, bobColAddr, '31500@FB'])
expect(typeof txid).toStrictEqual('string')
expect(txid.length).toStrictEqual(64)
await bob.generate(1)
}
await alice.container.generate(40)
await tGroup.waitForSync()
})
afterAll(async () => {
await tGroup.stop()
})
describe('listAuctionHistory without pagination', () => {
it('should listAuctionHistory with owner = mine', async () => {
{
const auctionhistory1 = await alice.rpc.loan.listAuctionHistory() // default to mine
const auctionhistory2 = await alice.rpc.loan.listAuctionHistory('mine')
expect(auctionhistory1).toStrictEqual(auctionhistory2)
expect(auctionhistory1.length).toStrictEqual(2)
{
const result = auctionhistory1.find(h => h.vaultId === vaultId1)
expect(result).toStrictEqual(
{
winner: aliceColAddr,
blockHeight: expect.any(Number),
blockHash: expect.any(String),
blockTime: expect.any(Number),
vaultId: vaultId1,
batchIndex: 0,
auctionBid: '7875.00000000@AAPL',
auctionWon: ['6666.66660000@DFI', '0.33333333@BTC']
}
)
}
{
const result = auctionhistory1.find(h => h.vaultId === vaultId2)
expect(result).toStrictEqual(
{
winner: aliceColAddr,
blockHeight: expect.any(Number),
blockHash: expect.any(String),
blockTime: expect.any(Number),
vaultId: vaultId2,
batchIndex: 1,
auctionBid: '15750.00000000@TSLA',
auctionWon: ['6666.66660000@DFI', '0.33333333@BTC']
}
)
}
}
{
const auctionhistory1 = await bob.rpc.loan.listAuctionHistory() // default to mine
const auctionhistory2 = await bob.rpc.loan.listAuctionHistory('mine')
expect(auctionhistory1).toStrictEqual(auctionhistory2)
expect(auctionhistory1.length).toStrictEqual(2)
{
const result = auctionhistory1.find(h => h.vaultId === vaultId3)
expect(result).toStrictEqual(
{
winner: bobColAddr,
blockHeight: expect.any(Number),
blockHash: expect.any(String),
blockTime: expect.any(Number),
vaultId: vaultId3,
batchIndex: 0,
auctionBid: '23625.00000000@MSFT',
auctionWon: ['6666.66660000@DFI', '0.33333333@BTC']
}
)
}
{
const result = auctionhistory1.find(h => h.vaultId === vaultId4)
expect(result).toStrictEqual(
{
winner: bobColAddr,
blockHeight: expect.any(Number),
blockHash: expect.any(String),
blockTime: expect.any(Number),
vaultId: vaultId4,
batchIndex: 1,
auctionBid: '31500.00000000@FB',
auctionWon: ['6666.66640000@DFI', '0.33333332@BTC']
}
)
}
}
})
it('should listAuctionHistory with owner = all', async () => {
const data = await alice.rpc.loan.listAuctionHistory('all')
expect(data.length).toStrictEqual(4)
const data1 = data.find(d => d.vaultId === vaultId1)
expect(data1).toBeDefined()
const data2 = data.find(d => d.vaultId === vaultId2)
expect(data2).toBeDefined()
const data3 = data.find(d => d.vaultId === vaultId3)
expect(data3).toBeDefined()
const data4 = data.find(d => d.vaultId === vaultId4)
expect(data4).toBeDefined()
})
it('should listAuctionHistory with owner = address', async () => {
{
const data = await alice.rpc.loan.listAuctionHistory(aliceColAddr)
const data1 = data.find(d => d.vaultId === vaultId1)
expect(data1).toBeDefined()
const data2 = data.find(d => d.vaultId === vaultId2)
expect(data2).toBeDefined()
const data3 = data.find(d => d.vaultId === vaultId3)
expect(data3).toBeUndefined()
const data4 = data.find(d => d.vaultId === vaultId4)
expect(data4).toBeUndefined()
}
{
const data = await alice.rpc.loan.listAuctionHistory(bobColAddr)
const data1 = data.find(d => d.vaultId === vaultId1)
expect(data1).toBeUndefined()
const data2 = data.find(d => d.vaultId === vaultId2)
expect(data2).toBeUndefined()
const data3 = data.find(d => d.vaultId === vaultId3)
expect(data3).toBeDefined()
const data4 = data.find(d => d.vaultId === vaultId4)
expect(data4).toBeDefined()
}
})
})
describe('listAuctionHistory with pagination', () => {
let auctionHistoryArr: ListAuctionHistoryDetail[]
let aliceAuctionHistoryArr: ListAuctionHistoryDetail[]
let bobAuctionHistoryArr: ListAuctionHistoryDetail[]
beforeAll(async () => {
auctionHistoryArr = await alice.rpc.loan.listAuctionHistory('all')
aliceAuctionHistoryArr = await alice.rpc.loan.listAuctionHistory('mine')
bobAuctionHistoryArr = await bob.rpc.loan.listAuctionHistory('mine')
})
it('should listAuctionHistory with maxBlockHeight only', async () => {
// All
// ListAuctionHistory for maxBlockHeight of first vault
{
const page = await alice.rpc.loan.listAuctionHistory('all',
{ maxBlockHeight: auctionHistoryArr[0].blockHeight }
)
expect(page.length).toStrictEqual(4)
expect(page[0].vaultId).toStrictEqual(auctionHistoryArr[0].vaultId)
expect(page[1].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(page[2].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
expect(page[3].vaultId).toStrictEqual(auctionHistoryArr[3].vaultId)
}
// ListAuctionHistory for maxBlockHeight of forth vault
{
const page = await alice.rpc.loan.listAuctionHistory('all',
{ maxBlockHeight: auctionHistoryArr[3].blockHeight }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(auctionHistoryArr[3].vaultId)
}
// Mine
// ListAuctionHistory for maxBlockHeight of first vault for Alice
{
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ maxBlockHeight: aliceAuctionHistoryArr[0].blockHeight }
)
expect(page.length).toStrictEqual(2)
expect(page[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[0].vaultId)
expect(page[1].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
}
// ListAuctionHistory for maxBlockHeight of second vault for Alice
{
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ maxBlockHeight: aliceAuctionHistoryArr[1].blockHeight }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
}
// Address
// ListAuctionHistory for maxBlockHeight of first vault for Bob
{
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ maxBlockHeight: bobAuctionHistoryArr[0].blockHeight }
)
expect(page.length).toStrictEqual(2)
expect(page[0].vaultId).toStrictEqual(bobAuctionHistoryArr[0].vaultId)
expect(page[1].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
}
// ListAuctionHistory for maxBlockHeight of second vault for Bob
{
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ maxBlockHeight: bobAuctionHistoryArr[1].blockHeight }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
}
})
it('should not listAuctionHistory with vaultId only', async () => { // This test shows that we can not use vaultId only for the pagination start point as the DB composite index starts with maxBlockHeight. Need to pass maxBlockHeight and vaultId together.
{
// All
const page = await alice.rpc.loan.listAuctionHistory('all',
{ vaultId: auctionHistoryArr[2].vaultId }
)
expect(page.length).toStrictEqual(4)
}
{
// Mine for Alice
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ vaultId: aliceAuctionHistoryArr[1].vaultId }
)
expect(page.length).toStrictEqual(2)
}
{
// Address for Bob
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ vaultId: bobAuctionHistoryArr[1].vaultId }
)
expect(page.length).toStrictEqual(2)
}
})
it('should not listAuctionHistory with index only', async () => { // This test shows that we can not use index only for the pagination start point as the DB composite index starts with maxBlockHeight.
{
// All
const page = await alice.rpc.loan.listAuctionHistory('all',
{ index: 1 }
)
expect(page.length).toStrictEqual(4)
}
{
// Mine for Alice
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ index: 5 }
)
expect(page.length).toStrictEqual(2)
}
{
// Address for Bob
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ index: 3 }
)
expect(page.length).toStrictEqual(2)
}
})
it('should listAuctionHistory with limit only', async () => {
{
// All
// ListAuctionHistory with limit < size
const pageLimit3 = await alice.rpc.loan.listAuctionHistory('all', { limit: 3 })
expect(pageLimit3.length).toStrictEqual(3)
expect(pageLimit3[0].vaultId).toStrictEqual(auctionHistoryArr[0].vaultId)
expect(pageLimit3[1].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(pageLimit3[2].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
// ListAuctionHistory with limit = size
const pageLimit4 = await alice.rpc.loan.listAuctionHistory('all', { limit: 4 })
expect(pageLimit4.length).toStrictEqual(4)
expect(pageLimit4[0].vaultId).toStrictEqual(auctionHistoryArr[0].vaultId)
expect(pageLimit4[1].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(pageLimit4[2].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
expect(pageLimit4[3].vaultId).toStrictEqual(auctionHistoryArr[3].vaultId)
// ListAuctionHistory with limit > size
const pageLimit5 = await alice.rpc.loan.listAuctionHistory('all', { limit: 5 })
expect(pageLimit5.length).toStrictEqual(4)
expect(pageLimit5).toStrictEqual(pageLimit4)
}
{
// Mine
// ListAuctionHistory with limit < size for Alice
const pageLimit1 = await alice.rpc.loan.listAuctionHistory('mine', { limit: 1 })
expect(pageLimit1.length).toStrictEqual(1)
expect(pageLimit1[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[0].vaultId)
// ListAuctionHistory with limit = size for Alice
const pageLimit2 = await alice.rpc.loan.listAuctionHistory('mine', { limit: 2 })
expect(pageLimit2.length).toStrictEqual(2)
expect(pageLimit2[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[0].vaultId)
expect(pageLimit2[1].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
// ListAuctionHistory with limit > size for Alice
const pageLimit3 = await alice.rpc.loan.listAuctionHistory('mine', { limit: 3 })
expect(pageLimit3.length).toStrictEqual(2)
expect(pageLimit3).toStrictEqual(pageLimit2)
}
{
// Address
// ListAuctionHistory with limit < size for Bob
const pageLimit1 = await bob.rpc.loan.listAuctionHistory(bobColAddr, { limit: 1 })
expect(pageLimit1.length).toStrictEqual(1)
expect(pageLimit1[0].vaultId).toStrictEqual(bobAuctionHistoryArr[0].vaultId)
// ListAuctionHistory with limit = size for Bob
const pageLimit2 = await bob.rpc.loan.listAuctionHistory(bobColAddr, { limit: 2 })
expect(pageLimit2.length).toStrictEqual(2)
expect(pageLimit2[0].vaultId).toStrictEqual(bobAuctionHistoryArr[0].vaultId)
expect(pageLimit2[1].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
// ListAuctionHistory with limit > size for Bob
const pageLimit3 = await bob.rpc.loan.listAuctionHistory(bobColAddr, { limit: 3 })
expect(pageLimit3.length).toStrictEqual(2)
expect(pageLimit3).toStrictEqual(pageLimit2)
}
})
it('should listAuctions with maxBlockHeight and vaultId', async () => {
// All
// ListAuctionHistory for maxBlockHeight and vaultId of second vault
{
const page = await alice.rpc.loan.listAuctionHistory('all',
{ maxBlockHeight: auctionHistoryArr[1].blockHeight, vaultId: auctionHistoryArr[1].vaultId }
)
expect(page.length).toStrictEqual(3)
expect(page[0].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(page[1].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
expect(page[2].vaultId).toStrictEqual(auctionHistoryArr[3].vaultId)
}
// Mine for Alice
// ListAuctionHistory for maxBlockHeight and vaultId of second vault
{
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ maxBlockHeight: aliceAuctionHistoryArr[1].blockHeight, vaultId: aliceAuctionHistoryArr[1].vaultId }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
}
// Address for Bob
// ListAuctionHistory for maxBlockHeight and vaultId of second vault
{
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ maxBlockHeight: bobAuctionHistoryArr[1].blockHeight, vaultId: bobAuctionHistoryArr[1].vaultId }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
}
})
it('should listAuctions with maxBlockHeight and index', async () => {
// All
// ListAuctionHistory for maxBlockHeight and index of second vault
{
const page = await alice.rpc.loan.listAuctionHistory('all',
{ maxBlockHeight: auctionHistoryArr[1].blockHeight, index: auctionHistoryArr[1].batchIndex }
)
expect(page.length).toStrictEqual(3)
expect(page[0].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(page[1].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
expect(page[2].vaultId).toStrictEqual(auctionHistoryArr[3].vaultId)
}
// Mine for Alice
// ListAuctionHistory for maxBlockHeight and index of second vault
{
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ maxBlockHeight: aliceAuctionHistoryArr[1].blockHeight, index: aliceAuctionHistoryArr[1].batchIndex }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
}
// Address for Bob
// ListAuctionHistory for maxBlockHeight and index of second vault
{
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ maxBlockHeight: bobAuctionHistoryArr[1].blockHeight, index: bobAuctionHistoryArr[1].batchIndex }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
}
})
it('should listAuctions with maxBlockHeight, vaultId, index and limit', async () => {
// All
// ListAuctionHistory for maxBlockHeight, vaultId and index of second vault with limit = 2
{
const page = await alice.rpc.loan.listAuctionHistory('all',
{ maxBlockHeight: auctionHistoryArr[1].blockHeight, vaultId: auctionHistoryArr[1].vaultId, index: auctionHistoryArr[1].batchIndex, limit: 2 }
)
expect(page.length).toStrictEqual(2)
expect(page[0].vaultId).toStrictEqual(auctionHistoryArr[1].vaultId)
expect(page[1].vaultId).toStrictEqual(auctionHistoryArr[2].vaultId)
}
// Mine
// ListAuctionHistory for maxBlockHeight, vaultId and index of second vault with limit = 1 for Alice
{
const page = await alice.rpc.loan.listAuctionHistory('mine',
{ maxBlockHeight: aliceAuctionHistoryArr[1].blockHeight, vaultId: aliceAuctionHistoryArr[1].vaultId, index: aliceAuctionHistoryArr[1].batchIndex, limit: 1 }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(aliceAuctionHistoryArr[1].vaultId)
}
// Address
// ListAuctionHistory for maxBlockHeight, vaultId and index of second vault with limit = 1 for Bob
{
const page = await bob.rpc.loan.listAuctionHistory(bobColAddr,
{ maxBlockHeight: bobAuctionHistoryArr[1].blockHeight, vaultId: bobAuctionHistoryArr[1].vaultId, index: bobAuctionHistoryArr[1].batchIndex, limit: 1 }
)
expect(page.length).toStrictEqual(1)
expect(page[0].vaultId).toStrictEqual(bobAuctionHistoryArr[1].vaultId)
}
})
})
}) | the_stack |
// 1. Use the rankItem function to rank an item
// 2. Use the resulting rankingInfo.passed to filter
// 3. Use the resulting rankingInfo.rank to sort
// For bundling purposes (mainly remove-accents not being esm safe/ready),
// we've also hard-coded remove-accents into this source.
// The remove-accents package is still included as a dependency
// for attribution purposes, but it will not be imported and bundled.
import { removeAccents } from './remove-accents'
export type AccessorAttributes = {
threshold?: Ranking
maxRanking: Ranking
minRanking: Ranking
}
export interface RankingInfo {
rankedValue: any
rank: Ranking
accessorIndex: number
accessorThreshold: Ranking | undefined
passed: boolean
}
export interface AccessorOptions<TItem> {
accessor: AccessorFn<TItem>
threshold?: Ranking
maxRanking?: Ranking
minRanking?: Ranking
}
export type AccessorFn<TItem> = (item: TItem) => string | Array<string>
export type Accessor<TItem> = AccessorFn<TItem> | AccessorOptions<TItem>
export interface RankItemOptions<TItem = unknown> {
accessors?: ReadonlyArray<Accessor<TItem>>
threshold?: Ranking
keepDiacritics?: boolean
}
export const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0,
} as const
export type Ranking = typeof rankings[keyof typeof rankings]
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {Array} keys - the keys to get values from the item for the ranking
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
export function rankItem<TItem>(
item: TItem,
value: string,
options?: RankItemOptions<TItem>
): RankingInfo {
options = options || {}
options.threshold = options.threshold ?? rankings.MATCHES
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item as unknown as string, value, options)
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold,
}
}
const valuesToRank = getAllValuesToRank(item, options.accessors)
const rankingInfo: RankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH as Ranking,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false,
}
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i]!
let newRank = getMatchRanking(rankValue.itemValue, value, options)
const { minRanking, maxRanking, threshold } = rankValue.attributes
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking
} else if (newRank > maxRanking) {
newRank = maxRanking
}
newRank = Math.min(newRank, maxRanking) as Ranking
if (newRank > rankingInfo.rank) {
rankingInfo.rank = newRank
rankingInfo.accessorIndex = i
rankingInfo.accessorThreshold = threshold
rankingInfo.rankedValue = rankValue.itemValue
}
}
return rankingInfo
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking<TItem>(
testString: string,
stringToRank: string,
options: RankItemOptions<TItem>
): Ranking {
testString = prepareValueForComparison(testString, options)
stringToRank = prepareValueForComparison(stringToRank, options)
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL
}
// Lower casing before further comparison
testString = testString.toLowerCase()
stringToRank = stringToRank.toLowerCase()
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank)
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string: string): string {
let acronym = ''
const wordsInString = string.split(' ')
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-')
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1)
})
})
return acronym
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(
testString: string,
stringToRank: string
): Ranking {
let matchingInOrderCharCount = 0
let charNumber = 0
function findMatchingCharacter(
matchChar: undefined | string,
string: string,
index: number
) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j]
if (stringChar === matchChar) {
matchingInOrderCharCount += 1
return j + 1
}
}
return -1
}
function getRanking(spread: number) {
const spreadPercentage = 1 / spread
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage
return ranking as Ranking
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0)
if (firstIndex < 0) {
return rankings.NO_MATCH
}
charNumber = firstIndex
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i]
charNumber = findMatchingCharacter(matchChar, testString, charNumber)
const found = charNumber > -1
if (!found) {
return rankings.NO_MATCH
}
}
const spread = charNumber - firstIndex
return getRanking(spread)
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
export function compareItems<TItem>(a: RankingInfo, b: RankingInfo): number {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison<TItem>(
value: string,
{ keepDiacritics }: RankItemOptions<TItem>
): string {
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}` // toString
if (!keepDiacritics) {
value = removeAccents(value)
}
return value
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues<TItem>(
item: TItem,
accessor: Accessor<TItem>
): Array<string> {
let accessorFn = accessor as AccessorFn<TItem>
if (typeof accessor === 'object') {
accessorFn = accessor.accessor
}
const value = accessorFn(item)
// because `value` can also be undefined
if (value == null) {
return []
}
if (Array.isArray(value)) {
return value
}
return [String(value)]
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank<TItem>(
item: TItem,
accessors: ReadonlyArray<Accessor<TItem>>
) {
const allValues: Array<{
itemValue: string
attributes: AccessorAttributes
}> = []
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j]!
const attributes = getAccessorAttributes(accessor)
const itemValues = getItemValues(item, accessor)
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i]!,
attributes,
})
}
}
return allValues
}
const defaultKeyAttributes = {
maxRanking: Infinity as Ranking,
minRanking: -Infinity as Ranking,
}
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes<TItem>(
accessor: Accessor<TItem>
): AccessorAttributes {
if (typeof accessor === 'function') {
return defaultKeyAttributes
}
return { ...defaultKeyAttributes, ...accessor }
} | the_stack |
import { join } from "path";
import * as vscode from "vscode";
import { MediaTypes, SettingEnum } from "../const/ENUM";
import { TemplatePath } from "../const/PATH";
import { ArticlePathReg, QuestionAnswerPathReg, QuestionPathReg, ZhihuPicReg } from "../const/REG";
import { AnswerAPI, AnswerURL, QuestionAPI, ZhuanlanAPI, ZhuanlanURL } from "../const/URL";
import { PostAnswer } from "../model/publish/answer.model";
import { IColumn } from "../model/publish/column.model";
import { IProfile, ITarget, ITopicTarget } from "../model/target/target";
import { beautifyDate, removeHtmlTag } from "../util/md-html-utils";
import { CollectionService, ICollectionItem } from "./collection.service";
import { EventService } from "./event.service";
import { HttpService, sendRequest } from "./http.service";
import { ProfileService } from "./profile.service";
import { WebviewService } from "./webview.service";
import * as MarkdownIt from "markdown-it";
import md5 = require("md5");
import { PasteService } from "./paste.service";
import { PipeService } from "./pipe.service";
import { getExtensionPath } from "../global/globa-var";
enum previewActions {
openInBrowser = '去看看'
}
interface TimeObject {
hour: number,
minute: number,
/**
* interval in millisec
*/
date: Date
}
export class PublishService {
public profile: IProfile;
constructor(
protected zhihuMdParser: MarkdownIt,
protected defualtMdParser: MarkdownIt,
protected webviewService: WebviewService,
protected collectionService: CollectionService,
protected eventService: EventService,
protected profileService: ProfileService,
protected pasteService: PasteService,
protected pipeService: PipeService
) {
this.registerPublishEvents();
}
/**
* When extension starts, all publish events should be re-registered,
* this is what pre-log tech comes in.
*/
private registerPublishEvents() {
let events = this.eventService.getEvents();
events.forEach(e => {
e.timeoutId = setTimeout(() => {
this.postArticle(e.content, e.title);
this.eventService.destroyEvent(e.hash);
}, e.date.getTime() - Date.now());
})
}
preview(textEdtior: vscode.TextEditor, edit: vscode.TextEditorEdit) {
let text = textEdtior.document.getText();
let url: URL = this.shebangParser(text);
// get rid of shebang line
if (url) text = text.slice(text.indexOf('\n') + 1);
let html = this.zhihuMdParser.render(text);
this.webviewService.renderHtml({
title: '预览',
pugTemplatePath: join(getExtensionPath(), TemplatePath, 'pre-publish.pug'),
pugObjects: {
title: '答案预览',
content: html
},
showOptions: {
viewColumn: vscode.ViewColumn.Beside,
preserveFocus: true
}
});
}
async publish(textEdtior: vscode.TextEditor, edit: vscode.TextEditorEdit) {
let title: string;
let titleImage: string;
let bgIndex: number;
let text = textEdtior.document.getText();
const url: URL = this.shebangParser(text);
const timeObject: TimeObject = { hour: 0, date: new Date(), minute: 0 };
// get rid of shebang line
if (url) text = text.slice(text.indexOf('\n') + 1);
text = text + "\n\n>本文使用 [Zhihu On VSCode](https://zhuanlan.zhihu.com/p/106057556) 创作并发布";
// let html = this.zhihuMdParser.render(text);
let tokens = this.zhihuMdParser.parse(text, {});
// convert local and outer link to zhihu link
let pipePromise = this.pipeService.sanitizeMdTokens(tokens);
vscode.window.withProgress({
location: vscode.ProgressLocation.Window,
cancellable: false,
title: '文章发布中...'
}, (progress, token) => {
return Promise.resolve(pipePromise);
})
await pipePromise;
let html = this.zhihuMdParser.renderer.render(tokens, {}, {});
const openIndex = tokens.findIndex(t => t.type == 'heading_open' && t.tag == 'h1');
const endIndex = tokens.findIndex(t => t.type == 'heading_close' && t.tag == 'h1');
if (openIndex >= 0) {
title = removeHtmlTag(this.zhihuMdParser.renderInline(tokens[openIndex+1].content));
for (let i = 0; i < openIndex; i++) {
if(tokens[i].type === 'inline') {
for (let c of tokens[i].children) {
if(c.type === 'image') {
let tmp = c.attrs.find(a => a[0] === 'src')
titleImage = tmp[1];
bgIndex = i;
}
}
}
}
}
const pubLater = await vscode.window.showQuickPick<vscode.QuickPickItem & { value: boolean }>(
[
{ label: '立即发布', description: '', value: false },
{ label: '稍后发布', description: '', value: true }
]
).then(item => item.value);
if (pubLater == undefined) return;
if (pubLater) {
let ClockReg = /^(\d\d?)[::](\d\d)\s*([ap]m)\s*$/i
let timeStr: string | undefined = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入发布时间,如 5:30 pm, 6:40 am 等,目前只支持当天发布!",
placeHolder: "",
validateInput: (s: string) => {
if (!ClockReg.test(s)) return '请输入正确的时间格式!'
if (parseInt(s.replace(ClockReg, '$1')) > 12 || parseInt(s.replace(ClockReg, '$2')) > 60) return '请输入正确的时间格式!'
return ''
}
});
let h = parseInt(timeStr.replace(ClockReg, '$1')), m = parseInt(timeStr.replace(ClockReg, '$2')), aOrPm = timeStr.replace(ClockReg, '$3');
if (!timeStr) return;
timeStr = timeStr.trim();
/**
* the time interval between now and the publish time in millisecs.
*/
timeObject.date.setHours(aOrPm == 'am' ? h : h + 12);
timeObject.date.setMinutes(m);
if (timeObject.date.getTime() < Date.now()) {
vscode.window.showWarningMessage('不能选择比现在更早的时间!');
return;
}
}
if (url) { // If url is provided
// just publish answer in terms of what shebang indicates
if (QuestionAnswerPathReg.test(url.pathname)) {
// answer link, update answer
let aId = url.pathname.replace(QuestionAnswerPathReg, '$3');
if (!this.eventService.registerEvent({
content: html,
type: MediaTypes.article,
date: timeObject.date,
hash: md5(html),
handler: () => {
this.putAnswer(html, aId);
this.eventService.destroyEvent(md5(html));
}
})) this.promptSameContentWarn()
else this.promptEventRegistedInfo(timeObject)
} else if (QuestionPathReg.test(url.pathname)) {
// question link, post new answer
let qId = url.pathname.replace(QuestionPathReg, '$1');
if (!this.eventService.registerEvent({
content: html,
type: MediaTypes.question,
date: timeObject.date,
hash: md5(html),
handler: () => {
this.postAnswer(html, qId);
this.eventService.destroyEvent(md5(html));
}
})) this.promptSameContentWarn()
else this.promptEventRegistedInfo(timeObject)
} else if (ArticlePathReg.test(url.pathname)) {
({ tokens, html } = this.removeTitleAndBgFromContent(tokens, openIndex, bgIndex, html));
let arId = url.pathname.replace(ArticlePathReg, '$1');
if (!title) {
title = await this._getTitle();
}
let column = await this._selectColumn();
if (!column) {
vscode.window
}
if (!this.eventService.registerEvent({
content: html,
type: MediaTypes.question,
date: timeObject.date,
title: title,
hash: md5(html),
handler: () => {
this.putArticle(html, arId, title, column, titleImage);
this.eventService.destroyEvent(md5(html));
}
})) this.promptSameContentWarn()
else this.promptEventRegistedInfo(timeObject)
}
} else { // url is not provided
const selectFrom: MediaTypes = await vscode.window.showQuickPick<vscode.QuickPickItem & { value: MediaTypes }>(
[
{ label: '发布新文章', description: '', value: MediaTypes.article },
{ label: '从收藏夹中选取', description: '', value: MediaTypes.answer }
]
).then(item => item.value);
if (selectFrom === MediaTypes.article) {
({ tokens, html } = this.removeTitleAndBgFromContent(tokens, openIndex, bgIndex, html));
// user select to publish new article
if (!title) {
title = await this._getTitle();
}
let column = await this._selectColumn();
if (!title) return;
if (!this.eventService.registerEvent({
content: html,
type: MediaTypes.article,
title,
date: timeObject.date,
hash: md5(html + title),
handler: () => {
this.postArticle(html, title, column, titleImage);
this.eventService.destroyEvent(md5(html + title));
}
})) this.promptSameContentWarn()
else this.promptEventRegistedInfo(timeObject)
} else if (selectFrom === MediaTypes.answer) {
// user select from collection
// shebang not found, then prompt a quick pick to select a question from collections
const selectedTarget: ICollectionItem | undefined = await vscode.window.showQuickPick<vscode.QuickPickItem & ICollectionItem>(
this.collectionService.getTargets(MediaTypes.question).then(
(targets) => {
let items = targets.map(t => ({ label: t.title ? t.title : t.excerpt, description: t.excerpt, id: t.id, type: t.type }));
return items;
}
)
).then(item => (item ? { id: item.id, type: item.type } : undefined));
if (!selectedTarget) return;
if (!this.eventService.registerEvent({
content: html,
type: MediaTypes.article,
date: timeObject.date,
hash: md5(html),
handler: () => {
this.postAnswer(html, selectedTarget.id);
this.eventService.destroyEvent(md5(html));
}
})) this.promptSameContentWarn();
else this.promptEventRegistedInfo(timeObject);
}
}
}
private removeTitleAndBgFromContent(tokens, openIndex: number, bgIndex: number, html: string) {
tokens = tokens.filter(this._removeTitleAndBg(openIndex, bgIndex));
html = this.zhihuMdParser.renderer.render(tokens, {}, {});
return { tokens, html };
}
private _removeTitleAndBg(openIndex: number, bgIndex: number) {
return (t, i) => Math.abs(openIndex + 1 - i) > 1 && bgIndex != i;
}
private promptEventRegistedInfo(timeObject: TimeObject) {
if (timeObject.date.getTime() > Date.now()) {
vscode.window.showInformationMessage(`答案将在 ${beautifyDate(timeObject.date)} 发布,请发布时保证VSCode处于打开状态,并` +
`激活知乎插件`);
}
}
private promptSameContentWarn() {
vscode.window.showWarningMessage(`你已经有一篇一模一样的内容还未发布!`);
}
private async _getTitle(): Promise<string | undefined> {
return vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入标题:",
placeHolder: "",
});
}
// private async _getTopics(): Promise<ITopicTarget[] | undefined> {
// topics
// vscode.window.showQuickPick<vscode.QuickPickItem & { value: ITopicTarget }>(
// [{ label: '不发布到专栏', value: undefined }].concat(columns.map(c => ({ label: c.title, value: c }))),
// {
// ignoreFocusOut: true,
// }
// ).then(item => item.value);
// }
private async _selectColumn(): Promise<IColumn | undefined> {
const columns = await this.profileService.getColumns();
if (!columns || columns.length === 0) return;
return vscode.window.showQuickPick<vscode.QuickPickItem & { value: IColumn }>(
[{ label: '不发布到专栏', value: undefined }].concat(columns.map(c => ({ label: c.title, value: c }))),
{
ignoreFocusOut: true,
}
).then(item => item.value);
}
public putAnswer(html: string, answerId: string) {
sendRequest({
uri: `${AnswerAPI}/${answerId}`,
method: 'put',
body: {
content: html,
reward_setting: { "can_reward": false, "tagline": "" },
},
json: true,
resolveWithFullResponse: true,
headers: {},
}).then(resp => {
if (resp.statusCode === 200) {
let newUrl = `${AnswerURL}/${answerId}`;
this.promptSuccessMsg(newUrl);
const pane = vscode.window.createWebviewPanel('zhihu', 'zhihu', vscode.ViewColumn.One, { enableScripts: true, enableCommandUris: true, enableFindWidget: true });
sendRequest({ uri: `${AnswerURL}/${answerId}`, gzip: true }).then(
resp => {
pane.webview.html = resp
}
);
} else {
vscode.window.showWarningMessage(`发布失败!错误代码 ${resp.statusCode}`)
}
})
}
public postAnswer(html: string, questionId: string) {
sendRequest({
uri: `${QuestionAPI}/${questionId}/answers`,
method: 'post',
body: new PostAnswer(html),
json: true,
resolveWithFullResponse: true,
headers: {}
}).then(resp => {
if (resp.statusCode == 200) {
let newUrl = `${AnswerURL}/${resp.body.id}`;
this.promptSuccessMsg(newUrl);
// const pane = vscode.window.createWebviewPanel('zhihu', 'zhihu', vscode.ViewColumn.One, { enableScripts: true, enableCommandUris: true, enableFindWidget: true });
// sendRequest({ uri: `${AnswerURL}/${resp.body.id}`, gzip: true }).then(
// resp => {
// pane.webview.html = resp
// }
// );
const editor = vscode.window.activeTextEditor;
const uri = editor.document.uri;
editor.edit(e => {
e.replace(editor.document.lineAt(0).range, `#! ${newUrl}\n`)
})
} else {
if (resp.statusCode == 400 || resp.statusCode == 403) {
vscode.window.showWarningMessage(`发布失败,你已经在该问题下发布过答案,请将头部链接更改为\
已回答的问题下的链接。`)
} else {
vscode.window.showWarningMessage(`发布失败!错误代码 ${resp.statusCode}`)
}
}
})
}
public async postArticle(content: string, title?: string, column?: IColumn, titleImage?: string) {
if (!title) {
title = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "输入文章标题:",
placeHolder: ""
})
}
if (!title) return;
let postResp: ITarget = await sendRequest({
uri: `${ZhuanlanAPI}/drafts`,
json: true,
method: 'post',
body: { "title": "h", "delta_time": 0 },
headers: {
'authority': 'zhuanlan.zhihu.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4101.0 Safari/537.36 Edg/83.0.474.0',
'origin': 'https://zhuanlan.zhihu.com',
'sec-fetch-site': 'same-origin',
'sec-fetch-mode': 'cors',
'sec-fetch-dest': 'empty',
'referer': 'https://zhuanlan.zhihu.com/write',
'x-requested-with': 'fetch'
}
})
let patchResp = await sendRequest({
uri: `${ZhuanlanAPI}/${postResp.id}/draft`,
json: true,
method: 'patch',
body: {
content: content,
title: title,
titleImage,
isTitleImageFullScreen: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.isTitleImageFullScreen)
},
headers: {}
})
let resp = await sendRequest({
uri: `${ZhuanlanAPI}/${postResp.id}/publish`,
json: true,
method: 'put',
body: { "column": column, "commentPermission": "anyone" },
headers: {},
resolveWithFullResponse: true
})
if (resp.statusCode < 300) {
const editor = vscode.window.activeTextEditor;
editor.edit(e => {
e.insert(new vscode.Position(0, 0), `#! ${ZhuanlanURL}${postResp.id}\n`)
})
this.promptSuccessMsg(`${ZhuanlanURL}${postResp.id}`, title)
} else {
vscode.window.showWarningMessage(`文章发布失败,错误代码${resp.statusCode}`)
}
return resp;
}
public async putArticle(content: string, articleId: string, title?: string, column?: IColumn, titleImage?: string) {
if (!title) {
title = await vscode.window.showInputBox({
ignoreFocusOut: true,
prompt: "修改文章标题:",
placeHolder: ""
})
}
if (!title) return;
let patchResp = await sendRequest({
uri: `${ZhuanlanAPI}/${articleId}/draft`,
json: true,
method: 'patch',
body: {
content: content,
title: title,
titleImage,
isTitleImageFullScreen: vscode.workspace.getConfiguration('zhihu').get(SettingEnum.isTitleImageFullScreen)
},
headers: {}
})
let resp = await sendRequest({
uri: `${ZhuanlanAPI}/${articleId}/publish`,
json: true,
method: 'put',
body: { "column": column, "commentPermission": "anyone" },
headers: {},
resolveWithFullResponse: true
})
if (resp.statusCode < 300) {
this.promptSuccessMsg(`${ZhuanlanURL}${articleId}`, title)
} else {
vscode.window.showWarningMessage(`文章发布失败,错误代码${resp.statusCode}`)
}
return resp;
}
private promptSuccessMsg(url: string, title?: string) {
vscode.window.showInformationMessage(`${title ? '"' + title + '"' : ''} 发布成功!\n`, { modal: true },
previewActions.openInBrowser
).then(r => r ? vscode.env.openExternal(vscode.Uri.parse(url)) : undefined);
}
shebangParser(text: string): URL {
let shebangRegExp = /#[!!]\s*((https?:\/\/)?(.+))$/i
let lf = text.indexOf('\n');
if (lf < 0) lf = text.length;
let link = text.slice(0, lf);
link = link.indexOf('\r') > 0 ? link.slice(0, link.length - 1) : link;
if (!shebangRegExp.test(link)) return undefined;
let url = new URL(link.replace(shebangRegExp, '$1'));
if (/^(\w)+\.zhihu\.com$/.test(url.host)) return url;
else return undefined;
// shebangRegExp = /(https?:\/\/)/i
}
} | the_stack |
import { expect } from 'chai';
import * as fs from 'fs';
import * as jestTestSupport from 'jest-editor-support';
import { SinonStub, stub } from 'sinon';
import * as vscode from 'vscode';
import URI from 'vscode-uri';
import { lwcTestIndexer } from '../../../../src/testSupport/testIndexer';
import {
TestFileInfo,
TestInfoKind,
TestResultStatus,
TestType
} from '../../../../src/testSupport/types';
describe('LWC Test Indexer', () => {
let lwcTests: URI[];
let existingTestFileCount: number;
before(async () => {
lwcTests = await vscode.workspace.findFiles(
new vscode.RelativePattern(
vscode.workspace.workspaceFolders![0],
'**/lwc/**/*.test.js'
)
);
existingTestFileCount = lwcTests.length;
});
describe('Test Indexer File Watcher', () => {
let onDidCreateEventEmitter: vscode.EventEmitter<vscode.Uri>;
let onDidChangeEventEmitter: vscode.EventEmitter<vscode.Uri>;
let onDidDeleteEventEmitter: vscode.EventEmitter<vscode.Uri>;
let readFileStub: SinonStub;
let mockFileSystemWatcher;
let createFileSystemWatcherStub: SinonStub<
[
vscode.GlobPattern,
(boolean | undefined)?,
(boolean | undefined)?,
(boolean | undefined)?
],
vscode.FileSystemWatcher
>;
let parseStub: SinonStub<
[string, (string | undefined)?, (boolean | undefined)?],
jestTestSupport.IParseResults
>;
beforeEach(async () => {
createFileSystemWatcherStub = stub(
vscode.workspace,
'createFileSystemWatcher'
);
onDidCreateEventEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidChangeEventEmitter = new vscode.EventEmitter<vscode.Uri>();
onDidDeleteEventEmitter = new vscode.EventEmitter<vscode.Uri>();
mockFileSystemWatcher = {
onDidCreate: onDidCreateEventEmitter.event,
onDidChange: onDidChangeEventEmitter.event,
onDidDelete: onDidDeleteEventEmitter.event
};
createFileSystemWatcherStub.returns(
mockFileSystemWatcher as vscode.FileSystemWatcher
);
const mockFile = `it('mockTestCase1', () => {})\nit('mockTestCase2', () => {})\n`;
readFileStub = stub(fs, 'readFileSync');
readFileStub.callsFake(fileName => {
return mockFile;
});
await lwcTestIndexer.configureAndIndex();
lwcTestIndexer.resetIndex();
});
afterEach(() => {
onDidCreateEventEmitter.dispose();
onDidChangeEventEmitter.dispose();
onDidDeleteEventEmitter.dispose();
createFileSystemWatcherStub.restore();
readFileStub.restore();
});
function assertTestCasesMatch(
actualTestFileInfo: TestFileInfo | undefined,
expectedFilePath: string
) {
const expectedTestCases = [
{
testFsPath: expectedFilePath,
testName: 'mockTestCase1'
},
{
testFsPath: expectedFilePath,
testName: 'mockTestCase2'
}
];
expect(
actualTestFileInfo!.testCasesInfo!.map(testCaseInfo => {
const { testName, testUri } = testCaseInfo;
return {
testFsPath: testUri.fsPath,
testName
};
})
).to.eql(expectedTestCases);
}
it('should update index on test file create', async () => {
let allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount);
const mockFilePath = /^win32/.test(process.platform)
? 'C:\\Users\\tester\\mockNewFile.test.js'
: '/Users/tester/mockNewFile.test.js';
const mockFileUri = URI.file(mockFilePath);
return new Promise(resolve => {
const handleDidUpdateTestIndex = lwcTestIndexer.onDidUpdateTestIndex(
async () => {
allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount + 1);
const createdTestFileInfo = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return testFileInfo.testUri.fsPath === mockFileUri.fsPath;
}
);
expect(createdTestFileInfo!.kind).to.equal(TestInfoKind.TEST_FILE);
expect(createdTestFileInfo!.testType).to.equal(TestType.LWC);
expect(createdTestFileInfo!.testLocation!.uri.fsPath).to.equal(
mockFileUri.fsPath
);
expect(
createdTestFileInfo!.testLocation!.range.start.line
).to.equal(0);
expect(
createdTestFileInfo!.testLocation!.range.start.character
).to.equal(0);
expect(createdTestFileInfo!.testLocation!.range.end.line).to.equal(
0
);
expect(
createdTestFileInfo!.testLocation!.range.end.character
).to.equal(0);
assertTestCasesMatch(createdTestFileInfo, mockFileUri.fsPath);
handleDidUpdateTestIndex.dispose();
resolve();
}
);
onDidCreateEventEmitter.fire(mockFileUri);
});
});
it('should update index on test file change', async () => {
const testFileUriToChange = lwcTests[0];
let allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount);
return new Promise(resolve => {
const handleDidUpdateTestIndex = lwcTestIndexer.onDidUpdateTestIndex(
async () => {
allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
const changedTestFileInfo = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return (
testFileInfo.testUri.fsPath === testFileUriToChange.fsPath
);
}
);
assertTestCasesMatch(
changedTestFileInfo,
testFileUriToChange.fsPath
);
handleDidUpdateTestIndex.dispose();
resolve();
}
);
onDidChangeEventEmitter.fire(testFileUriToChange);
});
});
it('should update index on test file change when parsing has an error', async () => {
// Mock parsing error
readFileStub.callsFake(fileName => {
throw new Error();
});
const testFileUriToChange = lwcTests[0];
let allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount);
return new Promise(resolve => {
const handleDidUpdateTestIndex = lwcTestIndexer.onDidUpdateTestIndex(
async () => {
allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
const changedTestFileInfo = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return (
testFileInfo.testUri.fsPath === testFileUriToChange.fsPath
);
}
);
// If there's a parsing error, expect empty test cases info
expect(changedTestFileInfo!.testCasesInfo).to.eql([]);
handleDidUpdateTestIndex.dispose();
resolve();
}
);
onDidChangeEventEmitter.fire(testFileUriToChange);
});
});
it('should update index on test file change and merge existing test results if possible', async () => {
const testFileUriToChange = lwcTests[0];
let allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount);
// Mock raw test results on test file info
// This could be test results generated from previous runs,
// we are making sure that it will get merged in test cases info when test file changes.
const testFileInfoToChange = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return testFileInfo.testUri.fsPath === testFileUriToChange.fsPath;
}
);
testFileInfoToChange!.rawTestResults = [
{
title: 'mockTestCase1',
ancestorTitles: [],
status: TestResultStatus.PASSED
},
{
title: 'mockTestCase2',
ancestorTitles: [],
status: TestResultStatus.FAILED
}
];
return new Promise(resolve => {
// Set up test file change handler
const handleDidUpdateTestIndex = lwcTestIndexer.onDidUpdateTestIndex(
async () => {
allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
const changedTestFileInfo = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return (
testFileInfo.testUri.fsPath === testFileUriToChange.fsPath
);
}
);
// Assert that raw test results status is merged into test cases info
const expectedTestCases = [
{
testFsPath: testFileUriToChange.fsPath,
testName: 'mockTestCase1',
testResult: {
status: TestResultStatus.PASSED
}
},
{
testFsPath: testFileUriToChange.fsPath,
testName: 'mockTestCase2',
testResult: {
status: TestResultStatus.FAILED
}
}
];
expect(
changedTestFileInfo!.testCasesInfo!.map(testCaseInfo => {
const { testName, testResult, testUri } = testCaseInfo;
return {
testFsPath: testUri.fsPath,
testName,
testResult
};
})
).to.eql(expectedTestCases);
// Restore
handleDidUpdateTestIndex.dispose();
testFileInfoToChange!.rawTestResults = undefined;
resolve();
}
);
// Changing the file
onDidChangeEventEmitter.fire(testFileUriToChange);
});
});
it('should update index on test file delete', async () => {
let allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount);
const testFileUriToDelete = lwcTests[0];
return new Promise(resolve => {
const handleDidUpdateTestIndex = lwcTestIndexer.onDidUpdateTestIndex(
async () => {
allTestFileInfo = await lwcTestIndexer.findAllTestFileInfo();
expect(allTestFileInfo.length).to.equal(existingTestFileCount - 1);
const deletedTestFileInfo = allTestFileInfo.find(
(testFileInfo: TestFileInfo) => {
return (
testFileInfo.testUri.fsPath === testFileUriToDelete.fsPath
);
}
);
expect(deletedTestFileInfo).to.be.an('undefined');
handleDidUpdateTestIndex.dispose();
resolve();
}
);
onDidDeleteEventEmitter.fire(testFileUriToDelete);
});
});
});
}); | the_stack |
import { asyncOra } from '@electron-forge/async-ora';
import PluginBase from '@electron-forge/plugin-base';
import { ElectronProcess, ForgeArch, ForgeConfig, ForgeHookFn, ForgePlatform } from '@electron-forge/shared-types';
import Logger, { Tab } from '@electron-forge/web-multi-logger';
import debug from 'debug';
import fs from 'fs-extra';
import http from 'http';
import { merge } from 'webpack-merge';
import path from 'path';
import { utils } from '@electron-forge/core';
import webpack, { Configuration, Watching } from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import { WebpackPluginConfig } from './Config';
import ElectronForgeLoggingPlugin from './util/ElectronForgeLogging';
import once from './util/once';
import WebpackConfigGenerator from './WebpackConfig';
const d = debug('electron-forge:plugin:webpack');
const DEFAULT_PORT = 3000;
const DEFAULT_LOGGER_PORT = 9000;
type WebpackToJsonOptions = Parameters<webpack.Stats['toJson']>[0];
type WebpackWatchHandler = Parameters<webpack.Compiler['watch']>[1];
export default class WebpackPlugin extends PluginBase<WebpackPluginConfig> {
name = 'webpack';
private isProd = false;
// The root of the Electron app
private projectDir!: string;
// Where the Webpack output is generated. Usually `$projectDir/.webpack`
private baseDir!: string;
private _configGenerator!: WebpackConfigGenerator;
private watchers: Watching[] = [];
private servers: http.Server[] = [];
private loggers: Logger[] = [];
private port = DEFAULT_PORT;
private loggerPort = DEFAULT_LOGGER_PORT;
constructor(c: WebpackPluginConfig) {
super(c);
if (c.port) {
if (this.isValidPort(c.port)) {
this.port = c.port;
}
}
if (c.loggerPort) {
if (this.isValidPort(c.loggerPort)) {
this.loggerPort = c.loggerPort;
}
}
this.startLogic = this.startLogic.bind(this);
this.getHook = this.getHook.bind(this);
}
private isValidPort = (port: number) => {
if (port < 1024) {
throw new Error(`Cannot specify port (${port}) below 1024, as they are privileged`);
} else if (port > 65535) {
throw new Error(`Port specified (${port}) is not a valid TCP port.`);
} else {
return true;
}
};
exitHandler = (options: { cleanup?: boolean; exit?: boolean }, err?: Error): void => {
d('handling process exit with:', options);
if (options.cleanup) {
for (const watcher of this.watchers) {
d('cleaning webpack watcher');
watcher.close(() => {
/* Do nothing when the watcher closes */
});
}
this.watchers = [];
for (const server of this.servers) {
d('cleaning http server');
server.close();
}
this.servers = [];
for (const logger of this.loggers) {
d('stopping logger');
logger.stop();
}
this.loggers = [];
}
if (err) console.error(err.stack);
// Why: This is literally what the option says to do.
// eslint-disable-next-line no-process-exit
if (options.exit) process.exit();
};
async writeJSONStats(type: string, stats: webpack.Stats | undefined, statsOptions: WebpackToJsonOptions): Promise<void> {
if (!stats) return;
d(`Writing JSON stats for ${type} config`);
const jsonStats = stats.toJson(statsOptions);
const jsonStatsFilename = path.resolve(this.baseDir, type, 'stats.json');
await fs.writeJson(jsonStatsFilename, jsonStats, { spaces: 2 });
}
// eslint-disable-next-line max-len
private runWebpack = async (options: Configuration, isRenderer = false): Promise<webpack.Stats | undefined> =>
new Promise((resolve, reject) => {
webpack(options).run(async (err, stats) => {
if (isRenderer && this.config.renderer.jsonStats) {
await this.writeJSONStats('renderer', stats, options.stats as WebpackToJsonOptions);
}
if (err) {
return reject(err);
}
return resolve(stats);
});
});
init = (dir: string): void => {
this.setDirectories(dir);
d('hooking process events');
process.on('exit', (_code) => this.exitHandler({ cleanup: true }));
process.on('SIGINT' as NodeJS.Signals, (_signal) => this.exitHandler({ exit: true }));
};
setDirectories = (dir: string): void => {
this.projectDir = dir;
this.baseDir = path.resolve(dir, '.webpack');
};
get configGenerator(): WebpackConfigGenerator {
// eslint-disable-next-line no-underscore-dangle
if (!this._configGenerator) {
// eslint-disable-next-line no-underscore-dangle
this._configGenerator = new WebpackConfigGenerator(this.config, this.projectDir, this.isProd, this.port);
}
// eslint-disable-next-line no-underscore-dangle
return this._configGenerator;
}
private loggedOutputUrl = false;
getHook(name: string): ForgeHookFn | null {
switch (name) {
case 'prePackage':
this.isProd = true;
return async (config: ForgeConfig, platform: ForgePlatform, arch: ForgeArch) => {
await fs.remove(this.baseDir);
await utils.rebuildHook(
this.projectDir,
await utils.getElectronVersion(this.projectDir, await fs.readJson(path.join(this.projectDir, 'package.json'))),
platform,
arch,
config.electronRebuildConfig
);
await this.compileMain();
await this.compileRenderers();
};
case 'postStart':
return async (_config: ForgeConfig, child: ElectronProcess) => {
if (!this.loggedOutputUrl) {
console.info(`\n\nWebpack Output Available: ${`http://localhost:${this.loggerPort}`.cyan}\n`);
this.loggedOutputUrl = true;
}
d('hooking electron process exit');
child.on('exit', () => {
if (child.restarted) return;
this.exitHandler({ cleanup: true, exit: true });
});
};
case 'resolveForgeConfig':
return this.resolveForgeConfig;
case 'packageAfterCopy':
return this.packageAfterCopy;
default:
return null;
}
}
resolveForgeConfig = async (forgeConfig: ForgeConfig): Promise<ForgeConfig> => {
if (!forgeConfig.packagerConfig) {
forgeConfig.packagerConfig = {};
}
if (forgeConfig.packagerConfig.ignore) {
if (typeof forgeConfig.packagerConfig.ignore !== 'function') {
console.error(
`You have set packagerConfig.ignore, the Electron Forge webpack plugin normally sets this automatically.
Your packaged app may be larger than expected if you dont ignore everything other than the '.webpack' folder`.red
);
}
return forgeConfig;
}
forgeConfig.packagerConfig.ignore = (file: string) => {
if (!file) return false;
if (this.config.jsonStats && file.endsWith(path.join('.webpack', 'main', 'stats.json'))) {
return true;
}
if (this.config.renderer.jsonStats && file.endsWith(path.join('.webpack', 'renderer', 'stats.json'))) {
return true;
}
return !/^[/\\]\.webpack($|[/\\]).*$/.test(file);
};
return forgeConfig;
};
packageAfterCopy = async (_forgeConfig: ForgeConfig, buildPath: string): Promise<void> => {
const pj = await fs.readJson(path.resolve(this.projectDir, 'package.json'));
if (!pj.main?.endsWith('.webpack/main')) {
throw new Error(`Electron Forge is configured to use the Webpack plugin. The plugin expects the
"main" entry point in "package.json" to be ".webpack/main" (where the plugin outputs
the generated files). Instead, it is ${JSON.stringify(pj.main)}`);
}
if (pj.config) {
delete pj.config.forge;
}
pj.devDependencies = {};
pj.dependencies = {};
pj.optionalDependencies = {};
pj.peerDependencies = {};
await fs.writeJson(path.resolve(buildPath, 'package.json'), pj, {
spaces: 2,
});
await fs.mkdirp(path.resolve(buildPath, 'node_modules'));
};
compileMain = async (watch = false, logger?: Logger): Promise<void> => {
let tab: Tab;
if (logger) {
tab = logger.createTab('Main Process');
}
await asyncOra('Compiling Main Process Code', async () => {
const mainConfig = this.configGenerator.getMainConfig();
await new Promise((resolve, reject) => {
const compiler = webpack(mainConfig);
const [onceResolve, onceReject] = once(resolve, reject);
const cb: WebpackWatchHandler = async (err, stats) => {
if (tab && stats) {
tab.log(
stats.toString({
colors: true,
})
);
}
if (this.config.jsonStats) {
await this.writeJSONStats('main', stats, mainConfig.stats as WebpackToJsonOptions);
}
if (err) return onceReject(err);
if (!watch && stats?.hasErrors()) {
return onceReject(new Error(`Compilation errors in the main process: ${stats.toString()}`));
}
return onceResolve(undefined);
};
if (watch) {
this.watchers.push(compiler.watch({}, cb));
} else {
compiler.run(cb);
}
});
});
};
compileRenderers = async (watch = false): Promise<void> => {
await asyncOra('Compiling Renderer Template', async () => {
const stats = await this.runWebpack(await this.configGenerator.getRendererConfig(this.config.renderer.entryPoints), true);
if (!watch && stats?.hasErrors()) {
throw new Error(`Compilation errors in the renderer: ${stats.toString()}`);
}
});
for (const entryPoint of this.config.renderer.entryPoints) {
if (entryPoint.preload) {
await asyncOra(`Compiling Renderer Preload: ${entryPoint.name}`, async () => {
const stats = await this.runWebpack(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
await this.configGenerator.getPreloadRendererConfig(entryPoint, entryPoint.preload!)
);
if (stats?.hasErrors()) {
throw new Error(`Compilation errors in the preload (${entryPoint.name}): ${stats.toString()}`);
}
});
}
}
};
launchDevServers = async (logger: Logger): Promise<void> => {
await asyncOra('Launch Dev Servers', async () => {
const tab = logger.createTab('Renderers');
const pluginLogs = new ElectronForgeLoggingPlugin(tab);
const config = await this.configGenerator.getRendererConfig(this.config.renderer.entryPoints);
if (!config.plugins) config.plugins = [];
config.plugins.push(pluginLogs);
const compiler = webpack(config);
const webpackDevServer = new WebpackDevServer(this.devServerOptions(), compiler);
await webpackDevServer.start();
this.servers.push(webpackDevServer.server);
});
await asyncOra('Compiling Preload Scripts', async () => {
for (const entryPoint of this.config.renderer.entryPoints) {
if (entryPoint.preload) {
const config = await this.configGenerator.getPreloadRendererConfig(
entryPoint,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
entryPoint.preload!
);
await new Promise((resolve, reject) => {
const tab = logger.createTab(`${entryPoint.name} - Preload`);
const [onceResolve, onceReject] = once(resolve, reject);
this.watchers.push(
webpack(config).watch({}, (err, stats) => {
if (stats) {
tab.log(
stats.toString({
colors: true,
})
);
}
if (err) return onceReject(err);
return onceResolve(undefined);
})
);
});
}
}
});
};
devServerOptions(): Record<string, unknown> {
const cspDirectives =
this.config.devContentSecurityPolicy ?? "default-src 'self' 'unsafe-inline' data:; script-src 'self' 'unsafe-eval' 'unsafe-inline' data:";
const defaults = {
hot: true,
devMiddleware: {
writeToDisk: true,
},
historyApiFallback: true,
};
const overrides = {
port: this.port,
setupExitSignals: true,
static: path.resolve(this.baseDir, 'renderer'),
headers: {
'Content-Security-Policy': cspDirectives,
},
};
return merge(defaults, this.config.devServer ?? {}, overrides);
}
private alreadyStarted = false;
async startLogic(): Promise<false> {
if (this.alreadyStarted) return false;
this.alreadyStarted = true;
await fs.remove(this.baseDir);
const logger = new Logger(this.loggerPort);
this.loggers.push(logger);
await this.compileMain(true, logger);
await this.launchDevServers(logger);
await logger.start();
return false;
}
} | the_stack |
import defaultMessagingSettings from "../../../../main/js/joynr/start/settings/defaultMessagingSettings";
import MessagingQos from "../../../../main/js/joynr/messaging/MessagingQos";
import * as MessagingQosEffort from "../../../../main/js/joynr/messaging/MessagingQosEffort";
describe("libjoynr-js.joynr.messaging.MessagingQos", () => {
it("is instantiable", () => {
expect(new MessagingQos()).toBeDefined();
expect(
new MessagingQos({
ttl: 60000
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
effort: MessagingQosEffort.BEST_EFFORT
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
encrypt: true
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
effort: MessagingQosEffort.BEST_EFFORT,
encrypt: true
})
).toBeDefined();
expect(
new MessagingQos({
effort: MessagingQosEffort.BEST_EFFORT,
encrypt: true
})
).toBeDefined();
expect(
new MessagingQos({
encrypt: true
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
effort: MessagingQosEffort.BEST_EFFORT,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
effort: MessagingQosEffort.BEST_EFFORT,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
encrypt: true,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
ttl: 60000,
effort: MessagingQosEffort.BEST_EFFORT,
encrypt: true,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
effort: MessagingQosEffort.BEST_EFFORT,
encrypt: true,
compress: true
})
).toBeDefined();
expect(
new MessagingQos({
compress: true,
encrypt: true
})
).toBeDefined();
});
it("is of correct type", () => {
const emptyMessagingQos = new MessagingQos();
expect(emptyMessagingQos).toBeDefined();
expect(emptyMessagingQos).not.toBeNull();
expect(typeof emptyMessagingQos === "object").toBeTruthy();
expect(emptyMessagingQos).toBeInstanceOf(MessagingQos);
const defaultMessagingQos = new MessagingQos();
expect(defaultMessagingQos).toBeDefined();
expect(defaultMessagingQos).not.toBeNull();
expect(typeof defaultMessagingQos === "object").toBeTruthy();
expect(defaultMessagingQos).toBeInstanceOf(MessagingQos);
});
it("constructs correct default object", () => {
expect(new MessagingQos()).toEqual(
new MessagingQos({
ttl: MessagingQos.DEFAULT_TTL
})
);
expect(new MessagingQos().encrypt).toEqual(false);
expect(new MessagingQos().compress).toEqual(false);
});
function testTtlValues(ttl: number) {
const messagingQos = new MessagingQos({
ttl
});
expect(messagingQos.ttl).toBe(ttl);
}
it("constructs with correct TTL values", () => {
testTtlValues(123456);
testTtlValues(0);
testTtlValues(-123456);
});
it("prevents ttl values larger than maxTtl", () => {
expect(
new MessagingQos({
ttl: defaultMessagingSettings.MAX_MESSAGING_TTL_MS + 1
})
).toEqual(
new MessagingQos({
ttl: defaultMessagingSettings.MAX_MESSAGING_TTL_MS
})
);
});
function testEffortValues(effort: any, expected: any) {
const messagingQos = new MessagingQos({
effort
});
expect(messagingQos.effort).toBe(expected);
}
it("constructs with correct effort values", () => {
testEffortValues(MessagingQosEffort.NORMAL, MessagingQosEffort.NORMAL);
testEffortValues(MessagingQosEffort.BEST_EFFORT, MessagingQosEffort.BEST_EFFORT);
testEffortValues(null, MessagingQosEffort.NORMAL);
testEffortValues("not an enum value", MessagingQosEffort.NORMAL);
});
function testEncryptValues(encrypt: any) {
const messagingQos = new MessagingQos({
encrypt
});
expect(messagingQos.encrypt).toBe(encrypt);
}
it("constructs with correct encrypt values", () => {
testEncryptValues(false);
testEncryptValues(true);
});
function testCompressValues(compress: any) {
const messagingQos = new MessagingQos({
compress
});
expect(messagingQos.compress).toBe(compress);
}
it("constructs with correct compress values", () => {
testCompressValues(false);
testCompressValues(true);
});
const runsWithCustomHeaders = [
{
params: {
key: "key",
value: "value"
},
ok: true
},
{
params: {
key: "1key",
value: "1value"
},
ok: true
},
{
params: {
key: "key1",
value: "value1"
},
ok: true
},
{
params: {
key: "key-1",
value: "value1"
},
ok: true
},
{
params: {
key: "123",
value: "123"
},
ok: true
},
{
params: {
key: "key",
value: "one two"
},
ok: true
},
{
params: {
key: "key",
value: "one;two"
},
ok: true
},
{
params: {
key: "key",
value: "one:two"
},
ok: true
},
{
params: {
key: "key",
value: "one,two"
},
ok: true
},
{
params: {
key: "key",
value: "one+two"
},
ok: true
},
{
params: {
key: "key",
value: "one&two"
},
ok: true
},
{
params: {
key: "key",
value: "one?two"
},
ok: true
},
{
params: {
key: "key",
value: "one-two"
},
ok: true
},
{
params: {
key: "key",
value: "one.two"
},
ok: true
},
{
params: {
key: "key",
value: "one*two"
},
ok: true
},
{
params: {
key: "key",
value: "one/two"
},
ok: true
},
{
params: {
key: "key",
value: "one\\two"
},
ok: true
},
{
params: {
key: "z4",
value: "ZbNk-PPNRwu39RhtIYysJw"
},
ok: true
},
{
params: {
key: "z4",
value: "Hmkjq8OoTjub1gXzv3QkZg"
},
ok: true
},
{
params: {
key: "z4",
value: "Pc_oYOf2SOK6r3zM2HAvnQ"
},
ok: true
},
{
params: {
key: "key",
value: "wrongvalue$"
},
ok: false
},
{
params: {
key: "key",
value: "wrongvalue%"
},
ok: false
},
{
params: {
key: "wrongkey ",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey;",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey:",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey,",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey+",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey&",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey?",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey.",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey*",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey/",
value: "value"
},
ok: false
},
{
params: {
key: "wrongkey\\",
value: "value"
},
ok: false
}
];
runsWithCustomHeaders.forEach((run: any) => {
const expectedTo = run.ok ? "passes" : "fails";
const params = run.params;
it(`setting custom header ${expectedTo} when key: ${params.key} value: ${params.value}`, () => {
const key = params.key;
const value = params.value;
const messagingQos = new MessagingQos();
if (run.ok) {
messagingQos.putCustomMessageHeader(key, value);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(messagingQos.customHeaders![key]).toEqual(value);
} else {
expect(() => {
messagingQos.putCustomMessageHeader(key, value);
}).toThrow();
}
});
});
}); | the_stack |
import Dexie from 'dexie';
import 'dexie-export-import';
import 'fake-indexeddb/auto';
import * as idb from 'idb';
import { DataStore, SortDirection } from '../src/index';
import { DATASTORE, SYNC, USER } from '../src/util';
import {
Author,
Blog,
BlogOwner,
Comment,
Nested,
Post,
PostAuthorJoin,
PostMetadata,
Person,
} from './model';
let db: idb.IDBPDatabase;
const indexedDB = require('fake-indexeddb');
const IDBKeyRange = require('fake-indexeddb/lib/FDBKeyRange');
Dexie.dependencies.indexedDB = indexedDB;
Dexie.dependencies.IDBKeyRange = IDBKeyRange;
describe('Indexed db storage test', () => {
let blog: InstanceType<typeof Blog>,
blog2: InstanceType<typeof Blog>,
blog3: InstanceType<typeof Blog>,
owner: InstanceType<typeof BlogOwner>,
owner2: InstanceType<typeof BlogOwner>;
beforeAll(async () => {
await DataStore.start();
db = await idb.openDB('amplify-datastore', 2);
});
beforeEach(async () => {
owner = new BlogOwner({ name: 'Owner 1' });
owner2 = new BlogOwner({ name: 'Owner 2' });
blog = new Blog({
name: 'Avatar: Last Airbender',
owner,
});
blog2 = new Blog({
name: 'blog2',
owner: owner2,
});
blog3 = new Blog({
name: 'Avatar 101',
owner: new BlogOwner({ name: 'owner 3' }),
});
});
test('setup function', async () => {
const createdObjStores = db.objectStoreNames;
const expectedStores = [
`${DATASTORE}_Setting`,
`${SYNC}_ModelMetadata`,
`${SYNC}_MutationEvent`,
`${USER}_Author`,
`${USER}_Blog`,
`${USER}_BlogOwner`,
`${USER}_Comment`,
`${USER}_Person`,
`${USER}_Post`,
`${USER}_PostAuthorJoin`,
];
expect(createdObjStores).toHaveLength(expectedStores.length);
expect(expectedStores).toMatchObject(createdObjStores);
expect(createdObjStores).not.toContain(`${USER}_blah`);
// TODO: better way to get this
const commentStore = (<any>db)._rawDatabase.rawObjectStores.get(
`${USER}_Comment`
);
const postAuthorStore = (<any>db)._rawDatabase.rawObjectStores.get(
`${USER}_PostAuthorJoin`
);
expect(commentStore.rawIndexes.has('byId')).toBe(true); // checks byIdIndex
expect(postAuthorStore.rawIndexes.has('byId')).toBe(true); // checks byIdIndex
expect(commentStore.rawIndexes.has('commentPostId')).toBe(true); // checks 1:M
expect(postAuthorStore.rawIndexes.has('postId')).toBe(true); // checks M:M
expect(postAuthorStore.rawIndexes.has('authorId')).toBe(true); // checks M:M
});
test('save function 1:1 insert', async () => {
await DataStore.save(blog);
await DataStore.save(owner);
const get1 = await db
.transaction(`${USER}_Blog`, 'readonly')
.objectStore(`${USER}_Blog`)
.index('byId')
.get(blog.id);
expect(get1).toBeDefined();
expect([...Object.keys(blog).sort(), 'blogOwnerId']).toEqual(
expect.arrayContaining(Object.keys(get1).sort())
);
expect(get1['blogOwnerId']).toBe(owner.id);
const get2 = await db
.transaction(`${USER}_BlogOwner`, 'readonly')
.objectStore(`${USER}_BlogOwner`)
.index('byId')
.get(owner.id);
expect([...Object.keys(owner)].sort()).toEqual(
expect.arrayContaining(Object.keys(get2).sort())
);
await DataStore.save(blog2);
const get3 = await db
.transaction(`${USER}_Blog`, 'readonly')
.objectStore(`${USER}_Blog`)
.index('byId')
.get(blog2.id);
expect([...Object.keys(blog2).sort(), 'blogOwnerId']).toEqual(
expect.arrayContaining(Object.keys(get3).sort())
);
});
test('save stores non-model types along the item (including nested)', async () => {
const p = new Post({
title: 'Avatar',
blog,
metadata: new PostMetadata({
rating: 3,
tags: ['a', 'b', 'c'],
nested: new Nested({
aField: 'Some value',
}),
}),
});
await DataStore.save(p);
const postFromDB = await db
.transaction(`${USER}_Post`, 'readonly')
.objectStore(`${USER}_Post`)
.index('byId')
.get(p.id);
expect(postFromDB.metadata).toMatchObject({
rating: 3,
tags: ['a', 'b', 'c'],
nested: new Nested({
aField: 'Some value',
}),
});
});
test('save function 1:M insert', async () => {
// test 1:M
const p = new Post({
title: 'Avatar',
blog,
});
const c1 = new Comment({ content: 'comment 1', post: p });
await DataStore.save(c1);
const getComment = await db
.transaction(`${USER}_Comment`, 'readonly')
.objectStore(`${USER}_Comment`)
.index('byId')
.get(c1.id);
expect([...Object.keys(c1), 'commentPostId'].sort()).toEqual(
expect.arrayContaining(Object.keys(getComment).sort())
);
const checkIndex = await db
.transaction(`${USER}_Comment`, 'readonly')
.objectStore(`${USER}_Comment`)
.index('commentPostId')
.get(p.id);
expect(checkIndex['commentPostId']).toEqual(p.id);
});
test('save function M:M insert', async () => {
const post = new Post({
title: 'Avatar',
blog,
});
await DataStore.save(post);
const getPost = await db
.transaction(`${USER}_Post`, 'readonly')
.objectStore(`${USER}_Post`)
.index('byId')
.get(post.id);
expect(getPost.author).toBeUndefined();
const a1 = new Author({ name: 'author1' });
const a2 = new Author({ name: 'author2' });
await DataStore.save(a1);
await DataStore.save(a2);
const getA1 = await db
.transaction(`${USER}_Author`, 'readonly')
.objectStore(`${USER}_Author`)
.index('byId')
.get(a1.id);
expect(getA1.name).toEqual('author1');
const getA2 = await db
.transaction(`${USER}_Author`, 'readonly')
.objectStore(`${USER}_Author`)
.index('byId')
.get(a2.id);
expect(getA2.name).toEqual('author2');
await DataStore.save(new PostAuthorJoin({ post, author: a1 }));
await DataStore.save(new PostAuthorJoin({ post, author: a2 }));
const p2 = new Post({ title: 'q', blog });
await DataStore.save(new PostAuthorJoin({ post: p2, author: a2 }));
const getAuthors = await db
.transaction(`${USER}_PostAuthorJoin`)
.objectStore(`${USER}_PostAuthorJoin`)
.index('postId')
.getAll(post.id);
expect(getAuthors).toHaveLength(2);
});
test('save update', async () => {
await DataStore.save(blog);
await DataStore.save(owner);
const get1 = await db
.transaction(`${USER}_Blog`, 'readonly')
.objectStore(`${USER}_Blog`)
.index('byId')
.get(blog.id);
expect(get1['blogOwnerId']).toBe(owner.id);
const updated = Blog.copyOf(blog, draft => {
draft.name = 'Avatar: The Last Airbender';
});
await DataStore.save(updated);
const get2 = await db
.transaction(`${USER}_Blog`, 'readonly')
.objectStore(`${USER}_Blog`)
.index('byId')
.get(blog.id);
expect(get2.name).toEqual(updated.name);
});
test('query function 1:1', async () => {
const res = await DataStore.save(blog);
await DataStore.save(owner);
const query = await DataStore.query(Blog, blog.id);
expect(query).toEqual(res);
await DataStore.save(blog3);
const query1 = await DataStore.query(Blog);
query1.forEach(item => {
if (item.owner) {
expect(item.owner).toHaveProperty('name');
}
});
});
test('query M:1 eager load', async () => {
const p = new Post({
title: 'Avatar',
blog,
});
const c1 = new Comment({ content: 'comment 1', post: p });
const c2 = new Comment({ content: 'comment 2', post: p });
await DataStore.save(p);
await DataStore.save(c1);
await DataStore.save(c2);
const q1 = await DataStore.query(Comment, c1.id);
expect(q1.post.id).toEqual(p.id);
});
test('query with sort on a single field', async () => {
const p1 = new Person({
firstName: 'John',
lastName: 'Snow',
});
const p2 = new Person({
firstName: 'Clem',
lastName: 'Fandango',
});
const p3 = new Person({
firstName: 'Beezus',
lastName: 'Fuffoon',
});
const p4 = new Person({
firstName: 'Meow Meow',
lastName: 'Fuzzyface',
});
await DataStore.save(p1);
await DataStore.save(p2);
await DataStore.save(p3);
await DataStore.save(p4);
const sortedPersons = await DataStore.query(Person, null, {
page: 0,
limit: 20,
sort: s => s.firstName(SortDirection.DESCENDING),
});
expect(sortedPersons[0].firstName).toEqual('Meow Meow');
expect(sortedPersons[1].firstName).toEqual('John');
expect(sortedPersons[2].firstName).toEqual('Clem');
expect(sortedPersons[3].firstName).toEqual('Beezus');
});
test('query with sort on multiple fields', async () => {
const p1 = new Person({
firstName: 'John',
lastName: 'Snow',
username: 'johnsnow',
});
const p2 = new Person({
firstName: 'John',
lastName: 'Umber',
username: 'smalljohnumber',
});
const p3 = new Person({
firstName: 'John',
lastName: 'Umber',
username: 'greatjohnumber',
});
await DataStore.save(p1);
await DataStore.save(p2);
await DataStore.save(p3);
const sortedPersons = await DataStore.query(
Person,
c => c.username('ne', undefined),
{
page: 0,
limit: 20,
sort: s =>
s
.firstName(SortDirection.ASCENDING)
.lastName(SortDirection.ASCENDING)
.username(SortDirection.ASCENDING),
}
);
expect(sortedPersons[0].username).toEqual('johnsnow');
expect(sortedPersons[1].username).toEqual('greatjohnumber');
expect(sortedPersons[2].username).toEqual('smalljohnumber');
});
test('delete 1:1 function', async () => {
await DataStore.save(blog);
await DataStore.save(owner);
await DataStore.delete(Blog, blog.id);
await DataStore.delete(BlogOwner, owner.id);
expect(await DataStore.query(BlogOwner, owner.id)).toBeUndefined();
expect(await DataStore.query(Blog, blog.id)).toBeUndefined();
await DataStore.save(owner);
await DataStore.save(owner2);
await DataStore.save(
Blog.copyOf(blog, draft => {
draft;
})
);
await DataStore.save(blog2);
await DataStore.save(blog3);
await DataStore.delete(Blog, c => c.name('beginsWith', 'Avatar'));
expect(await DataStore.query(Blog, blog.id)).toBeUndefined();
expect(await DataStore.query(Blog, blog2.id)).toBeDefined();
expect(await DataStore.query(Blog, blog3.id)).toBeUndefined();
});
test('delete M:1 function', async () => {
const post = new Post({
title: 'Avatar',
blog,
});
const c1 = new Comment({ content: 'c1', post });
const c2 = new Comment({ content: 'c2', post });
await DataStore.save(post);
await DataStore.save(c1);
await DataStore.save(c2);
await DataStore.delete(Comment, c1.id);
expect(await DataStore.query(Comment, c1.id)).toBeUndefined;
expect((await DataStore.query(Comment, c2.id)).id).toEqual(c2.id);
});
test('delete 1:M function', async () => {
const post = new Post({
title: 'Avatar 1',
blog,
});
const post2 = new Post({
title: 'Avatar 2',
blog,
});
await DataStore.save(post);
await DataStore.save(post2);
const c1 = new Comment({ content: 'c1', post });
const c2 = new Comment({ content: 'c2', post });
const c3 = new Comment({ content: 'c3', post: post2 });
await DataStore.save(c1);
await DataStore.save(c2);
await DataStore.save(c3);
await DataStore.delete(Post, post.id);
expect(await DataStore.query(Comment, c1.id)).toBeUndefined();
expect(await DataStore.query(Comment, c2.id)).toBeUndefined();
expect((await DataStore.query(Comment, c3.id)).id).toEqual(c3.id);
expect(await DataStore.query(Post, post.id)).toBeUndefined();
});
test('delete M:M function', async () => {
const a1 = new Author({ name: 'author1' });
const a2 = new Author({ name: 'author2' });
const a3 = new Author({ name: 'author3' });
const blog = new Blog({ name: 'B1', owner: new BlogOwner({ name: 'O1' }) });
const post = new Post({
title: 'Avatar',
blog,
});
const post2 = new Post({
title: 'Avatar 2',
blog,
});
await DataStore.save(post);
await DataStore.save(post2);
await DataStore.delete(Post, post.id);
const res = await db
.transaction('user_PostAuthorJoin', 'readwrite')
.objectStore('user_PostAuthorJoin')
.index('postId')
.getAll(post.id);
expect(res).toHaveLength(0);
await DataStore.delete(Post, c => c);
await DataStore.delete(Author, c => c);
});
test('delete cascade', async () => {
const a1 = await DataStore.save(new Author({ name: 'author1' }));
const a2 = await DataStore.save(new Author({ name: 'author2' }));
const blog = new Blog({
name: 'The Blog',
owner,
});
const p1 = new Post({
title: 'Post 1',
blog,
});
const p2 = new Post({
title: 'Post 2',
blog,
});
const c1 = await DataStore.save(new Comment({ content: 'c1', post: p1 }));
const c2 = await DataStore.save(new Comment({ content: 'c2', post: p1 }));
await DataStore.save(p1);
await DataStore.save(p2);
await DataStore.save(blog);
await DataStore.delete(BlogOwner, owner.id);
expect(await DataStore.query(Blog, blog.id)).toBeUndefined();
expect(await DataStore.query(BlogOwner, owner.id)).toBeUndefined();
expect(await DataStore.query(Post, p1.id)).toBeUndefined();
expect(await DataStore.query(Post, p2.id)).toBeUndefined();
expect(await DataStore.query(Comment, c1.id)).toBeUndefined();
expect(await DataStore.query(Comment, c2.id)).toBeUndefined();
expect(await DataStore.query(Author, a1.id)).toEqual(a1);
expect(await DataStore.query(Author, a2.id)).toEqual(a2);
const refResult = await db
.transaction(`${USER}_PostAuthorJoin`, 'readonly')
.objectStore(`${USER}_PostAuthorJoin`)
.index('postId')
.getAll(p1.id);
expect(refResult).toHaveLength(0);
});
test('delete non existent', async () => {
const author = new Author({ name: 'author1' });
const deleted = await DataStore.delete(author);
expect(deleted).toStrictEqual(author);
const fromDB = await db
.transaction(`${USER}_Author`, 'readonly')
.objectStore(`${USER}_Author`)
.get(author.id);
expect(fromDB).toBeUndefined();
});
});
describe('DB versions migration', () => {
beforeEach(async () => {
db.close();
await DataStore.clear();
});
test('Migration from v1 to v2', async () => {
const v1Data = require('./v1schema.data.json');
const blob = new Blob([JSON.stringify(v1Data)], {
type: 'application/json',
});
// Import V1
(await Dexie.import(blob)).close();
// Migrate to V2
await DataStore.start();
// Open V2
db = await idb.openDB('amplify-datastore', 2);
expect([...db.objectStoreNames].sort()).toMatchObject(
[
...v1Data.data.tables.map(({ name }) => name),
// Simulate Comment model added after IndexedDB was created,
// but before migration
`${USER}_Comment`,
`${USER}_Person`,
].sort()
);
for (const storeName of db.objectStoreNames) {
expect(db.transaction(storeName).store.indexNames).toContain('byId');
}
const dexie = await new Dexie('amplify-datastore').open();
const exportedBlob = await dexie.export();
function readBlob(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onabort = ev => reject(new Error('file read aborted'));
reader.onerror = ev => reject((ev.target as any).error);
reader.onload = ev => resolve((ev.target as any).result);
reader.readAsText(blob);
});
}
const exportedJSON = await readBlob(exportedBlob);
const exported = JSON.parse(exportedJSON);
for (const { schema } of exported.data.tables) {
expect(schema.split(',')).toContain('&id');
}
expect(exported).toMatchSnapshot('v2-schema');
});
}); | the_stack |
import action from '../src/action';
import * as utils from '../src/utils';
import * as github from '../src/github';
import * as core from '@actions/core';
import {
loadDefaultInputs,
setBranch,
setCommitSha,
setInput,
} from './helper.test';
jest.spyOn(core, 'debug').mockImplementation(() => {});
jest.spyOn(core, 'info').mockImplementation(() => {});
jest.spyOn(console, 'info').mockImplementation(() => {});
const mockCreateTag = jest
.spyOn(github, 'createTag')
.mockResolvedValue(undefined);
const mockSetOutput = jest
.spyOn(core, 'setOutput')
.mockImplementation(() => {});
const mockSetFailed = jest.spyOn(core, 'setFailed');
describe('github-tag-action', () => {
beforeEach(() => {
jest.clearAllMocks();
setBranch('master');
setCommitSha('79e0ea271c26aa152beef77c3275ff7b8f8d8274');
loadDefaultInputs();
});
describe('special cases', () => {
it('does create initial tag', async () => {
/*
* Given
*/
const commits = [{ message: 'fix: this is my first fix', hash: null }];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags: any[] = [];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v0.0.1',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create patch tag without commits', async () => {
/*
* Given
*/
const commits: any[] = [];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags: any[] = [];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v0.0.1',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does not create tag without commits and default_bump set to false', async () => {
/*
* Given
*/
setInput('default_bump', 'false');
const commits: any[] = [];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).not.toBeCalled();
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag using custom release types', async () => {
/*
* Given
*/
setInput('custom_release_rules', 'james:patch,bond:major');
const commits = [
{ message: 'james: is the new cool guy', hash: null },
{ message: 'bond: is his last name', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v2.0.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag using custom release types but non-custom commit message', async () => {
/*
* Given
*/
setInput('custom_release_rules', 'james:patch,bond:major');
const commits = [
{ message: 'fix: is the new cool guy', hash: null },
{ message: 'feat: is his last name', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.3.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
});
describe('release branches', () => {
beforeEach(() => {
jest.clearAllMocks();
setBranch('release');
setInput('release_branches', 'release');
});
it('does create patch tag', async () => {
/*
* Given
*/
const commits = [{ message: 'fix: this is my first fix', hash: null }];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.2.4',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create minor tag', async () => {
/*
* Given
*/
const commits = [
{ message: 'feat: this is my first feature', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.3.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create major tag', async () => {
/*
* Given
*/
const commits = [
{
message:
'my commit message\nBREAKING CHANGE:\nthis is a breaking change',
hash: null,
},
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v2.0.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag when pre-release tag is newer', async () => {
/*
* Given
*/
const commits = [
{ message: 'feat: some new feature on a release branch', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
{
name: 'v2.1.3-prerelease.0',
commit: { sha: '678901', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
{
name: 'v2.1.3-prerelease.1',
commit: { sha: '234567', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v2.2.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag with custom release rules', async () => {
/*
* Given
*/
setInput('custom_release_rules', 'james:preminor');
const commits = [
{
message: 'feat: some new feature on a pre-release branch',
hash: null,
},
{ message: 'james: this should make a preminor', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.3.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
});
describe('pre-release branches', () => {
beforeEach(() => {
jest.clearAllMocks();
setBranch('prerelease');
setInput('pre_release_branches', 'prerelease');
});
it('does create prepatch tag', async () => {
/*
* Given
*/
const commits = [{ message: 'fix: this is my first fix', hash: null }];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.2.4-prerelease.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create preminor tag', async () => {
/*
* Given
*/
const commits = [
{ message: 'feat: this is my first feature', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.3.0-prerelease.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create premajor tag', async () => {
/*
* Given
*/
const commits = [
{
message:
'my commit message\nBREAKING CHANGE:\nthis is a breaking change',
hash: null,
},
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v2.0.0-prerelease.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag when release tag is newer', async () => {
/*
* Given
*/
const commits = [
{
message: 'feat: some new feature on a pre-release branch',
hash: null,
},
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3-prerelease.0',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
{
name: 'v3.1.2-feature.0',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
{
name: 'v2.1.4',
commit: { sha: '234567', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v2.2.0-prerelease.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
it('does create tag with custom release rules', async () => {
/*
* Given
*/
setInput('custom_release_rules', 'james:preminor');
const commits = [
{
message: 'feat: some new feature on a pre-release branch',
hash: null,
},
{ message: 'james: this should make a preminor', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockCreateTag).toHaveBeenCalledWith(
'v1.3.0-prerelease.0',
expect.any(Boolean),
expect.any(String)
);
expect(mockSetFailed).not.toBeCalled();
});
});
describe('other branches', () => {
beforeEach(() => {
jest.clearAllMocks();
setBranch('development');
setInput('pre_release_branches', 'prerelease');
setInput('release_branches', 'release');
});
it('does output patch tag', async () => {
/*
* Given
*/
const commits = [{ message: 'fix: this is my first fix', hash: null }];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockSetOutput).toHaveBeenCalledWith('new_version', '1.2.4');
expect(mockCreateTag).not.toBeCalled();
expect(mockSetFailed).not.toBeCalled();
});
it('does output minor tag', async () => {
/*
* Given
*/
const commits = [
{ message: 'feat: this is my first feature', hash: null },
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockSetOutput).toHaveBeenCalledWith('new_version', '1.3.0');
expect(mockCreateTag).not.toBeCalled();
expect(mockSetFailed).not.toBeCalled();
});
it('does output major tag', async () => {
/*
* Given
*/
const commits = [
{
message:
'my commit message\nBREAKING CHANGE:\nthis is a breaking change',
hash: null,
},
];
jest
.spyOn(utils, 'getCommits')
.mockImplementation(async (sha) => commits);
const validTags = [
{
name: 'v1.2.3',
commit: { sha: '012345', url: '' },
zipball_url: '',
tarball_url: 'string',
node_id: 'string',
},
];
jest
.spyOn(utils, 'getValidTags')
.mockImplementation(async () => validTags);
/*
* When
*/
await action();
/*
* Then
*/
expect(mockSetOutput).toHaveBeenCalledWith('new_version', '2.0.0');
expect(mockCreateTag).not.toBeCalled();
expect(mockSetFailed).not.toBeCalled();
});
});
}); | the_stack |
import {
actionDec,
actionDecSep,
ActionTok,
atLeastOneRule,
atLeastOneSepRule,
callArguments,
ColonTok,
CommaTok,
DotTok,
IdentTok,
LParenTok,
LSquareTok,
paramSpec,
qualifiedNameSep,
RParenTok,
RSquareTok,
SemicolonTok
} from "./samples"
import {
NextAfterTokenWalker,
nextPossibleTokensAfter,
NextTerminalAfterAtLeastOneSepWalker,
NextTerminalAfterAtLeastOneWalker,
NextTerminalAfterManySepWalker,
NextTerminalAfterManyWalker,
possiblePathsFrom
} from "../../../src/parse/grammar/interpreter"
import { createRegularToken, setEquality } from "../../utils/matchers"
import { createToken } from "../../../src/scan/tokens_public"
import { map } from "@chevrotain/utils"
import { Lexer } from "../../../src/scan/lexer_public"
import {
augmentTokenTypes,
tokenStructuredMatcher
} from "../../../src/scan/tokens"
import { EmbeddedActionsParser } from "../../../src/parse/parser/traits/parser_traits"
import {
Alternation,
Alternative,
Repetition,
RepetitionWithSeparator,
Rule,
Terminal,
Option,
RepetitionMandatory,
NonTerminal,
RepetitionMandatoryWithSeparator
} from "../../../src/parse/grammar/gast/gast_public"
import { IToken, ITokenGrammarPath, TokenType } from "@chevrotain/types"
import { expect } from "chai"
describe("The Grammar Interpeter namespace", () => {
describe("The NextAfterTokenWalker", () => {
it("can compute the next possible token types From ActionDec in scope of ActionDec #1", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: ActionTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #2", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: IdentTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(LParenTok)
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #3", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: LParenTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [IdentTok, RParenTok])
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #4", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: CommaTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #5", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: RParenTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [SemicolonTok, ColonTok])
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #6", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: ColonTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
})
it("can compute the next possible token types From ActionDec in scope of ActionDec #7", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec"],
occurrenceStack: [1],
lastTok: SemicolonTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(0)
})
it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #1", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 1],
lastTok: IdentTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(ColonTok)
})
it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #2", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 1],
lastTok: ColonTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
})
it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #3", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 1],
lastTok: LSquareTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(RSquareTok)
})
it("can compute the next possible token types From the first paramSpec INSIDE ActionDec #4", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 1],
lastTok: RSquareTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [CommaTok, RParenTok])
})
it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #1", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 2],
lastTok: IdentTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(ColonTok)
})
it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #2", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 2],
lastTok: ColonTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
})
it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #3", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 2],
lastTok: LSquareTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(RSquareTok)
})
it("can compute the next possible token types From the second paramSpec INSIDE ActionDec #4", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec"],
occurrenceStack: [1, 2],
lastTok: RSquareTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [CommaTok, RParenTok])
})
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #1",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec", "qualifiedName"],
occurrenceStack: [1, 1, 1],
lastTok: IdentTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(4)
setEquality(possibleNextTokTypes, [
DotTok,
LSquareTok,
CommaTok,
RParenTok
])
}
)
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #2",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec", "qualifiedName"],
occurrenceStack: [1, 1, 1],
lastTok: DotTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
}
)
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #3",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["actionDec", "paramSpec", "qualifiedName"],
occurrenceStack: [1, 1, 1],
lastTok: IdentTok,
lastTokOccurrence: 2
}
const possibleNextTokTypes = new NextAfterTokenWalker(
actionDec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(4)
setEquality(possibleNextTokTypes, [
DotTok,
LSquareTok,
CommaTok,
RParenTok
])
}
)
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #3",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["paramSpec", "qualifiedName"],
occurrenceStack: [1, 1],
lastTok: IdentTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
paramSpec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [DotTok, LSquareTok])
}
)
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #3",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["paramSpec", "qualifiedName"],
occurrenceStack: [1, 1],
lastTok: DotTok,
lastTokOccurrence: 1
}
const possibleNextTokTypes = new NextAfterTokenWalker(
paramSpec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(1)
expect(possibleNextTokTypes[0]).to.equal(IdentTok)
}
)
it(
"can compute the next possible token types From a fqn inside an actionParamSpec" +
" inside an paramSpec INSIDE ActionDec #3",
() => {
const caPath: ITokenGrammarPath = {
ruleStack: ["paramSpec", "qualifiedName"],
occurrenceStack: [1, 1],
lastTok: IdentTok,
lastTokOccurrence: 2
}
const possibleNextTokTypes = new NextAfterTokenWalker(
paramSpec,
caPath
).startWalking()
expect(possibleNextTokTypes.length).to.equal(2)
setEquality(possibleNextTokTypes, [DotTok, LSquareTok])
}
)
it("will fail if we try to compute the next token starting from a rule that does not match the path", () => {
const caPath: ITokenGrammarPath = {
ruleStack: ["I_WILL_FAIL_THE_WALKER", "qualifiedName"],
occurrenceStack: [1, 1],
lastTok: IdentTok,
lastTokOccurrence: 2
}
const walker = new NextAfterTokenWalker(paramSpec, caPath)
expect(() => walker.startWalking()).to.throw(
"The path does not start with the walker's top Rule!"
)
})
})
})
describe("The NextTerminalAfterManyWalker", () => {
it("can compute the next possible token types after the MANY in QualifiedName", () => {
const rule = new Rule({
name: "TwoRepetitionRule",
definition: [
new Repetition({
definition: [
new Terminal({
terminalType: IdentTok,
idx: 1
})
],
idx: 2
}),
new Terminal({
terminalType: IdentTok,
idx: 2
}),
new Repetition({
definition: [
new Terminal({ terminalType: DotTok }),
new Terminal({
terminalType: IdentTok,
idx: 3
})
]
})
]
})
const result = new NextTerminalAfterManyWalker(rule, 1).startWalking()
//noinspection BadExpressionStatementJS
expect(result.occurrence).to.be.undefined
//noinspection BadExpressionStatementJS
expect(result.token).to.be.undefined
})
it("can compute the next possible token types after the MANY in paramSpec inside ActionDec", () => {
const result = new NextTerminalAfterManyWalker(actionDec, 1).startWalking()
expect(result.occurrence).to.equal(1)
expect(result.token).to.equal(RParenTok)
})
})
describe("The NextTerminalAfterManySepWalker", () => {
it("can compute the next possible token types after the MANY_SEP in QualifiedName", () => {
const result = new NextTerminalAfterManySepWalker(
callArguments,
1
).startWalking()
//noinspection BadExpressionStatementJS
expect(result.occurrence).to.be.undefined
//noinspection BadExpressionStatementJS
expect(result.token).to.be.undefined
})
it("can compute the next possible token types after the MANY in paramSpec inside ActionDec", () => {
const result = new NextTerminalAfterManySepWalker(
actionDecSep,
1
).startWalking()
expect(result.occurrence).to.equal(1)
expect(result.token).to.equal(RParenTok)
})
})
describe("The NextTerminalAfterAtLeastOneWalker", () => {
it("can compute the next possible token types after an AT_LEAST_ONE production", () => {
const result = new NextTerminalAfterAtLeastOneWalker(
atLeastOneRule,
1
).startWalking()
expect(result.occurrence).to.equal(2)
expect(result.token).to.equal(DotTok)
const result2 = new NextTerminalAfterAtLeastOneWalker(
atLeastOneRule,
2
).startWalking()
expect(result2.occurrence).to.equal(1)
expect(result2.token).to.equal(DotTok)
const result3 = new NextTerminalAfterAtLeastOneWalker(
atLeastOneRule,
3
).startWalking()
expect(result3.occurrence).to.equal(1)
expect(result3.token).to.equal(CommaTok)
})
it("can compute the next possible token types after an AT_LEAST_ONE production - EMPTY", () => {
const atLeastOneRule = new Rule({
name: "atLeastOneRule",
definition: [
new RepetitionMandatory({
definition: [
new Terminal({
terminalType: DotTok,
idx: 1
})
]
})
]
})
const result = new NextTerminalAfterAtLeastOneWalker(
atLeastOneRule,
1
).startWalking()
expect(result.occurrence).to.be.undefined
expect(result.token).to.be.undefined
})
})
describe("The NextTerminalAfterAtLeastOneSepWalker", () => {
it("can compute the next possible token types after an AT_LEAST_ONE_SEP production", () => {
const result = new NextTerminalAfterAtLeastOneSepWalker(
atLeastOneSepRule,
1
).startWalking()
expect(result.occurrence).to.equal(2)
expect(result.token).to.equal(DotTok)
const result2 = new NextTerminalAfterAtLeastOneSepWalker(
atLeastOneSepRule,
2
).startWalking()
expect(result2.occurrence).to.equal(1)
expect(result2.token).to.equal(DotTok)
const result3 = new NextTerminalAfterAtLeastOneSepWalker(
atLeastOneSepRule,
3
).startWalking()
expect(result3.occurrence).to.equal(1)
expect(result3.token).to.equal(CommaTok)
})
it("can compute the next possible token types after an AT_LEAST_ONE_SEP production EMPTY", () => {
const result = new NextTerminalAfterAtLeastOneSepWalker(
qualifiedNameSep,
1
).startWalking()
//noinspection BadExpressionStatementJS
expect(result.occurrence).to.be.undefined
//noinspection BadExpressionStatementJS
expect(result.token).to.be.undefined
})
})
describe("The chevrotain grammar interpreter capabilities", () => {
function extractPartialPaths(newResultFormat) {
return map(newResultFormat, (currItem) => currItem.partialPath)
}
class Alpha {
static PATTERN = /NA/
}
class Beta {
static PATTERN = /NA/
}
class Gamma {
static PATTERN = /NA/
}
class Comma {
static PATTERN = /NA/
}
augmentTokenTypes([Alpha, Beta, Gamma, Comma])
context("can calculate the next possible paths in a", () => {
it("Sequence", () => {
const seq = [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([
[Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([
[Alpha, Beta]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([
[Alpha, Beta, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([
[Alpha, Beta, Gamma]
])
})
it("Optional", () => {
const seq = [
new Terminal({ terminalType: Alpha }),
new Option({
definition: [new Terminal({ terminalType: Beta })]
}),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([
[Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([
[Alpha, Beta],
[Alpha, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([
[Alpha, Beta, Gamma],
[Alpha, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([
[Alpha, Beta, Gamma],
[Alpha, Gamma]
])
})
it("Alternation", () => {
const alts = [
new Alternation({
definition: [
new Alternative({
definition: [new Terminal({ terminalType: Alpha })]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Beta })
]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Gamma })
]
})
]
})
]
expect(extractPartialPaths(possiblePathsFrom(alts, 1))).to.deep.equal([
[Alpha],
[Beta],
[Beta]
])
expect(extractPartialPaths(possiblePathsFrom(alts, 2))).to.deep.equal([
[Alpha],
[Beta, Beta],
[Beta, Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(alts, 3))).to.deep.equal([
[Alpha],
[Beta, Beta],
[Beta, Alpha, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(alts, 4))).to.deep.equal([
[Alpha],
[Beta, Beta],
[Beta, Alpha, Gamma]
])
})
it("Repetition", () => {
const rep = [
new Repetition({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Alpha })
]
}),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(rep, 1))).to.deep.equal([
[Alpha],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 2))).to.deep.equal([
[Alpha, Alpha],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 3))).to.deep.equal([
[Alpha, Alpha, Alpha],
[Alpha, Alpha, Gamma],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 4))).to.deep.equal([
[Alpha, Alpha, Alpha, Alpha],
[Alpha, Alpha, Gamma],
[Gamma]
])
})
it("Mandatory Repetition", () => {
const repMand = [
new RepetitionMandatory({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Alpha })
]
}),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(repMand, 1))).to.deep.equal([
[Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(repMand, 2))).to.deep.equal([
[Alpha, Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(repMand, 3))).to.deep.equal([
[Alpha, Alpha, Alpha],
[Alpha, Alpha, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(repMand, 4))).to.deep.equal([
[Alpha, Alpha, Alpha, Alpha],
[Alpha, Alpha, Gamma]
])
})
it("Repetition with Separator", () => {
// same as Mandatory Repetition because currently possiblePaths only cares about
// the first repetition.
const rep = [
new RepetitionWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Alpha })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(rep, 1))).to.deep.equal([
[Alpha],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 2))).to.deep.equal([
[Alpha, Alpha],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 3))).to.deep.equal([
[Alpha, Alpha, Comma],
[Alpha, Alpha, Gamma],
[Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(rep, 4))).to.deep.equal([
[Alpha, Alpha, Comma, Alpha],
[Alpha, Alpha, Gamma],
[Gamma]
])
})
it("Mandatory Repetition with Separator", () => {
// same as Mandatory Repetition because currently possiblePaths only cares about
// the first repetition.
const repMandSep = [
new RepetitionMandatoryWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Alpha })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
expect(
extractPartialPaths(possiblePathsFrom(repMandSep, 1))
).to.deep.equal([[Alpha]])
expect(
extractPartialPaths(possiblePathsFrom(repMandSep, 2))
).to.deep.equal([[Alpha, Alpha]])
expect(
extractPartialPaths(possiblePathsFrom(repMandSep, 3))
).to.deep.equal([
[Alpha, Alpha, Comma],
[Alpha, Alpha, Gamma]
])
expect(
extractPartialPaths(possiblePathsFrom(repMandSep, 4))
).to.deep.equal([
[Alpha, Alpha, Comma, Alpha],
[Alpha, Alpha, Gamma]
])
})
it("NonTerminal", () => {
const someSubRule = new Rule({
name: "blah",
definition: [new Terminal({ terminalType: Beta })]
})
const seq = [
new Terminal({ terminalType: Alpha }),
new NonTerminal({
nonTerminalName: "blah",
referencedRule: someSubRule
}),
new Terminal({ terminalType: Gamma })
]
expect(extractPartialPaths(possiblePathsFrom(seq, 1))).to.deep.equal([
[Alpha]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 2))).to.deep.equal([
[Alpha, Beta]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 3))).to.deep.equal([
[Alpha, Beta, Gamma]
])
expect(extractPartialPaths(possiblePathsFrom(seq, 4))).to.deep.equal([
[Alpha, Beta, Gamma]
])
})
})
context("can calculate the next possible single tokens for: ", () => {
function INPUT(tokTypes: TokenType[]): IToken[] {
return map(tokTypes, (currTokType) => createRegularToken(currTokType))
}
function pluckTokenTypes(arr: any[]): TokenType[] {
return map(arr, (currItem) => currItem.nextTokenType)
}
it("Sequence positive", () => {
const seq = [
new Alternative({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Gamma })
]
})
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
seq,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Gamma]
)
})
it("Sequence negative", () => {
const seq = [
new Alternative({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Gamma })
]
})
]
// negative
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5)
).to.be.empty
})
it("Optional positive", () => {
const seq = [
new Terminal({ terminalType: Alpha }),
new Option({
definition: [new Terminal({ terminalType: Beta })]
}),
new Terminal({ terminalType: Gamma })
]
// setEquality(pluckTokenTypes(nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5)), [Alpha])
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
seq,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta, Gamma]
)
// setEquality(pluckTokenTypes(nextPossibleTokensAfter(seq, INPUT([Alpha, Beta]), tokenStructuredMatcher, 5)), [Gamma])
})
it("Optional Negative", () => {
const seq = [
new Terminal({ terminalType: Alpha }),
new Option({
definition: [new Terminal({ terminalType: Beta })]
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5)
).to.be.empty
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Alpha]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
it("Alternation positive", () => {
const alts = [
new Alternation({
definition: [
new Alternative({
definition: [new Terminal({ terminalType: Alpha })]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Beta })
]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Gamma })
]
}),
new Alternative({
definition: [new Terminal({ terminalType: Gamma })]
})
]
})
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(alts, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha, Beta, Beta, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
alts,
INPUT([Beta]),
tokenStructuredMatcher,
5
)
),
[Beta, Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
alts,
INPUT([Beta, Alpha]),
tokenStructuredMatcher,
5
)
),
[Gamma]
)
})
it("Alternation Negative", () => {
const alts = [
new Alternation({
definition: [
new Alternative({
definition: [new Terminal({ terminalType: Alpha })]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Beta })
]
}),
new Alternative({
definition: [
new Terminal({ terminalType: Beta }),
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Gamma })
]
})
]
})
]
expect(
nextPossibleTokensAfter(alts, INPUT([Alpha]), tokenStructuredMatcher, 5)
).to.be.empty
expect(
nextPossibleTokensAfter(
alts,
INPUT([Gamma, Alpha]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
alts,
INPUT([Beta, Beta]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(alts, INPUT([Gamma]), tokenStructuredMatcher, 5)
).to.be.empty
})
it("Repetition - positive", () => {
const rep = [
new Repetition({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
]
}),
new Terminal({ terminalType: Gamma })
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(rep, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
rep,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Alpha, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Beta, Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Beta, Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Alpha, Gamma]
)
})
it("Repetition - negative", () => {
const rep = [
new Repetition({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
]
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(rep, INPUT([Beta]), tokenStructuredMatcher, 5)
).to.be.empty
expect(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Beta, Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
rep,
INPUT([Alpha, Beta, Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
it("Mandatory Repetition - positive", () => {
const repMand = [
new RepetitionMandatory({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
]
}),
new Terminal({ terminalType: Gamma })
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(repMand, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Alpha, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Alpha, Gamma]
)
})
it("Mandatory Repetition - negative", () => {
const repMand = [
new RepetitionMandatory({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
]
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Beta]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
it("Repetition with Separator - positive", () => {
const repSep = [
new RepetitionWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(repSep, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Comma, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta, Comma]),
tokenStructuredMatcher,
5
)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta, Comma, Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Comma, Gamma]
)
})
it("Repetition with Separator - negative", () => {
const repMand = [
new RepetitionWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Comma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Comma, Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Comma, Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
it("Repetition with Separator Mandatory - positive", () => {
const repSep = [
new RepetitionMandatoryWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(repSep, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Comma, Gamma]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta, Comma]),
tokenStructuredMatcher,
5
)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
repSep,
INPUT([Alpha, Beta, Comma, Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Comma, Gamma]
)
})
it("Repetition with Separator Mandatory - negative", () => {
const repMand = [
new RepetitionMandatoryWithSeparator({
definition: [
new Terminal({ terminalType: Alpha }),
new Terminal({ terminalType: Beta })
],
separator: Comma
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Comma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Comma, Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
repMand,
INPUT([Alpha, Beta, Comma, Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
it("NonTerminal - positive", () => {
const someSubRule = new Rule({
name: "blah",
definition: [new Terminal({ terminalType: Beta })]
})
const seq = [
new Terminal({ terminalType: Alpha }),
new NonTerminal({
nonTerminalName: "blah",
referencedRule: someSubRule
}),
new Terminal({ terminalType: Gamma })
]
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(seq, INPUT([]), tokenStructuredMatcher, 5)
),
[Alpha]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
seq,
INPUT([Alpha]),
tokenStructuredMatcher,
5
)
),
[Beta]
)
setEquality(
pluckTokenTypes(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Beta]),
tokenStructuredMatcher,
5
)
),
[Gamma]
)
})
it("NonTerminal - negative", () => {
const someSubRule = new Rule({
name: "blah",
definition: [new Terminal({ terminalType: Beta })]
})
const seq = [
new Terminal({ terminalType: Alpha }),
new NonTerminal({
nonTerminalName: "blah",
referencedRule: someSubRule
}),
new Terminal({ terminalType: Gamma })
]
expect(
nextPossibleTokensAfter(seq, INPUT([Beta]), tokenStructuredMatcher, 5)
).to.be.empty
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
expect(
nextPossibleTokensAfter(
seq,
INPUT([Alpha, Beta, Gamma]),
tokenStructuredMatcher,
5
)
).to.be.empty
})
})
})
describe("issue 391 - WITH_SEP variants do not take SEP into account in lookahead", () => {
it("Reproduce issue", () => {
const LParen = createToken({
name: "LParen",
pattern: /\(/
})
const RParen = createToken({
name: "RParen",
pattern: /\)/
})
const Comma = createToken({ name: "Comma", pattern: /,/ })
const FatArrow = createToken({
name: "FatArrow",
pattern: /=>/
})
const Identifier = createToken({
name: "Identifier",
pattern: /[a-zA-Z]+/
})
const WhiteSpace = createToken({
name: "WhiteSpace",
pattern: /\s+/,
group: Lexer.SKIPPED,
line_breaks: true
})
const allTokens = [WhiteSpace, LParen, RParen, Comma, FatArrow, Identifier]
const issue391Lexer = new Lexer(allTokens)
class Issue391Parser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(allTokens, {
maxLookahead: 4
})
this.performSelfAnalysis()
this.input = input
}
topRule = this.RULE("topRule", () => {
return this.OR9([
{
// Lambda Function
ALT: () => {
this.CONSUME1(LParen)
this.MANY_SEP({
SEP: Comma,
DEF: () => {
this.CONSUME1(Identifier)
}
})
this.CONSUME1(RParen)
this.CONSUME1(FatArrow)
}
},
{
// Parenthesis Expression
ALT: () => {
this.CONSUME2(LParen)
this.CONSUME2(Identifier)
this.CONSUME2(RParen)
}
}
])
})
}
expect(() => new Issue391Parser([])).to.not.throw(
"Ambiguous alternatives: <1 ,2>"
)
const myParser = new Issue391Parser([])
function testInput(input) {
const tokens = issue391Lexer.tokenize(input).tokens
myParser.input = tokens
myParser.topRule()
expect(myParser.errors).to.be.empty
}
testInput("(x, y) => ")
testInput("() =>")
testInput("(x) =>")
testInput("(x)")
})
}) | the_stack |
import { EventEmitter, Injectable } from '@angular/core';
import { from, fromEvent, Observable, throwError } from 'rxjs';
import { filter, map, mergeMap, takeUntil } from 'rxjs/operators';
import { ConsoleLoggerService } from './logger.service';
import { BrowserWebBluetooth } from './platform/browser';
type ReadValueOptions = {
acceptAllDevices?: boolean;
optionalServices?: BluetoothServiceUUID[];
characteristic: BluetoothCharacteristicUUID,
service: BluetoothServiceUUID,
};
@Injectable({
providedIn: 'root'
})
export class BluetoothCore {
private device$: EventEmitter<BluetoothDevice>;
private gatt$: EventEmitter<BluetoothRemoteGATTServer>;
private characteristicValueChanges$: EventEmitter<DataView>;
private gattServer: BluetoothRemoteGATTServer;
constructor(private readonly webBle: BrowserWebBluetooth, private readonly console: ConsoleLoggerService) {
this.device$ = new EventEmitter<BluetoothDevice>();
this.gatt$ = new EventEmitter<BluetoothRemoteGATTServer>();
this.characteristicValueChanges$ = new EventEmitter<DataView>();
this.gattServer = null;
}
getDevice$(): Observable<BluetoothDevice> {
return this.device$;
}
getGATT$(): Observable<BluetoothRemoteGATTServer> {
return this.gatt$;
}
streamValues$(): Observable<DataView> {
return this.characteristicValueChanges$.pipe(filter(value => value && value.byteLength > 0));
}
/**
* Run the discovery process and read the value form the provided service and characteristic
* @param options the ReadValueOptions
*/
async value(options: ReadValueOptions) {
this.console.log('[BLE::Info] Reading value with options %o', options);
if (typeof options.acceptAllDevices === 'undefined') {
options.acceptAllDevices = true;
}
if (typeof options.optionalServices === 'undefined') {
options.optionalServices = [options.service];
}
else {
options.optionalServices = [...options.optionalServices];
}
this.console.log('[BLE::Info] Reading value with options %o', options);
try {
const device = await this.discover({
acceptAllDevices: options.acceptAllDevices,
optionalServices: options.optionalServices
}) as BluetoothDevice;
this.console.log('[BLE::Info] Device info %o', device);
const gatt = await this.connectDevice(device);
this.console.log('[BLE::Info] GATT info %o', gatt);
const primaryService = await this.getPrimaryService(gatt, options.service) as BluetoothRemoteGATTService;
this.console.log('[BLE::Info] Primary Service info %o', primaryService);
const characteristic = await this.getCharacteristic(primaryService, options.characteristic) as BluetoothRemoteGATTCharacteristic;
this.console.log('[BLE::Info] Characteristic info %o', characteristic);
const value = await characteristic.readValue();
this.console.log('[BLE::Info] Value info %o', value);
return value;
}
catch (error) {
throw new Error(error);
}
}
value$(options: ReadValueOptions) {
return from(this.value(options));
}
/**
* Run the discovery process.
*
* @param Options such as filters and optional services
* @return The GATT server for the chosen device
*/
async discover(options: RequestDeviceOptions = {} as RequestDeviceOptions) {
options.optionalServices = options.optionalServices || ['generic_access'];
this.console.log('[BLE::Info] Requesting devices with options %o', options);
let device = null;
try {
device = await this.webBle.requestDevice(options);
device.addEventListener('gattserverdisconnected', this.onDeviceDisconnected.bind(this));
if (device) {
this.device$.emit(device);
}
else {
this.device$.error(`[BLE::Error] Can not get the Bluetooth Remote GATT Server. Abort.`);
}
} catch (error) {
this.console.error(error);
}
return device;
}
/**
* This handler will trigger when the client disconnets from the server.
*
* @param event The onDeviceDisconnected event
*/
onDeviceDisconnected(event: Event) {
const disconnectedDevice = event.target as BluetoothDevice;
this.console.log('[BLE::Info] disconnected device %o', disconnectedDevice);
this.device$.emit(null);
}
/**
* Run the discovery process.
*
* @param Options such as filters and optional services
* @return Emites the value of the requested service read from the device
*/
discover$(options?: RequestDeviceOptions): Observable<void | BluetoothRemoteGATTServer> {
return from(this.discover(options)).pipe(mergeMap((device: BluetoothDevice) => this.connectDevice$(device)));
}
/**
* Connect to current device.
*
* @return Emites the gatt server instance of the requested device
*/
async connectDevice(device: BluetoothDevice) {
if (device) {
this.console.log('[BLE::Info] Connecting to Bluetooth Remote GATT Server of %o', device);
try {
const gattServer = await device.gatt.connect();
this.gattServer = gattServer;
this.gatt$.emit(gattServer);
return gattServer;
} catch (error) {
// probably the user has canceled the discovery
Promise.reject(`${error.message}`);
this.gatt$.error(`${error.message}`);
}
} else {
this.console.error('[BLE::Error] Was not able to connect to Bluetooth Remote GATT Server');
this.gatt$.error(null);
}
}
/**
* Connect to current device.
*
* @return Emites the gatt server instance of the requested device
*/
connectDevice$(device: BluetoothDevice) {
return from(this.connectDevice(device));
}
/**
* Disconnect the current connected device
*/
disconnectDevice() {
if (!this.gattServer) {
return;
}
this.console.log('[BLE::Info] Disconnecting from Bluetooth Device %o', this.gattServer);
if (this.gattServer.connected) {
this.gattServer.disconnect();
} else {
this.console.log('[BLE::Info] Bluetooth device is already disconnected');
}
}
/**
* Requests the primary service.
*
* @param gatt The BluetoothRemoteGATTServer sever
* @param service The UUID of the primary service
* @return The remote service (as a Promise)
*/
async getPrimaryService(gatt: BluetoothRemoteGATTServer, service: BluetoothServiceUUID): Promise<BluetoothRemoteGATTService> {
try {
const remoteService = await gatt.getPrimaryService(service);
return await Promise.resolve(remoteService);
}
catch (error) {
return await Promise.reject(`${error.message} (${service})`);
}
}
/**
* Requests the primary service.
*
* @param gatt The BluetoothRemoteGATTServer sever
* @param service The UUID of the primary service
* @return The remote service (as an observable).
*/
getPrimaryService$(gatt: BluetoothRemoteGATTServer, service: BluetoothServiceUUID): Observable<BluetoothRemoteGATTService> {
this.console.log('[BLE::Info] Getting primary service "%s" (if available) of %o', service, gatt);
if (gatt) {
return from(
this.getPrimaryService(gatt, service)
);
}
else {
return throwError(new Error('[BLE::Error] Was not able to connect to the Bluetooth Remote GATT Server'));
}
}
/**
* Requests a characteristic from the primary service.
*
* @param primaryService The primary service.
* @param characteristic The characteristic's UUID.
* @returns The characteristic description (as a Promise).
*/
async getCharacteristic(
primaryService: BluetoothRemoteGATTService,
characteristic: BluetoothCharacteristicUUID
): Promise<BluetoothRemoteGATTCharacteristic | void> {
this.console.log('[BLE::Info] Getting Characteristic "%s" of %o', characteristic, primaryService);
try {
const char = await primaryService.getCharacteristic(characteristic);
// listen for characteristic value changes
if (char.properties.notify) {
char.startNotifications().then(_ => {
this.console.log('[BLE::Info] Starting notifications of "%s"', characteristic);
char.addEventListener('characteristicvaluechanged', this.onCharacteristicChanged.bind(this));
}, (error: DOMException) => {
Promise.reject(`${error.message} (${characteristic})`);
});
}
else {
char.addEventListener('characteristicvaluechanged', this.onCharacteristicChanged.bind(this));
}
return char;
}
catch (rejectionError) {
Promise.reject(`${rejectionError.message} (${characteristic})`);
}
}
/**
* Requests a characteristic from the primary service.
*
* @param primaryService The primary service.
* @param characteristic The characteristic's UUID.
* @returns The characteristic description (as a Observable).
*/
getCharacteristic$(
primaryService: BluetoothRemoteGATTService,
characteristic: BluetoothCharacteristicUUID
): Observable<void | BluetoothRemoteGATTCharacteristic> {
this.console.log('[BLE::Info] Getting Characteristic "%s" of %o', characteristic, primaryService);
return from(this.getCharacteristic(primaryService, characteristic));
}
/**
* Sets the characteristic's state.
*
* @param service The parent service of the characteristic.
* @param characteristic The requested characteristic
* @param state An ArrayBuffer containing the value of the characteristic.
* @return The primary service (useful for chaining).
*/
setCharacteristicState(service: BluetoothServiceUUID, characteristic: BluetoothCharacteristicUUID, state: ArrayBuffer) {
const primaryService = this.getPrimaryService$(this.gattServer, service);
primaryService
// tslint:disable-next-line: variable-name
.pipe(mergeMap((_primaryService: BluetoothRemoteGATTService) => this.getCharacteristic$(_primaryService, characteristic)))
// tslint:disable-next-line: no-shadowed-variable
.subscribe((characteristic: BluetoothRemoteGATTCharacteristic) => this.writeValue$(characteristic, state));
return primaryService;
}
/**
* Enables the specified characteristic of a given service.
*
* @param service The parent service of the characteristic.
* @param characteristic The requested characteristic
* @return The primary service (useful for chaining).
*/
enableCharacteristic(service: BluetoothServiceUUID, characteristic: BluetoothCharacteristicUUID, state?: any) {
state = state || new Uint8Array([1]);
return this.setCharacteristicState(service, characteristic, state);
}
/**
* Disables the specified characteristic of a given service.
*
* @param service The parent service of the characteristic.
* @param characteristic The requested characteristic.
* @return The primary service (useful for chaining).
*/
disbaleCharacteristic(service: BluetoothServiceUUID, characteristic: BluetoothCharacteristicUUID, state?: any) {
state = state || new Uint8Array([0]);
return this.setCharacteristicState(service, characteristic, state);
}
/**
* Dispatches new values emitted by a characteristic.
*
* @param event the distpatched event.
*/
onCharacteristicChanged(event: Event) {
this.console.log('[BLE::Info] Dispatching new characteristic value %o', event);
const value = (event.target as BluetoothRemoteGATTCharacteristic).value;
this.characteristicValueChanges$.emit(value);
}
/**
* Reads a value from the characteristics, as a DataView.
*
* @param characteristic The requested characteristic.
* @return the DataView value (as an Observable).
*/
readValue$(characteristic: BluetoothRemoteGATTCharacteristic): Observable<DataView> {
this.console.log('[BLE::Info] Reading Characteristic %o', characteristic);
return from(
characteristic
.readValue()
.then((data: DataView) => Promise.resolve(data), (error: DOMException) => Promise.reject(`${error.message}`))
);
}
/**
* Writes a value into the specified characteristic.
*
* @param characteristic The requested characteristic.
* @param value The value to be written (as an ArrayBuffer or Uint8Array).
* @return an void Observable.
*/
writeValue$(characteristic: BluetoothRemoteGATTCharacteristic, value: ArrayBuffer | Uint8Array) {
this.console.log('[BLE::Info] Writing Characteristic %o', characteristic);
return from(characteristic.writeValue(value).then(_ => Promise.resolve(), (error: DOMException) => Promise.reject(`${error.message}`)));
}
/**
* A stream of DataView values emitted by the specified characteristic.
*
* @param characteristic The characteristic which value you want to observe
* @return The stream of DataView values.
*/
observeValue$(characteristic: BluetoothRemoteGATTCharacteristic): Observable<DataView> {
characteristic.startNotifications();
const disconnected = fromEvent(characteristic.service.device, 'gattserverdisconnected');
return fromEvent(characteristic, 'characteristicvaluechanged')
.pipe(
map((event: Event) => (event.target as BluetoothRemoteGATTCharacteristic).value as DataView),
takeUntil(disconnected)
);
}
/**
* A utility method to convert LE to an unsigned 16-bit integer values.
*
* @param data The DataView binary data.
* @param byteOffset The offset, in byte, from the start of the view where to read the data.
* @return An unsigned 16-bit integer number.
*/
littleEndianToUint16(data: any, byteOffset: number): number {
// tslint:disable-next-line:no-bitwise
return (this.littleEndianToUint8(data, byteOffset + 1) << 8) + this.littleEndianToUint8(data, byteOffset);
}
/**
* A utility method to convert LE to an unsigned 8-bit integer values.
*
* @param data The DataView binary data.
* @param byteOffset The offset, in byte, from the start of the view where to read the data.
* @return An unsigned 8-bit integer number.
*/
littleEndianToUint8(data: any, byteOffset: number): number {
return data.getUint8(byteOffset);
}
/**
* Sends random data (for testing purposes only).
*
* @return Random unsigned 8-bit integer values.
*/
fakeNext(fakeValue?: () => DataView) {
if (fakeValue === undefined) {
fakeValue = () => {
const dv = new DataView(new ArrayBuffer(8));
// tslint:disable-next-line:no-bitwise
dv.setUint8(0, (Math.random() * 110) | 0);
return dv;
};
}
this.characteristicValueChanges$.emit(fakeValue());
}
} | the_stack |
import "@esfx/metadata-shim";
import * as metadata from "@esfx/metadata";
import { MetadataKey } from "@esfx/metadata";
import { isFunction, isObject, isPropertyKey, isDefined } from "@esfx/internal-guards";
declare global {
namespace Reflect {
function decorate(decorators: ClassDecorator[], target: Function): Function;
function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: object, propertyKey: PropertyKey, descriptor?: PropertyDescriptor): PropertyDescriptor | undefined;
function defineMetadata(metadataKey: MetadataKey, metadataValue: unknown, target: object): void;
function defineMetadata(metadataKey: MetadataKey, metadataValue: unknown, target: object, propertyKey: PropertyKey): void;
function defineMetadata(metadataKey: MetadataKey, metadataValue: unknown, target: object, propertyKey: PropertyKey, parameterIndex: number): void;
function deleteMetadata(metadataKey: MetadataKey, target: object): boolean;
function deleteMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey): boolean;
function deleteMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey, parameterIndex: number): boolean;
function hasOwnMetadata(metadataKey: MetadataKey, target: object): boolean;
function hasOwnMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey): boolean;
function hasOwnMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey, parameterIndex: number): boolean;
function hasMetadata(metadataKey: MetadataKey, target: object): boolean;
function hasMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey): boolean;
function hasMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey, parameterIndex: number): boolean;
function getOwnMetadata(metadataKey: MetadataKey, target: object): unknown;
function getOwnMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey): unknown;
function getOwnMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey, parameterIndex: number): unknown;
function getMetadata(metadataKey: MetadataKey, target: object): unknown;
function getMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey): unknown;
function getMetadata(metadataKey: MetadataKey, target: object, propertyKey: PropertyKey, parameterIndex: number): unknown;
function getOwnMetadataKeys(target: object): MetadataKey[];
function getOwnMetadataKeys(target: object, propertyKey: PropertyKey): MetadataKey[];
function getOwnMetadataKeys(target: object, propertyKey: PropertyKey, parameterIndex: number): MetadataKey[];
function getMetadataKeys(target: object): MetadataKey[];
function getMetadataKeys(target: object, propertyKey: PropertyKey): MetadataKey[];
function getMetadataKeys(target: object, propertyKey: PropertyKey, parameterIndex: number): MetadataKey[];
}
}
type Overloads =
| readonly [object]
| readonly [object, PropertyKey]
| readonly [object, PropertyKey, number];
function isParameterOverload(args: Overloads): args is readonly [object, PropertyKey, number] {
if (args.length >= 3 && isObject(args[0]) && isPropertyKey(args[1]) && typeof args[2] === "number") return true;
return false;
}
function isMemberOverload(args: Overloads): args is readonly [object, PropertyKey] {
if (args.length >= 2 && isObject(args[0]) && isPropertyKey(args[1]) && (args.length === 2 || !isDefined(args[2]) || isObject(args[2]))) return true;
return false;
}
function isObjectOverload(args: Overloads): args is readonly [object] {
if (args.length >= 1 && isObject(args[0]) && (args.length === 1 || !isDefined(args[1]))) return true;
return false;
}
if (!Reflect.decorate) Reflect.decorate = (() => {
type DecorateOverloads =
| readonly [ClassDecorator[], Function]
| readonly [(PropertyDecorator | MethodDecorator)[], object, PropertyKey, PropertyDescriptor?];
function isDecorateClassOverload(args: DecorateOverloads): args is readonly [ClassDecorator[], Function] {
if (args.length >= 2 && Array.isArray(args[0]) && isFunction(args[1]) && (args.length === 2 || !isDefined(args[2])) && (args.length === 3 || !isDefined(args[3]))) return true;
return false;
}
function isDecorateMemberOverload(args: DecorateOverloads): args is readonly [(PropertyDecorator | MethodDecorator)[], object, PropertyKey, PropertyDescriptor?] {
if (args.length >= 3 && Array.isArray(args[0]) && isObject(args[1]) && isPropertyKey(args[2]) && (isObject(args[3]) || !isDefined(args[3]))) return true;
return false;
}
function decorate(decorators: ClassDecorator[], target: Function): Function;
function decorate(decorators: (PropertyDecorator | MethodDecorator)[], target: object, propertyKey: PropertyKey, descriptor?: PropertyDescriptor): PropertyDescriptor | undefined;
function decorate(...args: DecorateOverloads) {
if (isDecorateClassOverload(args)) return decorateClass(...args);
if (isDecorateMemberOverload(args)) return decorateMember(...args);
throw new TypeError();
}
function decorateClass(decorators: ClassDecorator[], target: Function): Function {
for (let i = decorators.length - 1; i >= 0; i--) {
const decorator = decorators[i];
const decorated = decorator(target);
if (isDefined(decorated)) {
if (!isFunction(decorated)) throw new TypeError();
target = decorated;
}
}
return target;
}
function decorateMember(decorators: (PropertyDecorator | MethodDecorator)[], target: object, propertyKey: PropertyKey, descriptor?: PropertyDescriptor): PropertyDescriptor | undefined {
if (typeof propertyKey !== "symbol") propertyKey = "" + propertyKey;
for (let i = decorators.length - 1; i >= 0; i--) {
const decorator = decorators[i];
const decorated = decorator(target, propertyKey, descriptor!);
if (isDefined(decorated)) {
if (!isObject(decorated)) throw new TypeError();
descriptor = decorated;
}
}
return descriptor;
}
return decorate;
})();
if (!Reflect.defineMetadata) Reflect.defineMetadata = function (metadataKey: MetadataKey, metadataValue: unknown, ...args: Overloads) {
if (isParameterOverload(args)) return void metadata.defineParameterMetadata(args[0], args[1], args[2], metadataKey, metadataValue);
if (isMemberOverload(args)) return void metadata.definePropertyMetadata(args[0], args[1], metadataKey, metadataValue);
if (isObjectOverload(args)) return void metadata.defineObjectMetadata(args[0], metadataKey, metadataValue);
throw new TypeError();
};
if (!Reflect.deleteMetadata) Reflect.deleteMetadata = function (metadataKey: MetadataKey, ...args: Overloads) {
if (isParameterOverload(args)) return metadata.deleteParameterMetadata(args[0], args[1], args[2], metadataKey);
if (isMemberOverload(args)) return metadata.deletePropertyMetadata(args[0], args[1], metadataKey);
if (isObjectOverload(args)) return metadata.deleteObjectMetadata(args[0], metadataKey);
throw new TypeError();
}
if (!Reflect.hasOwnMetadata) Reflect.hasOwnMetadata = function (metadataKey: MetadataKey, ...args: Overloads) {
if (isParameterOverload(args)) return metadata.hasOwnParameterMetadata(args[0], args[1], args[2], metadataKey);
if (isMemberOverload(args)) return metadata.hasOwnPropertyMetadata(args[0], args[1], metadataKey);
if (isObjectOverload(args)) return metadata.hasOwnObjectMetadata(args[0], metadataKey);
throw new TypeError();
}
if (!Reflect.hasMetadata) Reflect.hasMetadata = function (metadataKey: MetadataKey, ...args: Overloads) {
if (isParameterOverload(args)) return metadata.hasParameterMetadata(args[0], args[1], args[2], metadataKey);
if (isMemberOverload(args)) return metadata.hasPropertyMetadata(args[0], args[1], metadataKey);
if (isObjectOverload(args)) return metadata.hasObjectMetadata(args[0], metadataKey);
throw new TypeError();
}
if (!Reflect.getOwnMetadata) Reflect.getOwnMetadata = function (metadataKey: MetadataKey, ...args: Overloads) {
if (isParameterOverload(args)) return metadata.getOwnParameterMetadata(args[0], args[1], args[2], metadataKey);
if (isMemberOverload(args)) return metadata.getOwnPropertyMetadata(args[0], args[1], metadataKey);
if (isObjectOverload(args)) return metadata.getOwnObjectMetadata(args[0], metadataKey);
throw new TypeError();
}
if (!Reflect.getMetadata) Reflect.getMetadata = function (metadataKey: MetadataKey, ...args: Overloads) {
if (isParameterOverload(args)) return metadata.getParameterMetadata(args[0], args[1], args[2], metadataKey);
if (isMemberOverload(args)) return metadata.getPropertyMetadata(args[0], args[1], metadataKey);
if (isObjectOverload(args)) return metadata.getObjectMetadata(args[0], metadataKey);
throw new TypeError();
}
if (!Reflect.getOwnMetadataKeys) Reflect.getOwnMetadataKeys = function (...args: Overloads) {
if (isParameterOverload(args)) return metadata.getOwnParameterMetadataKeys(args[0], args[1], args[2]);
if (isMemberOverload(args)) return metadata.getOwnPropertyMetadataKeys(args[0], args[1]);
if (isObjectOverload(args)) return metadata.getOwnObjectMetadataKeys(args[0]);
throw new TypeError();
}
if (!Reflect.getMetadataKeys) Reflect.getMetadataKeys = function (...args: Overloads) {
if (isParameterOverload(args)) return metadata.getParameterMetadataKeys(args[0], args[1], args[2]);
if (isMemberOverload(args)) return metadata.getPropertyMetadataKeys(args[0], args[1]);
if (isObjectOverload(args)) return metadata.getObjectMetadataKeys(args[0]);
throw new TypeError();
} | the_stack |
export const Abilities: {[k: string]: ModdedAbilityData} = {
damp: {
inherit: true,
onAnyDamage(damage, target, source, effect) {
if (effect && (effect.id === 'aftermath' || effect.id === 'ability:aftermath')) {
return false;
}
},
},
flowerveil: {
inherit: true,
onAllySetStatus(status, target, source, effect) {
if (target.hasType('Grass') && source && target !== source && effect && effect.id !== 'yawn') {
this.debug('interrupting setStatus with Flower Veil');
if (effect.id.endsWith('synchronize') || (effect.effectType === 'Move' && !effect.secondaries)) {
const effectHolder = this.effectState.target;
this.add('-block', target, 'ability: Flower Veil', '[of] ' + effectHolder);
}
return null;
}
},
},
innerfocus: {
inherit: true,
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate' || effect.id === 'ability:intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Inner Focus', '[of] ' + target);
}
},
},
mirrorarmor: {
inherit: true,
onBoost(boost, target, source, effect) {
// Don't bounce self stat changes, or boosts that have already bounced
if (target === source || !boost || effect.id === 'mirrorarmor' || effect.id === 'ability:mirrorarmor') return;
let b: BoostID;
for (b in boost) {
if (boost[b]! < 0) {
if (target.boosts[b] === -6) continue;
const negativeBoost: SparseBoostsTable = {};
negativeBoost[b] = boost[b];
delete boost[b];
this.add('-ability', target, 'Mirror Armor');
this.boost(negativeBoost, source, target, null, true);
}
}
},
},
mummy: {
inherit: true,
onDamagingHit(damage, target, source, move) {
if (target.ability === 'mummy') {
const sourceAbility = source.getAbility();
if (sourceAbility.isPermanent || sourceAbility.id === 'mummy') {
return;
}
if (this.checkMoveMakesContact(move, source, target, !source.isAlly(target))) {
const oldAbility = source.setAbility('mummy', target);
if (oldAbility) {
this.add('-activate', target, 'ability: Mummy', this.dex.abilities.get(oldAbility).name, '[of] ' + source);
}
}
} else {
const possibleAbilities = [source.ability, ...(source.m.innates || [])]
.filter(val => !this.dex.abilities.get(val).isPermanent && val !== 'mummy');
if (!possibleAbilities.length) return;
if (this.checkMoveMakesContact(move, source, target, !source.isAlly(target))) {
const abil = this.sample(possibleAbilities);
if (abil === source.ability) {
const oldAbility = source.setAbility('mummy', target);
if (oldAbility) {
this.add('-activate', target, 'ability: Mummy', this.dex.abilities.get(oldAbility).name, '[of] ' + source);
}
} else {
source.removeVolatile('ability:' + abil);
source.addVolatile('ability:mummy', source);
if (abil) {
this.add('-activate', target, 'ability: Mummy', this.dex.abilities.get(abil).name, '[of] ' + source);
}
}
}
}
},
},
neutralizinggas: {
inherit: true,
// Ability suppression implemented in sim/pokemon.ts:Pokemon#ignoringAbility
onPreStart(pokemon) {
this.add('-ability', pokemon, 'Neutralizing Gas');
pokemon.abilityState.ending = false;
// Remove setter's innates before the ability starts
if (pokemon.m.innates) {
for (const innate of pokemon.m.innates) {
if (this.dex.abilities.get(innate).isPermanent || innate === 'neutralizinggas') continue;
pokemon.removeVolatile('ability:' + innate);
}
}
for (const target of this.getAllActive()) {
if (target.illusion) {
this.singleEvent('End', this.dex.abilities.get('Illusion'), target.abilityState, target, pokemon, 'neutralizinggas');
}
if (target.volatiles['slowstart']) {
delete target.volatiles['slowstart'];
this.add('-end', target, 'Slow Start', '[silent]');
}
if (target.m.innates) {
for (const innate of target.m.innates) {
if (this.dex.abilities.get(innate).isPermanent) continue;
target.removeVolatile('ability:' + innate);
}
}
}
},
onEnd(source) {
this.add('-end', source, 'ability: Neutralizing Gas');
// FIXME this happens before the pokemon switches out, should be the opposite order.
// Not an easy fix since we cant use a supported event. Would need some kind of special event that
// gathers events to run after the switch and then runs them when the ability is no longer accessible.
// (If you're tackling this, do note extreme weathers have the same issue)
// Mark this pokemon's ability as ending so Pokemon#ignoringAbility skips it
if (source.abilityState.ending) return;
source.abilityState.ending = true;
const sortedActive = this.getAllActive();
this.speedSort(sortedActive);
for (const pokemon of sortedActive) {
if (pokemon !== source) {
// Will be suppressed by Pokemon#ignoringAbility if needed
this.singleEvent('Start', pokemon.getAbility(), pokemon.abilityState, pokemon);
if (pokemon.m.innates) {
for (const innate of pokemon.m.innates) {
// permanent abilities
if (pokemon.volatiles['ability:' + innate]) continue;
pokemon.addVolatile('ability:' + innate, pokemon);
}
}
}
}
},
},
oblivious: {
inherit: true,
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate' || effect.id === 'ability:intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Oblivious', '[of] ' + target);
}
},
},
owntempo: {
inherit: true,
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate' || effect.id === 'ability:intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Own Tempo', '[of] ' + target);
}
},
},
poisontouch: {
inherit: true,
// Activate after Sheer Force to make interaction determistic. The ordering for this ability is
// an arbitary decision, but is modelled on Stench, which is reflective of on-cart behaviour.
onModifyMovePriority: -1,
},
powerofalchemy: {
inherit: true,
onAllyFaint(ally) {
const pokemon = this.effectState.target;
if (!pokemon.hp) return;
const isAbility = pokemon.ability === 'powerofalchemy';
let possibleAbilities = [ally.ability];
if (ally.m.innates) possibleAbilities.push(...ally.m.innates);
const additionalBannedAbilities = [
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'wonderguard', pokemon.ability, ...(pokemon.m.innates || []),
];
possibleAbilities = possibleAbilities
.filter(val => !this.dex.abilities.get(val).isPermanent && !additionalBannedAbilities.includes(val));
if (!possibleAbilities.length) return;
const ability = this.dex.abilities.get(possibleAbilities[this.random(possibleAbilities.length)]);
this.add('-ability', pokemon, ability, '[from] ability: Power of Alchemy', '[of] ' + ally);
if (isAbility) {
pokemon.setAbility(ability);
} else {
pokemon.removeVolatile("ability:powerofalchemy");
pokemon.addVolatile("ability:" + ability, pokemon);
}
},
},
rattled: {
inherit: true,
onAfterBoost(boost, target, source, effect) {
if (effect && (effect.id === 'intimidate' || effect.id === 'ability:intimidate')) {
this.boost({spe: 1});
}
},
},
receiver: {
inherit: true,
onAllyFaint(ally) {
const pokemon = this.effectState.target;
if (!pokemon.hp) return;
const isAbility = pokemon.ability === 'receiver';
let possibleAbilities = [ally.ability];
if (ally.m.innates) possibleAbilities.push(...ally.m.innates);
const additionalBannedAbilities = [
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'wonderguard', pokemon.ability, ...(pokemon.m.innates || []),
];
possibleAbilities = possibleAbilities
.filter(val => !this.dex.abilities.get(val).isPermanent && !additionalBannedAbilities.includes(val));
if (!possibleAbilities.length) return;
const ability = this.dex.abilities.get(possibleAbilities[this.random(possibleAbilities.length)]);
this.add('-ability', pokemon, ability, '[from] ability: Receiver', '[of] ' + ally);
if (isAbility) {
pokemon.setAbility(ability);
} else {
pokemon.removeVolatile("ability:receiver");
pokemon.addVolatile("ability:" + ability, pokemon);
}
},
},
scrappy: {
inherit: true,
onBoost(boost, target, source, effect) {
if (effect.id === 'intimidate' || effect.id === 'ability:intimidate') {
delete boost.atk;
this.add('-fail', target, 'unboost', 'Attack', '[from] ability: Scrappy', '[of] ' + target);
}
},
},
trace: {
inherit: true,
onUpdate(pokemon) {
if (!pokemon.isStarted) return;
const isAbility = pokemon.ability === 'trace';
const possibleTargets: Pokemon[] = [];
for (const target of pokemon.side.foe.active) {
if (target && !target.fainted) {
possibleTargets.push(target);
}
}
while (possibleTargets.length) {
const rand = this.random(possibleTargets.length);
const target = possibleTargets[rand];
let possibleAbilities = [target.ability];
if (target.m.innates) possibleAbilities.push(...target.m.innates);
const additionalBannedAbilities = [
// Zen Mode included here for compatability with Gen 5-6
'noability', 'flowergift', 'forecast', 'hungerswitch', 'illusion', 'imposter', 'neutralizinggas', 'powerofalchemy', 'receiver', 'trace', 'zenmode', pokemon.ability, ...(pokemon.m.innates || []),
];
possibleAbilities = possibleAbilities
.filter(val => !this.dex.abilities.get(val).isPermanent && !additionalBannedAbilities.includes(val));
if (!possibleAbilities.length) {
possibleTargets.splice(rand, 1);
continue;
}
const ability = this.dex.abilities.get(this.sample(possibleAbilities));
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
if (isAbility) {
pokemon.setAbility(ability);
} else {
pokemon.removeVolatile("ability:trace");
pokemon.addVolatile("ability:" + ability, pokemon);
}
return;
}
},
},
wanderingspirit: {
inherit: true,
onDamagingHit(damage, target, source, move) {
const isAbility = target.ability === 'wanderingspirit';
const additionalBannedAbilities = ['hungerswitch', 'illusion', 'neutralizinggas', 'wonderguard'];
if (isAbility) {
if (source.getAbility().isPermanent || additionalBannedAbilities.includes(source.ability) ||
target.volatiles['dynamax']
) {
return;
}
if (this.checkMoveMakesContact(move, source, target)) {
const sourceAbility = source.setAbility('wanderingspirit', target);
if (!sourceAbility) return;
if (target.isAlly(source)) {
this.add('-activate', target, 'Skill Swap', '', '', '[of] ' + source);
} else {
this.add('-activate', target, 'ability: Wandering Spirit', this.dex.abilities.get(sourceAbility).name, 'Wandering Spirit', '[of] ' + source);
}
target.setAbility(sourceAbility);
}
} else {
// Make Wandering Spirit replace a random ability
const possibleAbilities = [source.ability, ...(source.m.innates || [])]
.filter(val => !this.dex.abilities.get(val).isPermanent && !additionalBannedAbilities.includes(val));
if (!possibleAbilities.length || target.volatiles['dynamax']) return;
if (move.flags['contact']) {
const sourceAbility = this.sample(possibleAbilities);
if (sourceAbility === source.ability) {
if (!source.setAbility('wanderingspirit', target)) return;
} else {
source.removeVolatile('ability:' + sourceAbility);
source.addVolatile('ability:wanderingspirit', source);
}
if (target.isAlly(source)) {
this.add('-activate', target, 'Skill Swap', '', '', '[of] ' + source);
} else {
this.add('-activate', target, 'ability: Wandering Spirit', this.dex.abilities.get(sourceAbility).name, 'Wandering Spirit', '[of] ' + source);
}
if (sourceAbility === source.ability) {
target.setAbility(sourceAbility);
} else {
target.removeVolatile('ability:wanderingspirit');
target.addVolatile('ability:' + sourceAbility, target);
}
}
}
},
},
}; | the_stack |
/// <reference path="botbuilder.d.ts" />
declare var cytoscape: any;
module VORLON {
declare var vorlonBaseURL: string;
export class BotFrameworkInspectorDashboard extends DashboardPlugin {
constructor() {
super("botFrameworkInspector", "control.html", "control.css");
this._ready = false;
this._id = "BOTFRAMEWORKINSPECTOR";
}
private _lastReceivedBotInfo: BotInfo;
private _dialogsContainer: HTMLDivElement;
private _dialogStacksContainer: HTMLDivElement;
private _divPluginBot: HTMLDivElement;
private _datacheckbox: HTMLInputElement;
public startDashboardSide(div: HTMLDivElement = null): void {
this._insertHtmlContentAsync(div, (filledDiv) => {
this._dialogsContainer = <HTMLDivElement>document.getElementById("dialogs");
this._dialogStacksContainer = <HTMLDivElement>document.getElementById("dialogstacks");
var firstInitialization = () => {
if (!this._ready && this._divPluginBot.style.display === "none") {
window.setTimeout(firstInitialization, 500);
}
else {
this._ready = true;
this.display();
//this._drawGraphNodes();
}
};
this._loadScript("/vorlon/plugins/botFrameworkInspector/cytoscape.min.js", () => {
this._loadScript("/vorlon/plugins/botFrameworkInspector/dagre.min.js", () => {
this._loadScript("/vorlon/plugins/botFrameworkInspector/cytoscape-dagre.js", () => {
this._divPluginBot = <HTMLDivElement>document.getElementsByClassName("plugin-botframeworkinspector")[0];
window.setTimeout(firstInitialization, 500);
});
});
});
this._datacheckbox = document.getElementById("showdatacheckbox") as HTMLInputElement;
this._datacheckbox.addEventListener("click", (elem) => {
var from = 'data';
var to = 'data-hidden';
if (this._datacheckbox.checked) {
from = 'data-hidden';
to = 'data';
}
var els = document.getElementsByClassName(from);
while (els.length) {
els[0].className = to;
}
});
});
}
private _drawGraphNodes(nodesList: any[], edgesList: any[]) {
var cy = cytoscape({
container: <HTMLElement>document.getElementById('right'),
boxSelectionEnabled: false,
autounselectify: true,
wheelSensitivity: 0.2,
layout: {
name: 'dagre'
},
style: [
{
selector: 'node',
style: {
'content': 'data(value)',
'text-opacity': 0.5,
'text-valign': 'center',
'text-halign': 'right',
'background-color': '#11479e'
}
},
{
selector: 'edge',
style: {
'width': 2,
'target-arrow-shape': 'triangle',
'line-color': '#9dbaea',
'target-arrow-color': '#9dbaea',
'curve-style': 'bezier'
}
},
{
selector: 'node.currentState',
style: {
'background-color': '#86B342'
}
}
],
elements: {
nodes: nodesList,
edges: edgesList
},
});
cy.on('tap', 'node', function(event){
var evtTarget = event.cyTarget;
console.log(evtTarget.id());
});
}
private _loadScript(url, callback) {
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = function () {
callback();
};
script.src = vorlonBaseURL + url;
document.getElementsByTagName("head")[0].appendChild(script);
}
public onRealtimeMessageReceivedFromClientSide(receivedObject: any): void {
this._lastReceivedBotInfo = receivedObject;
this.display();
//this._drawGraphNodes();
}
public display() {
var nodesList = [];
var edgesList = [];
var currentTreeBranch = [];
if (this._lastReceivedBotInfo) {
this._dialogsContainer.innerHTML = null;
this._lastReceivedBotInfo.dialogDataList.forEach((dataList) => {
var dialog = document.createElement("div");
dialog.classList.add("dialog");
var dialogid = document.createElement("p");
dialogid.innerText = `${dataList.library} > ${dataList.id}`;
dialogid.classList.add("dialog-id");
dialog.appendChild(dialogid);
var dialogDetail = document.createElement("div");
dialogDetail.classList.add("dialog-detail");
dialog.appendChild(dialogDetail);
var waterfallStepsLabel = document.createElement("p");
waterfallStepsLabel.innerText = "Steps ";
dialogDetail.appendChild(waterfallStepsLabel);
var waterfallSteps = document.createElement("div");
waterfallSteps.classList.add("waterfall-steps");
dialogDetail.appendChild(waterfallSteps);
if (dataList.dialog && dataList.dialog.length) {
if(dataList.dialog.length > 0){
for(var i = 0; i < dataList.dialog.length; i++){
var waterfallStep = document.createElement("div");
waterfallStep.classList.add("waterfall-step");
waterfallStep.innerText = (i + 1).toString();
waterfallStep.title = dataList.dialog[i];
waterfallSteps.appendChild(waterfallStep);
}
}
else {
waterfallStepsLabel.innerText += " none.";
}
}
else {
waterfallStepsLabel.innerText += " none.";
}
this._dialogsContainer.appendChild(dialog);
});
if(this._lastReceivedBotInfo.userEntries && this._lastReceivedBotInfo.userEntries.length){
this._dialogStacksContainer.innerHTML = null;
this._lastReceivedBotInfo.userEntries.forEach((botUserEntry) => {
var userEntry = document.createElement("div");
userEntry.classList.add("user-entry");
var entry = document.createElement("p");
entry.classList.add("entry");
entry.innerHTML = "<strong>User entry:</strong> " + botUserEntry.message.text;
userEntry.appendChild(entry);
var stacks = document.createElement("div");
stacks.classList.add("stacks");
userEntry.appendChild(stacks);
//loop on each stack: one for now
botUserEntry.dialogStacks.forEach((dialogSessionInfo) => {
var stack = document.createElement("div");
stack.classList.add("stack");
stacks.appendChild(stack);
var dialogsInStack = document.createElement("div");
dialogsInStack.classList.add("dialogs-in-stack");
stack.appendChild(dialogsInStack);
if(dialogSessionInfo.sessionState.callstack && dialogSessionInfo.sessionState.callstack.length > 0){
var lineSeparator:HTMLDivElement;
//loop on each dialog in the stack
dialogSessionInfo.sessionState.callstack.forEach((dialog) => {
var dialogInStack = document.createElement("div");
dialogInStack.classList.add("dialog-in-stack");
dialogInStack.innerText = dialog.id;
if(dialog.state["BotBuilder.Data.WaterfallStep"] != undefined)
dialogInStack.innerText += "(" + (dialog.state["BotBuilder.Data.WaterfallStep"] + 1) + ")";
dialogsInStack.appendChild(dialogInStack);
lineSeparator = document.createElement("div");
lineSeparator.classList.add("line");
dialogsInStack.appendChild(lineSeparator);
});
}
else {
dialogsInStack.innerText = "(No dialog in stack)";
lineSeparator = document.createElement("div");
lineSeparator.classList.add("line");
dialogsInStack.appendChild(lineSeparator);
}
var eventType = document.createElement("p");
eventType.innerText = `[${EventType[dialogSessionInfo.eventType]}`;
if(dialogSessionInfo.impactedDialogId) {
eventType.innerText += `(${dialogSessionInfo.impactedDialogId})]`;
if (dialogSessionInfo.eventType === EventType.BeginDialog) {
//If begin dialog is called from an empty start
if(!dialogSessionInfo.sessionState.callstack || dialogSessionInfo.sessionState.callstack.length == 0){
//Make sure we start from scratch
currentTreeBranch = [];
}
var newNode = {data: { id: nodesList.length, value: dialogSessionInfo.impactedDialogId}};
nodesList.push(newNode);
currentTreeBranch.push(newNode);
if (currentTreeBranch.length > 1) {
var currentIndex = currentTreeBranch.length - 1;
var newEdge = { data: { source: currentTreeBranch[currentIndex-1].data.id, target: currentTreeBranch[currentIndex].data.id } };
edgesList.push(newEdge);
}
}
}
else {
eventType.innerText += "]";
}
if (dialogSessionInfo.eventType === EventType.EndDialog || dialogSessionInfo.eventType === EventType.EndDialogWithResult) {
if (currentTreeBranch.length > 1) {
var currentIndex = currentTreeBranch.length - 1;
var newEdge = { data: { source: currentTreeBranch[currentIndex].data.id, target: currentTreeBranch[currentIndex-1].data.id } };
edgesList.push(newEdge);
currentTreeBranch.pop();
}
}
if (dialogSessionInfo.eventType === EventType.EndConversation) {
if (currentTreeBranch.length > 1) {
currentTreeBranch = [];
}
}
dialogsInStack.appendChild(eventType);
var userData = document.createElement("div");
userData.classList.add(this._datacheckbox.checked ? "data" : "data-hidden");
userData.innerHTML = "<p><strong>ConversationData:</strong> " + JSON.stringify(dialogSessionInfo.conversationData) + "</p>";
userData.innerHTML += "<p><strong>DialogData:</strong> " + JSON.stringify(dialogSessionInfo.dialogData) + "</p>";
userData.innerHTML += "<p><strong>PrivateConversationData:</strong> " + JSON.stringify(dialogSessionInfo.privateConversationData) + "</p>";
userData.innerHTML += "<p><strong>UserData:</strong> " + JSON.stringify(dialogSessionInfo.userData) + "</p>";
stack.appendChild(userData);
});
this._dialogStacksContainer.appendChild(userEntry);
});
nodesList[nodesList.length - 1].classes = 'currentState';
this._drawGraphNodes(nodesList, edgesList);
}
}
}
}
//Register the plugin with vorlon core
Core.RegisterDashboardPlugin(new BotFrameworkInspectorDashboard());
}
interface Window {
flowchart: FlowChart;
}
interface FlowChart {
parse(code: string): any;
}; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
VirtualMachineScaleSet,
VirtualMachineScaleSetsListOptionalParams,
VirtualMachineScaleSetsListAllOptionalParams,
VirtualMachineScaleSetSku,
VirtualMachineScaleSetsListSkusOptionalParams,
UpgradeOperationHistoricalStatusInfo,
VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams,
VirtualMachineScaleSetsCreateOrUpdateOptionalParams,
VirtualMachineScaleSetsCreateOrUpdateResponse,
VirtualMachineScaleSetUpdate,
VirtualMachineScaleSetsUpdateOptionalParams,
VirtualMachineScaleSetsUpdateResponse,
VirtualMachineScaleSetsDeleteOptionalParams,
VirtualMachineScaleSetsGetOptionalParams,
VirtualMachineScaleSetsGetResponse,
VirtualMachineScaleSetsDeallocateOptionalParams,
VirtualMachineScaleSetVMInstanceRequiredIDs,
VirtualMachineScaleSetsDeleteInstancesOptionalParams,
VirtualMachineScaleSetsGetInstanceViewOptionalParams,
VirtualMachineScaleSetsGetInstanceViewResponse,
VirtualMachineScaleSetsPowerOffOptionalParams,
VirtualMachineScaleSetsRestartOptionalParams,
VirtualMachineScaleSetsStartOptionalParams,
VirtualMachineScaleSetsRedeployOptionalParams,
VirtualMachineScaleSetsPerformMaintenanceOptionalParams,
VirtualMachineScaleSetsUpdateInstancesOptionalParams,
VirtualMachineScaleSetsReimageOptionalParams,
VirtualMachineScaleSetsReimageAllOptionalParams,
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkOptionalParams,
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse,
VMScaleSetConvertToSinglePlacementGroupInput,
VirtualMachineScaleSetsConvertToSinglePlacementGroupOptionalParams,
OrchestrationServiceStateInput,
VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a VirtualMachineScaleSets. */
export interface VirtualMachineScaleSets {
/**
* Gets a list of all VM scale sets under a resource group.
* @param resourceGroupName The name of the resource group.
* @param options The options parameters.
*/
list(
resourceGroupName: string,
options?: VirtualMachineScaleSetsListOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSet>;
/**
* Gets a list of all VM Scale Sets in the subscription, regardless of the associated resource group.
* Use nextLink property in the response to get the next page of VM Scale Sets. Do this till nextLink
* is null to fetch all the VM Scale Sets.
* @param options The options parameters.
*/
listAll(
options?: VirtualMachineScaleSetsListAllOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSet>;
/**
* Gets a list of SKUs available for your VM scale set, including the minimum and maximum VM instances
* allowed for each SKU.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
listSkus(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsListSkusOptionalParams
): PagedAsyncIterableIterator<VirtualMachineScaleSetSku>;
/**
* Gets list of OS upgrades on a VM scale set instance.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
listOSUpgradeHistory(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOSUpgradeHistoryOptionalParams
): PagedAsyncIterableIterator<UpgradeOperationHistoricalStatusInfo>;
/**
* Create or update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSet,
options?: VirtualMachineScaleSetsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<VirtualMachineScaleSetsCreateOrUpdateResponse>,
VirtualMachineScaleSetsCreateOrUpdateResponse
>
>;
/**
* Create or update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSet,
options?: VirtualMachineScaleSetsCreateOrUpdateOptionalParams
): Promise<VirtualMachineScaleSetsCreateOrUpdateResponse>;
/**
* Update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSetUpdate,
options?: VirtualMachineScaleSetsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<VirtualMachineScaleSetsUpdateResponse>,
VirtualMachineScaleSetsUpdateResponse
>
>;
/**
* Update a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set to create or update.
* @param parameters The scale set object.
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VirtualMachineScaleSetUpdate,
options?: VirtualMachineScaleSetsUpdateOptionalParams
): Promise<VirtualMachineScaleSetsUpdateResponse>;
/**
* Deletes a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeleteOptionalParams
): Promise<void>;
/**
* Display information about a virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetOptionalParams
): Promise<VirtualMachineScaleSetsGetResponse>;
/**
* Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and
* releases the compute resources. You are not billed for the compute resources that this virtual
* machine scale set deallocates.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginDeallocate(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeallocateOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deallocates specific virtual machines in a VM scale set. Shuts down the virtual machines and
* releases the compute resources. You are not billed for the compute resources that this virtual
* machine scale set deallocates.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginDeallocateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsDeallocateOptionalParams
): Promise<void>;
/**
* Deletes virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
beginDeleteInstances(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsDeleteInstancesOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
beginDeleteInstancesAndWait(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsDeleteInstancesOptionalParams
): Promise<void>;
/**
* Gets the status of a VM scale set instance.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
getInstanceView(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsGetInstanceViewOptionalParams
): Promise<VirtualMachineScaleSetsGetInstanceViewResponse>;
/**
* Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still
* attached and you are getting charged for the resources. Instead, use deallocate to release resources
* and avoid charges.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginPowerOff(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPowerOffOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Power off (stop) one or more virtual machines in a VM scale set. Note that resources are still
* attached and you are getting charged for the resources. Instead, use deallocate to release resources
* and avoid charges.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginPowerOffAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPowerOffOptionalParams
): Promise<void>;
/**
* Restarts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginRestart(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRestartOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Restarts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginRestartAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRestartOptionalParams
): Promise<void>;
/**
* Starts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginStart(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsStartOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Starts one or more virtual machines in a VM scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginStartAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsStartOptionalParams
): Promise<void>;
/**
* Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and
* powers them back on.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginRedeploy(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRedeployOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Shuts down all the virtual machines in the virtual machine scale set, moves them to a new node, and
* powers them back on.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginRedeployAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsRedeployOptionalParams
): Promise<void>;
/**
* Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which
* are not eligible for perform maintenance will be failed. Please refer to best practices for more
* details:
* https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginPerformMaintenance(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPerformMaintenanceOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Perform maintenance on one or more virtual machines in a VM scale set. Operation on instances which
* are not eligible for perform maintenance will be failed. Please refer to best practices for more
* details:
* https://docs.microsoft.com/en-us/azure/virtual-machine-scale-sets/virtual-machine-scale-sets-maintenance-notifications
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginPerformMaintenanceAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsPerformMaintenanceOptionalParams
): Promise<void>;
/**
* Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
beginUpdateInstances(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsUpdateInstancesOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Upgrades one or more virtual machines to the latest SKU set in the VM scale set model.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param vmInstanceIDs A list of virtual machine instance IDs from the VM scale set.
* @param options The options parameters.
*/
beginUpdateInstancesAndWait(
resourceGroupName: string,
vmScaleSetName: string,
vmInstanceIDs: VirtualMachineScaleSetVMInstanceRequiredIDs,
options?: VirtualMachineScaleSetsUpdateInstancesOptionalParams
): Promise<void>;
/**
* Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't
* have a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is
* reset to initial state.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginReimage(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Reimages (upgrade the operating system) one or more virtual machines in a VM scale set which don't
* have a ephemeral OS disk, for virtual machines who have a ephemeral OS disk the virtual machine is
* reset to initial state.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginReimageAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageOptionalParams
): Promise<void>;
/**
* Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This
* operation is only supported for managed disks.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginReimageAll(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageAllOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Reimages all the disks ( including data disks ) in the virtual machines in a VM scale set. This
* operation is only supported for managed disks.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param options The options parameters.
*/
beginReimageAllAndWait(
resourceGroupName: string,
vmScaleSetName: string,
options?: VirtualMachineScaleSetsReimageAllOptionalParams
): Promise<void>;
/**
* Manual platform update domain walk to update virtual machines in a service fabric virtual machine
* scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the VM scale set.
* @param platformUpdateDomain The platform update domain for which a manual recovery walk is requested
* @param options The options parameters.
*/
forceRecoveryServiceFabricPlatformUpdateDomainWalk(
resourceGroupName: string,
vmScaleSetName: string,
platformUpdateDomain: number,
options?: VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkOptionalParams
): Promise<
VirtualMachineScaleSetsForceRecoveryServiceFabricPlatformUpdateDomainWalkResponse
>;
/**
* Converts SinglePlacementGroup property to false for a existing virtual machine scale set.
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for ConvertToSinglePlacementGroup API.
* @param options The options parameters.
*/
convertToSinglePlacementGroup(
resourceGroupName: string,
vmScaleSetName: string,
parameters: VMScaleSetConvertToSinglePlacementGroupInput,
options?: VirtualMachineScaleSetsConvertToSinglePlacementGroupOptionalParams
): Promise<void>;
/**
* Changes ServiceState property for a given service
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for SetOrchestrationServiceState API.
* @param options The options parameters.
*/
beginSetOrchestrationServiceState(
resourceGroupName: string,
vmScaleSetName: string,
parameters: OrchestrationServiceStateInput,
options?: VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Changes ServiceState property for a given service
* @param resourceGroupName The name of the resource group.
* @param vmScaleSetName The name of the virtual machine scale set to create or update.
* @param parameters The input object for SetOrchestrationServiceState API.
* @param options The options parameters.
*/
beginSetOrchestrationServiceStateAndWait(
resourceGroupName: string,
vmScaleSetName: string,
parameters: OrchestrationServiceStateInput,
options?: VirtualMachineScaleSetsSetOrchestrationServiceStateOptionalParams
): Promise<void>;
} | the_stack |
import type Prettier from "prettier";
import * as Codec from "@truffle/codec";
import * as Abi from "@truffle/abi-utils";
import {Abi as SchemaAbi} from "@truffle/contract-schema/spec";
import { version } from "../package.json";
import {Visitor, VisitOptions, dispatch, Node} from "./visitor";
import { forRange, VersionFeatures, mixed } from "./version-features";
import * as defaults from "./defaults";
import {
Component,
Declaration,
Declarations,
collectDeclarations,
} from "./declarations";
import { collectAbiFeatures, AbiFeatures } from "./abi-features";
let prettier: typeof Prettier
try {
prettier = require("prettier");
} catch {
// no-op
}
export interface GenerateSolidityOptions {
abi: Abi.Abi | SchemaAbi;
name?: string;
solidityVersion?: string;
license?: string;
prettifyOutput?: boolean;
}
export const generateSolidity = ({
abi,
name = defaults.name,
solidityVersion = defaults.solidityVersion,
license = defaults.license,
prettifyOutput = prettier && defaults.prettifyOutput,
}: GenerateSolidityOptions) => {
if (!prettier && prettifyOutput) {
throw new Error("Could not require() prettier");
}
const versionFeatures = forRange(solidityVersion);
const abiFeatures = collectAbiFeatures(abi);
const declarations = collectDeclarations(abi);
const generated = dispatch({
node: abi,
visitor: new SolidityGenerator({
name,
solidityVersion,
license,
versionFeatures,
abiFeatures,
declarations,
}),
});
if (!prettifyOutput) {
return generated;
}
try {
return prettier.format(generated, {
plugins: ["prettier-plugin-solidity"],
// @ts-ignore
parser: "solidity-parse",
});
} catch (error) {
return generated;
}
};
interface Context {
interfaceName?: string;
parameterModifiers?: (parameter: Abi.Parameter) => string[];
}
type Visit<N extends Node> = VisitOptions<N, Context | undefined>;
type ConstructorOptions = {
versionFeatures: VersionFeatures;
abiFeatures: AbiFeatures;
declarations: Declarations;
} & Required<
Omit<GenerateSolidityOptions, "abi" | "prettifyOutput">
>;
const shimGlobalInterfaceName = "__Structs";
class SolidityGenerator implements Visitor<string, Context | undefined> {
private name: string;
private license: string;
private solidityVersion: string;
private versionFeatures: VersionFeatures;
private abiFeatures: AbiFeatures;
private declarations: Declarations;
private identifiers: {
[signature: string]: {
identifier: string;
container?: string;
}
};
constructor({
name,
license,
solidityVersion,
versionFeatures,
abiFeatures,
declarations,
}: ConstructorOptions) {
this.name = name;
this.license = license;
this.solidityVersion = solidityVersion;
this.versionFeatures = versionFeatures;
this.abiFeatures = abiFeatures;
this.declarations = declarations;
this.identifiers = {};
let index = 0;
for (const [container, signatures] of Object.entries(declarations.containerSignatures)) {
for (const signature of signatures) {
const {
identifier = `S_${index++}`
} = declarations.signatureDeclarations[signature];
if (container === "" && this.versionFeatures["global-structs"] !== true) {
this.identifiers[signature] = {
container: shimGlobalInterfaceName,
identifier
};
} else if (container === "") {
this.identifiers[signature] = { identifier };
} else {
this.identifiers[signature] = {
container,
identifier
}
}
}
}
}
visitAbi({node: abi}: Visit<Abi.Abi>) {
return [
this.generateHeader(),
this.generateInterface(abi),
this.generateDeclarations(),
this.generateAutogeneratedNotice(abi),
].join("\n\n");
}
visitFunctionEntry({node: entry, context}: Visit<Abi.FunctionEntry>): string {
const {name, inputs, stateMutability} = entry;
return [
`function ${name}(`,
entry.inputs.map((node) =>
dispatch({
node,
visitor: this,
context: {
...context,
parameterModifiers: (parameter: Abi.Parameter) =>
parameter.type.startsWith("tuple") ||
parameter.type.includes("[") ||
parameter.type === "bytes" ||
parameter.type === "string"
? [this.generateArrayParameterLocation(parameter)]
: [],
},
})
),
`) external`,
this.generateStateMutability(entry),
entry.outputs && entry.outputs.length > 0
? [
`returns (`,
entry.outputs
.map((node) =>
dispatch({
node,
visitor: this,
context: {
parameterModifiers: (parameter: Abi.Parameter) =>
parameter.type.startsWith("tuple") ||
parameter.type.includes("[") ||
parameter.type === "bytes" ||
parameter.type === "string"
? ["memory"]
: [],
},
})
)
.join(", "),
`)`,
].join("")
: ``,
`;`,
].join(" ");
}
visitConstructorEntry({node: entry}: Visit<Abi.ConstructorEntry>): string {
// interfaces don't have constructors
return "";
}
visitFallbackEntry({ node: entry }: Visit<Abi.FallbackEntry>): string {
const servesAsReceive = this.abiFeatures["defines-receive"] &&
this.versionFeatures["receive-keyword"] !== true;
const { stateMutability } = entry;
return `${this.generateFallbackName()} () external ${
stateMutability === "payable" || servesAsReceive ? "payable" : ""
};`;
}
visitReceiveEntry() {
// if version has receive, emit as normal
if (this.versionFeatures["receive-keyword"] === true) {
return `receive () external payable;`;
}
// if this ABI defines a fallback separately, emit nothing, since
// visitFallbackEntry will cover it
if (this.abiFeatures["defines-fallback"]) {
return "";
}
// otherwise, explicitly invoke visitFallbackEntry
return this.visitFallbackEntry({
node: { type: "fallback", stateMutability: "payable" },
});
}
visitEventEntry({node: entry, context}: Visit<Abi.EventEntry>): string {
const {name, inputs, anonymous} = entry;
return [
`event ${name}(`,
inputs.map((node) =>
dispatch({
node,
visitor: this,
context: {
...context,
parameterModifiers: (parameter: Abi.Parameter) =>
// TODO fix this
(parameter as Abi.EventParameter).indexed ? ["indexed"] : [],
},
})
),
`)`,
`${anonymous ? "anonymous" : ""};`,
].join(" ");
}
visitErrorEntry({node: entry, context}: Visit<Abi.ErrorEntry>): string {
if (this.versionFeatures["custom-errors"] !== true) {
throw new Error("ABI defines custom errors; use Solidity v0.8.4 or higher");
}
const {name, inputs} = entry;
return [
`error ${name}(`,
inputs.map((node) =>
dispatch({
node,
visitor: this,
context: {
...context,
parameterModifiers: (parameter: Abi.Parameter) => []
},
})
),
`);`,
].join(" ");
}
visitParameter({node: parameter, context}: Visit<Abi.Parameter>) {
const type = this.generateType(parameter, context);
// @ts-ignore
const {parameterModifiers} = context;
return [type, ...parameterModifiers(parameter), parameter.name].join(" ");
}
private generateHeader(): string {
const includeExperimentalPragma =
this.abiFeatures["needs-abiencoder-v2"] &&
this.versionFeatures["abiencoder-v2"] !== "default";
return [
`// SPDX-License-Identifier: ${this.license}`,
`// !! THIS FILE WAS AUTOGENERATED BY abi-to-sol v${version}. SEE SOURCE BELOW. !!`,
`pragma solidity ${this.solidityVersion};`,
...(
includeExperimentalPragma
? [`pragma experimental ABIEncoderV2;`]
: []
)
].join("\n");
}
private generateAutogeneratedNotice(abi: Abi.Abi): string {
return [
``,
`// THIS FILE WAS AUTOGENERATED FROM THE FOLLOWING ABI JSON:`,
`/*`,
JSON.stringify(abi),
`*/`,
].join("\n");
}
private generateDeclarations(): string {
if (
this.versionFeatures["structs-in-interfaces"] !== true &&
Object.keys(this.declarations.signatureDeclarations).length > 0
) {
throw new Error(
"abi-to-sol does not support custom struct types for this Solidity version"
);
}
const externalContainers = Object.keys(this.declarations.containerSignatures)
.filter(container => container !== "" && container !== this.name);
const externalDeclarations = externalContainers
.map(container => [
`interface ${container} {`,
this.generateDeclarationsForContainer(container),
`}`
].join("\n"))
.join("\n\n");
const globalSignatures = this.declarations.containerSignatures[""] || [];
if (globalSignatures.length > 0) {
const declarations = this.versionFeatures["global-structs"] === true
? this.generateDeclarationsForContainer("")
: [
`interface ${shimGlobalInterfaceName} {`,
this.generateDeclarationsForContainer(""),
`}`
].join("\n");
return [declarations, externalDeclarations].join("\n\n");
}
return externalDeclarations;
}
private generateDeclarationsForContainer(container: string): string {
const signatures = new Set(
this.declarations.containerSignatures[container]
);
if (container === "" && this.versionFeatures["global-structs"] !== true) {
container = shimGlobalInterfaceName;
}
return Object.entries(this.declarations.signatureDeclarations)
.filter(([signature]) => signatures.has(signature))
.map(([signature, declaration]) => {
const { identifier } = this.identifiers[signature];
const components = this.generateComponents(declaration, { interfaceName: container });
return `struct ${identifier} { ${components} }`;
})
.join("\n\n");
}
private generateComponents(
declaration: Declaration,
context?: Pick<Context, "interfaceName">
): string {
return declaration.components
.map((component) => {
const {name} = component;
return `${this.generateType(component, context)} ${name};`;
})
.join("\n");
}
private generateType(
variable: Abi.Parameter | Component,
context: Pick<Context, "interfaceName"> = {}
): string {
const signature = this.generateSignature(variable);
if (!signature) {
return variable.type;
}
const { type } = variable;
const { container, identifier } = this.identifiers[signature];
if (container && container !== context.interfaceName) {
return type.replace("tuple", `${container}.${identifier}`);
}
if (!container && this.versionFeatures["global-structs"] !== true) {
return type.replace("tuple", `${shimGlobalInterfaceName}.${identifier}`);
}
return type.replace("tuple", identifier);
}
private generateSignature(
variable: Abi.Parameter | Component
): string | undefined {
if ("signature" in variable && variable.signature) {
return variable.signature;
}
if ("components" in variable && variable.components) {
return Codec.AbiData.Utils.abiTupleSignature(variable.components);
}
}
private generateStateMutability(
entry:
| Abi.FunctionEntry
| Abi.FallbackEntry
| Abi.ConstructorEntry
| Abi.ReceiveEntry
): string {
if (entry.stateMutability && entry.stateMutability !== "nonpayable") {
return entry.stateMutability;
}
return "";
}
private generateFallbackName(): string {
switch (this.versionFeatures["fallback-keyword"]) {
case true: {
return "fallback";
}
case false: {
return "function";
}
case mixed: {
throw new Error(
`Desired Solidity range lacks unambigious fallback syntax.`
);
}
}
}
private generateArrayParameterLocation(parameter: Abi.Parameter): string {
switch (this.versionFeatures["array-parameter-location"]) {
case undefined: {
return "";
}
case mixed: {
throw new Error(
`Desired Solidity range lacks unambiguous location specifier for ` +
`parameter of type "${parameter.type}".`
);
}
default: {
return this.versionFeatures["array-parameter-location"];
}
}
}
private generateInterface(abi: Abi.Abi): string {
return [
`interface ${this.name} {`,
this.generateDeclarationsForContainer(this.name),
``,
...abi.map((node) => dispatch({
node,
context: { interfaceName: this.name },
visitor: this
})),
`}`,
].join("\n");
}
} | the_stack |
* 应用设置
*
* @interface options
*/
interface options {
server: server
config: config
user: userCollection
newUserData: userData
info: optionsInfo
}
interface server {
path: string
hostname: string
port: number
protocol: string
}
interface config {
[x: string]: boolean | number | number[] | string | string[]
excludeCMD: string[]
sysmsg: string
}
type userCollection = Record<string, userData>
interface userData {
[x: string]: boolean | number | number[] | string | string[]
status: boolean
userHash: string
welcome: string
usermsg: string
raffle: boolean
lottery: boolean
pklottery: boolean
beatStorm: boolean
anchorLot: boolean
boxActivity: boolean
}
type optionsInfo = {
[x in keyof (config & userData)]: configInfoData
}
interface configInfoData {
description: string
tip: string
type: string
cognate?: string
}
/*******************
**** dm_client ****
*******************/
declare enum dmErrorStatus {
'client' = 0,
'danmaku' = 1,
'timeout' = 2
}
interface DMclientOptions {
roomID?: number
userID?: number
protocol?: DMclientProtocol
key?: string
}
type DMclientProtocol = 'socket' | 'flash' | 'ws' | 'wss'
type DMerror = DMclientError | DMdanmakuError
interface DMclientError {
status: dmErrorStatus.client | dmErrorStatus.timeout
error: Error
}
interface DMdanmakuError {
status: dmErrorStatus.danmaku
error: TypeError
data: Buffer
}
// 弹幕服务器
interface danmuInfo {
code: number
message: string
ttl: number
data: danmuInfoData
}
interface danmuInfoData {
refresh_row_factor: number
refresh_rate: number
max_delay: number
token: string
host_list: danmuInfoDataHostList[]
ip_list: danmuInfoDataIPList[]
}
interface danmuInfoDataHostList {
host: string
port: number
wss_port: number
ws_port: number
}
interface danmuInfoDataIPList {
host: string
port: number
}
/*******************
*** app_client ****
*******************/
declare enum appStatus {
'success' = 0,
'error' = 1,
'httpError' = 2,
'captcha' = 3,
'validate' = 4,
'authcode' = 5,
}
/**
* 公钥返回
*
* @interface getKeyResponse
*/
interface getKeyResponse {
ts: number
code: number
data: getKeyResponseData
}
interface getKeyResponseData {
hash: string
key: string
}
/**
* 验证返回
*
* @interface authResponse
*/
interface authResponse {
ts: number
code: number
data: authResponseData & authResponseTokeninfo
}
interface authResponseData {
url: string
}
interface authResponseData {
status: number
token_info: authResponseTokeninfo
cookie_info: authResponseCookieinfo
sso: string[]
}
interface authResponseCookieinfo {
cookies: authResponseCookieinfoCooky[]
domains: string[]
}
interface authResponseCookieinfoCooky {
name: string
value: string
http_only: number
expires: number
}
interface authResponseTokeninfo {
mid: number
access_token: string
refresh_token: string
expires_in: number
}
/**
* 注销返回
*
* @interface revokeResponse
*/
interface revokeResponse {
message: string
ts: number
code: number
}
/**
* 登录返回信息
*/
type loginResponse = loginResponseSuccess | loginResponseCaptcha | loginResponseError | loginResponseHttp
interface loginResponseSuccess {
status: appStatus.success
data: authResponse
}
interface loginResponseCaptcha {
status: appStatus.captcha | appStatus.validate | appStatus.authcode
data: authResponse
}
interface loginResponseError {
status: appStatus.error
data: authResponse
}
interface loginResponseHttp {
status: appStatus.httpError
data: XHRresponse<getKeyResponse> | XHRresponse<authResponse> | undefined
}
/**
* 登出返回信息
*/
type logoutResponse = revokeResponseSuccess | revokeResponseError | revokeResponseHttp
interface revokeResponseSuccess {
status: appStatus.success
data: revokeResponse
}
interface revokeResponseError {
status: appStatus.error
data: revokeResponse
}
interface revokeResponseHttp {
status: appStatus.httpError
data: XHRresponse<revokeResponse> | undefined
}
/**
* 验证码返回信息
*/
type captchaResponse = captchaResponseSuccess | captchaResponseError
interface captchaResponseSuccess {
status: appStatus.success
data: Buffer
}
interface captchaResponseError {
status: appStatus.error
data: XHRresponse<Buffer> | undefined
}
/**
* 二维码返回
*
* @interface authcodeResponse
*/
interface authcodeResponse {
code: number
message: string
ttl: number
data: authcodeResponseData
}
interface authcodeResponseData {
auth_code: string
url: string
}
/**
* 二维码返回信息
*/
type qrcodeResponse = qrcodeResponseSuccess | qrcodeResponseError | qrcodeResponseHttp
interface qrcodeResponseSuccess {
status: appStatus.success
data: authcodeResponse
}
interface qrcodeResponseError {
status: appStatus.error
data: authcodeResponse
}
interface qrcodeResponseHttp {
status: appStatus.httpError
data: XHRresponse<authcodeResponse> | undefined
}
/*******************
****** tools ******
*******************/
/**
* XHR设置
* 因为request已经为Deprecated状态, 为了兼容把设置项缩小, 可以会影响一些插件
*
* @interface XHRoptions
*/
interface XHRoptions {
/** @deprecated 为了兼容request, 现在可以使用url */
uri?: string | URL
url?: string | URL
// OutgoingHttpHeaders包含number, 导致无法兼容got
headers?: import('http').IncomingHttpHeaders
method?: import('got').Method
body?: string | Buffer
/** @deprecated 为了兼容request, 现在可以使用cookieJar */
jar?: import('tough-cookie').CookieJar
cookieJar?: import('tough-cookie').CookieJar
/** 为了兼容request, 保留null */
encoding?: BufferEncoding | null
/** @deprecated 为了兼容request, 现在可以使用responseType */
json?: boolean
responseType?: 'json' | 'buffer' | 'text'
}
/**
* XHR返回
*
* @interface response
* @template T
*/
interface XHRresponse<T> {
response: import('got').Response
body: T
}
/**
* 客户端消息
*
* @interface systemMSG
*/
interface systemMSG {
message: string
}
/*******************
******* db ********
*******************/
/**
* db.roomList
*
* @interface roomList
*/
interface roomList {
roomID: number
masterID: number
beatStorm: number
smallTV: number
raffle: number
lottery: number
pklottery: number
anchorLot: number
boxActivity: number
updateTime: number
}
/*******************
** bilive_client **
*******************/
/**
* 消息格式
*
* @interface raffleMessage
*/
interface raffleMessage {
cmd: 'raffle'
roomID: number
id: number
type: string
title: string
time: number
max_time: number
time_wait: number
raw: '' | TV_START | RAFFLE_START
}
/**
* 消息格式
*
* @interface lotteryMessage
*/
interface lotteryMessage {
cmd: 'lottery' | 'pklottery'
roomID: number
id: number
type: string
title: string
time: number
raw: '' | LOTTERY_START | PK_LOTTERY_START
}
/**
* 消息格式
*
* @interface beatStormMessage
*/
interface beatStormMessage {
cmd: 'beatStorm'
roomID: number
id: number
type: string
title: string
time: number
raw: '' | SPECIAL_GIFT
}
/**
* 消息格式
*
* @interface anchorLotMessage
*/
interface anchorLotMessage {
cmd: 'anchorLot'
roomID: number
id: number
title: string
raw: '' | ANCHOR_LOT_START
}
/**
* 消息格式
*
* @interface boxActivityMessage
*/
interface boxActivityMessage {
cmd: 'boxActivity'
roomID: number
id: number
title: string
raw: '' | BOX_ACTIVITY_START
}
/**
* 消息格式
*
* @interface systemMessage
*/
interface systemMessage {
cmd: 'sysmsg'
msg: string
}
type message = raffleMessage | lotteryMessage | beatStormMessage | anchorLotMessage | boxActivityMessage | systemMessage
/*******************
**** listener *****
*******************/
/**
* 统一抽奖信息
*
* @interface lotteryInfo
*/
interface lotteryInfo {
code: number
message: string
ttl: number
data: lotteryInfoData
}
interface lotteryInfoData {
activity_box: null
bls_box: null
gift_list: lotteryInfoDataGiftList[]
guard: lotteryInfoDataGuard[]
pk: lotteryInfoDataPk[]
slive_box: lotteryInfoDataSliveBox
storm: lotteryInfoDataStorm
}
interface lotteryInfoDataGiftList {
raffleId: number
title: string
type: string
payflow_id: number
from_user: lotteryInfoDataGiftListFromUser
time_wait: number
time: number
max_time: number
status: number
asset_animation_pic: string
asset_tips_pic: string
sender_type: number
}
interface lotteryInfoDataGiftListFromUser {
uname: string
face: string
}
interface lotteryInfoDataGuard {
id: number
sender: lotteryInfoDataGuardSender
keyword: string
privilege_type: number
time: number
status: number
payflow_id: string
}
interface lotteryInfoDataGuardSender {
uid: number
uname: string
face: string
}
interface lotteryInfoDataPk {
id: number
pk_id: number
room_id: number
time: number
status: number
asset_icon: string
asset_animation_pic: string
title: string
max_time: number
}
interface lotteryInfoDataSliveBox {
minute: number
silver: number
time_end: number
time_start: number
times: number
max_times: number
status: number
}
interface lotteryInfoDataStorm {
id: number
num: number
time: number
content: string
hadJoin: number
storm_gif: string
}
/**
* 获取直播列表
*
* @interface getAllList
*/
interface getAllList {
code: number
msg: string
message: string
data: getAllListData
}
interface getAllListData {
interval: number
module_list: getAllListDataList[]
}
type getAllListDataList = getAllListDataModules | getAllListDataRooms
interface getAllListDataModules {
module_info: getAllListDataModuleInfo
list: getAllListDataModuleList[]
}
interface getAllListDataRooms {
module_info: getAllListDataRoomInfo
list: getAllListDataRoomList[]
}
interface getAllListDataBaseInfo {
id: number
type: number
pic: string
title: string
link: string
}
interface getAllListDataModuleInfo extends getAllListDataBaseInfo {
count?: number
}
interface getAllListDataRoomInfo extends getAllListDataBaseInfo {
type: 6 | 9
}
interface getAllListDataModuleList {
id: number
pic: string
link: string
title: string
}
interface getAllListDataRoomList {
roomid: number
title: string
uname: string
online: number
cover: string
link: string
face: string
area_v2_parent_id: number
area_v2_parent_name: string
area_v2_id: number
area_v2_name: string
play_url: string
current_quality: number
accept_quality: number[]
broadcast_type: number
pendent_ld: string
pendent_ru: string
rec_type: number
pk_id: number
}
/*******************
** roomlistener ***
*******************/
/**
* 房间信息
*
* @interface roomInit
*/
interface roomInit {
code: number
msg: string
message: string
data: roomInitDataData
}
interface roomInitDataData {
room_id: number
short_id: number
uid: number
need_p2p: number
is_hidden: boolean
is_locked: boolean
is_portrait: boolean
live_status: number
hidden_till: number
lock_till: number
encrypted: boolean
pwd_verified: boolean
}
/*******************
***** wsserver ****
*******************/
/**
* WebSocket消息
*
* @interface clientMessage
*/
interface adminMessage {
cmd: string
ts: string
msg?: string
uid?: string
data?: config | optionsInfo | string[] | userData
} | the_stack |
* @module iModelHubClient
*/
import deepAssign from "deep-assign";
import { AccessToken, GuidString, Id64String, IModelHubStatus, Logger } from "@itwin/core-bentley";
import { ResponseError } from "@bentley/itwin-client";
import { ECJsonTypeMap, WsgInstance } from "../wsg/ECJsonTypeMap";
import { WsgQuery } from "../wsg/WsgQuery";
import { HttpRequestOptions, WsgRequestOptions } from "../wsg/WsgClient";
import { IModelHubClientLoggerCategory } from "../IModelHubClientLoggerCategories";
import { IModelBaseHandler } from "./BaseHandler";
import { AggregateResponseError, ArgumentCheck, IModelHubError } from "./Errors";
const loggerCategory: string = IModelHubClientLoggerCategory.IModelHub;
/**
* [[Lock]] type describes the kind of object that is locked.
* @internal
*/
export enum LockType {
/** Lock for the entire file. This is a global Lock that can only be taken with objectId 1. */
Db,
/** Lock for a model. It should be acquired together with a [[LockLevel.Shared]] Db Lock. */
Model,
/** Lock for a single element. It should be acquired together with a [[LockLevel.Shared]] Model Lock. */
Element,
/** Lock used to change schemas. This is a global Lock that can only be taken with objectId 1. This lock cannot have [[LockLevel.Shared]]. */
Schemas,
/** Lock used to change CodeSpecs. This is a global Lock that can only be taken with objectId 1. This lock cannot have [[LockLevel.Shared]]. */
CodeSpecs,
}
/**
* [[Lock]] level describes how restrictive the Lock is.
* @internal
*/
export enum LockLevel {
/** Lock is not owned. */
None,
/** Lock can be owned by multiple [[Briefcase]]s. Shared Lock is usually acquired together with Locks for lower level objects that depend on this object. */
Shared,
/** Lock can only be owned by a single briefcase. Exclusive Lock is required to modify model or element when using pessimistic concurrency. */
Exclusive,
}
/**
* Gets encoded instance id for a lock to be used in an URI.
* @param lock Lock to get instance id for.
* @returns Encoded lock instance id.
* @internal
*/
function getLockInstanceId(lock: Lock): string | undefined {
if (!lock || lock.briefcaseId === undefined || lock.lockType === undefined || !lock.objectId)
return undefined;
return `${lock.lockType}-${lock.objectId}-${lock.briefcaseId}`;
}
/**
* Object for specifying options when sending [[Lock]]s update requests. See [[LockHandler.update]].
* @internal
*/
export interface LockUpdateOptions {
/** Return [[Lock]]s that could not be acquired. Conflicting Locks will be set to [[ConflictingLocksError.conflictingLocks]]. If unlimitedReporting is enabled and locksPerRequest value is high, some conflicting Locks could be missed. */
deniedLocks?: boolean;
/** Attempt to get all failed [[Lock]]s, ignoring iModelHub limits. Server responses might fail when trying to return large number of conflicting Locks. */
unlimitedReporting?: boolean;
/** Number of [[Lock]]s per single request. Multiple requests will be sent if there are more Locks. If an error happens on a subsequent request, previous successful updates will not be reverted. */
locksPerRequest?: number;
/** Don't fail request on a conflict. If conflict occurs, [[Lock]]s that didn't have conflicts will be updated and any remaining subsequent requests will still be sent. */
continueOnConflict?: boolean;
}
/** Provider for default LockUpdateOptions, used by LockHandler to set defaults.
* @internal
*/
export class DefaultLockUpdateOptionsProvider {
protected _defaultOptions: LockUpdateOptions;
/** Creates an instance of DefaultRequestOptionsProvider and sets up the default options. */
constructor() {
this._defaultOptions = {
locksPerRequest: 2000,
};
}
/** Augments options with the provider's default values.
* @note The options passed in override any defaults where necessary.
* @param options Options that should be augmented.
*/
public async assignOptions(options: LockUpdateOptions): Promise<void> {
const clonedOptions: LockUpdateOptions = { ...options };
deepAssign(options, this._defaultOptions);
deepAssign(options, clonedOptions); // ensure the supplied options override the defaults
}
}
/**
* Error for conflicting [[Lock]]s. It contains an array of Locks that failed to acquire. This is returned when calling [[LockHandler.update]] with [[LockUpdateOptions.deniedLocks]] set to true.
* @internal
*/
export class ConflictingLocksError extends IModelHubError {
/** Locks that couldn't be updated due to other users owning them. */
public conflictingLocks?: Lock[];
/** Create ConflictingLocksError from IModelHubError instance.
* @param error IModelHubError to get error data from.
* @returns Undefined if the error is not for a lock conflict, otherwise newly created error instance.
* @internal
*/
public static fromError(error: IModelHubError): ConflictingLocksError | undefined {
if (error.errorNumber !== IModelHubStatus.LockOwnedByAnotherBriefcase
&& error.errorNumber !== IModelHubStatus.ConflictsAggregate) {
return undefined;
}
const result = new ConflictingLocksError(error.errorNumber);
deepAssign(result, error);
result.addLocks(error);
return result;
}
/**
* Amends this error instance with conflicting locks from another IModelHubError.
* @param error Error to get additional conflicting locks from.
* @internal
*/
public addLocks(error: IModelHubError) {
if (!error.data || !error.data.ConflictingLocks) {
return;
}
if (!this.conflictingLocks) {
this.conflictingLocks = [];
}
for (const value of (error.data.ConflictingLocks as any[])) {
const instance = { className: "Lock", schemaName: "iModelScope", properties: value };
const lock = ECJsonTypeMap.fromJson<Lock>(Lock, "wsg", instance);
if (lock) {
this.conflictingLocks.push(lock);
}
}
}
}
/**
* Base class for [[Lock]]s.
* @internal
*/
export class LockBase extends WsgInstance {
/** Type of the Lock. It describes what kind of object is locked. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.LockType")
public lockType?: LockType;
/** Level of the Lock. It describes how restrictive the Lock is. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.LockLevel")
public lockLevel?: LockLevel;
/** Id of the [[Briefcase]] that owns the Lock. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.BriefcaseId")
public briefcaseId?: number;
/** Id of the file, that the Lock belongs to. See [[Briefcase.fileId]]. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.SeedFileId")
public seedFileId?: GuidString;
/** Id of the [[ChangeSet]] that the Lock was last used with. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.ReleasedWithChangeSet")
public releasedWithChangeSet?: string;
/** Index of the [[ChangeSet]] that the Lock was last used with. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.ReleasedWithChangeSetIndex")
public releasedWithChangeSetIndex?: string;
}
/**
* Lock instance. When using pessimistic concurrency, locks ensure that only a single user can modify an object at a time.
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "iModelScope.Lock", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class Lock extends LockBase {
/** Id of the locked object. */
@ECJsonTypeMap.propertyToJson("wsg", "properties.ObjectId")
public objectId?: Id64String;
}
/**
* MultiLock: data about locks grouped by BriefcaseId, LockLevel and LockType.
* @internal
*/
@ECJsonTypeMap.classToJson("wsg", "iModelScope.MultiLock", { schemaPropertyName: "schemaName", classPropertyName: "className" })
export class MultiLock extends LockBase {
@ECJsonTypeMap.propertyToJson("wsg", "properties.ObjectIds")
public objectIds?: Id64String[];
}
/**
* Query object for getting [[Lock]]s. You can use this to modify the [[LockHandler.get]] results.
* @internal
*/
export class LockQuery extends WsgQuery {
private _isMultiLockQuery = true;
/**
* Default page size which is used when querying Locks
* @internal
*/
public static defaultPageSize: number = 10000;
/** Constructor that sets default page size. */
constructor() {
super();
this.pageSize(LockQuery.defaultPageSize);
}
/**
* Used by the handler to check whether locks in query can be grouped.
* @internal
*/
public get isMultiLockQuery() {
return this._isMultiLockQuery;
}
/**
* Query [[Lock]]s by [[Briefcase]] id.
* @param briefcaseId Id of the Briefcase.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if briefcaseId is undefined or it contains an invalid [[Briefcase]] id value.
*/
public byBriefcaseId(briefcaseId: number) {
ArgumentCheck.validBriefcaseId("briefcaseId", briefcaseId);
this.addFilter(`BriefcaseId+eq+${briefcaseId}`);
return this;
}
/**
* Query [[Lock]]s by [[LockType]].
* @param lockType Lock type to query.
* @returns This query.
*/
public byLockType(lockType: LockType) {
this.addFilter(`LockType+eq+${lockType}`);
return this;
}
/**
* Query [[Lock]]s by [[LockLevel]].
* @param lockLevel Lock level to query.
* @returns This query.
*/
public byLockLevel(lockLevel: LockLevel) {
this.addFilter(`LockLevel+eq+${lockLevel}`);
return this;
}
/**
* Query [[Lock]]s by ObjectId.
* @param objectId Id of the object.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) if objectId is undefined.
*/
public byObjectId(objectId: Id64String) {
ArgumentCheck.defined("objectId", objectId);
this._isMultiLockQuery = false;
this.addFilter(`ObjectId+eq+'${objectId}'`);
return this;
}
/**
* Query [[Lock]]s by [[ChangeSet]] id that it was released with.
* @param changesetId Id of the ChangeSet.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if changeSetId is undefined or empty, or it contains an invalid [[ChangeSet]] id value.
*/
public byReleasedWithChangeSet(changeSetId: string) {
ArgumentCheck.validChangeSetId("changeSetId", changeSetId);
this.addFilter(`ReleasedWithChangeSet+eq+'${changeSetId}'`);
return this;
}
/**
* Query [[Lock]]s by [[ChangeSet]] index that it was released with.
* @param changeSetIndex Index of the changeSet.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley)
* if changeSetIndex is undefined.
*/
public byReleasedWithChangeSetIndex(changeSetIndex: number) {
ArgumentCheck.definedNumber("changeSetIndex", changeSetIndex);
this.addFilter(`ReleasedWithChangeSetIndex+eq+${changeSetIndex}`);
return this;
}
/**
* Query [[Lock]]s by their instance ids.
* @param locks Locks to query. They must have their BriefcaseId, LockType and ObjectId set.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if locks array is undefined or empty, or it contains invalid [[Lock]] values.
*/
public byLocks(locks: Lock[]) {
ArgumentCheck.nonEmptyArray("locks", locks);
let filter = "$id+in+[";
let index = 0;
for (const lock of locks) {
const id = getLockInstanceId(lock);
ArgumentCheck.valid(`locks[${index}]`, id);
if (0 !== index++)
filter += ",";
filter += `'${id}'`;
}
filter += "]";
this.addFilter(filter);
this._isMultiLockQuery = false;
return this;
}
/**
* Query unavailable [[Lock]]s. It will include all Locks owned by other [[Briefcase]]s and locks that were released with a newer [[ChangeSet]].
* @param briefcaseId Id of the Briefcase.
* @param lastChangeSetIndex Index of the last ChangeSet that user has pulled.
* @returns This query.
* @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if one of the values is undefined or briefcaseId is not in a valid [[Briefcase]] id value.
*/
public unavailableLocks(briefcaseId: number, lastChangeSetIndex: string) {
ArgumentCheck.validBriefcaseId("briefcaseId", briefcaseId);
ArgumentCheck.defined("lastChangeSetIndex", lastChangeSetIndex);
let filter = `BriefcaseId+ne+${briefcaseId}`;
filter += `+and+(LockLevel+gt+0+or+ReleasedWithChangeSetIndex+gt+${lastChangeSetIndex})`;
this.addFilter(filter);
return this;
}
}
/**
* Handler for managing [[Lock]]s. Use [[IModelClient.Locks]] to get an instance of this class.
* In most cases, you should use [ConcurrencyControl]($backend) methods instead. You can read more about concurrency control [here]($docs/learning/backend/concurrencycontrol).
* @internal
*/
export class LockHandler {
private _handler: IModelBaseHandler;
private static _defaultUpdateOptionsProvider: DefaultLockUpdateOptionsProvider;
/**
* Constructor for LockHandler.
* @param handler Handler for WSG requests.
* @internal
*/
constructor(handler: IModelBaseHandler) {
this._handler = handler;
}
private getRelativeUrl(iModelId: GuidString, multilock = true, lockId?: string) {
return `/Repositories/iModel--${iModelId}/iModelScope/${multilock ? "MultiLock" : "Lock"}/${lockId || ""}`;
}
private static convertLocksToMultiLocks(locks: Lock[]): MultiLock[] {
const map = new Map<string, MultiLock>();
for (const lock of locks) {
const id: string = `${lock.lockType}-${lock.lockLevel}`;
if (map.has(id)) {
map.get(id)!.objectIds!.push(lock.objectId!);
} else {
const multiLock = new MultiLock();
multiLock.changeState = "new";
multiLock.briefcaseId = lock.briefcaseId;
multiLock.seedFileId = lock.seedFileId;
multiLock.releasedWithChangeSet = lock.releasedWithChangeSet;
multiLock.releasedWithChangeSetIndex = lock.releasedWithChangeSetIndex;
multiLock.lockLevel = lock.lockLevel;
multiLock.lockType = lock.lockType;
multiLock.objectIds = [lock.objectId!];
map.set(id, multiLock);
}
}
return Array.from(map.values());
}
private static convertMultiLocksToLocks(multiLocks: MultiLock[]): Lock[] {
const result: Lock[] = [];
for (const multiLock of multiLocks) {
for (const value of multiLock.objectIds!) {
const lock = new Lock();
lock.objectId = value;
lock.briefcaseId = multiLock.briefcaseId;
if (lock.seedFileId)
lock.seedFileId = multiLock.seedFileId;
lock.lockLevel = multiLock.lockLevel;
lock.lockType = multiLock.lockType;
result.push(lock);
}
}
return result;
}
/** Augment update options with defaults returned by the DefaultLockUpdateOptionsProvider.
* The options passed in by clients override any defaults where necessary.
* @param options Options the caller wants to augment with the defaults.
*/
private async setupOptionDefaults(options: LockUpdateOptions): Promise<void> {
if (!LockHandler._defaultUpdateOptionsProvider)
LockHandler._defaultUpdateOptionsProvider = new DefaultLockUpdateOptionsProvider();
return LockHandler._defaultUpdateOptionsProvider.assignOptions(options);
}
/** Send partial request for lock updates */
private async updateInternal(accessToken: AccessToken, iModelId: GuidString, locks: Lock[], updateOptions?: LockUpdateOptions): Promise<Lock[]> {
let requestOptions: WsgRequestOptions | undefined;
if (updateOptions) {
requestOptions = {};
requestOptions.CustomOptions = {};
if (updateOptions.deniedLocks === false) {
requestOptions.CustomOptions.DetailedError_Codes = "false"; // eslint-disable-line @typescript-eslint/naming-convention
}
if (updateOptions.unlimitedReporting) {
requestOptions.CustomOptions.DetailedError_MaximumInstances = "-1"; // eslint-disable-line @typescript-eslint/naming-convention
}
if (updateOptions.continueOnConflict) {
requestOptions.CustomOptions.ConflictStrategy = "Continue";
}
if (Object.getOwnPropertyNames(requestOptions.CustomOptions).length === 0) {
requestOptions = undefined;
}
}
const result = await this._handler.postInstances<MultiLock>(accessToken, MultiLock, `/Repositories/iModel--${iModelId}/$changeset`, LockHandler.convertLocksToMultiLocks(locks), requestOptions);
return LockHandler.convertMultiLocksToLocks(result);
}
/** Update multiple [[Lock]]s. This call can simultaneously acquire new Locks and update states of already owned Locks. If large amount of Locks are updated, they are split across multiple requests. See [[LockUpdateOptions.locksPerRequest]]. Default is 2000 Locks per request.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param locks Locks to acquire. Requires briefcaseId, seedFileId to be set for every
* Lock instance. They must be consistent throughout all of the Locks.
* @param updateOptions Options for the update request. You can set this to change
* how conflicts are handled or to handle different amount of Locks per request.
* @returns Updated Lock values.
* @throws [[ConflictingLocksError]] when [[LockUpdateOptions.deniedLocks]] is set and conflicts occurred. See [Handling Conflicts]($docs/learning/iModelHub/CodesAndLocksConflicts.md) for more information.
* @throws [[AggregateResponseError]] when multiple requests where sent and more than 1 of the following errors occurred.
* @throws [[IModelHubError]] with status indicating a conflict. See [Handling Conflicts]($docs/learning/iModelHub/CodesAndLocksConflicts.md) section for more information.
* @throws [[IModelHubError]] with [IModelHubStatus.InvalidBriefcase]($bentley) when including locks with different briefcaseId values in the request.
* @throws [[IModelHubError]] with [IModelHubStatus.OperationFailed]($bentley) when including multiple identical locks in the request.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async update(accessToken: AccessToken, iModelId: GuidString, locks: Lock[], updateOptions?: LockUpdateOptions): Promise<Lock[]> {
Logger.logInfo(loggerCategory, "Requesting locks", () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
ArgumentCheck.nonEmptyArray("locks", locks);
updateOptions = updateOptions || {};
await this.setupOptionDefaults(updateOptions);
const result: Lock[] = [];
let conflictError: ConflictingLocksError | undefined;
const aggregateError = new AggregateResponseError();
for (let i = 0; i < locks.length; i += updateOptions.locksPerRequest!) {
const chunk = locks.slice(i, i + updateOptions.locksPerRequest!);
try {
result.push(...await this.updateInternal(accessToken, iModelId, chunk, updateOptions));
} catch (error) {
if (error instanceof ResponseError) {
if (updateOptions && updateOptions.deniedLocks && error instanceof IModelHubError
&& (error.errorNumber === IModelHubStatus.LockOwnedByAnotherBriefcase || error.errorNumber === IModelHubStatus.ConflictsAggregate)) {
if (conflictError) {
conflictError.addLocks(error);
} else {
conflictError = ConflictingLocksError.fromError(error);
}
if (!updateOptions.continueOnConflict) {
throw conflictError;
}
} else {
aggregateError.errors.push(error);
}
}
}
}
if (conflictError) {
throw conflictError;
}
if (aggregateError.errors.length > 0) {
throw aggregateError.errors.length > 1 ? aggregateError : aggregateError.errors[0];
}
Logger.logTrace(loggerCategory, `Requested ${locks.length} locks for iModel`, () => ({ iModelId }));
return result;
}
/** Get the [[Lock]]s that have been issued for the iModel.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param query Optional query object to filter the queried Locks or select different data from them.
* @returns Resolves to an array of Locks matching the query.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async get(accessToken: AccessToken, iModelId: GuidString, query: LockQuery = new LockQuery()): Promise<Lock[]> {
Logger.logInfo(loggerCategory, "Querying locks", () => ({ iModelId }));
ArgumentCheck.validGuid("iModelId", iModelId);
let locks: Lock[];
if (query.isMultiLockQuery) {
const result = await this._handler.getInstances<MultiLock>(accessToken, MultiLock, this.getRelativeUrl(iModelId), query.getQueryOptions());
locks = LockHandler.convertMultiLocksToLocks(result);
} else {
locks = await this._handler.postQuery<Lock>(accessToken, Lock, this.getRelativeUrl(iModelId, false), query.getQueryOptions());
locks = locks.map((value: Lock) => {
const result = new Lock();
result.briefcaseId = value.briefcaseId;
result.lockLevel = value.lockLevel;
result.lockType = value.lockType;
result.objectId = value.objectId;
if (value.seedFileId)
result.seedFileId = value.seedFileId;
return result;
});
}
Logger.logTrace(loggerCategory, `Queried ${locks.length} locks for iModel`, () => ({ iModelId }));
return locks;
}
/** Delete all [[Lock]]s owned by the specified [[Briefcase]].
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param briefcaseId Id of the Briefcase.
* @throws [[IModelHubError]] with [IModelHubStatus.BriefcaseDoesNotExist]($bentley) if [[Briefcase]] with specified briefcaseId does not exist. This can happen if number was not given as a Briefcase id yet, or Briefcase with that id was already deleted.
* @throws [[IModelHubError]] with [IModelHubStatus.UserDoesNotHavePermission]($bentley) if [[Briefcase]] belongs to another user and user sending the request does not have ManageResources permission.
* @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors)
*/
public async deleteAll(accessToken: AccessToken, iModelId: GuidString, briefcaseId: number): Promise<void> {
Logger.logInfo(loggerCategory, "Deleting all locks from briefcase", () => ({ iModelId, briefcaseId }));
ArgumentCheck.validGuid("iModelId", iModelId);
ArgumentCheck.validBriefcaseId("briefcaseId", briefcaseId);
await this.deleteAllLocksInChunks(accessToken, iModelId, briefcaseId);
Logger.logTrace(loggerCategory, "Deleted all locks from briefcase", () => ({ iModelId, briefcaseId }));
}
/** Helper method to iteratively delete chunks of [[Lock]]s for the specified [[Briefcase]] until there are no more left.
* @param iModelId Id of the iModel. See [[HubIModel]].
* @param briefcaseId Id of the Briefcase.
*/
private async deleteAllLocksInChunks(accessToken: AccessToken, iModelId: GuidString, briefcaseId: number): Promise<void> {
const relativeUrl = this.getRelativeUrl(iModelId, false, `DeleteChunk-${briefcaseId}`);
const requestOptions: HttpRequestOptions = { timeout: { response: 45000 } };
let shouldDeleteAnotherChunk = true;
do {
try {
await this._handler.delete(accessToken, relativeUrl, requestOptions);
Logger.logTrace(loggerCategory, "Deleted a chunk of locks from briefcase", () => ({ iModelId, briefcaseId }));
} catch (error) {
if (error instanceof IModelHubError && error.errorNumber === IModelHubStatus.LockChunkDoesNotExist)
shouldDeleteAnotherChunk = false;
else
throw error;
}
} while (shouldDeleteAnotherChunk);
Logger.logTrace(loggerCategory, "Deleted all locks from briefcase", () => ({ iModelId, briefcaseId }));
}
} | the_stack |
import { strict as assert } from "assert";
import { Writable } from "stream";
import { DebugAdapterTracker, DebugAdapterTrackerFactory, DebugSession, DebugSessionCustomEvent, window } from "vscode";
import { DebugProtocol } from "vscode-debugprotocol";
import { TestSessionCoordinator } from "../shared/test/coordinator";
import { Notification, Test, TestDoneNotification, TestStartNotification } from "../shared/test_protocol";
import { getRandomInt } from "../shared/utils/fs";
import { waitFor } from "../shared/utils/promises";
import { DebugCommandHandler } from "../shared/vscode/interfaces";
import { DebugClient, ILocation, IPartialLocation } from "./debug_client_ms";
import { delay, logger, watchPromise, withTimeout } from "./helpers";
const customEventsToForward = ["dart.log", "dart.serviceExtensionAdded", "dart.serviceRegistered", "dart.debuggerUris", "dart.startTerminalProcess", "dart.exposeUrl"];
type DebugClientArgs = { runtime: string, executable: string, args: string[], port?: undefined } | { runtime?: undefined, executable?: undefined, args?: undefined, port: number };
export class DartDebugClient extends DebugClient {
private readonly port: number | undefined;
public currentSession?: DebugSession;
public currentTracker?: DebugAdapterTracker;
public hasStarted = false;
public readonly isDartDap: boolean;
constructor(args: DebugClientArgs, private readonly debugCommands: DebugCommandHandler, readonly testCoordinator: TestSessionCoordinator | undefined, private readonly debugTrackerFactory: DebugAdapterTrackerFactory) {
super(args.runtime, args.executable, args.args, "dart", undefined, true);
this.isDartDap = args.runtime !== undefined && args.runtime !== "node";
this.port = args.port;
// HACK to handle incoming requests..
const me = (this as unknown as { dispatch(body: string): void });
const oldDispatch = me.dispatch;
me.dispatch = (body: string) => {
const rawData = JSON.parse(body);
if (this.currentTracker?.onWillReceiveMessage)
this.currentTracker.onWillReceiveMessage(rawData);
if (rawData.type === "request") {
const request = rawData as DebugProtocol.Request;
this.emit(request.command, request);
} else {
oldDispatch.bind(this)(body);
}
};
// Set up handlers for any custom events our tests may rely on (can't find
// a way to just do them all 🤷♂️).
customEventsToForward.forEach((evt) => this.on(evt, (e) => this.handleCustomEvent(e)));
// Log important events to make troubleshooting tests easier.
this.on("output", (event: DebugProtocol.OutputEvent) => {
logger.info(`[${event.body.category}] ${event.body.output}`);
});
this.on("terminated", (event: DebugProtocol.TerminatedEvent) => {
logger.info(`[terminated]`);
});
this.on("stopped", (event: DebugProtocol.StoppedEvent) => {
logger.info(`[stopped] ${event.body.reason}`);
});
this.on("initialized", (event: DebugProtocol.InitializedEvent) => {
logger.info(`[initialized]`);
});
this.on("runInTerminal", (request: DebugProtocol.RunInTerminalRequest) => {
logger.info(`[runInTerminal]`);
const terminal = window.createTerminal({
cwd: request.arguments.cwd,
env: request.arguments.env,
name: request.arguments.title,
shellArgs: request.arguments.args.slice(1),
shellPath: request.arguments.args[0],
});
terminal.show();
terminal.processId.then((pid) => {
this.sendResponse(request, { shellProcessId: pid });
});
});
// If we were given a test provider, forward the test notifications on to
// it as it won't receive the events normally because this is not a Code-spawned
// debug session.
if (testCoordinator) {
this.on("dart.testNotification", (e: DebugSessionCustomEvent) => testCoordinator.handleDebugSessionCustomEvent(this.currentSession!.id, this.currentSession!.configuration.dartCodeDebugSessionID, e.event, e.body));
this.on("terminated", (e: DebugProtocol.TerminatedEvent) => testCoordinator.handleDebugSessionEnd(this.currentSession!.id, this.currentSession!.configuration.dartCodeDebugSessionID));
}
}
public send(command: string, args?: any): Promise<any> {
if (this.currentTracker?.onDidSendMessage)
this.currentTracker.onDidSendMessage({ command, args });
return super.send(command, args);
}
public start(port?: number): Promise<void> {
this.hasStarted = true;
if (port)
throw new Error("Do not provide a port to DartDebugClient.start!");
return super.start(this.port);
}
private sendResponse(request: DebugProtocol.Request, body: any): void {
// Hack: Underlyung class doesn't have response support.
const me = (this as unknown as { outputStream: Writable, sequence: number });
const response: DebugProtocol.Response = {
body,
command: request.command,
// eslint-disable-next-line camelcase
request_seq: request.seq,
seq: me.sequence++,
success: true,
type: "response",
};
const json = JSON.stringify(response);
me.outputStream.write(`Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`, "utf8");
}
private handleCustomEvent(e: DebugSessionCustomEvent) {
this.debugCommands.handleDebugSessionCustomEvent({
body: e.body,
event: e.event,
session: this.currentSession!,
});
}
public async launch(launchArgs: any): Promise<void> {
// The new DAP doesn't default to breaking on any exceptions so to simplify tests
// set it based on whether we'd in debug mode or not.
const isDebugging = !(launchArgs.noDebug ?? false);
if (isDebugging)
await this.setExceptionBreakpointsRequest({ filters: ["Unhandled"] });
const configuration = Object.assign(
{
name: "Dart & Flutter",
request: "launch",
type: "dart",
},
launchArgs,
);
this.currentSession = {
configuration,
customRequest: async (cmd, args) => (await this.customRequest(cmd, args)).body,
getDebugProtocolBreakpoint: () => { throw new Error("Not implemented for tests"); },
id: `INTEGRATION-TEST-${getRandomInt(0x1000, 0x10000).toString(16)}`,
name: configuration.name,
type: configuration.type,
workspaceFolder: undefined,
};
// Set up logging.
this.currentTracker = (await this.debugTrackerFactory.createDebugAdapterTracker(this.currentSession))!;
this.currentTracker.onWillStartSession!();
this.on("terminated", (e: DebugProtocol.TerminatedEvent) => {
if (this.currentTracker?.onWillStopSession)
this.currentTracker.onWillStopSession();
});
this.debugCommands.handleDebugSessionStart(this.currentSession);
this.waitForEvent("terminated")
.then(() => this.debugCommands.handleDebugSessionEnd(this.currentSession!))
.catch((e) => console.error(`Error while waiting for termiantion: ${e}`));
// We override the base method to swap for attachRequest when required, so that
// all the existing methods that provide useful functionality but assume launching
// (for ex. hitBreakpoint) can be used in attach tests.
const response = await watchPromise("launch->initializeRequest", this.initializeRequest());
if (response.body && response.body.supportsConfigurationDoneRequest) {
this._supportsConfigurationDoneRequest = true;
}
// Attach will be paused by default and issue a step when we connect; but our tests
// generally assume we will automatically resume.
if (launchArgs.request === "attach" && launchArgs.deviceId !== "flutter-tester") {
logger.info("Attaching to process...");
await watchPromise("launch->attach->attachRequest", this.attachRequest(launchArgs));
logger.info("Waiting for stopped (step/entry) event...");
const event = await watchPromise("launch->attach->waitForEvent:stopped", this.waitForEvent("stopped"));
// Allow either step (old DC DA) or entry (SDK DA).
if (event.body.reason !== "step")
assert.equal(event.body.reason, "entry");
// HACK: Put a fake delay in after attachRequest to ensure isolates become runnable and breakpoints are transmitted
// This should help fix the tests so we can be sure they're otherwise good, before we fix this properly.
// https://github.com/Dart-Code/Dart-Code/issues/911
await new Promise((resolve) => setTimeout(resolve, 1000));
// It's possible the resume will never return because the process will terminate as soon as it starts resuming
// so we will assume that if we get a terminate the resume worked.
logger.info("Resuming and waiting for success or terminate...");
await watchPromise(
"launch()->attach->terminate/resume",
Promise.race([
this.waitForEvent("terminated")
.catch(() => {
// Swallow errors, we're only using this to avoid waiting on a resume response forever.
// It's possible it'll time out after some period because the test finished more quickly/slowly.
}),
this.resume(),
]),
);
} else if (launchArgs.request === "attach") {
// For Flutter, we don't need all the crazy stuff above, just issue a standard
// attach request.
logger.info("Attaching to process...");
await watchPromise("launch->attach->attachRequest", this.attachRequest(launchArgs));
} else {
await watchPromise("launch()->launchRequest", this.launchRequest(launchArgs));
}
}
public setBreakpointWithoutHitting(launchArgs: any, location: ILocation, expectedBPLocation?: IPartialLocation): Promise<any> {
return this.hitBreakpoint(launchArgs, location, undefined, expectedBPLocation, true);
}
public async getMainThread(): Promise<DebugProtocol.Thread> {
// For tests, we can assume the last thread is the "main" one, as dartdev, pub etc. will all
// be spawned first.
const threadsResponse = await this.threadsRequest();
const threads = threadsResponse.body.threads;
return threads[threads.length - 1];
}
public async resume(): Promise<DebugProtocol.ContinueResponse> {
const thread = await this.getMainThread();
return this.continueRequest({ threadId: thread.id });
}
public async stepIn(): Promise<DebugProtocol.StepInResponse> {
const thread = await this.getMainThread();
return this.stepInRequest({ threadId: thread.id });
}
public async getStack(startFrame?: number, levels?: number): Promise<DebugProtocol.StackTraceResponse> {
const thread = await this.getMainThread();
return this.stackTraceRequest({ threadId: thread.id, startFrame, levels });
}
public async getTopFrameVariables(scope: "Exceptions" | "Locals"): Promise<DebugProtocol.Variable[]> {
const stack = await this.getStack();
const scopes = await this.scopesRequest({ frameId: stack.body.stackFrames[0].id });
const s = scopes.body.scopes.find((s) => s.name === scope);
assert.ok(s);
return this.getVariables(s.variablesReference);
}
public async getVariables(variablesReference: number): Promise<DebugProtocol.Variable[]> {
const variables = await this.variablesRequest({ variablesReference });
return variables.body.variables;
}
public async evaluateForFrame(expression: string, context?: string): Promise<{
result: string;
type?: string;
variablesReference: number;
namedVariables?: number;
indexedVariables?: number;
}> {
const thread = await this.getMainThread();
const stack = await this.stackTraceRequest({ threadId: thread.id });
const result = await this.evaluateRequest({ expression, frameId: stack.body.stackFrames[0].id, context });
return result.body;
}
public assertOutputContains(category: string, text: string): Promise<DebugProtocol.OutputEvent> {
let output = "";
let cleanup = () => { }; // tslint:disable-line: no-empty
const textLF = text.replace(/\r/g, "");
const textCRLF = textLF.replace(/\n/g, "\r\n");
return withTimeout(
new Promise<DebugProtocol.OutputEvent>((resolve) => {
function handleOutput(event: DebugProtocol.OutputEvent) {
if (event.body.category === category) {
output += event.body.output;
if (output.indexOf(textLF) !== -1 || output.indexOf(textCRLF) !== -1) {
resolve(event);
}
}
}
cleanup = () => this.removeListener("output", handleOutput);
this.on("output", handleOutput);
}),
() => `Didn't find text "${text}" in ${category}\nGot: ${output}`,
).finally(() => cleanup());
}
public waitForCustomEvent<T>(type: string, filter: (notification: T) => boolean): Promise<T> {
return new Promise((resolve, reject) => {
setTimeout(
() => {
reject(new Error(`No customEvent '${type}' matching ${filter} received after ${this.defaultTimeout} ms`));
},
this.defaultTimeout,
);
const handler = (event: DebugProtocol.Event) => {
try {
const notification = event.body as T;
if (filter(notification)) {
this.removeListener(type, handler);
resolve(notification);
}
} catch (e) {
this.removeListener(type, handler);
reject(e);
}
};
this.on(type, handler);
this.on("terminated", () => this.removeListener(type, handler));
});
}
public async waitForTestNotification<T extends Notification>(type: string, filter: (notification: T) => boolean): Promise<void> {
await this.waitForCustomEvent<T>(
"dart.testNotification",
(event) => event.type === type && filter(event),
);
}
public async tryWaitUntilGlobalEvaluationIsAvailable(): Promise<void> {
// We can't evaluate until the main thread is runnable (which there's no event for) so
// just retry for a short period until it works (or times out).
await waitFor(() => this.evaluateRequest({ expression: `"test"` }).then(() => true, () => false));
}
private assertTestStatus(testName: string, expectedStatus: "success" | "failure" | "error"): Promise<void> {
let test: Test;
return Promise.all([
this.waitForTestNotification<TestStartNotification>(
"testStart",
(e) => {
if (e.test.name === testName) {
test = e.test;
return true;
} else {
return false;
}
},
),
this.waitForTestNotification<TestDoneNotification>(
"testDone",
(e) => {
if (test && e.testID === test.id) {
assert.equal(e.result, expectedStatus, `Test ${test.name} result was not as expected`);
return true;
} else {
return false;
}
},
),
]).then(() => undefined);
}
public assertPassingTest(testName: string) {
return this.assertTestStatus(testName, "success");
}
public assertFailingTest(testName: string) {
return this.assertTestStatus(testName, "failure");
}
public assertErroringTest(testName: string) {
return this.assertTestStatus(testName, "error");
}
public async waitForHotReload(): Promise<void> {
// We might get the text in either stderr or stdout depending on
// whether an error occurred during reassemble.
await Promise.race([
this.assertOutputContains("stdout", "Reloaded"),
this.assertOutputContains("stderr", "Reloaded"),
// TODO: Remove these two when web isn't doing restarts for reloads.
this.assertOutputContains("stdout", "Restarted"),
this.assertOutputContains("stderr", "Restarted"),
]);
}
public async hotReload(): Promise<void> {
// If we reload too fast, things fail :-/
await delay(500);
await Promise.all([
this.waitForHotReload(),
this.customRequest("hotReload"),
]);
}
} | the_stack |
import * as nbformat from '@jupyterlab/nbformat';
import { NotebookCell, NotebookCellData, NotebookCellKind, NotebookCellOutput } from 'vscode';
import { CellMetadata, CellOutputMetadata } from './common';
import { textMimeTypes } from './deserializers';
const textDecoder = new TextDecoder();
enum CellOutputMimeTypes {
error = 'application/vnd.code.notebook.error',
stderr = 'application/vnd.code.notebook.stderr',
stdout = 'application/vnd.code.notebook.stdout'
}
export function createJupyterCellFromNotebookCell(
vscCell: NotebookCellData,
preferredLanguage: string | undefined
): nbformat.IRawCell | nbformat.IMarkdownCell | nbformat.ICodeCell {
let cell: nbformat.IRawCell | nbformat.IMarkdownCell | nbformat.ICodeCell;
if (vscCell.kind === NotebookCellKind.Markup) {
cell = createMarkdownCellFromNotebookCell(vscCell);
} else if (vscCell.languageId === 'raw') {
cell = createRawCellFromNotebookCell(vscCell);
} else {
cell = createCodeCellFromNotebookCell(vscCell, preferredLanguage);
}
return cell;
}
/**
* Sort the JSON to minimize unnecessary SCM changes.
* Jupyter notbeooks/labs sorts the JSON keys in alphabetical order.
* https://github.com/microsoft/vscode-python/issues/13155
*/
export function sortObjectPropertiesRecursively(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(sortObjectPropertiesRecursively);
}
if (obj !== undefined && obj !== null && typeof obj === 'object' && Object.keys(obj).length > 0) {
return (
Object.keys(obj)
.sort()
.reduce<Record<string, any>>((sortedObj, prop) => {
sortedObj[prop] = sortObjectPropertiesRecursively(obj[prop]);
return sortedObj;
}, {}) as any
);
}
return obj;
}
export function getCellMetadata(cell: NotebookCell | NotebookCellData) {
return cell.metadata?.custom as CellMetadata | undefined;
}
function createCodeCellFromNotebookCell(cell: NotebookCellData, preferredLanguage: string | undefined): nbformat.ICodeCell {
const cellMetadata = getCellMetadata(cell);
let metadata = cellMetadata?.metadata || {}; // This cannot be empty.
if (cell.languageId !== preferredLanguage) {
metadata = {
...metadata,
vscode: {
languageId: cell.languageId
}
};
} else {
// cell current language is the same as the preferred cell language in the document, flush the vscode custom language id metadata
metadata.vscode = undefined;
}
const codeCell: any = {
cell_type: 'code',
execution_count: cell.executionSummary?.executionOrder ?? null,
source: splitMultilineString(cell.value.replace(/\r\n/g, '\n')),
outputs: (cell.outputs || []).map(translateCellDisplayOutput),
metadata: metadata
};
if (cellMetadata?.id) {
codeCell.id = cellMetadata.id;
}
return codeCell;
}
function createRawCellFromNotebookCell(cell: NotebookCellData): nbformat.IRawCell {
const cellMetadata = getCellMetadata(cell);
const rawCell: any = {
cell_type: 'raw',
source: splitMultilineString(cell.value.replace(/\r\n/g, '\n')),
metadata: cellMetadata?.metadata || {} // This cannot be empty.
};
if (cellMetadata?.attachments) {
rawCell.attachments = cellMetadata.attachments;
}
if (cellMetadata?.id) {
rawCell.id = cellMetadata.id;
}
return rawCell;
}
function splitMultilineString(source: nbformat.MultilineString): string[] {
if (Array.isArray(source)) {
return source as string[];
}
const str = source.toString();
if (str.length > 0) {
// Each line should be a separate entry, but end with a \n if not last entry
const arr = str.split('\n');
return arr
.map((s, i) => {
if (i < arr.length - 1) {
return `${s}\n`;
}
return s;
})
.filter(s => s.length > 0); // Skip last one if empty (it's the only one that could be length 0)
}
return [];
}
function translateCellDisplayOutput(output: NotebookCellOutput): JupyterOutput {
const customMetadata = output.metadata as CellOutputMetadata | undefined;
let result: JupyterOutput;
// Possible some other extension added some output (do best effort to translate & save in ipynb).
// In which case metadata might not contain `outputType`.
const outputType = customMetadata?.outputType as nbformat.OutputType;
switch (outputType) {
case 'error': {
result = translateCellErrorOutput(output);
break;
}
case 'stream': {
result = convertStreamOutput(output);
break;
}
case 'display_data': {
result = {
output_type: 'display_data',
data: output.items.reduce((prev: any, curr) => {
prev[curr.mime] = convertOutputMimeToJupyterOutput(curr.mime, curr.data as Uint8Array);
return prev;
}, {}),
metadata: customMetadata?.metadata || {} // This can never be undefined.
};
break;
}
case 'execute_result': {
result = {
output_type: 'execute_result',
data: output.items.reduce((prev: any, curr) => {
prev[curr.mime] = convertOutputMimeToJupyterOutput(curr.mime, curr.data as Uint8Array);
return prev;
}, {}),
metadata: customMetadata?.metadata || {}, // This can never be undefined.
execution_count:
typeof customMetadata?.executionCount === 'number' ? customMetadata?.executionCount : null // This can never be undefined, only a number or `null`.
};
break;
}
case 'update_display_data': {
result = {
output_type: 'update_display_data',
data: output.items.reduce((prev: any, curr) => {
prev[curr.mime] = convertOutputMimeToJupyterOutput(curr.mime, curr.data as Uint8Array);
return prev;
}, {}),
metadata: customMetadata?.metadata || {} // This can never be undefined.
};
break;
}
default: {
const isError =
output.items.length === 1 && output.items.every((item) => item.mime === CellOutputMimeTypes.error);
const isStream = output.items.every(
(item) => item.mime === CellOutputMimeTypes.stderr || item.mime === CellOutputMimeTypes.stdout
);
if (isError) {
return translateCellErrorOutput(output);
}
// In the case of .NET & other kernels, we need to ensure we save ipynb correctly.
// Hence if we have stream output, save the output as Jupyter `stream` else `display_data`
// Unless we already know its an unknown output type.
const outputType: nbformat.OutputType =
<nbformat.OutputType>customMetadata?.outputType || (isStream ? 'stream' : 'display_data');
let unknownOutput: nbformat.IUnrecognizedOutput | nbformat.IDisplayData | nbformat.IStream;
if (outputType === 'stream') {
// If saving as `stream` ensure the mandatory properties are set.
unknownOutput = convertStreamOutput(output);
} else if (outputType === 'display_data') {
// If saving as `display_data` ensure the mandatory properties are set.
const displayData: nbformat.IDisplayData = {
data: {},
metadata: {},
output_type: 'display_data'
};
unknownOutput = displayData;
} else {
unknownOutput = {
output_type: outputType
};
}
if (customMetadata?.metadata) {
unknownOutput.metadata = customMetadata.metadata;
}
if (output.items.length > 0) {
unknownOutput.data = output.items.reduce((prev: any, curr) => {
prev[curr.mime] = convertOutputMimeToJupyterOutput(curr.mime, curr.data as Uint8Array);
return prev;
}, {});
}
result = unknownOutput;
break;
}
}
// Account for transient data as well
// `transient.display_id` is used to update cell output in other cells, at least thats one use case we know of.
if (result && customMetadata && customMetadata.transient) {
result.transient = customMetadata.transient;
}
return result;
}
function translateCellErrorOutput(output: NotebookCellOutput): nbformat.IError {
// it should have at least one output item
const firstItem = output.items[0];
// Bug in VS Code.
if (!firstItem.data) {
return {
output_type: 'error',
ename: '',
evalue: '',
traceback: []
};
}
const originalError: undefined | nbformat.IError = output.metadata?.originalError;
const value: Error = JSON.parse(textDecoder.decode(firstItem.data));
return {
output_type: 'error',
ename: value.name,
evalue: value.message,
// VS Code needs an `Error` object which requires a `stack` property as a string.
// Its possible the format could change when converting from `traceback` to `string` and back again to `string`
// When .NET stores errors in output (with their .NET kernel),
// stack is empty, hence store the message instead of stack (so that somethign gets displayed in ipynb).
traceback: originalError?.traceback || splitMultilineString(value.stack || value.message || '')
};
}
function getOutputStreamType(output: NotebookCellOutput): string | undefined {
if (output.items.length > 0) {
return output.items[0].mime === CellOutputMimeTypes.stderr ? 'stderr' : 'stdout';
}
return;
}
type JupyterOutput =
| nbformat.IUnrecognizedOutput
| nbformat.IExecuteResult
| nbformat.IDisplayData
| nbformat.IStream
| nbformat.IError;
function convertStreamOutput(output: NotebookCellOutput): JupyterOutput {
const outputs: string[] = [];
output.items
.filter((opit) => opit.mime === CellOutputMimeTypes.stderr || opit.mime === CellOutputMimeTypes.stdout)
.map((opit) => textDecoder.decode(opit.data))
.forEach(value => {
// Ensure each line is a seprate entry in an array (ending with \n).
const lines = value.split('\n');
// If the last item in `outputs` is not empty and the first item in `lines` is not empty, then concate them.
// As they are part of the same line.
if (outputs.length && lines.length && lines[0].length > 0) {
outputs[outputs.length - 1] = `${outputs[outputs.length - 1]}${lines.shift()!}`;
}
for (const line of lines) {
outputs.push(line);
}
});
for (let index = 0; index < (outputs.length - 1); index++) {
outputs[index] = `${outputs[index]}\n`;
}
// Skip last one if empty (it's the only one that could be length 0)
if (outputs.length && outputs[outputs.length - 1].length === 0) {
outputs.pop();
}
const streamType = getOutputStreamType(output) || 'stdout';
return {
output_type: 'stream',
name: streamType,
text: outputs
};
}
function convertOutputMimeToJupyterOutput(mime: string, value: Uint8Array) {
if (!value) {
return '';
}
try {
if (mime === CellOutputMimeTypes.error) {
const stringValue = textDecoder.decode(value);
return JSON.parse(stringValue);
} else if (mime.startsWith('text/') || textMimeTypes.includes(mime)) {
const stringValue = textDecoder.decode(value);
return splitMultilineString(stringValue);
} else if (mime.startsWith('image/') && mime !== 'image/svg+xml') {
// Images in Jupyter are stored in base64 encoded format.
// VS Code expects bytes when rendering images.
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
return Buffer.from(value).toString('base64');
} else {
return btoa(value.reduce((s: string, b: number) => s + String.fromCharCode(b), ''));
}
} else if (mime.toLowerCase().includes('json')) {
const stringValue = textDecoder.decode(value);
return stringValue.length > 0 ? JSON.parse(stringValue) : stringValue;
} else {
const stringValue = textDecoder.decode(value);
return stringValue;
}
} catch (ex) {
return '';
}
}
function createMarkdownCellFromNotebookCell(cell: NotebookCellData): nbformat.IMarkdownCell {
const cellMetadata = getCellMetadata(cell);
const markdownCell: any = {
cell_type: 'markdown',
source: splitMultilineString(cell.value.replace(/\r\n/g, '\n')),
metadata: cellMetadata?.metadata || {} // This cannot be empty.
};
if (cellMetadata?.attachments) {
markdownCell.attachments = cellMetadata.attachments;
}
if (cellMetadata?.id) {
markdownCell.id = cellMetadata.id;
}
return markdownCell;
}
export function pruneCell(cell: nbformat.ICell): nbformat.ICell {
// Source is usually a single string on input. Convert back to an array
const result = {
...cell,
source: splitMultilineString(cell.source)
} as nbformat.ICell;
// Remove outputs and execution_count from non code cells
if (result.cell_type !== 'code') {
delete (<any>result).outputs;
delete (<any>result).execution_count;
} else {
// Clean outputs from code cells
result.outputs = result.outputs ? (result.outputs as nbformat.IOutput[]).map(fixupOutput) : [];
}
return result;
}
const dummyStreamObj: nbformat.IStream = {
output_type: 'stream',
name: 'stdout',
text: ''
};
const dummyErrorObj: nbformat.IError = {
output_type: 'error',
ename: '',
evalue: '',
traceback: ['']
};
const dummyDisplayObj: nbformat.IDisplayData = {
output_type: 'display_data',
data: {},
metadata: {}
};
const dummyExecuteResultObj: nbformat.IExecuteResult = {
output_type: 'execute_result',
name: '',
execution_count: 0,
data: {},
metadata: {}
};
const AllowedCellOutputKeys = {
['stream']: new Set(Object.keys(dummyStreamObj)),
['error']: new Set(Object.keys(dummyErrorObj)),
['display_data']: new Set(Object.keys(dummyDisplayObj)),
['execute_result']: new Set(Object.keys(dummyExecuteResultObj))
};
function fixupOutput(output: nbformat.IOutput): nbformat.IOutput {
let allowedKeys: Set<string>;
switch (output.output_type) {
case 'stream':
case 'error':
case 'execute_result':
case 'display_data':
allowedKeys = AllowedCellOutputKeys[output.output_type];
break;
default:
return output;
}
const result = { ...output };
for (const k of Object.keys(output)) {
if (!allowedKeys.has(k)) {
delete result[k];
}
}
return result;
} | the_stack |
import fs from "fs";
import stream from "stream";
import { getUserAgent } from "universal-user-agent";
import fetchMock from "fetch-mock";
import { Headers, RequestInit } from "node-fetch";
import { createAppAuth } from "@octokit/auth-app";
import lolex from "lolex";
import {
EndpointOptions,
RequestInterface,
ResponseHeaders,
} from "@octokit/types";
import { request } from "../src";
const userAgent = `octokit-request.js/0.0.0-development ${getUserAgent()}`;
const stringToArrayBuffer = require("string-to-arraybuffer");
describe("request()", () => {
it("is a function", () => {
expect(request).toBeInstanceOf(Function);
});
it("README example", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/orgs/octokit/repos?type=private", [], {
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual([]);
});
});
it("README example alternative", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/orgs/octokit/repos?type=private", []);
return request({
method: "GET",
url: "/orgs/{org}/repos",
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual([]);
});
});
it("README authentication example", async () => {
const clock = lolex.install({
now: 0,
toFake: ["Date"],
});
const APP_ID = 1;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1c7+9z5Pad7OejecsQ0bu3aozN3tihPmljnnudb9G3HECdnH
lWu2/a1gB9JW5TBQ+AVpum9Okx7KfqkfBKL9mcHgSL0yWMdjMfNOqNtrQqKlN4kE
p6RD++7sGbzbfZ9arwrlD/HSDAWGdGGJTSOBM6pHehyLmSC3DJoR/CTu0vTGTWXQ
rO64Z8tyXQPtVPb/YXrcUhbBp8i72b9Xky0fD6PkEebOy0Ip58XVAn2UPNlNOSPS
ye+Qjtius0Md4Nie4+X8kwVI2Qjk3dSm0sw/720KJkdVDmrayeljtKBx6AtNQsSX
gzQbeMmiqFFkwrG1+zx6E7H7jqIQ9B6bvWKXGwIDAQABAoIBAD8kBBPL6PPhAqUB
K1r1/gycfDkUCQRP4DbZHt+458JlFHm8QL6VstKzkrp8mYDRhffY0WJnYJL98tr4
4tohsDbqFGwmw2mIaHjl24LuWXyyP4xpAGDpl9IcusjXBxLQLp2m4AKXbWpzb0OL
Ulrfc1ZooPck2uz7xlMIZOtLlOPjLz2DuejVe24JcwwHzrQWKOfA11R/9e50DVse
hnSH/w46Q763y4I0E3BIoUMsolEKzh2ydAAyzkgabGQBUuamZotNfvJoDXeCi1LD
8yNCWyTlYpJZJDDXooBU5EAsCvhN1sSRoaXWrlMSDB7r/E+aQyKua4KONqvmoJuC
21vSKeECgYEA7yW6wBkVoNhgXnk8XSZv3W+Q0xtdVpidJeNGBWnczlZrummt4xw3
xs6zV+rGUDy59yDkKwBKjMMa42Mni7T9Fx8+EKUuhVK3PVQyajoyQqFwT1GORJNz
c/eYQ6VYOCSC8OyZmsBM2p+0D4FF2/abwSPMmy0NgyFLCUFVc3OECpkCgYEA5OAm
I3wt5s+clg18qS7BKR2DuOFWrzNVcHYXhjx8vOSWV033Oy3yvdUBAhu9A1LUqpwy
Ma+unIgxmvmUMQEdyHQMcgBsVs10dR/g2xGjMLcwj6kn+xr3JVIZnbRT50YuPhf+
ns1ScdhP6upo9I0/sRsIuN96Gb65JJx94gQ4k9MCgYBO5V6gA2aMQvZAFLUicgzT
u/vGea+oYv7tQfaW0J8E/6PYwwaX93Y7Q3QNXCoCzJX5fsNnoFf36mIThGHGiHY6
y5bZPPWFDI3hUMa1Hu/35XS85kYOP6sGJjf4kTLyirEcNKJUWH7CXY+00cwvTkOC
S4Iz64Aas8AilIhRZ1m3eQKBgQCUW1s9azQRxgeZGFrzC3R340LL530aCeta/6FW
CQVOJ9nv84DLYohTVqvVowdNDTb+9Epw/JDxtDJ7Y0YU0cVtdxPOHcocJgdUGHrX
ZcJjRIt8w8g/s4X6MhKasBYm9s3owALzCuJjGzUKcDHiO2DKu1xXAb0SzRcTzUCn
7daCswKBgQDOYPZ2JGmhibqKjjLFm0qzpcQ6RPvPK1/7g0NInmjPMebP0K6eSPx0
9/49J6WTD++EajN7FhktUSYxukdWaCocAQJTDNYP0K88G4rtC2IYy5JFn9SWz5oh
x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
-----END RSA PRIVATE KEY-----`;
// see https://runkit.com/gr2m/reproducable-jwt
const BEARER =
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOi0zMCwiZXhwIjo1NzAsImlzcyI6MX0.q3foRa78U3WegM5PrWLEh5N0bH1SD62OqW66ZYzArp95JBNiCbo8KAlGtiRENCIfBZT9ibDUWy82cI4g3F09mdTq3bD1xLavIfmTksIQCz5EymTWR5v6gL14LSmQdWY9lSqkgUG0XCFljWUglEP39H4yeHbFgdjvAYg3ifDS12z9oQz2ACdSpvxPiTuCC804HkPVw8Qoy0OSXvCkFU70l7VXCVUxnuhHnk8-oCGcKUspmeP6UdDnXk-Aus-eGwDfJbU2WritxxaXw6B4a3flTPojkYLSkPBr6Pi0H2-mBsW_Nvs0aLPVLKobQd4gqTkosX3967DoAG8luUMhrnxe8Q";
const mock = fetchMock
.sandbox()
.postOnce("https://api.github.com/app/installations/123/access_tokens", {
token: "secret123",
expires_at: "1970-01-01T01:00:00.000Z",
permissions: {
metadata: "read",
},
repository_selection: "all",
})
.getOnce(
"https://api.github.com/app",
{ id: 123 },
{
headers: {
accept: "application/vnd.github.machine-man-preview+json",
"user-agent": userAgent,
authorization: `bearer ${BEARER}`,
},
}
)
.postOnce(
"https://api.github.com/repos/octocat/hello-world/issues",
{ id: 456 },
{
headers: {
accept: "application/vnd.github.machine-man-preview+json",
"user-agent": userAgent,
authorization: `token secret123`,
},
}
);
const auth = createAppAuth({
appId: APP_ID,
privateKey: PRIVATE_KEY,
installationId: 123,
});
const requestWithAuth = request.defaults({
mediaType: {
previews: ["machine-man"],
},
request: {
fetch: mock,
hook: auth.hook,
},
});
await requestWithAuth("GET /app");
await requestWithAuth("POST /repos/{owner}/{repo}/issues", {
owner: "octocat",
repo: "hello-world",
title: "Hello from the engine room",
});
expect(mock.done()).toBe(true);
clock.reset();
});
it("Request with body", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/repos/octocat/hello-world/issues", 201, {
headers: {
"content-type": "application/json; charset=utf-8",
},
});
request("POST /repos/{owner}/{repo}/issues", {
owner: "octocat",
repo: "hello-world",
headers: {
accept: "text/html;charset=utf-8",
},
title: "Found a bug",
body: "I'm having a problem with this.",
assignees: ["octocat"],
milestone: 1,
labels: ["bug"],
request: {
fetch: mock,
},
}).then((response) => {
expect(response.status).toEqual(201);
});
});
it("Put without request body", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/user/starred/octocat/hello-world", 204, {
headers: {
"content-length": 0,
},
});
request("PUT /user/starred/{owner}/{repo}", {
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
owner: "octocat",
repo: "hello-world",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.status).toEqual(204);
});
});
it("HEAD requests (octokit/rest.js#841)", () => {
const mock = fetchMock
.sandbox()
.head("https://api.github.com/repos/whatwg/html/pulls/1", {
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": "19137",
},
})
.head("https://api.github.com/repos/whatwg/html/pulls/2", {
status: 404,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": "120",
},
});
const options = {
owner: "whatwg",
repo: "html",
number: 1,
request: {
fetch: mock,
},
};
request(`HEAD /repos/{owner}/{repo}/pulls/{number}`, options)
.then((response) => {
expect(response.status).toEqual(200);
return request(
`HEAD /repos/{owner}/{repo}/pulls/{number}`,
Object.assign(options, { number: 2 })
);
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(404);
});
});
it.skip("Binary response with redirect (🤔 unclear how to mock fetch redirect properly)", () => {
const mock = fetchMock
.sandbox()
.get(
"https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
status: 200,
body: Buffer.from(
"1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000",
"hex"
),
headers: {
"content-type": "application/x-gzip",
"content-length": "172",
},
}
);
return request("GET /repos/{owner}/{repo}/{archive_format}/{ref}", {
owner: "octokit-fixture-org",
repo: "get-archive",
archive_format: "tarball",
ref: "master",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data.length).toEqual(172);
});
});
// TODO: fails with "response.buffer is not a function" in browser
it("Binary response", () => {
const mock = fetchMock
.sandbox()
.get(
"https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
status: 200,
// expect(response.data.length).toEqual(172)
// body: Buffer.from('1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000', 'hex'),
body: Buffer.from(
"1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000",
"hex"
),
headers: {
"content-type": "application/x-gzip",
"content-length": "172",
},
}
);
return request(
"GET https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
request: {
fetch: mock,
},
}
);
});
it("304 etag", () => {
const mock = fetchMock.sandbox().get((url, { headers }) => {
return (
url === "https://api.github.com/orgs/myorg" &&
(headers as ResponseHeaders)["if-none-match"] === "etag"
);
}, 304);
return request("GET /orgs/{org}", {
org: "myorg",
headers: { "If-None-Match": "etag" },
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(304);
});
});
it("304 last-modified", () => {
const mock = fetchMock.sandbox().get((url, { headers }) => {
return (
url === "https://api.github.com/orgs/myorg" &&
(headers as ResponseHeaders)["if-modified-since"] ===
"Sun Dec 24 2017 22:00:00 GMT-0600 (CST)"
);
}, 304);
return request("GET /orgs/{org}", {
org: "myorg",
headers: {
"If-Modified-Since": "Sun Dec 24 2017 22:00:00 GMT-0600 (CST)",
},
request: {
fetch: mock,
},
})
.then((response) => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(304);
});
});
it("Not found", () => {
const mock = fetchMock.sandbox().get("path:/orgs/nope", 404);
return request("GET /orgs/{org}", {
org: "nope",
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(404);
expect(error.request.method).toEqual("GET");
expect(error.request.url).toEqual("https://api.github.com/orgs/nope");
});
});
it("non-JSON response", () => {
const mock = fetchMock
.sandbox()
.get("path:/repos/octokit-fixture-org/hello-world/contents/README.md", {
status: 200,
body: "# hello-world",
headers: {
"content-length": "13",
"content-type": "application/vnd.github.v3.raw; charset=utf-8",
},
});
return request("GET /repos/{owner}/{repo}/contents/{path}", {
headers: {
accept: "application/vnd.github.v3.raw",
},
owner: "octokit-fixture-org",
repo: "hello-world",
path: "README.md",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("# hello-world");
});
});
it("Request error", () => {
// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
return request("GET https://127.0.0.1:8/")
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(500);
});
});
it("custom user-agent", () => {
const mock = fetchMock
.sandbox()
.get(
(url, { headers }) =>
(headers as ResponseHeaders)["user-agent"] === "funky boom boom pow",
200
);
return request("GET /", {
headers: {
"user-agent": "funky boom boom pow",
},
request: {
fetch: mock,
},
});
});
it("passes node-fetch options to fetch only", () => {
const mock = (url: string, options: RequestInit) => {
expect(url).toEqual("https://api.github.com/");
expect(options.timeout).toEqual(100);
return Promise.reject(new Error("ok"));
};
return request("GET /", {
headers: {
"user-agent": "funky boom boom pow",
},
request: {
timeout: 100,
fetch: mock,
},
}).catch((error) => {
if (error.message === "ok") {
return;
}
throw error;
});
});
it("422 error with details", () => {
const mock = fetchMock
.sandbox()
.post("https://api.github.com/repos/octocat/hello-world/labels", {
status: 422,
headers: {
"Content-Type": "application/json; charset=utf-8",
"X-Foo": "bar",
},
body: {
message: "Validation Failed",
errors: [
{
resource: "Label",
code: "invalid",
field: "color",
},
],
documentation_url:
"https://developer.github.com/v3/issues/labels/#create-a-label",
},
});
return request("POST /repos/octocat/hello-world/labels", {
name: "foo",
color: "invalid",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.status).toEqual(422);
expect(error.response.headers["x-foo"]).toEqual("bar");
expect(error.response.data.documentation_url).toEqual(
"https://developer.github.com/v3/issues/labels/#create-a-label"
);
expect(error.response.data.errors).toEqual([
{ resource: "Label", code: "invalid", field: "color" },
]);
});
});
it("redacts credentials from error.request.headers.authorization", () => {
const mock = fetchMock.sandbox().get("https://api.github.com/", {
status: 500,
});
return request("/", {
headers: {
authorization: "token secret123",
},
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.request.headers.authorization).toEqual("token [REDACTED]");
});
});
it("redacts credentials from error.request.url", () => {
const mock = fetchMock
.sandbox()
.get("https://api.github.com/?client_id=123&client_secret=secret123", {
status: 500,
});
return request("/", {
client_id: "123",
client_secret: "secret123",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.request.url).toEqual(
"https://api.github.com/?client_id=123&client_secret=[REDACTED]"
);
});
});
it("Just URL", () => {
const mock = fetchMock.sandbox().get("path:/", 200);
return request("/", {
request: {
fetch: mock,
},
}).then(({ status }) => {
expect(status).toEqual(200);
});
});
it("Resolves with url", function () {
// this test cannot be mocked with `fetch-mock`. I don’t like to rely on
// external websites to run tests, but in this case I’ll make an exception.
// The alternative would be to start a local server we then send a request to,
// this would only work in Node, so we would need to adapt the test setup, too.
// We also can’t test the GitHub API, because on Travis unauthenticated
// GitHub API requests are usually blocked due to IP rate limiting
return request("https://www.githubstatus.com/api/v2/status.json").then(
({ url }) => {
expect(url).toEqual("https://www.githubstatus.com/api/v2/status.json");
}
);
});
it("options.request.signal is passed as option to fetch", function () {
return request("/", {
request: {
signal: "funk",
},
})
.then(() => {
throw new Error("Should not resolve");
})
.catch((error) => {
expect(error.message).toMatch(/\bsignal\b/i);
expect(error.message).toMatch(/\bAbortSignal\b/i);
});
});
it("options.request.fetch", function () {
return request("/", {
request: {
fetch: () =>
Promise.resolve({
status: 200,
headers: new Headers({
"Content-Type": "application/json; charset=utf-8",
}),
url: "http://api.github.com/",
json() {
return Promise.resolve("funk");
},
}),
},
}).then((result) => {
expect(result.data).toEqual("funk");
});
});
it("options.request.hook", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/foo",
{ ok: true },
{
headers: {
"x-foo": "bar",
},
}
);
const hook = (request: RequestInterface, options: EndpointOptions) => {
expect(request.endpoint).toBeInstanceOf(Function);
expect(request.defaults).toBeInstanceOf(Function);
expect(options).toEqual({
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent,
},
mediaType: {
format: "",
previews: [],
},
method: "GET",
request: {
fetch: mock,
hook: hook,
},
url: "/",
});
return request("/foo", {
headers: {
"x-foo": "bar",
},
request: {
fetch: mock,
},
});
};
return request("/", {
request: {
fetch: mock,
hook,
},
}).then((result) => {
expect(result.data).toEqual({ ok: true });
});
});
it("options.mediaType.format", function () {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/repos/octokit/request.js/issues/1", "ok", {
headers: {
accept: "application/vnd.github.v3.raw+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /repos/{owner}/{repo}/issues/{number}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
mediaType: {
format: "raw+json",
},
owner: "octokit",
repo: "request.js",
number: 1,
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("ok");
});
});
it("options.mediaType.previews", function () {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/repos/octokit/request.js/issues/1", "ok", {
headers: {
accept:
"application/vnd.github.foo-preview+json,application/vnd.github.bar-preview+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /repos/{owner}/{repo}/issues/{number}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
mediaType: {
previews: ["foo", "bar"],
},
owner: "octokit",
repo: "request.js",
number: 1,
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("ok");
});
});
it("octokit/octokit.js#1497", function () {
const mock = fetchMock.sandbox().mock(
"https://request-errors-test.com/repos/gr2m/sandbox/branches/gr2m-patch-1/protection",
{
status: 400,
body: {
message: "Validation failed",
errors: [
"Only organization repositories can have users and team restrictions",
{ resource: "Search", field: "q", code: "invalid" },
],
documentation_url:
"https://developer.github.com/v3/repos/branches/#update-branch-protection",
},
},
{
method: "PUT",
headers: {
accept: "application/vnd.github.luke-cage-preview+json",
authorization: "token secret123",
},
}
);
return request("PUT /repos/{owner}/{repo}/branches/{branch}/protection", {
baseUrl: "https://request-errors-test.com",
mediaType: { previews: ["luke-cage"] },
headers: {
authorization: "token secret123",
},
owner: "gr2m",
repo: "sandbox",
branch: "gr2m-patch-1",
required_status_checks: { strict: true, contexts: ["wip"] },
enforce_admins: true,
required_pull_request_reviews: {
required_approving_review_count: 1,
dismiss_stale_reviews: true,
require_code_owner_reviews: true,
dismissal_restrictions: { users: [], teams: [] },
},
restrictions: { users: [], teams: [] },
request: {
fetch: mock,
},
})
.then(() => {
fail("This should return error.");
})
.catch((error) => {
expect(error).toHaveProperty(
"message",
`Validation failed: "Only organization repositories can have users and team restrictions", {"resource":"Search","field":"q","code":"invalid"}`
);
});
});
it("logs deprecation warning if `deprecation` header is present", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/teams/123",
{
body: {
id: 123,
},
headers: {
deprecation: "Sat, 01 Feb 2020 00:00:00 GMT",
sunset: "Mon, 01 Feb 2021 00:00:00 GMT",
link: '<https://developer.github.com/changes/2020-01-21-moving-the-team-api-endpoints/>; rel="deprecation"; type="text/html", <https://api.github.com/organizations/3430433/team/4177875>; rel="alternate"',
},
},
{
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
}
);
const warn = jest.fn();
return request("GET /teams/{team_id}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
team_id: 123,
request: { fetch: mock, log: { warn } },
}).then((response) => {
expect(response.data).toEqual({ id: 123 });
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
'[@octokit/request] "GET https://api.github.com/teams/123" is deprecated. It is scheduled to be removed on Mon, 01 Feb 2021 00:00:00 GMT. See https://developer.github.com/changes/2020-01-21-moving-the-team-api-endpoints/'
);
});
});
it("deprecation header without deprecation link", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/teams/123",
{
body: {
id: 123,
},
headers: {
deprecation: "Sat, 01 Feb 2020 00:00:00 GMT",
sunset: "Mon, 01 Feb 2021 00:00:00 GMT",
},
},
{
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
}
);
const warn = jest.fn();
return request("GET /teams/{team_id}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
team_id: 123,
request: { fetch: mock, log: { warn } },
}).then((response) => {
expect(response.data).toEqual({ id: 123 });
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
'[@octokit/request] "GET https://api.github.com/teams/123" is deprecated. It is scheduled to be removed on Mon, 01 Feb 2021 00:00:00 GMT'
);
});
});
it("404 not found", () => {
const mock = fetchMock
.sandbox()
.get("https://api.github.com/repos/octocat/unknown", {
status: 404,
headers: {},
body: {
message: "Not Found",
documentation_url:
"https://docs.github.com/en/rest/reference/repos#get-a-repository",
},
});
return request("GET /repos/octocat/unknown", {
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.status).toEqual(404);
expect(error.response.data.message).toEqual("Not Found");
expect(error.response.data.documentation_url).toEqual(
"https://docs.github.com/en/rest/reference/repos#get-a-repository"
);
});
});
it("Request timeout", () => {
const delay = (millis = 3000) => {
return new Promise((resolve) => {
setTimeout(resolve, millis);
});
};
const mock = (url: string, options: RequestInit) => {
expect(url).toEqual("https://api.github.com/");
expect(options.timeout).toEqual(100);
return delay().then(() => {
return {
status: 200,
headers: {},
body: {
message: "OK",
},
};
});
};
return request("GET /", {
request: {
timeout: 100,
fetch: mock,
},
})
.then((response) => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.name).toEqual("HttpError");
expect(error.status).toEqual(500);
});
});
it("validate request with readstream data", () => {
const size = fs.statSync(__filename).size;
const mock = fetchMock
.sandbox()
.post(
"https://api.github.com/repos/octokit-fixture-org/release-assets/releases/v1.0.0/assets",
{
status: 200,
}
);
return request("POST /repos/{owner}/{repo}/releases/{release_id}/assets", {
owner: "octokit-fixture-org",
repo: "release-assets",
release_id: "v1.0.0",
request: {
fetch: mock,
},
headers: {
"content-type": "text/json",
"content-length": size,
},
data: fs.createReadStream(__filename),
name: "test-upload.txt",
label: "test",
}).then((response) => {
expect(response.status).toEqual(200);
expect(mock.lastOptions()?.body).toBeInstanceOf(stream.Readable);
expect(mock.done()).toBe(true);
});
});
it("validate request with data set to Buffer type", () => {
const mock = fetchMock
.sandbox()
.post(
"https://api.github.com/repos/octokit-fixture-org/release-assets/releases/tags/v1.0.0",
{
status: 200,
}
);
return request("POST /repos/{owner}/{repo}/releases/tags/{tag}", {
owner: "octokit-fixture-org",
repo: "release-assets",
tag: "v1.0.0",
request: {
fetch: mock,
},
headers: {
"content-type": "text/plain",
},
data: Buffer.from("Hello, world!\n"),
name: "test-upload.txt",
label: "test",
}).then((response) => {
expect(response.status).toEqual(200);
expect(mock.lastOptions()?.body).toEqual(Buffer.from("Hello, world!\n"));
expect(mock.done()).toBe(true);
});
});
it("validate request with data set to ArrayBuffer type", () => {
const mock = fetchMock
.sandbox()
.post(
"https://api.github.com/repos/octokit-fixture-org/release-assets/releases/tags/v1.0.0",
{
status: 200,
}
);
return request("POST /repos/{owner}/{repo}/releases/tags/{tag}", {
owner: "octokit-fixture-org",
repo: "release-assets",
tag: "v1.0.0",
request: {
fetch: mock,
},
headers: {
"content-type": "text/plain",
},
data: stringToArrayBuffer("Hello, world!\n"),
name: "test-upload.txt",
label: "test",
}).then((response) => {
expect(response.status).toEqual(200);
expect(mock.lastOptions()?.body).toEqual(
stringToArrayBuffer("Hello, world!\n")
);
expect(mock.done()).toBe(true);
});
});
}); | the_stack |
import { Components, JSX } from '@bulmil/core';
interface BmInputProps {
/** Control Classes */
controlClass?: Components.BmInput["controlClass"]
/** Placeholder */
placeholder?: Components.BmInput["placeholder"]
/** Value */
value?: Components.BmInput["value"]
/** Type */
type?: Components.BmInput["type"]
/** Color */
color?: Components.BmInput["color"]
/** Size */
size?: Components.BmInput["size"]
/** State */
state?: Components.BmInput["state"]
/** Name */
name?: Components.BmInput["name"]
/** Required */
required?: Components.BmInput["required"]
/** Disabled state */
disabled?: Components.BmInput["disabled"]
/** The input will look similar to a normal one, but is not editable and has no shadow */
readonly?: Components.BmInput["readonly"]
/** Rounded */
isRounded?: Components.BmInput["isRounded"]
/** Loading state */
isLoading?: Components.BmInput["isLoading"]
/** Removes the background, border, shadow, and horizontal padding */
isStatic?: Components.BmInput["isStatic"]
}
interface BmInputEvents {
}
interface BmInputSlots {
default: any
}
/* generated by Svelte v3.42.6 */
import {
SvelteComponent,
binding_callbacks,
create_slot,
detach,
element,
flush,
get_all_dirty_from_scope,
get_slot_changes,
init,
insert,
safe_not_equal,
set_custom_element_data,
transition_in,
transition_out,
update_slot_base
} from "svelte/internal";
import { createEventDispatcher, onMount } from 'svelte';
function create_fragment(ctx) {
let bm_input;
let current;
const default_slot_template = /*#slots*/ ctx[17].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[16], null);
return {
c() {
bm_input = element("bm-input");
if (default_slot) default_slot.c();
set_custom_element_data(bm_input, "control-class", /*controlClass*/ ctx[0]);
set_custom_element_data(bm_input, "placeholder", /*placeholder*/ ctx[1]);
set_custom_element_data(bm_input, "value", /*value*/ ctx[2]);
set_custom_element_data(bm_input, "type", /*type*/ ctx[3]);
set_custom_element_data(bm_input, "color", /*color*/ ctx[4]);
set_custom_element_data(bm_input, "size", /*size*/ ctx[5]);
set_custom_element_data(bm_input, "state", /*state*/ ctx[6]);
set_custom_element_data(bm_input, "name", /*name*/ ctx[7]);
set_custom_element_data(bm_input, "required", /*required*/ ctx[8]);
set_custom_element_data(bm_input, "disabled", /*disabled*/ ctx[9]);
set_custom_element_data(bm_input, "readonly", /*readonly*/ ctx[10]);
set_custom_element_data(bm_input, "is-rounded", /*isRounded*/ ctx[11]);
set_custom_element_data(bm_input, "is-loading", /*isLoading*/ ctx[12]);
set_custom_element_data(bm_input, "is-static", /*isStatic*/ ctx[13]);
},
m(target, anchor) {
insert(target, bm_input, anchor);
if (default_slot) {
default_slot.m(bm_input, null);
}
/*bm_input_binding*/ ctx[18](bm_input);
current = true;
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 65536)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[16],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[16])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[16], dirty, null),
null
);
}
}
if (!current || dirty & /*controlClass*/ 1) {
set_custom_element_data(bm_input, "control-class", /*controlClass*/ ctx[0]);
}
if (!current || dirty & /*placeholder*/ 2) {
set_custom_element_data(bm_input, "placeholder", /*placeholder*/ ctx[1]);
}
if (!current || dirty & /*value*/ 4) {
set_custom_element_data(bm_input, "value", /*value*/ ctx[2]);
}
if (!current || dirty & /*type*/ 8) {
set_custom_element_data(bm_input, "type", /*type*/ ctx[3]);
}
if (!current || dirty & /*color*/ 16) {
set_custom_element_data(bm_input, "color", /*color*/ ctx[4]);
}
if (!current || dirty & /*size*/ 32) {
set_custom_element_data(bm_input, "size", /*size*/ ctx[5]);
}
if (!current || dirty & /*state*/ 64) {
set_custom_element_data(bm_input, "state", /*state*/ ctx[6]);
}
if (!current || dirty & /*name*/ 128) {
set_custom_element_data(bm_input, "name", /*name*/ ctx[7]);
}
if (!current || dirty & /*required*/ 256) {
set_custom_element_data(bm_input, "required", /*required*/ ctx[8]);
}
if (!current || dirty & /*disabled*/ 512) {
set_custom_element_data(bm_input, "disabled", /*disabled*/ ctx[9]);
}
if (!current || dirty & /*readonly*/ 1024) {
set_custom_element_data(bm_input, "readonly", /*readonly*/ ctx[10]);
}
if (!current || dirty & /*isRounded*/ 2048) {
set_custom_element_data(bm_input, "is-rounded", /*isRounded*/ ctx[11]);
}
if (!current || dirty & /*isLoading*/ 4096) {
set_custom_element_data(bm_input, "is-loading", /*isLoading*/ ctx[12]);
}
if (!current || dirty & /*isStatic*/ 8192) {
set_custom_element_data(bm_input, "is-static", /*isStatic*/ ctx[13]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(bm_input);
if (default_slot) default_slot.d(detaching);
/*bm_input_binding*/ ctx[18](null);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
let __ref;
let __mounted = false;
const dispatch = createEventDispatcher();
let { controlClass = undefined } = $$props;
let { placeholder = undefined } = $$props;
let { value = undefined } = $$props;
let { type = undefined } = $$props;
let { color = undefined } = $$props;
let { size = undefined } = $$props;
let { state = undefined } = $$props;
let { name = undefined } = $$props;
let { required = undefined } = $$props;
let { disabled = undefined } = $$props;
let { readonly = undefined } = $$props;
let { isRounded = undefined } = $$props;
let { isLoading = undefined } = $$props;
let { isStatic = undefined } = $$props;
const getWebComponent = () => __ref;
onMount(() => {
__mounted = true;
});
const setProp = (prop, value) => {
if (__ref) $$invalidate(14, __ref[prop] = value, __ref);
};
const onEvent = e => {
e.stopPropagation();
dispatch(e.type, e.detail);
};
function bm_input_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
__ref = $$value;
$$invalidate(14, __ref);
});
}
$$self.$$set = $$props => {
if ('controlClass' in $$props) $$invalidate(0, controlClass = $$props.controlClass);
if ('placeholder' in $$props) $$invalidate(1, placeholder = $$props.placeholder);
if ('value' in $$props) $$invalidate(2, value = $$props.value);
if ('type' in $$props) $$invalidate(3, type = $$props.type);
if ('color' in $$props) $$invalidate(4, color = $$props.color);
if ('size' in $$props) $$invalidate(5, size = $$props.size);
if ('state' in $$props) $$invalidate(6, state = $$props.state);
if ('name' in $$props) $$invalidate(7, name = $$props.name);
if ('required' in $$props) $$invalidate(8, required = $$props.required);
if ('disabled' in $$props) $$invalidate(9, disabled = $$props.disabled);
if ('readonly' in $$props) $$invalidate(10, readonly = $$props.readonly);
if ('isRounded' in $$props) $$invalidate(11, isRounded = $$props.isRounded);
if ('isLoading' in $$props) $$invalidate(12, isLoading = $$props.isLoading);
if ('isStatic' in $$props) $$invalidate(13, isStatic = $$props.isStatic);
if ('$$scope' in $$props) $$invalidate(16, $$scope = $$props.$$scope);
};
return [
controlClass,
placeholder,
value,
type,
color,
size,
state,
name,
required,
disabled,
readonly,
isRounded,
isLoading,
isStatic,
__ref,
getWebComponent,
$$scope,
slots,
bm_input_binding
];
}
class BmInput extends SvelteComponent {
$$prop_def: BmInputProps;
$$events_def: BmInputEvents;
$$slot_def: BmInputSlots;
$on<K extends keyof BmInputEvents>(type: K, callback: (e: BmInputEvents[K]) => any): () => void {
return super.$on(type, callback);
}
$set($$props: Partial<BmInputProps>): void {
super.$set($$props);
}
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {
controlClass: 0,
placeholder: 1,
value: 2,
type: 3,
color: 4,
size: 5,
state: 6,
name: 7,
required: 8,
disabled: 9,
readonly: 10,
isRounded: 11,
isLoading: 12,
isStatic: 13,
getWebComponent: 15
});
}
get controlClass() {
return this.$$.ctx[0];
}
set controlClass(controlClass) {
this.$$set({ controlClass });
flush();
}
get placeholder() {
return this.$$.ctx[1];
}
set placeholder(placeholder) {
this.$$set({ placeholder });
flush();
}
get value() {
return this.$$.ctx[2];
}
set value(value) {
this.$$set({ value });
flush();
}
get type() {
return this.$$.ctx[3];
}
set type(type) {
this.$$set({ type });
flush();
}
get color() {
return this.$$.ctx[4];
}
set color(color) {
this.$$set({ color });
flush();
}
get size() {
return this.$$.ctx[5];
}
set size(size) {
this.$$set({ size });
flush();
}
get state() {
return this.$$.ctx[6];
}
set state(state) {
this.$$set({ state });
flush();
}
get name() {
return this.$$.ctx[7];
}
set name(name) {
this.$$set({ name });
flush();
}
get required() {
return this.$$.ctx[8];
}
set required(required) {
this.$$set({ required });
flush();
}
get disabled() {
return this.$$.ctx[9];
}
set disabled(disabled) {
this.$$set({ disabled });
flush();
}
get readonly() {
return this.$$.ctx[10];
}
set readonly(readonly) {
this.$$set({ readonly });
flush();
}
get isRounded() {
return this.$$.ctx[11];
}
set isRounded(isRounded) {
this.$$set({ isRounded });
flush();
}
get isLoading() {
return this.$$.ctx[12];
}
set isLoading(isLoading) {
this.$$set({ isLoading });
flush();
}
get isStatic() {
return this.$$.ctx[13];
}
set isStatic(isStatic) {
this.$$set({ isStatic });
flush();
}
get getWebComponent(): HTMLBmInputElement | undefined {
return this.$$.ctx[15];
}
}
export default BmInput; | the_stack |
* @module MarkupApp
*/
import { BentleyError, Logger } from "@itwin/core-bentley";
import { Point3d, XAndY } from "@itwin/core-geometry";
import { ImageSource, ImageSourceFormat } from "@itwin/core-common";
import { FrontendLoggerCategory, imageElementFromImageSource, IModelApp, ScreenViewport } from "@itwin/core-frontend";
import { adopt, create, G, Matrix, Point, Svg, SVG } from "@svgdotjs/svg.js";
import * as redlineTool from "./RedlineTool";
import { MarkupSelected, SelectTool } from "./SelectTool";
import * as textTool from "./TextEdit";
import { UndoManager } from "./Undo";
// cspell:ignore blanchedalmond, lmultiply, svgs
/** The width and height of a Markup image, in pixels.
* @public */
export interface WidthAndHeight {
width: number;
height: number;
}
/** The size and SVG string for a Markup
* @public
*/
export interface MarkupSvgData {
/** The size of the image, in pixels. This also indicates the aspect ratio of the SVG data. */
rect: WidthAndHeight;
/** a string holding the svg data for the markup. Will be undefined if [[MarkupApp.stop]] is called without an active Markup */
svg?: string;
}
/** Markup data returned by [[MarkupApp.stop]]
* @public
*/
export interface MarkupData extends MarkupSvgData {
/** a base64 encoded string with the image of the view that was marked up. See [[MarkupApp.props.result]] for options. */
image?: string;
}
/**
* The main object for the Markup package. It is a singleton that stores the state of the Markup application.
* It has only static members and methods. Applications may customize and control the behavior of the Markup by
* setting members of [[MarkupApp.props]]. When [[MarkupApp.start]] is first called, it registers a set of "Markup.xxx"
* tools that may be invoked from UI controls.
* @public
*/
export class MarkupApp {
/** the current Markup being created */
public static markup?: Markup;
/** The namespace for the Markup tools */
public static namespace?: string;
/** By setting members of this object, applications can control the appearance and behavior of various parts of MarkupApp. */
public static props = {
/** the UI controls displayed on Elements by the Select Tool to allow users to modify them. */
handles: {
/** The diameter of the circles for the handles. */
size: 10,
/** The attributes of the stretch handles */
stretch: { "fill-opacity": .85, "stroke": "black", "fill": "white" },
/** The attributes of the line that connects the top-center stretch handle to the rotate handle. */
rotateLine: { "stroke": "grey", "fill-opacity": .85 },
/** The attributes of the rotate handle. */
rotate: { "cursor": "url(Markup/rotate.png) 12 12, auto", "fill-opacity": .85, "stroke": "black", "fill": "lightBlue" },
/** The attributes of box around the element. */
moveOutline: { "cursor": "move", "stroke-dasharray": "6,6", "fill": "none", "stroke-opacity": .85, "stroke": "white" },
/** The attributes of box that provides the move cursor. */
move: { "cursor": "move", "opacity": 0, "stroke-width": 10, "stroke": "white" },
/** The attributes of handles on the vertices of lines. */
vertex: { "cursor": "url(cursors/crosshair.cur), crosshair", "fill-opacity": .85, "stroke": "black", "fill": "white" },
},
/** properties for providing feedback about selected elements. */
hilite: {
/** the color of selected elements */
color: "magenta",
/** the color of an element as the cursor passes over it */
flash: "cyan",
},
/** optionally, show a drop-shadow behind all markup elements. */
dropShadow: {
/** if false, no drop shadow */
enable: true,
/** the attributes of the drop shadow. See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDropShadow */
attr: {
"stdDeviation": 2,
"dx": 1.2,
"dy": 1.4,
"flood-color": "#1B3838",
},
},
/** The "active placement" parameters. New elements are created with these parameters, so UI controls should set them. */
active: {
/** the CSS style properties of new text elements. */
text: {
"font-family": "sans-serif",
"font-size": "30px",
"stroke": "none",
"fill": "red",
},
/** the CSS style properties of new elements. */
element: {
"stroke": "red",
"stroke-opacity": 0.8,
"stroke-width": 3,
"stroke-dasharray": 0,
"stroke-linecap": "round",
"stroke-linejoin": "round",
"fill": "blue",
"fill-opacity": 0.2,
},
arrow: {
length: 7,
width: 6,
},
cloud: {
path: "M3.0,2.5 C3.9,.78 5.6,-.4 8.1,1.0 C9.1,0 11.3,-.2 12.5,.5 C14.2,-.5 17,.16 17.9,2.5 C21,3 20.2,7.3 17.6,7.5 C16.5,9.2 14.4,9.8 12.7,8.9 C11.6,10 9.5,10.3 8.1,9.4 C5.7,10.8 3.3,9.4 2.6,7.5 C-.9,7.7 .6,1.7 3.0,2.5z",
},
},
/** Values for placing and editing Text. */
text: {
/** A default string for the Markup.Text.Place command. Applications can turn this off, or supply the user's initials, for example. */
startValue: "Note: ",
/** Parameters for the size and appearance of the text editor */
edit: {
background: "blanchedalmond",
/** Starting size, will be updated if user stretches the box */
size: { width: "25%", height: "4em" },
/** font size of the text editor */
fontSize: "14pt",
/** A background box drawn around text so user can tell what's being selected */
textBox: { "fill": "lightGrey", "fill-opacity": .1, "stroke-opacity": .85, "stroke": "lightBlue" },
},
},
/** Used to draw the border outline around the view while it is being marked up so the user can tell Markup is active */
borderOutline: {
"stroke": "gold",
"stroke-width": 6,
"stroke-opacity": 0.4,
"fill": "none",
},
/** Used to draw the border corner symbols for the view while it is being marked up so the user can tell Markup is active */
borderCorners: {
"stroke": "black",
"stroke-width": 2,
"stroke-opacity": 0.2,
"fill": "gold",
"fill-opacity": 0.2,
},
/** Determines what is returned by MarkupApp.stop */
result: {
/** The format for the image data. */
imageFormat: "image/png",
/** If true, the markup graphics will be imprinted in the returned image. */
imprintSvgOnImage: true,
/** the maximum width for the returned image. If the source view width is larger than this, it will be scaled down to this size. */
maxWidth: 2048,
},
};
private static _saveDefaultToolId = "";
/** @internal */
public static screenToVbMtx(): Matrix {
const matrix = this.markup?.svgMarkup?.screenCTM().inverse();
return (undefined !== matrix ? matrix : new Matrix());
}
/** @internal */
public static getVpToScreenMtx(): Matrix { const rect = this.markup!.markupDiv.getBoundingClientRect(); return (new Matrix()).translateO(rect.left, rect.top); }
/** @internal */
public static getVpToVbMtx(): Matrix { return this.getVpToScreenMtx().lmultiplyO(this.screenToVbMtx()); }
/** @internal */
public static convertVpToVb(pt: XAndY): Point3d {
const pt0 = new Point(pt.x, pt.y);
pt0.transformO(this.getVpToVbMtx());
return new Point3d(pt0.x, pt0.y, 0);
}
/** determine whether there's a markup session currently active */
public static get isActive() { return undefined !== this.markup; }
public static markupSelectToolId = "Markup.Select";
protected static createMarkup(view: ScreenViewport, markupData?: MarkupSvgData) { return new Markup(view, markupData); }
protected static lockViewportSize(view: ScreenViewport, markupData?: MarkupSvgData) {
const parentDiv = view.vpDiv;
const rect = parentDiv.getBoundingClientRect();
let width = rect.width;
let height = rect.height;
if (markupData) {
const aspect = markupData.rect.height / markupData.rect.width;
if ((width * aspect) > height)
width = Math.floor(height / aspect);
else
height = Math.floor(width * aspect);
}
const style = parentDiv.style;
style.width = `${width}px`;
style.height = `${height}px`;
}
/** @internal */
public static getActionName(action: string) { return IModelApp.localization.getLocalizedString(`${this.namespace}:actions.${action}`); }
/** Start a markup session */
public static async start(view: ScreenViewport, markupData?: MarkupSvgData): Promise<void> {
if (this.markup)
return; // a markup session is already active.
await this.initialize();
// first, lock the viewport to its current size while the markup session is running
this.lockViewportSize(view, markupData);
this.markup = this.createMarkup(view, markupData); // start a markup against the provided view.
if (!this.markup.svgMarkup) {
ScreenViewport.setToParentSize(this.markup.vp.vpDiv);
this.markup.markupDiv.remove();
return;
}
IModelApp.toolAdmin.markupView = view; // so viewing tools won't operate on the view.
// set the markup Select tool as the default tool and start it, saving current default tool
this._saveDefaultToolId = IModelApp.toolAdmin.defaultToolId;
IModelApp.toolAdmin.defaultToolId = this.markupSelectToolId;
return IModelApp.toolAdmin.startDefaultTool();
}
/** Read the result of a Markup session, then stop the session.
* @note see [MarkupApp.props.result] for options.
*/
public static async stop(): Promise<MarkupData> {
const data = await this.readMarkup();
if (!this.markup)
return data;
// restore original size for vp.
ScreenViewport.setToParentSize(this.markup.vp.vpDiv);
IModelApp.toolAdmin.markupView = undefined; // re-enable viewing tools for the view being marked-up
this.markup.destroy();
this.markup = undefined;
// now restore the default tool and start it
IModelApp.toolAdmin.defaultToolId = this._saveDefaultToolId;
this._saveDefaultToolId = "";
await IModelApp.toolAdmin.startDefaultTool();
return data;
}
/** Call this method to initialize the Markup system.
* It asynchronously loads the MarkupTools namespace for the prompts and tool names for the Markup system, and
* also registers all of the Markup tools.
* @return a Promise that may be awaited to ensure that the MarkupTools namespace had been loaded.
* @note This method is automatically called every time you call [[start]]. Since the Markup tools cannot
* start unless there is a Markup active, there's really no need to call this method directly.
* The only virtue in doing so is to pre-load the Markup namespace if you have an opportunity to do so earlier in your
* startup code.
* @note This method may be called multiple times, but only the first time initiates the loading/registering. Subsequent
* calls return the same Promise.
*/
public static async initialize(): Promise<void> {
if (undefined === this.namespace) { // only need to do this once
this.namespace = "MarkupTools";
const namespacePromise = IModelApp.localization.registerNamespace(this.namespace);
IModelApp.tools.register(SelectTool, this.namespace);
IModelApp.tools.registerModule(redlineTool, this.namespace);
IModelApp.tools.registerModule(textTool, this.namespace);
return namespacePromise;
}
return IModelApp.localization.getNamespacePromise(this.namespace)!; // so caller can make sure localized messages are ready.
}
/** convert the current markup SVG into a string, but don't include decorations or dynamics
* @internal
*/
protected static readMarkupSvg() {
const markup = this.markup;
if (!markup || !markup.svgContainer)
return undefined;
markup.svgDecorations!.remove(); // we don't want the decorations or dynamics to be included
markup.svgDynamics!.remove();
void IModelApp.toolAdmin.startDefaultTool();
return markup.svgContainer.svg(); // string-ize the SVG data
}
/** convert the current markup SVG into a string (after calling readMarkupSvg) making sure width and height are specified.
* @internal
*/
protected static readMarkupSvgForDrawImage() {
const markup = this.markup;
if (!markup || !markup.svgContainer)
return undefined;
// Firefox requires width and height on top-level svg or drawImage does nothing, passing width/height to drawImage doesn't work.
const rect = markup.markupDiv.getBoundingClientRect();
markup.svgContainer.width(rect.width);
markup.svgContainer.height(rect.height);
return markup.svgContainer.svg(); // string-ize the SVG data
}
/** @internal */
protected static async readMarkup(): Promise<MarkupData> {
const result = this.props.result;
let canvas = this.markup!.vp.readImageToCanvas();
let svg, image;
try {
svg = this.readMarkupSvg(); // read the current svg data for the markup
const svgForImage = (svg && result.imprintSvgOnImage ? this.readMarkupSvgForDrawImage() : undefined);
if (svgForImage) {
const svgImage = await imageElementFromImageSource(new ImageSource(svgForImage, ImageSourceFormat.Svg));
canvas.getContext("2d")!.drawImage(svgImage, 0, 0); // draw markup svg onto view's canvas2d
}
// is the source view too wide? If so, we need to scale the image down.
if (canvas.width > result.maxWidth) {
// yes, we have to scale it down, create a new canvas and set the new canvas' size
const newCanvas = document.createElement("canvas");
newCanvas.width = result.maxWidth;
newCanvas.height = canvas.height * (result.maxWidth / canvas.width);
newCanvas.getContext("2d")!.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, newCanvas.width, newCanvas.height);
canvas = newCanvas; // return the image from adjusted canvas, not view canvas.
}
// return the markup data to be saved by the application.
image = (!result.imageFormat ? undefined : canvas.toDataURL(result.imageFormat));
} catch (e) {
Logger.logError(`${FrontendLoggerCategory.Package}.markup`, "Error creating image from svg", BentleyError.getErrorProps(e));
}
return { rect: { width: canvas.width, height: canvas.height }, svg, image };
}
/** @internal */
public static markupPrefix = "markup-";
/** @internal */
public static get dropShadowId() { return `${this.markupPrefix}dropShadow`; } // this is referenced in the markup Svg to apply the drop-shadow filter to all markup elements.
/** @internal */
public static get cornerId() { return `${this.markupPrefix}photoCorner`; }
/** @internal */
public static get containerClass() { return `${this.markupPrefix}container`; }
/** @internal */
public static get dynamicsClass() { return `${this.markupPrefix}dynamics`; }
/** @internal */
public static get decorationsClass() { return `${this.markupPrefix}decorations`; }
/** @internal */
public static get markupSvgClass() { return `${this.markupPrefix}svg`; }
/** @internal */
public static get boxedTextClass() { return `${this.markupPrefix}boxedText`; }
/** @internal */
public static get textClass() { return `${this.markupPrefix}text`; }
/** @internal */
public static get stretchHandleClass() { return `${this.markupPrefix}stretchHandle`; }
/** @internal */
public static get rotateLineClass() { return `${this.markupPrefix}rotateLine`; }
/** @internal */
public static get rotateHandleClass() { return `${this.markupPrefix}rotateHandle`; }
/** @internal */
public static get vertexHandleClass() { return `${this.markupPrefix}vertexHandle`; }
/** @internal */
public static get moveHandleClass() { return `${this.markupPrefix}moveHandle`; }
/** @internal */
public static get textOutlineClass() { return `${this.markupPrefix}textOutline`; }
/** @internal */
public static get textEditorClass() { return `${this.markupPrefix}textEditor`; }
}
const removeSvgNamespace = (svg: Svg) => { svg.node.removeAttribute("xmlns:svgjs"); return svg; };
const newSvgElement = (name: string) => adopt(create(name));
/**
* The current markup being created/edited. Holds the SVG elements, plus the active [[MarkupTool]].
* When starting a Markup, a new Div is added as a child of the ScreenViewport's vpDiv.
* @public
*/
export class Markup {
/** @internal */
public readonly markupDiv: HTMLDivElement;
/** @internal */
public readonly undo = new UndoManager();
/** @internal */
public readonly selected!: MarkupSelected;
/** @internal */
public readonly svgContainer?: Svg;
/** @internal */
public readonly svgMarkup?: G;
/** @internal */
public readonly svgDynamics?: G;
/** @internal */
public readonly svgDecorations?: G;
/** create the drop-shadow filter in the Defs section of the supplied svg element */
private createDropShadow(svg: Svg) {
const filter = SVG(`#${MarkupApp.dropShadowId}`); // see if we already have one?
if (filter) filter.remove(); // yes, remove it. This must be someone modifying the drop shadow properties
// create a new filter, and add it to the Defs of the supplied svg
svg.defs()
.add(newSvgElement("filter").id(MarkupApp.dropShadowId)
.add(newSvgElement("feDropShadow").attr(MarkupApp.props.dropShadow.attr)));
}
private addNested(className: string): G { return this.svgContainer!.group().addClass(className); }
private addBorder() {
const rect = this.svgContainer!.viewbox();
const inset = MarkupApp.props.borderOutline["stroke-width"];
const cornerSize = inset * 6;
const cornerPts = [0, 0, cornerSize, 0, cornerSize * .7, cornerSize * .3, cornerSize * .3, cornerSize * .3, cornerSize * .3, cornerSize * .7, 0, cornerSize];
const decorations = this.svgDecorations!;
const photoCorner = decorations.symbol().polygon(cornerPts).attr(MarkupApp.props.borderCorners).id(MarkupApp.cornerId);
const cornerGroup = decorations.group();
cornerGroup.rect(rect.width - inset, rect.height - inset).move(inset / 2, inset / 2).attr(MarkupApp.props.borderOutline);
cornerGroup.use(photoCorner);
cornerGroup.use(photoCorner).rotate(90).translate(rect.width - cornerSize, 0);
cornerGroup.use(photoCorner).rotate(180).translate(rect.width - cornerSize, rect.height - cornerSize);
cornerGroup.use(photoCorner).rotate(270).translate(0, rect.height - cornerSize);
}
/** Create a new Markup for the supplied ScreenViewport. Adds a new "overlay-markup" div into the "vpDiv"
* of the viewport.
* @note you must call destroy on this object at end of markup to remove the markup div.
*/
public constructor(public vp: ScreenViewport, markupData?: MarkupSvgData) {
this.markupDiv = vp.addNewDiv("overlay-markup", true, 20); // this div goes on top of the canvas, but behind UI layers
const rect = this.markupDiv.getBoundingClientRect();
// First, see if there is a markup passed in as an argument
if (markupData && markupData.svg) {
this.markupDiv.innerHTML = markupData.svg; // make it a child of the markupDiv
this.svgContainer = SVG(`.${MarkupApp.containerClass}`) as Svg | undefined; // get it in svg.js format
this.svgMarkup = SVG(`.${MarkupApp.markupSvgClass}`) as G | undefined;
if (!this.svgContainer || !this.svgMarkup) // if either isn't present, its not a valid markup
return;
removeSvgNamespace(this.svgContainer); // the SVG call above adds this - remove it
this.svgMarkup.each(() => { }, true); // create an SVG.Element for each entry in the supplied markup.
} else {
// create the container that will be returned as the "svg" data for this markup
this.svgContainer = SVG().addTo(this.markupDiv).addClass(MarkupApp.containerClass).viewbox(0, 0, rect.width, rect.height);
removeSvgNamespace(this.svgContainer);
this.svgMarkup = this.addNested(MarkupApp.markupSvgClass);
}
if (MarkupApp.props.dropShadow.enable) {
this.createDropShadow(this.svgContainer);
this.svgContainer.attr("filter", `url(#${MarkupApp.dropShadowId})`);
}
/** add two nested groups for providing feedback during the markup session. These Svgs are removed before the data is returned. */
this.svgDynamics = this.addNested(MarkupApp.dynamicsClass); // only for tool dynamics of SVG graphics.
this.svgDecorations = this.addNested(MarkupApp.decorationsClass); // only for temporary decorations of SVG graphics.
this.addBorder();
this.selected = new MarkupSelected(this.svgDecorations);
}
/** Called when the Markup is destroyed */
public destroy() { this.markupDiv.remove(); }
/** Turn on picking the markup elements in the markup view */
public enablePick() { this.markupDiv.style.pointerEvents = "auto"; }
/** Turn off picking the markup elements in the markup view */
public disablePick() { this.markupDiv.style.pointerEvents = "none"; }
/** Change the default cursor for the markup view */
public setCursor(cursor: string) { this.markupDiv.style.cursor = cursor; }
/** Delete all the entries in the selection set, then empty it. */
public deleteSelected() { this.selected.deleteAll(this.undo); }
/** Bring all the entries in the selection set to the front. */
public bringToFront() { this.selected.reposition(MarkupApp.getActionName("toFront"), this.undo, (el) => el.front()); }
/** Send all the entries in the selection set to the back. */
public sendToBack() { this.selected.reposition(MarkupApp.getActionName("toBack"), this.undo, (el) => el.back()); }
/** Group all the entries in the selection set, then select the group. */
public groupSelected() { if (undefined !== this.svgMarkup) this.selected.groupAll(this.undo); }
/** Ungroup all the group entries in the selection set. */
public ungroupSelected() { if (undefined !== this.svgMarkup) this.selected.ungroupAll(this.undo); }
} | the_stack |
* @module Topology
*/
import { CurveLocationDetail } from "../curve/CurveLocationDetail";
import { LineSegment3d } from "../curve/LineSegment3d";
import { Geometry } from "../Geometry";
import { Angle } from "../geometry3d/Angle";
import { Point2d, Vector2d } from "../geometry3d/Point2dVector2d";
import { Range3d } from "../geometry3d/Range";
import { ClusterableArray } from "../numerics/ClusterableArray";
import { SmallSystem } from "../numerics/Polynomials";
import { HalfEdge, HalfEdgeGraph, HalfEdgeMask } from "./Graph";
import { HalfEdgePriorityQueueWithPartnerArray } from "./HalfEdgePriorityQueue";
import { RegularizationContext } from "./RegularizeFace";
import { MultiLineStringDataVariant, Triangulator } from "./Triangulation";
export class GraphSplitData {
public numUpEdge = 0;
public numIntersectionTest = 0;
public numSplit = 0;
public numPopOut = 0;
public numA0B0 = 0;
public numA0B1 = 0;
public constructor() {
}
}
/**
* Structure for data used when sorting outbound edges "around a node"
*/
export class VertexNeighborhoodSortData {
public index: number;
public radiusOfCurvature: number;
public node: HalfEdge;
public radians?: number;
public constructor(index: number, key: number, node: HalfEdge, radians?: number) {
this.index = index;
this.radiusOfCurvature = key;
this.node = node;
this.radians = radians;
}
}
/** Function signature for announcing a vertex neighborhood during sorting. */
export type AnnounceVertexNeighborhoodSortData = (data: VertexNeighborhoodSortData[]) => any;
/**
* * Assorted methods used in algorithms on HalfEdgeGraph.
* @internal
*/
export class HalfEdgeGraphOps {
/** Compare function for sorting with primary y compare, secondary x compare. */
public static compareNodesYXUp(a: HalfEdge, b: HalfEdge) {
// Check y's
// if (!Geometry.isSameCoordinate(a.y, b.y))
if (a.y < b.y)
return -1;
else if (a.y > b.y)
return 1;
// Check x's
// if (!Geometry.isSameCoordinate(a.x, b.x))
if (a.x < b.x)
return -1;
else if (a.x > b.x)
return 1;
return 0;
}
/** Return true if nodeB (a) is lower than both its neighbors and (b) inflects as a downward peak (rather than an upward trough) */
public static isDownPeak(nodeB: HalfEdge) {
const nodeA = nodeB.facePredecessor;
const nodeC = nodeB.faceSuccessor;
return this.compareNodesYXUp(nodeB, nodeA) < 0
&& this.compareNodesYXUp(nodeB, nodeC) < 0
&& this.crossProductToTargets(nodeB, nodeA, nodeC) > 0;
}
/** return the cross product of vectors from base to targetA and base to targetB
* @param base base vertex of both vectors.
* @param targetA target vertex of first vector
* @param targetB target vertex of second vector
*/
public static crossProductToTargets(base: HalfEdge, targetA: HalfEdge, targetB: HalfEdge): number {
return Geometry.crossProductXYXY(targetA.x - base.x, targetA.y - base.y, targetB.x - base.x, targetB.y - base.y);
}
// ---------------------------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------------
public static graphRange(graph: HalfEdgeGraph): Range3d {
const range = Range3d.create();
for (const node of graph.allHalfEdges) {
range.extendXYZ(node.x, node.y, node.z);
}
return range;
}
/** Returns an array of all nodes (both ends) of edges created from segments. */
public static segmentArrayToGraphEdges(segments: LineSegment3d[], returnGraph: HalfEdgeGraph, mask: HalfEdgeMask): HalfEdge[] {
const result = [];
let idxCounter = 0;
// Push the endpoints of each segment onto arr[] in the form {(x, y, theta), Node}
for (const segment of segments) {
const node0 = returnGraph.createEdgeXYZXYZ(
segment.point0Ref.x, segment.point0Ref.y, segment.point0Ref.z,
idxCounter,
segment.point1Ref.x, segment.point1Ref.y, segment.point1Ref.z,
idxCounter + 1);
const node1 = node0.edgeMate;
idxCounter += 2;
node0.setMaskAroundFace(mask); // Original given coordinates must be part of boundary
result.push(node0);
result.push(node1);
}
return result;
}
/**
* * Visit all nodes in `graph`.
* * invoke `pinch(node, vertexPredecessor)`
* * this leaves the graph as isolated edges.
* @param graph graph to modify
*/
public static isolateAllEdges(graph: HalfEdgeGraph) {
for (const nodeA of graph.allHalfEdges) {
const nodeB = nodeA.vertexPredecessor;
HalfEdge.pinch(nodeA, nodeB);
}
}
/**
* Compute convexity of a sector of a super-face.
* @param base node whose edge is to be tested for removal
* @param ignore edges with this mask (on either side) are ignored for the purposes of computing convexity
* @param barrier edges with this mask (on either side) will not be removed
* @return whether removing the edge at base would create a convex sector in the super-face
*/
private static isSectorConvexAfterEdgeRemoval(base: HalfEdge, ignore: HalfEdgeMask, barrier: HalfEdgeMask): boolean {
let vs = base;
do { // loop ccw around vertex looking for a super-face predecessor
if (vs.isMaskSet(barrier) || vs.edgeMate.isMaskSet(barrier))
break;
vs = vs.vertexSuccessor;
} while (vs !== base && vs.isMaskSet(ignore));
if (vs === base)
return false;
let vp = base;
do { // loop cw around vertex looking for a super-face successor
if (vp.isMaskSet(barrier) || vp.edgeMate.isMaskSet(barrier))
break;
vp = vp.vertexPredecessor;
} while (vp !== base && vp.isMaskSet(ignore));
if (vp === base)
return false;
return HalfEdge.isSectorConvex(vs.edgeMate, base, vp.faceSuccessor);
}
/**
* Mask edges between faces if the union of the faces is convex.
* Uses a greedy algorithm with no regard to quality of resulting convex faces.
* Best results when input faces are convex.
* @param graph graph to examine and mark
* @param mark the mask used to mark (both sides of) removable edges
* @param barrier edges with this mask (on either side) will not be marked. Defaults to HalfEdgeMask.BOUNDARY_EDGE.
* @return number of edges masked (half the number of HalfEdges masked)
*/
public static markRemovableEdgesToExpandConvexFaces(graph: HalfEdgeGraph, mark: HalfEdgeMask, barrier: HalfEdgeMask = HalfEdgeMask.BOUNDARY_EDGE): number {
if (HalfEdgeMask.NULL_MASK === mark)
return 0;
const visit = graph.grabMask(true);
let numMarked = 0;
for (const node of graph.allHalfEdges) {
if (!node.isMaskSet(visit)) {
if (!node.isMaskSet(barrier) && !node.edgeMate.isMaskSet(barrier)) {
if (this.isSectorConvexAfterEdgeRemoval(node, mark, barrier) && this.isSectorConvexAfterEdgeRemoval(node.edgeMate, mark, barrier)) {
node.setMaskAroundEdge(mark);
++numMarked;
}
}
}
node.setMaskAroundEdge(visit);
}
return numMarked;
}
/**
* Collect edges between faces if the union of the faces is convex.
* Uses a greedy algorithm with no regard to quality of resulting convex faces.
* Best results when input faces are convex.
* @param graph graph to examine
* @param barrier edges with this mask (on either side) will not be collected. Defaults to HalfEdgeMask.BOUNDARY_EDGE.
* @return one HalfEdge per removable edge
*/
public static collectRemovableEdgesToExpandConvexFaces(graph: HalfEdgeGraph, barrier: HalfEdgeMask = HalfEdgeMask.BOUNDARY_EDGE): HalfEdge[] | undefined {
const removable: HalfEdge[] = [];
const mark = graph.grabMask(true);
if (0 < this.markRemovableEdgesToExpandConvexFaces(graph, mark, barrier)) {
const visited = graph.grabMask(true);
for (const node of graph.allHalfEdges) {
if (node.isMaskSet(mark) && !node.isMaskSet(visited)) {
node.setMaskAroundEdge(visited);
removable.push(node);
}
}
graph.dropMask(visited);
}
graph.dropMask(mark);
return removable;
}
/**
* Remove edges between faces if the union of the faces is convex.
* Uses a greedy algorithm with no regard to quality of resulting convex faces.
* Best results when input faces are convex.
* @param graph graph to modify
* @param barrier edges with this mask (on either side) will not be removed. Defaults to HalfEdgeMask.BOUNDARY_EDGE.
* @return number of edges deleted
*/
public static expandConvexFaces(graph: HalfEdgeGraph, barrier: HalfEdgeMask = HalfEdgeMask.BOUNDARY_EDGE): number {
const mark = graph.grabMask(true);
const numRemovedEdges = this.markRemovableEdgesToExpandConvexFaces(graph, mark, barrier);
if (numRemovedEdges > 0)
graph.yankAndDeleteEdges((node: HalfEdge) => node.getMask(mark));
graph.dropMask(mark);
return numRemovedEdges;
}
/**
* Test desired faces for convexity.
* @param graph graph to examine
* @param avoid faces with this mask will not be examined. Defaults to HalfEdgeMask.EXTERIOR.
* @return whether every face in the graph is convex
*/
public static isEveryFaceConvex(graph: HalfEdgeGraph, avoid: HalfEdgeMask = HalfEdgeMask.EXTERIOR): boolean {
const allFaces = graph.collectFaceLoops();
for (const node of allFaces) {
if (node.isMaskedAroundFace(avoid))
continue;
if (!node.isFaceConvex())
return false;
}
return true;
}
}
/**
* @internal
*/
export class HalfEdgeGraphMerge {
// return k2 <= kB such that stored angles (at extra data index 0 !) kA<=k<kC match.
// * Note that the usual case (when angle at k0 is not repeated) is k0+1 === kC
public static getCommonThetaEndIndex(clusters: ClusterableArray, order: Uint32Array, kA: number, kB: number): number{
let kC = kA + 1;
const thetaA = clusters.getExtraData(order[kA], 0);
while (kC < kB) {
const thetaB = clusters.getExtraData(order[kC], 0);
if (!Angle.isAlmostEqualRadiansAllowPeriodShift(thetaA, thetaB)) {
return kC;
}
kC++;
}
return kC;
}
private static _announceVertexNeighborhoodFunction?: AnnounceVertexNeighborhoodSortData;
/**
* public property setter for a function to be called with sorted edge data around a vertex.
*/
public static set announceVertexNeighborhoodFunction(func: AnnounceVertexNeighborhoodSortData | undefined) { this._announceVertexNeighborhoodFunction = func; }
private static doAnnounceVertexNeighborhood(clusters: ClusterableArray, order: Uint32Array, allNodes: HalfEdge[], k0: number, k1: number) {
if (this._announceVertexNeighborhoodFunction) {
const sortData: VertexNeighborhoodSortData[] = [];
// build and share the entire vertex order
for (let k = k0; k < k1; k++){
const index = clusters.getExtraData(order[k], 1);
const theta = clusters.getExtraData(order[k], 0);
const node = allNodes[index];
const signedDistance = this.curvatureSortKey(node);
sortData.push(new VertexNeighborhoodSortData(order[k], signedDistance, node, theta));
}
this._announceVertexNeighborhoodFunction(sortData);
}
}
// assumptions about cluster array:
// * data order is: x,y,theta, nodeIndex
// * theta and nodeIndex are the "extra" data.
// * only want to do anything here when curves are present.
// * k0<=k<k1 are around a vertex
// * These are sorted by theta.
private static secondarySortAroundVertex(clusters: ClusterableArray, order: Uint32Array, allNodes: HalfEdge[], k0: number, k1: number) {
const sortData: VertexNeighborhoodSortData[] = [];
for (let k = k0; k < k1;) {
const kB = this.getCommonThetaEndIndex(clusters, order,k, k1);
if (k + 1 < kB) {
sortData.length = 0;
for (let kA = k; kA < kB; kA++) {
const index = clusters.getExtraData(order[kA], 1);
const node = allNodes[index];
const signedDistance = this.curvatureSortKey(node);
sortData.push(new VertexNeighborhoodSortData(order[kA], signedDistance, node));
}
sortData.sort((a: VertexNeighborhoodSortData, b: VertexNeighborhoodSortData) => (a.radiusOfCurvature - b.radiusOfCurvature));
for (let i = 0; i < sortData.length; i++){
order[k + i] = sortData[i].index;
}
}
k = kB;
}
}
// Return the sort key for sorting by curvature.
// This is the signed distance from the curve to center of curvature.
// This should need to be upgraded to account for higher derivatives in the case of higher-than-tangent match.
private static curvatureSortKey(node: HalfEdge): number {
const cld = node.edgeTag as CurveLocationDetail;
if (cld !== undefined) {
const fraction = cld.fraction;
const curve = cld.curve;
if (curve) {
let radius = curve.fractionToSignedXYRadiusOfCurvature(fraction);
if (node.sortData !== undefined && node.sortData < 0)
radius = -radius;
return radius;
}
}
return 0.0;
}
/** Simplest merge algorithm:
* * collect array of (x,y,theta) at all nodes
* * lexical sort of the array.
* * twist all vertices together.
* * This effectively creates valid face loops for a planar subdivision if there are no edge crossings.
* * If there are edge crossings, the graph can be a (highly complicated) Klein bottle topology.
* * Mask.NULL_FACE is cleared throughout and applied within null faces.
*/
public static clusterAndMergeXYTheta(graph: HalfEdgeGraph, outboundRadiansFunction?: (he: HalfEdge) => number) {
const allNodes = graph.allHalfEdges;
const numNodes = allNodes.length;
graph.clearMask(HalfEdgeMask.NULL_FACE);
const clusters = new ClusterableArray(2, 2, numNodes); // data order: x,y,theta, nodeIndex. But theta is not set in first round.
for (let i = 0; i < numNodes; i++) {
const nodeA = allNodes[i];
const xA = nodeA.x;
const yA = nodeA.y;
HalfEdge.pinch(nodeA, nodeA.vertexSuccessor); // pull it out of its current vertex loop.
clusters.addDirect(xA, yA, 0.0, i);
}
const order = clusters.clusterIndicesLexical();
let k0 = 0;
const numK = order.length;
for (let k1 = 0; k1 < numK; k1++) {
if (order[k1] === ClusterableArray.clusterTerminator) {
// nodes identified in order[k0]..order[k1] are properly sorted around a vertex.
if (k1 > k0) {
const iA = clusters.getExtraData(order[k0], 1);
const nodeA0 = allNodes[iA];
for (let k = k0 + 1; k < k1; k++) {
const iB = clusters.getExtraData(order[k], 1);
const nodeB = allNodes[iB];
nodeB.x = nodeA0.x;
nodeB.y = nodeA0.y;
}
}
k0 = k1 + 1;
}
}
// NOW
// 1) There are identical coordinates at all nodes around each vertex loop.
// 2) Hence ready do sort (at each vertex) by theta.
// insert theta as extra data in the sort table . . .
for (const clusterTableIndex of order) {
if (clusterTableIndex !== ClusterableArray.clusterTerminator) {
const nodeA = allNodes[clusterTableIndex];
const nodeB = nodeA.faceSuccessor;
let radians = outboundRadiansFunction ? outboundRadiansFunction(nodeA) : Math.atan2(nodeB.y - nodeA.y, nodeB.x - nodeA.x);
if (Angle.isAlmostEqualRadiansAllowPeriodShift(radians, -Math.PI))
radians = Math.PI;
clusters.setExtraData(clusterTableIndex, 0, radians);
}
}
clusters.sortSubsetsBySingleKey(order, 2);
const unmatchedNullFaceNodes: HalfEdge[] = [];
k0 = 0;
let thetaA, thetaB;
// eslint-disable-next-line no-console
// console.log("START VERTEX LINKS");
// now pinch each neighboring pair together
for (let k1 = 0; k1 < numK; k1++) {
if (order[k1] === ClusterableArray.clusterTerminator) {
// nodes identified in order[k0]..order[k1] are properly sorted around a vertex.
if (k1 > k0) {
// const xy = clusters.getPoint2d(order[k0]);
// eslint-disable-next-line no-console
// console.log({ k0, k1, x: xy.x, y: xy.y });
if (k1 > k0 + 1)
this.secondarySortAroundVertex(clusters, order, allNodes, k0, k1);
this.doAnnounceVertexNeighborhood(clusters, order, allNodes, k0, k1);
const iA = clusters.getExtraData(order[k0], 1);
thetaA = clusters.getExtraData(order[k0], 0);
const nodeA0 = allNodes[iA];
let nodeA = nodeA0;
for (let k = k0 + 1; k < k1; k++) {
const iB = clusters.getExtraData(order[k], 1);
thetaB = clusters.getExtraData(order[k], 0);
const nodeB = allNodes[iB];
if (nodeA.isMaskSet(HalfEdgeMask.NULL_FACE)) {
// nope, this edge was flagged and pinched from the other end.
const j = unmatchedNullFaceNodes.findIndex((node: HalfEdge) => nodeA === node);
if (j >= 0) {
unmatchedNullFaceNodes[j] = unmatchedNullFaceNodes[unmatchedNullFaceNodes.length - 1];
unmatchedNullFaceNodes.pop();
}
nodeA = nodeB;
thetaA = thetaB;
} else if (nodeB.isMaskSet(HalfEdgeMask.NULL_FACE)) {
const j = unmatchedNullFaceNodes.findIndex((node: HalfEdge) => nodeA === node);
if (j >= 0) {
unmatchedNullFaceNodes[j] = unmatchedNullFaceNodes[unmatchedNullFaceNodes.length - 1];
unmatchedNullFaceNodes.pop();
}
// NO leave nodeA and thetaA ignore nodeB -- later step will get the outside of its banana.
} else {
HalfEdge.pinch(nodeA, nodeB);
if (Angle.isAlmostEqualRadiansAllowPeriodShift(thetaA, thetaB)) {
const nodeA1 = nodeA.faceSuccessor;
const nodeB1 = nodeB.edgeMate;
// WE TRUST -- nodeA1 and node B1 must have identical xy.
// pinch them together and mark the face loop as null ..
HalfEdge.pinch(nodeA1, nodeB1);
nodeA.setMask(HalfEdgeMask.NULL_FACE);
nodeB1.setMask(HalfEdgeMask.NULL_FACE);
unmatchedNullFaceNodes.push(nodeB1);
}
nodeA = nodeB;
thetaA = thetaB;
}
}
}
k0 = k1 + 1;
}
}
}
private static buildVerticalSweepPriorityQueue(graph: HalfEdgeGraph): HalfEdgePriorityQueueWithPartnerArray {
const sweepHeap = new HalfEdgePriorityQueueWithPartnerArray();
for (const p of graph.allHalfEdges) {
if (HalfEdgeGraphOps.compareNodesYXUp(p, p.faceSuccessor) < 0) {
sweepHeap.priorityQueue.push(p);
}
}
return sweepHeap;
}
private static snapFractionToNode(xy: Point2d, fraction: number, node: HalfEdge, nodeFraction: number): number{
if (Geometry.isSameCoordinate(xy.x, node.x) && Geometry.isSameCoordinate(xy.y, node.y))
return nodeFraction;
return fraction;
}
private static computeIntersectionFractionsOnEdges(nodeA0: HalfEdge, nodeB0: HalfEdge, fractions: Vector2d, pointA: Point2d, pointB: Point2d): boolean {
const nodeA1 = nodeA0.faceSuccessor;
const ax0 = nodeA0.x;
const ay0 = nodeA0.y;
const ux = nodeA1.x - ax0;
const uy = nodeA1.y - ay0;
const nodeB1 = nodeB0.faceSuccessor;
const bx0 = nodeB0.x;
const by0 = nodeB0.y;
const vx = nodeB1.x - bx0;
const vy = nodeB1.y - by0;
// cspell:word lineSegmentXYUVTransverseIntersectionUnbounded
if (SmallSystem.lineSegmentXYUVTransverseIntersectionUnbounded(ax0, ay0, ux, uy,
bx0, by0, vx, vy, fractions)) {
pointA.x = ax0 + fractions.x * ux;
pointA.y = ay0 + fractions.x * uy;
pointB.x = bx0 + fractions.y * vx;
pointB.y = by0 + fractions.y * vy;
fractions.x = this.snapFractionToNode(pointA, fractions.x, nodeA0, 0.0);
fractions.x = this.snapFractionToNode(pointA, fractions.x, nodeA1, 1.0);
fractions.y = this.snapFractionToNode(pointB, fractions.y, nodeB0, 0.0);
fractions.y = this.snapFractionToNode(pointB, fractions.y, nodeB1, 1.0);
return Geometry.isIn01(fractions.x) && Geometry.isIn01(fractions.y);
}
return false;
}
/**
* Split edges at intersections.
* * This is a large operation.
* @param graph
*/
public static splitIntersectingEdges(graph: HalfEdgeGraph): GraphSplitData {
const data = new GraphSplitData();
const sweepHeap = this.buildVerticalSweepPriorityQueue(graph);
let nodeA0, nodeB1;
const smallFraction = 1.0e-8;
const largeFraction = 1.0 - smallFraction;
let i;
const fractions = Vector2d.create();
const pointA = Point2d.create();
const pointB = Point2d.create();
let nodeB0;
const popTolerance = Geometry.smallMetricDistance;
while (undefined !== (nodeA0 = sweepHeap.priorityQueue.pop())) {
data.numUpEdge++;
const n0 = sweepHeap.activeEdges.length;
sweepHeap.removeArrayMembersWithY1Below(nodeA0.y - popTolerance);
data.numPopOut += n0 - sweepHeap.activeEdges.length;
for (i = 0; i < sweepHeap.activeEdges.length; i++) {
nodeB0 = sweepHeap.activeEdges[i];
nodeB1 = nodeB0.faceSuccessor;
// const nodeB1 = nodeB0.faceSuccessor;
if (Geometry.isSameCoordinateXY(nodeA0.x, nodeA0.y, nodeB0.x, nodeB0.y)) {
data.numA0B0++;
} else if (Geometry.isSameCoordinateXY(nodeB1.x, nodeB1.y, nodeA0.x, nodeA0.y)) {
data.numA0B1++;
} else {
data.numIntersectionTest++;
if (this.computeIntersectionFractionsOnEdges(nodeA0, nodeB0, fractions, pointA, pointB)) {
if (fractions.x > smallFraction && fractions.x < largeFraction) {
const nodeC0 = graph.splitEdgeAtFraction(nodeA0, fractions.x);
sweepHeap.priorityQueue.push(nodeC0); // The upper portion will be reviewed as a nodeA0 later !!!
data.numSplit++;
}
if (fractions.y > smallFraction && fractions.y < largeFraction) {
const nodeD0 = graph.splitEdgeAtFraction(nodeB0, fractions.y);
sweepHeap.priorityQueue.push(nodeD0); // The upper portion will be reviewed as a nodeA0 later !!!
data.numSplit++;
}
// existing nodeA0 and its shortened edge remain for further intersections
}
}
}
sweepHeap.activeEdges.push(nodeA0);
}
return data;
}
/**
* Returns a graph structure formed from the given LineSegment array
*
* * Find all intersections among segments, and split them if necessary
* * Record endpoints of every segment in the form X, Y, Theta; This information is stored as a new node and sorted to match up
* vertices.
* * For vertices that match up, pinch the nodes to create vertex loops, which in closed objects, will also eventually form face
* loops
*/
public static formGraphFromSegments(lineSegments: LineSegment3d[]): HalfEdgeGraph {
// Structure of an index of the array: { xyTheta: Point3d, node: Node }
const graph = new HalfEdgeGraph();
HalfEdgeGraphOps.segmentArrayToGraphEdges(lineSegments, graph, HalfEdgeMask.BOUNDARY_EDGE);
this.splitIntersectingEdges(graph);
this.clusterAndMergeXYTheta(graph);
return graph;
}
/**
* * Input is random linestrings, not necessarily loops
* * Graph gets full splitEdges, regularize, and triangulate.
* @returns triangulated graph, or undefined if bad data.
*/
public static formGraphFromChains(chains: MultiLineStringDataVariant, regularize: boolean = true, mask: HalfEdgeMask = HalfEdgeMask.PRIMARY_EDGE): HalfEdgeGraph | undefined {
if (chains.length < 1)
return undefined;
const graph = new HalfEdgeGraph();
const chainSeeds = Triangulator.directCreateChainsFromCoordinates(graph, chains);
for (const seed of chainSeeds)
seed.setMaskAroundFace(mask);
this.splitIntersectingEdges(graph);
this.clusterAndMergeXYTheta(graph);
if (regularize) {
const context = new RegularizationContext(graph);
context.regularizeGraph(true, true);
}
return graph;
}
} | the_stack |
import { CSSInJSRule } from "./css";
export interface ErsatzElement {
element: HTMLElement;
}
export declare function isErsatzElement(obj: any): obj is ErsatzElement;
export interface ErsatzElements {
elements: HTMLElement[];
}
export declare function isErsatzElements(obj: any): obj is ErsatzElements;
export declare type Elements = HTMLElement | ErsatzElement;
export interface IElementAppliable {
applyToElement(x: Elements): void;
}
export declare function isIElementAppliable(obj: any): obj is IElementAppliable;
export declare type ElementChild = Node | Elements | ErsatzElements | IElementAppliable | string | number | boolean | Date;
export declare function isElementChild(obj: any): obj is ElementChild;
export interface IFocusable {
focus(): void;
}
export declare function isFocusable(elem: any): elem is IFocusable;
export declare function elementSetDisplay(elem: Elements, visible: boolean, visibleDisplayType?: string): void;
export declare function elementIsDisplayed(elem: Elements): boolean;
export declare function elementToggleDisplay(elem: Elements, visibleDisplayType?: string): void;
export declare function elementApply(elem: Elements, ...children: ElementChild[]): void;
export declare function getElement<T extends HTMLElement>(selector: string): T;
export declare function getButton(selector: string): HTMLButtonElement;
export declare function getInput(selector: string): HTMLInputElement;
export declare function getSelect(selector: string): HTMLSelectElement;
export declare function getCanvas(selector: string): HTMLCanvasElement;
/**
* Creates an HTML element for a given tag name.
*
* Boolean attributes that you want to default to true can be passed
* as just the attribute creating function,
* e.g. `Audio(autoPlay)` vs `Audio(autoPlay(true))`
* @param name - the name of the tag
* @param rest - optional attributes, child elements, and text
* @returns
*/
export declare function tag<T extends HTMLElement>(name: string, ...rest: ElementChild[]): T;
export interface IDisableable {
disabled: boolean;
}
export declare function isDisableable(obj: any): obj is IDisableable;
/**
* Empty an element of all children. This is faster than setting `innerHTML = ""`.
*/
export declare function elementClearChildren(elem: Elements): void;
export declare function elementSetText(elem: Elements, text: string): void;
export declare type HTMLAudioElementWithSinkID = HTMLAudioElement & {
sinkId: string;
setSinkId(id: string): Promise<void>;
};
export declare function A(...rest: ElementChild[]): HTMLAnchorElement;
export declare function Abbr(...rest: ElementChild[]): HTMLElement;
export declare function Address(...rest: ElementChild[]): HTMLElement;
export declare function Area(...rest: ElementChild[]): HTMLAreaElement;
export declare function Article(...rest: ElementChild[]): HTMLElement;
export declare function Aside(...rest: ElementChild[]): HTMLElement;
export declare function Audio(...rest: ElementChild[]): HTMLAudioElementWithSinkID;
export declare function B(...rest: ElementChild[]): HTMLElement;
export declare function Base(...rest: ElementChild[]): HTMLBaseElement;
export declare function BDI(...rest: ElementChild[]): HTMLElement;
export declare function BDO(...rest: ElementChild[]): HTMLElement;
export declare function BlockQuote(...rest: ElementChild[]): HTMLQuoteElement;
export declare function Body(...rest: ElementChild[]): HTMLBodyElement;
export declare function BR(): HTMLBRElement;
export declare function ButtonRaw(...rest: ElementChild[]): HTMLButtonElement;
export declare function Button(...rest: ElementChild[]): HTMLButtonElement;
export declare function ButtonSubmit(...rest: ElementChild[]): HTMLButtonElement;
export declare function ButtonReset(...rest: ElementChild[]): HTMLButtonElement;
export declare function Canvas(...rest: ElementChild[]): HTMLCanvasElement;
export declare function Caption(...rest: ElementChild[]): HTMLTableCaptionElement;
export declare function Cite(...rest: ElementChild[]): HTMLElement;
export declare function Code(...rest: ElementChild[]): HTMLElement;
export declare function Col(...rest: ElementChild[]): HTMLTableColElement;
export declare function ColGroup(...rest: ElementChild[]): HTMLTableColElement;
export declare function Data(...rest: ElementChild[]): HTMLDataElement;
export declare function DataList(...rest: ElementChild[]): HTMLDataListElement;
export declare function DD(...rest: ElementChild[]): HTMLElement;
export declare function Del(...rest: ElementChild[]): HTMLModElement;
export declare function Details(...rest: ElementChild[]): HTMLDetailsElement;
export declare function DFN(...rest: ElementChild[]): HTMLElement;
export declare function Dialog(...rest: ElementChild[]): HTMLDialogElement;
export declare function Dir(...rest: ElementChild[]): HTMLDirectoryElement;
export declare function Div(...rest: ElementChild[]): HTMLDivElement;
export declare function DL(...rest: ElementChild[]): HTMLDListElement;
export declare function DT(...rest: ElementChild[]): HTMLElement;
export declare function Em(...rest: ElementChild[]): HTMLElement;
export declare function Embed(...rest: ElementChild[]): HTMLEmbedElement;
export declare function FieldSet(...rest: ElementChild[]): HTMLFieldSetElement;
export declare function FigCaption(...rest: ElementChild[]): HTMLElement;
export declare function Figure(...rest: ElementChild[]): HTMLElement;
export declare function Footer(...rest: ElementChild[]): HTMLElement;
export declare function Form(...rest: ElementChild[]): HTMLFormElement;
export declare function H1(...rest: ElementChild[]): HTMLHeadingElement;
export declare function H2(...rest: ElementChild[]): HTMLHeadingElement;
export declare function H3(...rest: ElementChild[]): HTMLHeadingElement;
export declare function H4(...rest: ElementChild[]): HTMLHeadingElement;
export declare function H5(...rest: ElementChild[]): HTMLHeadingElement;
export declare function H6(...rest: ElementChild[]): HTMLHeadingElement;
export declare function HR(...rest: ElementChild[]): HTMLHRElement;
export declare function Head(...rest: ElementChild[]): HTMLHeadElement;
export declare function Header(...rest: ElementChild[]): HTMLElement;
export declare function HGroup(...rest: ElementChild[]): HTMLElement;
export declare function HTML(...rest: ElementChild[]): HTMLHtmlElement;
export declare function I(...rest: ElementChild[]): HTMLElement;
export declare function IFrame(...rest: ElementChild[]): HTMLIFrameElement;
export declare function Img(...rest: ElementChild[]): HTMLImageElement;
export declare function Input(...rest: ElementChild[]): HTMLInputElement;
export declare function Ins(...rest: ElementChild[]): HTMLModElement;
export declare function KBD(...rest: ElementChild[]): HTMLElement;
export declare function Label(...rest: ElementChild[]): HTMLLabelElement;
export declare function Legend(...rest: ElementChild[]): HTMLLegendElement;
export declare function LI(...rest: ElementChild[]): HTMLLIElement;
export declare function Link(...rest: ElementChild[]): HTMLLinkElement;
export declare function Main(...rest: ElementChild[]): HTMLElement;
export declare function HtmlMap(...rest: ElementChild[]): HTMLMapElement;
export declare function Mark(...rest: ElementChild[]): HTMLElement;
export declare function Marquee(...rest: ElementChild[]): HTMLMarqueeElement;
export declare function Menu(...rest: ElementChild[]): HTMLMenuElement;
export declare function Meta(...rest: ElementChild[]): HTMLMetaElement;
export declare function Meter(...rest: ElementChild[]): HTMLMeterElement;
export declare function Nav(...rest: ElementChild[]): HTMLElement;
export declare function NoScript(...rest: ElementChild[]): HTMLElement;
export declare function HtmlObject(...rest: ElementChild[]): HTMLObjectElement;
export declare function OL(...rest: ElementChild[]): HTMLOListElement;
export declare function OptGroup(...rest: ElementChild[]): HTMLOptGroupElement;
export declare function Option(...rest: ElementChild[]): HTMLOptionElement;
export declare function Output(...rest: ElementChild[]): HTMLOutputElement;
export declare function P(...rest: ElementChild[]): HTMLParagraphElement;
export declare function Param(...rest: ElementChild[]): HTMLParamElement;
export declare function Picture(...rest: ElementChild[]): HTMLPictureElement;
export declare function Pre(...rest: ElementChild[]): HTMLPreElement;
export declare function Progress(...rest: ElementChild[]): HTMLProgressElement;
export declare function Q(...rest: ElementChild[]): HTMLQuoteElement;
export declare function RB(...rest: ElementChild[]): HTMLElement;
export declare function RP(...rest: ElementChild[]): HTMLElement;
export declare function RT(...rest: ElementChild[]): HTMLElement;
export declare function RTC(...rest: ElementChild[]): HTMLElement;
export declare function Ruby(...rest: ElementChild[]): HTMLElement;
export declare function S(...rest: ElementChild[]): HTMLElement;
export declare function Samp(...rest: ElementChild[]): HTMLElement;
export declare function Script(...rest: ElementChild[]): HTMLScriptElement;
export declare function Section(...rest: ElementChild[]): HTMLElement;
export declare function Select(...rest: ElementChild[]): HTMLSelectElement;
export declare function Slot(...rest: ElementChild[]): HTMLSlotElement;
export declare function Small(...rest: ElementChild[]): HTMLElement;
export declare function Source(...rest: ElementChild[]): HTMLSourceElement;
export declare function Span(...rest: ElementChild[]): HTMLSpanElement;
export declare function Strong(...rest: ElementChild[]): HTMLElement;
export declare function Sub(...rest: ElementChild[]): HTMLElement;
export declare function Summary(...rest: ElementChild[]): HTMLElement;
export declare function Sup(...rest: ElementChild[]): HTMLElement;
export declare function Table(...rest: ElementChild[]): HTMLTableElement;
export declare function TBody(...rest: ElementChild[]): HTMLTableSectionElement;
export declare function TD(...rest: ElementChild[]): HTMLTableDataCellElement;
export declare function Template(...rest: ElementChild[]): HTMLTemplateElement;
export declare function TextArea(...rest: ElementChild[]): HTMLTextAreaElement;
export declare function TFoot(...rest: ElementChild[]): HTMLTableSectionElement;
export declare function TH(...rest: ElementChild[]): HTMLTableHeaderCellElement;
export declare function THead(...rest: ElementChild[]): HTMLTableSectionElement;
export declare function Time(...rest: ElementChild[]): HTMLTimeElement;
export declare function Title(...rest: ElementChild[]): HTMLTitleElement;
export declare function TR(...rest: ElementChild[]): HTMLTableRowElement;
export declare function Track(...rest: ElementChild[]): HTMLTrackElement;
export declare function U(...rest: ElementChild[]): HTMLElement;
export declare function UL(...rest: ElementChild[]): HTMLUListElement;
export declare function Var(...rest: ElementChild[]): HTMLElement;
export declare function Video(...rest: ElementChild[]): HTMLVideoElement;
export declare function WBR(): HTMLElement;
/**
* creates an HTML Input tag that is a button.
*/
export declare function InputButton(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a checkbox.
*/
export declare function InputCheckbox(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a color picker.
*/
export declare function InputColor(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a date picker.
*/
export declare function InputDate(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a local date-time picker.
*/
export declare function InputDateTime(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is an email entry field.
*/
export declare function InputEmail(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a file picker.
*/
export declare function InputFile(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a hidden field.
*/
export declare function InputHidden(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a graphical submit button.
*/
export declare function InputImage(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a month picker.
*/
export declare function InputMonth(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a month picker.
*/
export declare function InputNumber(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a password entry field.
*/
export declare function InputPassword(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a radio button.
*/
export declare function InputRadio(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a range selector.
*/
export declare function InputRange(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a form reset button.
*/
export declare function InputReset(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a search entry field.
*/
export declare function InputSearch(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a submit button.
*/
export declare function InputSubmit(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a telephone number entry field.
*/
export declare function InputTelephone(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a text entry field.
*/
export declare function InputText(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a time picker.
*/
export declare function InputTime(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a URL entry field.
*/
export declare function InputURL(...rest: ElementChild[]): HTMLInputElement;
/**
* creates an HTML Input tag that is a week picker.
*/
export declare function InputWeek(...rest: ElementChild[]): HTMLInputElement;
/**
* Creates a text node out of the give input.
*/
export declare function TextNode(txt: any): Text;
/**
* Creates a Div element with margin: auto.
*/
export declare function Run(...rest: ElementChild[]): HTMLDivElement;
export declare function Style(...rest: CSSInJSRule[]): HTMLStyleElement; | the_stack |
import {
AccountSASPermissions,
AccountSASResourceTypes,
AccountSASServices,
AnonymousCredential,
BlobSASPermissions,
ContainerSASPermissions,
generateAccountSASQueryParameters,
generateBlobSASQueryParameters,
SASProtocol,
BlobServiceClient,
newPipeline,
StorageSharedKeyCredential,
ContainerClient,
PageBlobClient,
AppendBlobClient
} from "@azure/storage-blob";
import * as assert from "assert";
import { configLogger } from "../../src/common/Logger";
import BlobTestServerFactory from "../BlobTestServerFactory";
import { getUniqueName } from "../testutils";
import {
EMULATOR_ACCOUNT_KEY_STR,
EMULATOR_ACCOUNT_NAME
} from "../../src/blob/utils/constants";
import { URLBuilder } from "@azure/ms-rest-js";
const EMULATOR_ACCOUNT2_NAME = "devstoreaccount2";
const EMULATOR_ACCOUNT2_KEY_STR =
"MTAwCjE2NQoyMjUKMTAzCjIxOAoyNDEKNDAKNzgKMTkxCjE3OAoyMTQKMTY5CjIxMwo2MQoyNTIKMTQxCg==";
// Set true to enable debug log
configLogger(false);
describe("Shared Access Signature (SAS) authentication", () => {
// Setup two accounts for validating cross-account copy operations
process.env[
"AZURITE_ACCOUNTS"
] = `${EMULATOR_ACCOUNT_NAME}:${EMULATOR_ACCOUNT_KEY_STR};${EMULATOR_ACCOUNT2_NAME}:${EMULATOR_ACCOUNT2_KEY_STR}`;
const factory = new BlobTestServerFactory();
const server = factory.createServer();
const baseURL = `http://${server.config.host}:${server.config.port}/devstoreaccount1`;
const serviceClient = new BlobServiceClient(
baseURL,
newPipeline(
new StorageSharedKeyCredential(
EMULATOR_ACCOUNT_NAME,
EMULATOR_ACCOUNT_KEY_STR
),
{
retryOptions: { maxTries: 1 },
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
}
)
);
const baseURL2 = `http://${server.config.host}:${server.config.port}/devstoreaccount2`;
const serviceClient2 = new BlobServiceClient(
baseURL2,
newPipeline(
new StorageSharedKeyCredential(
EMULATOR_ACCOUNT2_NAME,
EMULATOR_ACCOUNT2_KEY_STR
),
{
retryOptions: { maxTries: 1 },
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
}
)
);
before(async () => {
await server.start();
});
after(async () => {
await server.close();
await server.clean();
});
it("generateAccountSASQueryParameters should work @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rwdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("btqf").toString(),
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
await serviceClientWithSAS.getAccountInfo();
});
it("generateAccountSASQueryParameters should work for set blob tier @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("w"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("btqf").toString(),
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerClientWithSAS = serviceClientWithSAS.getContainerClient(
getUniqueName("con")
);
await containerClientWithSAS.create();
const blockBlobClientWithSAS = containerClientWithSAS.getBlockBlobClient(
getUniqueName("blob")
);
await blockBlobClientWithSAS.upload("abc", 3);
await blockBlobClientWithSAS.setAccessTier("Hot");
});
it("generateAccountSASQueryParameters should not work with invalid permission @loki @sql", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
permissions: AccountSASPermissions.parse("wdlcup"),
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("btqf").toString()
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
let error;
try {
await serviceClientWithSAS.getProperties();
} catch (err) {
error = err;
}
assert.ok(error);
});
it("generateAccountSASQueryParameters should not work with invalid service @loki @sql", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
permissions: AccountSASPermissions.parse("rwdlacup"),
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("tqf").toString()
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
let error;
try {
await serviceClientWithSAS.getProperties();
} catch (err) {
error = err;
}
assert.ok(error);
});
it("generateAccountSASQueryParameters should not work with invalid resource type @loki @sql", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rwdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
let error;
try {
await serviceClientWithSAS.getProperties();
} catch (err) {
error = err;
}
assert.ok(error);
});
it("Synchronized copy blob should work with write permission in account SAS to override an existing blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rwdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.syncCopyFromURL(blob1.url);
// this copy should not throw any errors
await blob2.syncCopyFromURL(blob1.url);
});
it("Synchronized copy blob shouldn't work without write permission in account SAS to override an existing blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.syncCopyFromURL(blob1.url);
// this copy should throw 403 error
let error;
try {
await blob2.syncCopyFromURL(blob1.url);
} catch (err) {
error = err;
}
assert.deepEqual(error.statusCode, 403);
assert.ok(error !== undefined);
});
it("Synchronized copy blob should work without write permission in account SAS to an nonexisting blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
// this copy should work
await blob2.syncCopyFromURL(blob1.url);
});
it("Copy blob should work with write permission in account SAS to override an existing blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rwdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.beginCopyFromURL(blob1.url);
// this copy should not throw any errors
await blob2.beginCopyFromURL(blob1.url);
});
it("Copy blob shouldn't work without write permission in account SAS to override an existing blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("rdlacup"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.beginCopyFromURL(blob1.url);
// this copy should throw 403 error
let error;
try {
await blob2.beginCopyFromURL(blob1.url);
} catch (err) {
error = err;
}
assert.deepEqual(error.statusCode, 403);
assert.ok(error !== undefined);
});
it("Copy blob should work without write permission in account SAS to an nonexisting blob @loki", async () => {
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const sas = generateAccountSASQueryParameters(
{
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: AccountSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
resourceTypes: AccountSASResourceTypes.parse("co").toString(),
services: AccountSASServices.parse("btqf").toString(),
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sasURL = `${serviceClient.url}?${sas}`;
const serviceClientWithSAS = new BlobServiceClient(
sasURL,
newPipeline(new AnonymousCredential(), {
// Make sure socket is closed once the operation is done.
keepAliveOptions: { enable: false }
})
);
const containerName = getUniqueName("con");
const containerClient = serviceClientWithSAS.getContainerClient(
containerName
);
await containerClient.create();
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
// this copy should work
await blob2.beginCopyFromURL(blob1.url);
});
it("generateBlobSASQueryParameters should work for container @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("racwdl"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await await containerClientWithSAS.listBlobsFlat().byPage();
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for page blob with original headers @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024, {
blobHTTPHeaders: {
blobCacheControl: "cache-control-original",
blobContentType: "content-type-original",
blobContentDisposition: "content-disposition-original",
blobContentEncoding: "content-encoding-original",
blobContentLanguage: "content-language-original"
}
});
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-original");
assert.equal(properties.contentDisposition, "content-disposition-original");
assert.equal(properties.contentEncoding, "content-encoding-original");
assert.equal(properties.contentLanguage, "content-language-original");
assert.equal(properties.contentType, "content-type-original");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-original");
assert.equal(downloadResponse.contentDisposition, "content-disposition-original");
assert.equal(downloadResponse.contentEncoding, "content-encoding-original");
assert.equal(downloadResponse.contentLanguage, "content-language-original");
assert.equal(downloadResponse.contentType, "content-type-original");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for page blob and rscd arguments for filenames with spaces and special characters @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = "this is a test file Ж 大 仮.jpg"; //filename contains spaces and special characters
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024, {
blobHTTPHeaders: {
blobCacheControl: "cache-control-original",
blobContentType: "content-type-original",
blobContentDisposition: "content-type-disposition",
blobContentEncoding: "content-encoding-original",
blobContentLanguage: "content-language-original"
}
});
const escapedblobName = encodeURIComponent(blobName);
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
//https://tools.ietf.org/html/rfc5987
contentDisposition: `attachment; filename=\"${escapedblobName}\"; filename*=UTF-8''${escapedblobName}`,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-original");
assert.equal(properties.contentDisposition, `attachment; filename=\"${escapedblobName}\"; filename*=UTF-8''${escapedblobName}`);
assert.equal(properties.contentEncoding, "content-encoding-original");
assert.equal(properties.contentLanguage, "content-language-original");
assert.equal(properties.contentType, "content-type-original");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-original");
assert.equal(downloadResponse.contentDisposition, `attachment; filename=\"${escapedblobName}\"; filename*=UTF-8''${escapedblobName}`);
assert.equal(downloadResponse.contentEncoding, "content-encoding-original");
assert.equal(downloadResponse.contentLanguage, "content-language-original");
assert.equal(downloadResponse.contentType, "content-type-original");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for page blob and override headers @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024, {
blobHTTPHeaders: {
blobContentType: "content-type-original"
}
});
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
cacheControl: "cache-control-override",
containerName,
contentDisposition: "content-disposition-override",
contentEncoding: "content-encoding-override",
contentLanguage: "content-language-override",
contentType: "content-type-override",
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-override");
assert.equal(properties.contentDisposition, "content-disposition-override");
assert.equal(properties.contentEncoding, "content-encoding-override");
assert.equal(properties.contentLanguage, "content-language-override");
assert.equal(properties.contentType, "content-type-override");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-override");
assert.equal(downloadResponse.contentDisposition, "content-disposition-override");
assert.equal(downloadResponse.contentEncoding, "content-encoding-override");
assert.equal(downloadResponse.contentLanguage, "content-language-override");
assert.equal(downloadResponse.contentType, "content-type-override");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for append blob with original headers @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getAppendBlobClient(blobName);
await blobClient.create({
blobHTTPHeaders: {
blobCacheControl: "cache-control-original",
blobContentType: "content-type-original",
blobContentDisposition: "content-disposition-original",
blobContentEncoding: "content-encoding-original",
blobContentLanguage: "content-language-original"
}
});
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new AppendBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-original");
assert.equal(properties.contentDisposition, "content-disposition-original");
assert.equal(properties.contentEncoding, "content-encoding-original");
assert.equal(properties.contentLanguage, "content-language-original");
assert.equal(properties.contentType, "content-type-original");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-original");
assert.equal(downloadResponse.contentDisposition, "content-disposition-original");
assert.equal(downloadResponse.contentEncoding, "content-encoding-original");
assert.equal(downloadResponse.contentLanguage, "content-language-original");
assert.equal(downloadResponse.contentType, "content-type-original");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for append blob and override headers @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getAppendBlobClient(blobName);
await blobClient.create({
blobHTTPHeaders: {
blobContentType: "content-type-original"
}
});
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
cacheControl: "cache-control-override",
containerName,
contentDisposition: "content-disposition-override",
contentEncoding: "content-encoding-override",
contentLanguage: "content-language-override",
contentType: "content-type-override",
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new AppendBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-override");
assert.equal(properties.contentDisposition, "content-disposition-override");
assert.equal(properties.contentEncoding, "content-encoding-override");
assert.equal(properties.contentLanguage, "content-language-override");
assert.equal(properties.contentType, "content-type-override");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-override");
assert.equal(downloadResponse.contentDisposition, "content-disposition-override");
assert.equal(downloadResponse.contentEncoding, "content-encoding-override");
assert.equal(downloadResponse.contentLanguage, "content-language-override");
assert.equal(downloadResponse.contentType, "content-type-override");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for blob with special naming @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container-with-dash");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName(
// tslint:disable-next-line:max-line-length
"////Upper/blob/empty /another 汉字 ру́сский язы́к ру́сский язы́к عربي/عربى にっぽんご/にほんご . special ~!@#$%^&*()_+`1234567890-={}|[]\\:\";'<>?,/'"
);
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024, {
blobHTTPHeaders: {
blobContentType: "content-type-original"
}
});
const blobSAS = generateBlobSASQueryParameters(
{
// NOTICE: Azure Storage Server will replace "\" with "/" in the blob names
blobName: blobName.replace(/\\/g, "/"),
cacheControl: "cache-control-override",
containerName,
contentDisposition: "content-disposition-override",
contentEncoding: "content-encoding-override",
contentLanguage: "content-language-override",
contentType: "content-type-override",
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
const properties = await blobClientWithSAS.getProperties();
assert.equal(properties.cacheControl, "cache-control-override");
assert.equal(properties.contentDisposition, "content-disposition-override");
assert.equal(properties.contentEncoding, "content-encoding-override");
assert.equal(properties.contentLanguage, "content-language-override");
assert.equal(properties.contentType, "content-type-override");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-override");
assert.equal(downloadResponse.contentDisposition, "content-disposition-override");
assert.equal(downloadResponse.contentEncoding, "content-encoding-override");
assert.equal(downloadResponse.contentLanguage, "content-language-override");
assert.equal(downloadResponse.contentType, "content-type-override");
await containerClient.delete();
});
it("generateBlobSASQueryParameters should work for blob with access policy @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024);
const id = "unique-id";
const result = await containerClient.setAccessPolicy(undefined, [
{
accessPolicy: {
expiresOn: tmr,
permissions: ContainerSASPermissions.parse("racwdl").toString(),
startsOn: now
},
id
}
]);
assert.equal(
result._response.request.headers.get("x-ms-client-request-id"),
result.clientRequestId
);
const blobSAS = generateBlobSASQueryParameters(
{
containerName,
identifier: id
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${blobClient.url}?${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
await blobClientWithSAS.getProperties();
await containerClient.delete();
});
it("Synchronized copy blob should work with write permission in blob SAS to override an existing blob @loki", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("w"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.upload("world", 5);
// this copy should not throw any errors
await blob2SAS.syncCopyFromURL(blob1.url);
});
it("Synchronized copy blob shouldn't work without write permission in blob SAS to override an existing blob @loki", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.upload("world", 5);
// this copy should throw 403 error
let error;
try {
await blob2SAS.syncCopyFromURL(blob1.url);
} catch (err) {
error = err;
}
assert.deepEqual(error.statusCode, 403);
assert.ok(error !== undefined);
});
it("Synchronized copy blob should work without write permission in account SAS to an nonexisting blob @loki", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
// this copy should work
await blob2SAS.syncCopyFromURL(blob1.url);
});
it("Copy blob should work with write permission in blob SAS to override an existing blob @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("w"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.upload("world", 5);
// this copy should not throw any errors
await blob2SAS.beginCopyFromURL(blob1.url);
});
it("Copy blob shouldn't work without write permission in blob SAS to override an existing blob @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2 = containerClient.getBlockBlobClient(blobName2);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
await blob2.upload("world", 5);
// this copy should throw 403 error
let error;
try {
await blob2SAS.beginCopyFromURL(blob1.url);
} catch (err) {
error = err;
}
assert.deepEqual(error.statusCode, 403);
assert.ok(error !== undefined);
});
it("Copy blob should work without write permission in account SAS to an nonexisting blob @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const containerSAS = generateBlobSASQueryParameters(
{
containerName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: ContainerSASPermissions.parse("c"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${containerClient.url}?${containerSAS}`;
const containerClientWithSAS = new ContainerClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const blobName1 = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const blob1 = containerClient.getBlockBlobClient(blobName1);
const blob2SAS = containerClientWithSAS.getBlockBlobClient(blobName2);
await blob1.upload("hello", 5);
// this copy should work
await blob2SAS.beginCopyFromURL(blob1.url);
});
it("GenerateUserDelegationSAS should work for blob snapshot @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const storageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("container");
const containerClient = serviceClient.getContainerClient(containerName);
await containerClient.create();
const blobName = getUniqueName("blob");
const blobClient = containerClient.getPageBlobClient(blobName);
await blobClient.create(1024, {
blobHTTPHeaders: {
blobContentType: "content-type-original"
}
});
const response = await blobClient.createSnapshot();
const blobSAS = generateBlobSASQueryParameters(
{
blobName,
cacheControl: "cache-control-override",
containerName,
contentDisposition: "content-disposition-override",
contentEncoding: "content-encoding-override",
contentLanguage: "content-language-override",
contentType: "content-type-override",
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("racwd"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
snapshotTime: response.snapshot
},
storageSharedKeyCredential as StorageSharedKeyCredential
);
const sasURL = `${
blobClient.withSnapshot(response.snapshot!).url
}&${blobSAS}`;
const blobClientWithSAS = new PageBlobClient(
sasURL,
newPipeline(new AnonymousCredential())
);
const properties = await blobClientWithSAS.getProperties();
assert.ok(properties);
assert.equal(properties.cacheControl, "cache-control-override");
assert.equal(properties.contentDisposition, "content-disposition-override");
assert.equal(properties.contentEncoding, "content-encoding-override");
assert.equal(properties.contentLanguage, "content-language-override");
assert.equal(properties.contentType, "content-type-override");
const downloadResponse = await blobClientWithSAS.download();
assert.equal(downloadResponse.cacheControl, "cache-control-override");
assert.equal(downloadResponse.contentDisposition, "content-disposition-override");
assert.equal(downloadResponse.contentEncoding, "content-encoding-override");
assert.equal(downloadResponse.contentLanguage, "content-language-override");
assert.equal(downloadResponse.contentType, "content-type-override");
await containerClient.delete();
});
it("Copy blob across accounts should require SAS token @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const sourceStorageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create();
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const sas = generateBlobSASQueryParameters(
{
containerName,
blobName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("r"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
sourceStorageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5);
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
let error;
try {
await targetBlob.beginCopyFromURL(sourceBlob.url);
} catch (err) {
error = err;
}
assert.ok(error !== undefined);
assert.equal(error.statusCode, 403);
assert.equal(error.details.errorCode, "CannotVerifyCopySource");
assert.equal(error.details.Code, "CannotVerifyCopySource");
// this copy should work
const operation = await targetBlob.beginCopyFromURL(
`${sourceBlob.url}?${sas}`
);
const copyResponse = await operation.pollUntilDone();
assert.equal("success", copyResponse.copyStatus);
const fileBuffer = await targetBlob.downloadToBuffer();
assert.equal(fileBuffer.toString(), "hello");
});
it("Copy blob across accounts should error if hosts mismatch @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create();
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5);
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
const sourceUriBuilder = URLBuilder.parse(sourceBlob.url);
sourceUriBuilder.setHost("somewhereelse");
let error;
try {
await targetBlob.beginCopyFromURL(sourceUriBuilder.toString());
} catch (err) {
error = err;
}
assert.deepEqual(error.statusCode, 404);
assert.ok(error !== undefined);
});
it("Copy blob across accounts should succeed for public blob access @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create({
access: "blob"
});
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5);
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
const operation = await targetBlob.beginCopyFromURL(sourceBlob.url);
const copyResponse = await operation.pollUntilDone();
assert.equal("success", copyResponse.copyStatus);
const fileBuffer = await targetBlob.downloadToBuffer();
assert.equal(fileBuffer.toString(), "hello");
});
it("Copy blob across accounts should succeed for public container access @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create({
access: "container"
});
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5);
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
const operation = await targetBlob.beginCopyFromURL(sourceBlob.url);
const copyResponse = await operation.pollUntilDone();
assert.equal("success", copyResponse.copyStatus);
const fileBuffer = await targetBlob.downloadToBuffer();
assert.equal(fileBuffer.toString(), "hello");
});
it("Copy blob across accounts should honor metadata when provided @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const sourceStorageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create();
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const blobName2 = getUniqueName("blob");
const sas = generateBlobSASQueryParameters(
{
containerName,
blobName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("r"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
sourceStorageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5, {
metadata: {
foo: "1",
bar: "2"
}
});
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
const operation = await targetBlob.beginCopyFromURL(
`${sourceBlob.url}?${sas}`
);
const copyResponse = await operation.pollUntilDone();
assert.equal("success", copyResponse.copyStatus);
const properties = await targetBlob.getProperties();
assert.equal(properties.metadata!["foo"], "1");
assert.equal(properties.metadata!["bar"], "2");
const targetBlobWithProps = targetContainerClient.getBlockBlobClient(
blobName2
);
const operation2 = await targetBlobWithProps.beginCopyFromURL(
`${sourceBlob.url}?${sas}`,
{
metadata: {
baz: "3"
}
}
);
const copyResponse2 = await operation2.pollUntilDone();
assert.equal("success", copyResponse2.copyStatus);
const properties2 = await targetBlobWithProps.getProperties();
assert.equal(properties2.metadata!["foo"], undefined);
assert.equal(properties2.metadata!["bar"], undefined);
assert.equal(properties2.metadata!["baz"], "3");
});
it("Copy blob across accounts should fail if source is archived @loki @sql", async () => {
const now = new Date();
now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server
const tmr = new Date();
tmr.setDate(tmr.getDate() + 1);
// By default, credential is always the last element of pipeline factories
const factories = (serviceClient as any).pipeline.factories;
const sourceStorageSharedKeyCredential = factories[factories.length - 1];
const containerName = getUniqueName("con");
const sourceContainerClient = serviceClient.getContainerClient(
containerName
);
const targetContainerClient = serviceClient2.getContainerClient(
containerName
);
await sourceContainerClient.create();
await targetContainerClient.create();
const blobName = getUniqueName("blob");
const sas = generateBlobSASQueryParameters(
{
containerName,
blobName,
expiresOn: tmr,
ipRange: { start: "0.0.0.0", end: "255.255.255.255" },
permissions: BlobSASPermissions.parse("r"),
protocol: SASProtocol.HttpsAndHttp,
startsOn: now,
version: "2016-05-31"
},
sourceStorageSharedKeyCredential as StorageSharedKeyCredential
).toString();
const sourceBlob = sourceContainerClient.getBlockBlobClient(blobName);
await sourceBlob.upload("hello", 5);
sourceBlob.setAccessTier("Archive");
const targetBlob = targetContainerClient.getBlockBlobClient(blobName);
let error;
try {
await targetBlob.beginCopyFromURL(`${sourceBlob.url}?${sas}`);
} catch (err) {
error = err;
}
assert.ok(error !== undefined);
assert.equal(error.statusCode, 409);
assert.equal(error.details.Code, "BlobArchived");
});
}); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [guardduty](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonguardduty.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Guardduty extends PolicyStatement {
public servicePrefix = 'guardduty';
/**
* Statement provider for service [guardduty](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonguardduty.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to accept invitations to become a GuardDuty member account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_AcceptInvitation.html
*/
public toAcceptInvitation() {
return this.to('AcceptInvitation');
}
/**
* Grants permission to archive GuardDuty findings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ArchiveFindings.html
*/
public toArchiveFindings() {
return this.to('ArchiveFindings');
}
/**
* Grants permission to create a detector
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateDetector.html
*/
public toCreateDetector() {
return this.to('CreateDetector');
}
/**
* Grants permission to create GuardDuty filters. A filters defines finding attributes and conditions used to filter findings
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateFilter.html
*/
public toCreateFilter() {
return this.to('CreateFilter');
}
/**
* Grants permission to create an IPSet
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateIPSet.html
*/
public toCreateIPSet() {
return this.to('CreateIPSet');
}
/**
* Grants permission to create GuardDuty member accounts, where the account used to create a member becomes the GuardDuty administrator account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateMembers.html
*/
public toCreateMembers() {
return this.to('CreateMembers');
}
/**
* Grants permission to create a publishing destination
*
* Access Level: Write
*
* Dependent actions:
* - s3:GetObject
* - s3:ListBucket
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreatePublishingDestination.html
*/
public toCreatePublishingDestination() {
return this.to('CreatePublishingDestination');
}
/**
* Grants permission to create sample findings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateSampleFindings.html
*/
public toCreateSampleFindings() {
return this.to('CreateSampleFindings');
}
/**
* Grants permission to create GuardDuty ThreatIntelSets, where a ThreatIntelSet consists of known malicious IP addresses used by GuardDuty to generate findings
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_CreateThreatIntelSet.html
*/
public toCreateThreatIntelSet() {
return this.to('CreateThreatIntelSet');
}
/**
* Grants permission to decline invitations to become a GuardDuty member account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeclineInvitations.html
*/
public toDeclineInvitations() {
return this.to('DeclineInvitations');
}
/**
* Grants permission to delete GuardDuty detectors
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteDetector.html
*/
public toDeleteDetector() {
return this.to('DeleteDetector');
}
/**
* Grants permission to delete GuardDuty filters
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteFilter.html
*/
public toDeleteFilter() {
return this.to('DeleteFilter');
}
/**
* Grants permission to delete GuardDuty IPSets
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteIPSet.html
*/
public toDeleteIPSet() {
return this.to('DeleteIPSet');
}
/**
* Grants permission to delete invitations to become a GuardDuty member account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteInvitations.html
*/
public toDeleteInvitations() {
return this.to('DeleteInvitations');
}
/**
* Grants permission to delete GuardDuty member accounts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteMembers.html
*/
public toDeleteMembers() {
return this.to('DeleteMembers');
}
/**
* Grants permission to delete a publishing destination
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeletePublishingDestination.html
*/
public toDeletePublishingDestination() {
return this.to('DeletePublishingDestination');
}
/**
* Grants permission to delete GuardDuty ThreatIntelSets
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteThreatIntelSet.html
*/
public toDeleteThreatIntelSet() {
return this.to('DeleteThreatIntelSet');
}
/**
* Grants permission to retrieve details about the delegated administrator associated with a GuardDuty detector
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DescribeOrganizationConfiguration.html
*/
public toDescribeOrganizationConfiguration() {
return this.to('DescribeOrganizationConfiguration');
}
/**
* Grants permission to retrieve details about a publishing destination
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DescribePublishingDestination.html
*/
public toDescribePublishingDestination() {
return this.to('DescribePublishingDestination');
}
/**
* Grants permission to disable the organization delegated administrator for GuardDuty
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DisableOrganizationAdminAccount.html
*/
public toDisableOrganizationAdminAccount() {
return this.to('DisableOrganizationAdminAccount');
}
/**
* Grants permission to disassociate a GuardDuty member account from its GuardDuty master account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DisassociateFromMasterAccount.html
*/
public toDisassociateFromMasterAccount() {
return this.to('DisassociateFromMasterAccount');
}
/**
* Grants permission to disassociate GuardDuty member accounts from their master GuardDuty account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DisassociateMembers.html
*/
public toDisassociateMembers() {
return this.to('DisassociateMembers');
}
/**
* Grants permission to enable an organization delegated administrator for GuardDuty
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_EnableOrganizationAdminAccount.html
*/
public toEnableOrganizationAdminAccount() {
return this.to('EnableOrganizationAdminAccount');
}
/**
* Grants permission to retrieve GuardDuty detectors
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetDetector.html
*/
public toGetDetector() {
return this.to('GetDetector');
}
/**
* Grants permission to retrieve GuardDuty filters
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetFilter.html
*/
public toGetFilter() {
return this.to('GetFilter');
}
/**
* Grants permission to retrieve GuardDuty findings
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetFindings.html
*/
public toGetFindings() {
return this.to('GetFindings');
}
/**
* Grants permission to retrieve a list of GuardDuty finding statistics
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetFindingsStatistics.html
*/
public toGetFindingsStatistics() {
return this.to('GetFindingsStatistics');
}
/**
* Grants permsission to retrieve GuardDuty IPSets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetIPSet.html
*/
public toGetIPSet() {
return this.to('GetIPSet');
}
/**
* Grants permission to retrieve the count of all GuardDuty invitations sent to a specified account, which does not include the accepted invitation
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetInvitationsCount.html
*/
public toGetInvitationsCount() {
return this.to('GetInvitationsCount');
}
/**
* Grants permission to retrieve details of the GuardDuty master account associated with a member account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetMasterAccount.html
*/
public toGetMasterAccount() {
return this.to('GetMasterAccount');
}
/**
* Grants permission to describe which data sources are enabled for member accounts detectors
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetMemberDetectors.html
*/
public toGetMemberDetectors() {
return this.to('GetMemberDetectors');
}
/**
* Grants permission to retrieve the member accounts associated with a master account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetMembers.html
*/
public toGetMembers() {
return this.to('GetMembers');
}
/**
* Grants permission to retrieve GuardDuty ThreatIntelSets
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetThreatIntelSet.html
*/
public toGetThreatIntelSet() {
return this.to('GetThreatIntelSet');
}
/**
* Grants permission to list Amazon GuardDuty usage statistics over the last 30 days for the specified detector ID
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_GetUsageStatistics.html
*/
public toGetUsageStatistics() {
return this.to('GetUsageStatistics');
}
/**
* Grants permission to invite other AWS accounts to enable GuardDuty and become GuardDuty member accounts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_InviteMembers.html
*/
public toInviteMembers() {
return this.to('InviteMembers');
}
/**
* Grants permission to retrieve a list of GuardDuty detectors
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListDetectors.html
*/
public toListDetectors() {
return this.to('ListDetectors');
}
/**
* Grants permission to retrieve a list of GuardDuty filters
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListFilters.html
*/
public toListFilters() {
return this.to('ListFilters');
}
/**
* Grants permission to retrieve a list of GuardDuty findings
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListFindings.html
*/
public toListFindings() {
return this.to('ListFindings');
}
/**
* Grants permission to retrieve a list of GuardDuty IPSets
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListIPSets.html
*/
public toListIPSets() {
return this.to('ListIPSets');
}
/**
* Grants permission to retrieve a lists of all of the GuardDuty membership invitations that were sent to an AWS account
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListInvitations.html
*/
public toListInvitations() {
return this.to('ListInvitations');
}
/**
* Grants permission to retrierve a lsit of GuardDuty member accounts associated with a master account
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListMembers.html
*/
public toListMembers() {
return this.to('ListMembers');
}
/**
* Grants permission to list details about the organization delegated administrator for GuardDuty
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListOrganizationAdminAccounts.html
*/
public toListOrganizationAdminAccounts() {
return this.to('ListOrganizationAdminAccounts');
}
/**
* Grants permission to retrieve a list of publishing destinations
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListPublishingDestinations.html
*/
public toListPublishingDestinations() {
return this.to('ListPublishingDestinations');
}
/**
* Grants permission to retrieve a list of tags associated with a GuardDuty resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to retrieve a list of GuardDuty ThreatIntelSets
*
* Access Level: List
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_ListThreatIntelSets.html
*/
public toListThreatIntelSets() {
return this.to('ListThreatIntelSets');
}
/**
* Grants permission to a GuardDuty administrator account to monitor findings from GuardDuty member accounts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_StartMonitoringMembers.html
*/
public toStartMonitoringMembers() {
return this.to('StartMonitoringMembers');
}
/**
* Grants permission to disable monitoring findings from member accounts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_StopMonitoringMembers.html
*/
public toStopMonitoringMembers() {
return this.to('StopMonitoringMembers');
}
/**
* Grants permission to add tags to a GuardDuty resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to unarchive GuardDuty findings
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UnarchiveFindings.html
*/
public toUnarchiveFindings() {
return this.to('UnarchiveFindings');
}
/**
* Grants permission to remove tags from a GuardDuty resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update GuardDuty detectors
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateDetector.html
*/
public toUpdateDetector() {
return this.to('UpdateDetector');
}
/**
* Grants permission to updates GuardDuty filters
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateFilter.html
*/
public toUpdateFilter() {
return this.to('UpdateFilter');
}
/**
* Grants permission to update findings feedback to mark GuardDuty findings as useful or not useful
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateFindingsFeedback.html
*/
public toUpdateFindingsFeedback() {
return this.to('UpdateFindingsFeedback');
}
/**
* Grants permission to update GuardDuty IPSets
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateIPSet.html
*/
public toUpdateIPSet() {
return this.to('UpdateIPSet');
}
/**
* Grants permission to update which data sources are enabled for member accounts detectors
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateMemberDetectors.html
*/
public toUpdateMemberDetectors() {
return this.to('UpdateMemberDetectors');
}
/**
* Grants permission to update the delegated administrator configuration associated with a GuardDuty detector
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateOrganizationConfiguration.html
*/
public toUpdateOrganizationConfiguration() {
return this.to('UpdateOrganizationConfiguration');
}
/**
* Grants permission to update a publishing destination
*
* Access Level: Write
*
* Dependent actions:
* - s3:GetObject
* - s3:ListBucket
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdatePublishingDestination.html
*/
public toUpdatePublishingDestination() {
return this.to('UpdatePublishingDestination');
}
/**
* Grants permission to updates the GuardDuty ThreatIntelSets
*
* Access Level: Write
*
* https://docs.aws.amazon.com/guardduty/latest/APIReference/API_UpdateThreatIntelSet.html
*/
public toUpdateThreatIntelSet() {
return this.to('UpdateThreatIntelSet');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AcceptInvitation",
"ArchiveFindings",
"CreateDetector",
"CreateFilter",
"CreateIPSet",
"CreateMembers",
"CreatePublishingDestination",
"CreateSampleFindings",
"CreateThreatIntelSet",
"DeclineInvitations",
"DeleteDetector",
"DeleteFilter",
"DeleteIPSet",
"DeleteInvitations",
"DeleteMembers",
"DeletePublishingDestination",
"DeleteThreatIntelSet",
"DisableOrganizationAdminAccount",
"DisassociateFromMasterAccount",
"DisassociateMembers",
"EnableOrganizationAdminAccount",
"InviteMembers",
"StartMonitoringMembers",
"StopMonitoringMembers",
"UnarchiveFindings",
"UpdateDetector",
"UpdateFilter",
"UpdateFindingsFeedback",
"UpdateIPSet",
"UpdateMemberDetectors",
"UpdateOrganizationConfiguration",
"UpdatePublishingDestination",
"UpdateThreatIntelSet"
],
"Read": [
"DescribeOrganizationConfiguration",
"DescribePublishingDestination",
"GetDetector",
"GetFilter",
"GetFindings",
"GetFindingsStatistics",
"GetIPSet",
"GetInvitationsCount",
"GetMasterAccount",
"GetMemberDetectors",
"GetMembers",
"GetThreatIntelSet",
"GetUsageStatistics",
"ListTagsForResource"
],
"List": [
"ListDetectors",
"ListFilters",
"ListFindings",
"ListIPSets",
"ListInvitations",
"ListMembers",
"ListOrganizationAdminAccounts",
"ListPublishingDestinations",
"ListThreatIntelSets"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type detector to the statement
*
* https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_managing_access.html#guardduty-resources
*
* @param detectorId - Identifier for the detectorId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onDetector(detectorId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}';
arn = arn.replace('${DetectorId}', detectorId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type filter to the statement
*
* https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_managing_access.html#guardduty-resources
*
* @param detectorId - Identifier for the detectorId.
* @param filterName - Identifier for the filterName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onFilter(detectorId: string, filterName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/filter/${FilterName}';
arn = arn.replace('${DetectorId}', detectorId);
arn = arn.replace('${FilterName}', filterName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type ipset to the statement
*
* https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_managing_access.html#guardduty-resources
*
* @param detectorId - Identifier for the detectorId.
* @param iPSetId - Identifier for the iPSetId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onIpset(detectorId: string, iPSetId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/ipset/${IPSetId}';
arn = arn.replace('${DetectorId}', detectorId);
arn = arn.replace('${IPSetId}', iPSetId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type threatintelset to the statement
*
* https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_managing_access.html#guardduty-resources
*
* @param detectorId - Identifier for the detectorId.
* @param threatIntelSetId - Identifier for the threatIntelSetId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onThreatintelset(detectorId: string, threatIntelSetId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/threatintelset/${ThreatIntelSetId}';
arn = arn.replace('${DetectorId}', detectorId);
arn = arn.replace('${ThreatIntelSetId}', threatIntelSetId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type publishingDestination to the statement
*
* https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_managing_access.html#guardduty-resources
*
* @param detectorId - Identifier for the detectorId.
* @param publishingDestinationId - Identifier for the publishingDestinationId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onPublishingDestination(detectorId: string, publishingDestinationId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/publishingDestination/${PublishingDestinationId}';
arn = arn.replace('${DetectorId}', detectorId);
arn = arn.replace('${PublishingDestinationId}', publishingDestinationId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
module es {
export class RectangleExt {
/**
* 获取指定边的位置
* @param rect
* @param edge
*/
public static getSide(rect: Rectangle, edge: Edge) {
switch (edge) {
case Edge.top:
return rect.top;
case Edge.bottom:
return rect.bottom;
case es.Edge.left:
return rect.left;
case Edge.right:
return rect.right;
}
}
/**
* 计算两个矩形的并集。结果将是一个包含其他两个的矩形。
* @param first
* @param point
*/
public static union(first: Rectangle, point: Vector2) {
let rect = new Rectangle(point.x, point.y, 0, 0);
let result = new Rectangle();
result.x = Math.min(first.x, rect.x);
result.y = Math.min(first.y, rect.y);
result.width = Math.max(first.right, rect.right) - result.x;
result.height = Math.max(first.bottom, rect.bottom) - result.y;
return result;
}
public static getHalfRect(rect: Rectangle, edge: Edge) {
switch (edge) {
case Edge.top:
return new Rectangle(rect.x, rect.y, rect.width, rect.height / 2);
case Edge.bottom:
return new Rectangle(rect.x, rect.y + rect.height / 2, rect.width, rect.height / 2);
case Edge.left:
return new Rectangle(rect.x, rect.y, rect.width / 2, rect.height);
case Edge.right:
return new Rectangle(rect.x + rect.width / 2, rect.y, rect.width / 2, rect.height);
}
}
/**
* 获取矩形的一部分,其宽度/高度的大小位于矩形的边缘,但仍然包含在其中。
* @param rect
* @param edge
* @param size
*/
public static getRectEdgePortion(rect: Rectangle, edge: Edge, size: number = 1) {
switch (edge) {
case es.Edge.top:
return new Rectangle(rect.x, rect.y, rect.width, size);
case Edge.bottom:
return new Rectangle(rect.x, rect.y + rect.height - size, rect.width, size);
case Edge.left:
return new Rectangle(rect.x, rect.y, size, rect.height);
case Edge.right:
return new Rectangle(rect.x + rect.width - size, rect.y, size, rect.height);
}
}
public static expandSide(rect: Rectangle, edge: Edge, amount: number) {
amount = Math.abs(amount);
switch (edge) {
case Edge.top:
rect.y -= amount;
rect.height += amount;
break;
case es.Edge.bottom:
rect.height += amount;
break;
case Edge.left:
rect.x -= amount;
rect.width += amount;
break;
case Edge.right:
rect.width += amount;
break;
}
}
public static contract(rect: Rectangle, horizontalAmount, verticalAmount) {
rect.x += horizontalAmount;
rect.y += verticalAmount;
rect.width -= horizontalAmount * 2;
rect.height -= verticalAmount * 2;
}
/**
* 给定多边形的点,计算其边界
* @param points
*/
public static boundsFromPolygonVector(points: Vector2[]) {
// 我们需要找到最小/最大的x/y值。
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
for (let i = 0; i < points.length; i++) {
let pt = points[i];
if (pt.x < minX)
minX = pt.x;
if (pt.x > maxX)
maxX = pt.x;
if (pt.y < minY)
minY = pt.y;
if (pt.y > maxY)
maxY = pt.y;
}
return this.fromMinMaxVector(new Vector2(minX, minY), new Vector2(maxX, maxY));
}
/**
* 创建一个给定最小/最大点(左上角,右下角)的矩形
* @param min
* @param max
*/
public static fromMinMaxVector(min: Vector2, max: Vector2) {
return new Rectangle(min.x, min.y, max.x - min.x, max.y - min.y);
}
/**
* 返回一个跨越当前边界和提供的delta位置的Bounds
* @param rect
* @param deltaX
* @param deltaY
*/
public static getSweptBroadphaseBounds(rect: Rectangle, deltaX: number, deltaY: number) {
let broadphasebox = Rectangle.empty;
broadphasebox.x = deltaX > 0 ? rect.x : rect.x + deltaX;
broadphasebox.y = deltaY > 0 ? rect.y : rect.y + deltaY;
broadphasebox.width = deltaX > 0 ? deltaX + rect.width : rect.width - deltaX;
broadphasebox.height = deltaY > 0 ? deltaY + rect.height : rect.height - deltaY;
return broadphasebox;
}
/**
* 如果矩形发生碰撞,返回true
* moveX和moveY将返回b1为避免碰撞而必须移动的移动量
* @param rect
* @param other
* @param moveX
* @param moveY
*/
public collisionCheck(rect: Rectangle, other: Rectangle, moveX: Ref<number>, moveY: Ref<number>) {
moveX.value = moveY.value = 0;
let l = other.x - (rect.x + rect.width);
let r = (other.x + other.width) - rect.x;
let t = other.y - (rect.y + rect.height);
let b = (other.y + other.height) - rect.y;
// 检验是否有碰撞
if (l > 0 || r < 0 || t > 0 || b < 0)
return false;
// 求两边的偏移量
moveX.value = Math.abs(l) < r ? l : r;
moveY.value = Math.abs(t) < b ? t : b;
// 只使用最小的偏移量
if (Math.abs(moveX.value) < Math.abs(moveY.value))
moveY.value = 0;
else
moveX.value = 0;
return true;
}
/**
* 计算两个矩形之间有符号的交点深度
* @param rectA
* @param rectB
* @returns 两个相交的矩形之间的重叠量。
* 这些深度值可以是负值,取决于矩形相交的边。
* 这允许调用者确定正确的推送对象的方向,以解决碰撞问题。
* 如果矩形不相交,则返回Vector2.zero。
*/
public static getIntersectionDepth(rectA: Rectangle, rectB: Rectangle) {
// 计算半尺寸
let halfWidthA = rectA.width / 2;
let halfHeightA = rectA.height / 2;
let halfWidthB = rectB.width / 2;
let halfHeightB = rectB.height / 2;
// 计算中心
let centerA = new Vector2(rectA.left + halfWidthA, rectA.top + halfHeightA);
let centerB = new Vector2(rectB.left + halfWidthB, rectB.top + halfHeightB);
// 计算当前中心间的距离和最小非相交距离
let distanceX = centerA.x - centerB.x;
let distanceY = centerA.y - centerB.y;
let minDistanceX = halfWidthA + halfWidthB;
let minDistanceY = halfHeightA + halfHeightB;
// 如果我们根本不相交,则返回(0,0)
if (Math.abs(distanceX) >= minDistanceX || Math.abs(distanceY) >= minDistanceY)
return Vector2.zero;
// 计算并返回交叉点深度
let depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
let depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector2(depthX, depthY);
}
public static getClosestPointOnBoundsToOrigin(rect: Rectangle) {
let max = this.getMax(rect);
let minDist = Math.abs(rect.location.x);
let boundsPoint = new Vector2(rect.location.x, 0);
if (Math.abs(max.x) < minDist) {
minDist = Math.abs(max.x);
boundsPoint.x = max.x;
boundsPoint.y = 0;
}
if (Math.abs(max.y) < minDist) {
minDist = Math.abs(max.y);
boundsPoint.x = 0;
boundsPoint.y = max.y;
}
if (Math.abs(rect.location.y) < minDist) {
minDist = Math.abs(rect.location.y);
boundsPoint.x = 0;
boundsPoint.y = rect.location.y;
}
return boundsPoint;
}
/**
* 将Rectangle中或上的最接近点返回给定点
* @param rect
* @param point
*/
public static getClosestPointOnRectangleToPoint(rect: Rectangle, point: Vector2) {
// 对于每个轴,如果该点在盒子外面,则将在盒子上,否则不理会它
let res = es.Vector2.zero;
res.x = MathHelper.clamp(point.x, rect.left, rect.right)
res.y = MathHelper.clamp(point.y, rect.top, rect.bottom);
return res;
}
/**
* 获取矩形边界上与给定点最接近的点
* @param rect
* @param point
*/
public static getClosestPointOnRectangleBorderToPoint(rect: Rectangle, point: Vector2) {
// 对于每个轴,如果该点在盒子外面,则将在盒子上,否则不理会它
let res = es.Vector2.zero;
res.x = MathHelper.clamp(Math.trunc(point.x), rect.left, rect.right)
res.y = MathHelper.clamp(Math.trunc(point.y), rect.top, rect.bottom);
// 如果点在矩形内,我们需要将res推到边框,因为它将在矩形内
if (rect.contains(res.x, res.y)) {
let dl = rect.x - rect.left;
let dr = rect.right - res.x;
let dt = res.y - rect.top;
let db = rect.bottom - res.y;
let min = Math.min(dl, dr, dt, db);
if (min == dt)
res.y = rect.top;
else if (min == db)
res.y = rect.bottom;
else if (min == dl)
res.x == rect.left;
else
res.x = rect.right;
}
return res;
}
public static getMax(rect: Rectangle) {
return new Vector2(rect.right, rect.bottom);
}
/**
* 以Vector2的形式获取矩形的中心点
* @param rect
* @returns
*/
public static getCenter(rect: Rectangle) {
return new Vector2(rect.x + rect.width / 2, rect.y + rect.height / 2);
}
/**
* 给定多边形的点即可计算边界
* @param points
*/
public static boundsFromPolygonPoints(points: Vector2[]) {
// 我们需要找到最小/最大x / y值
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
for (let i = 0; i < points.length; i++) {
let pt = points[i];
if (pt.x < minX)
minX = pt.x;
if (pt.x > maxX)
maxX = pt.x
if (pt.y < minY)
minY = pt.y;
if (pt.y > maxY)
maxY = pt.y;
}
return this.fromMinMaxVector(new Vector2(Math.trunc(minX), Math.trunc(minY)), new Vector2(Math.trunc(maxX), Math.trunc(maxY)));
}
public static calculateBounds(rect: Rectangle, parentPosition: Vector2, position: Vector2, origin: Vector2, scale: Vector2,
rotation: number, width: number, height: number) {
if (rotation == 0) {
rect.x = Math.trunc(parentPosition.x + position.x - origin.x * scale.x);
rect.y = Math.trunc(parentPosition.y + position.y - origin.y * scale.y);
rect.width = Math.trunc(width * scale.x);
rect.height = Math.trunc(height * scale.y);
} else {
// 我们需要找到我们的绝对最小/最大值,并据此创建边界
let worldPosX = parentPosition.x + position.x;
let worldPosY = parentPosition.y + position.y;
let tempMat: Matrix2D;
// 考虑到原点,将参考点设置为世界参考
let transformMatrix = new Matrix2D();
Matrix2D.createTranslation(-worldPosX - origin.x, -worldPosY - origin.y, transformMatrix);
Matrix2D.createScale(scale.x, scale.y, tempMat);
transformMatrix = transformMatrix.multiply(tempMat);
Matrix2D.createRotation(rotation, tempMat);
transformMatrix =transformMatrix.multiply(tempMat);
Matrix2D.createTranslation(worldPosX, worldPosY, tempMat);
transformMatrix = transformMatrix.multiply(tempMat);
// TODO: 我们可以把世界变换留在矩阵中,避免在世界空间中得到所有的四个角
let topLeft = new Vector2(worldPosX, worldPosY);
let topRight = new Vector2(worldPosX + width, worldPosY);
let bottomLeft = new Vector2(worldPosX, worldPosY + height);
let bottomRight = new Vector2(worldPosX + width, worldPosY + height);
Vector2Ext.transformR(topLeft, transformMatrix, topLeft);
Vector2Ext.transformR(topRight, transformMatrix, topRight);
Vector2Ext.transformR(bottomLeft, transformMatrix, bottomLeft);
Vector2Ext.transformR(bottomRight, transformMatrix, bottomRight);
// 找出最小值和最大值,这样我们就可以计算出我们的边界框。
let minX = Math.trunc(Math.min(topLeft.x, bottomRight.x, topRight.x, bottomLeft.x));
let maxX = Math.trunc(Math.max(topLeft.x, bottomRight.x, topRight.x, bottomLeft.x));
let minY = Math.trunc(Math.min(topLeft.y, bottomRight.y, topRight.y, bottomLeft.y));
let maxY = Math.trunc(Math.max(topLeft.y, bottomRight.y, topRight.y, bottomLeft.y));
rect.location = new Vector2(minX, minY);
rect.width = Math.trunc(maxX - minX);
rect.height = Math.trunc(maxY - minY);
}
}
/**
* 缩放矩形
* @param rect
* @param scale
*/
public static scale(rect: Rectangle, scale: Vector2) {
rect.x = Math.trunc(rect.x * scale.x);
rect.y = Math.trunc(rect.y * scale.y);
rect.width = Math.trunc(rect.width * scale.x);
rect.height = Math.trunc(rect.height * scale.y);
}
public static translate(rect: Rectangle, vec: Vector2) {
rect.location.addEqual(vec);
}
}
} | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>Exception that indicates the specified <code>AttackId</code> does not exist, or the requester does not have the appropriate permissions to access the <code>AttackId</code>.</p>
*/
export interface AccessDeniedException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedException";
$fault: "client";
message?: string;
}
export namespace AccessDeniedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedException): any => ({
...obj,
});
}
/**
* <p>In order to grant the necessary access to the Shield Response Team (SRT) the user submitting the request must have the <code>iam:PassRole</code> permission. This error indicates the user did not have the appropriate permissions. For more information, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html">Granting a User Permissions to Pass a Role to an Amazon Web Services Service</a>. </p>
*/
export interface AccessDeniedForDependencyException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedForDependencyException";
$fault: "client";
message?: string;
}
export namespace AccessDeniedForDependencyException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedForDependencyException): any => ({
...obj,
});
}
export interface AssociateDRTLogBucketRequest {
/**
* <p>The Amazon S3 bucket that contains the logs that you want to share.</p>
*/
LogBucket: string | undefined;
}
export namespace AssociateDRTLogBucketRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateDRTLogBucketRequest): any => ({
...obj,
});
}
export interface AssociateDRTLogBucketResponse {}
export namespace AssociateDRTLogBucketResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateDRTLogBucketResponse): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that a problem occurred with the service infrastructure. You
* can retry the request.</p>
*/
export interface InternalErrorException extends __SmithyException, $MetadataBearer {
name: "InternalErrorException";
$fault: "server";
message?: string;
}
export namespace InternalErrorException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalErrorException): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that the operation would not cause any change to occur.</p>
*/
export interface InvalidOperationException extends __SmithyException, $MetadataBearer {
name: "InvalidOperationException";
$fault: "client";
message?: string;
}
export namespace InvalidOperationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidOperationException): any => ({
...obj,
});
}
/**
* <p>Provides information about a particular parameter passed inside a request that resulted in an exception.</p>
*/
export interface ValidationExceptionField {
/**
* <p>The name of the parameter that failed validation.</p>
*/
name: string | undefined;
/**
* <p>The message describing why the parameter failed validation.</p>
*/
message: string | undefined;
}
export namespace ValidationExceptionField {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ValidationExceptionField): any => ({
...obj,
});
}
export enum ValidationExceptionReason {
FIELD_VALIDATION_FAILED = "FIELD_VALIDATION_FAILED",
OTHER = "OTHER",
}
/**
* <p>Exception that indicates that the parameters passed to the API are invalid. If available, this exception includes details in additional properties. </p>
*/
export interface InvalidParameterException extends __SmithyException, $MetadataBearer {
name: "InvalidParameterException";
$fault: "client";
message?: string;
/**
* <p>Additional information about the exception.</p>
*/
reason?: ValidationExceptionReason | string;
/**
* <p>Fields that caused the exception.</p>
*/
fields?: ValidationExceptionField[];
}
export namespace InvalidParameterException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidParameterException): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that the operation would exceed a limit.</p>
*/
export interface LimitsExceededException extends __SmithyException, $MetadataBearer {
name: "LimitsExceededException";
$fault: "client";
message?: string;
/**
* <p>The type of limit that would be exceeded.</p>
*/
Type?: string;
/**
* <p>The threshold that would be exceeded.</p>
*/
Limit?: number;
}
export namespace LimitsExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LimitsExceededException): any => ({
...obj,
});
}
/**
* <p>The ARN of the role that you specifed does not exist.</p>
*/
export interface NoAssociatedRoleException extends __SmithyException, $MetadataBearer {
name: "NoAssociatedRoleException";
$fault: "client";
message?: string;
}
export namespace NoAssociatedRoleException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: NoAssociatedRoleException): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that the resource state has been modified by another
* client. Retrieve the resource and then retry your request.</p>
*/
export interface OptimisticLockException extends __SmithyException, $MetadataBearer {
name: "OptimisticLockException";
$fault: "client";
message?: string;
}
export namespace OptimisticLockException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: OptimisticLockException): any => ({
...obj,
});
}
/**
* <p>Exception indicating the specified resource does not exist. If available, this exception includes details in additional properties. </p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
message?: string;
/**
* <p>Type of resource.</p>
*/
resourceType?: string;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
export interface AssociateDRTRoleRequest {
/**
* <p>The Amazon Resource Name (ARN) of the role the SRT will use to access your Amazon Web Services account.</p>
* <p>Prior to making the <code>AssociateDRTRole</code> request, you must attach the <a href="https://console.aws.amazon.com/iam/home?#/policies/arn:aws:iam::aws:policy/service-role/AWSShieldDRTAccessPolicy">AWSShieldDRTAccessPolicy</a> managed policy to this role. For more information see <a href=" https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html">Attaching and Detaching IAM Policies</a>.</p>
*/
RoleArn: string | undefined;
}
export namespace AssociateDRTRoleRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateDRTRoleRequest): any => ({
...obj,
});
}
export interface AssociateDRTRoleResponse {}
export namespace AssociateDRTRoleResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateDRTRoleResponse): any => ({
...obj,
});
}
export interface AssociateHealthCheckRequest {
/**
* <p>The unique identifier (ID) for the <a>Protection</a> object to add the health check association to. </p>
*/
ProtectionId: string | undefined;
/**
* <p>The Amazon Resource Name (ARN) of the health check to associate with the protection.</p>
*/
HealthCheckArn: string | undefined;
}
export namespace AssociateHealthCheckRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateHealthCheckRequest): any => ({
...obj,
});
}
export interface AssociateHealthCheckResponse {}
export namespace AssociateHealthCheckResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateHealthCheckResponse): any => ({
...obj,
});
}
/**
* <p>Contact information that the SRT can use to contact you if you have proactive engagement enabled, for escalations to the SRT and to initiate proactive customer support.</p>
*/
export interface EmergencyContact {
/**
* <p>The email address for the contact.</p>
*/
EmailAddress: string | undefined;
/**
* <p>The phone number for the contact.</p>
*/
PhoneNumber?: string;
/**
* <p>Additional notes regarding the contact. </p>
*/
ContactNotes?: string;
}
export namespace EmergencyContact {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EmergencyContact): any => ({
...obj,
});
}
export interface AssociateProactiveEngagementDetailsRequest {
/**
* <p>A list of email addresses and phone numbers that the Shield Response Team (SRT) can use to contact you for escalations to the SRT and to initiate proactive customer support. </p>
* <p>To enable proactive engagement, the contact list must include at least one phone number.</p>
* <note>
* <p>The contacts that you provide here replace any contacts that were already defined. If you already have contacts defined and want to use them, retrieve the list using <code>DescribeEmergencyContactSettings</code> and then provide it here. </p>
* </note>
*/
EmergencyContactList: EmergencyContact[] | undefined;
}
export namespace AssociateProactiveEngagementDetailsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateProactiveEngagementDetailsRequest): any => ({
...obj,
});
}
export interface AssociateProactiveEngagementDetailsResponse {}
export namespace AssociateProactiveEngagementDetailsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AssociateProactiveEngagementDetailsResponse): any => ({
...obj,
});
}
/**
* <p>The counter that describes a DDoS attack.</p>
*/
export interface SummarizedCounter {
/**
* <p>The counter name.</p>
*/
Name?: string;
/**
* <p>The maximum value of the counter for a specified time period.</p>
*/
Max?: number;
/**
* <p>The average value of the counter for a specified time period.</p>
*/
Average?: number;
/**
* <p>The total of counter values for a specified time period.</p>
*/
Sum?: number;
/**
* <p>The number of counters for a specified time period.</p>
*/
N?: number;
/**
* <p>The unit of the counters.</p>
*/
Unit?: string;
}
export namespace SummarizedCounter {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SummarizedCounter): any => ({
...obj,
});
}
export enum AttackLayer {
APPLICATION = "APPLICATION",
NETWORK = "NETWORK",
}
export enum AttackPropertyIdentifier {
DESTINATION_URL = "DESTINATION_URL",
REFERRER = "REFERRER",
SOURCE_ASN = "SOURCE_ASN",
SOURCE_COUNTRY = "SOURCE_COUNTRY",
SOURCE_IP_ADDRESS = "SOURCE_IP_ADDRESS",
SOURCE_USER_AGENT = "SOURCE_USER_AGENT",
WORDPRESS_PINGBACK_REFLECTOR = "WORDPRESS_PINGBACK_REFLECTOR",
WORDPRESS_PINGBACK_SOURCE = "WORDPRESS_PINGBACK_SOURCE",
}
/**
* <p>A contributor to the attack and their contribution.</p>
*/
export interface Contributor {
/**
* <p>The name of the contributor. This is dependent on the <code>AttackPropertyIdentifier</code>. For example, if the <code>AttackPropertyIdentifier</code> is <code>SOURCE_COUNTRY</code>, the <code>Name</code> could be <code>United States</code>.</p>
*/
Name?: string;
/**
* <p>The contribution of this contributor expressed in <a>Protection</a> units. For example <code>10,000</code>.</p>
*/
Value?: number;
}
export namespace Contributor {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Contributor): any => ({
...obj,
});
}
export enum Unit {
BITS = "BITS",
BYTES = "BYTES",
PACKETS = "PACKETS",
REQUESTS = "REQUESTS",
}
/**
* <p>Details of a Shield event. This is provided as part of an <a>AttackDetail</a>.</p>
*/
export interface AttackProperty {
/**
* <p>The type of Shield event that was observed. <code>NETWORK</code> indicates layer 3 and layer 4 events and <code>APPLICATION</code>
* indicates layer 7 events.</p>
* <p>For infrastructure
* layer events (L3 and L4 events) after January 25, 2021, you can view metrics for top contributors in Amazon CloudWatch metrics.
* For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/monitoring-cloudwatch.html#set-ddos-alarms">Shield metrics and alarms</a>
* in the <i>WAF Developer Guide</i>. </p>
*/
AttackLayer?: AttackLayer | string;
/**
* <p>Defines the Shield event property information that is provided. The
* <code>WORDPRESS_PINGBACK_REFLECTOR</code> and <code>WORDPRESS_PINGBACK_SOURCE</code>
* values are valid only for WordPress reflective pingback events.</p>
*/
AttackPropertyIdentifier?: AttackPropertyIdentifier | string;
/**
* <p>Contributor objects for the top five contributors to a Shield event. </p>
*/
TopContributors?: Contributor[];
/**
* <p>The unit used for the <code>Contributor</code>
* <code>Value</code> property. </p>
*/
Unit?: Unit | string;
/**
* <p>The total contributions made to this Shield event by all contributors.</p>
*/
Total?: number;
}
export namespace AttackProperty {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackProperty): any => ({
...obj,
});
}
/**
* <p>The mitigation applied to a DDoS attack.</p>
*/
export interface Mitigation {
/**
* <p>The name of the mitigation taken for this attack.</p>
*/
MitigationName?: string;
}
export namespace Mitigation {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Mitigation): any => ({
...obj,
});
}
/**
* <p>A summary of information about the attack.</p>
*/
export interface SummarizedAttackVector {
/**
* <p>The attack type, for example, SNMP reflection or SYN flood.</p>
*/
VectorType: string | undefined;
/**
* <p>The list of counters that describe the details of the attack.</p>
*/
VectorCounters?: SummarizedCounter[];
}
export namespace SummarizedAttackVector {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SummarizedAttackVector): any => ({
...obj,
});
}
export enum SubResourceType {
IP = "IP",
URL = "URL",
}
/**
* <p>The attack information for the specified SubResource.</p>
*/
export interface SubResourceSummary {
/**
* <p>The <code>SubResource</code> type.</p>
*/
Type?: SubResourceType | string;
/**
* <p>The unique identifier (ID) of the <code>SubResource</code>.</p>
*/
Id?: string;
/**
* <p>The list of attack types and associated counters.</p>
*/
AttackVectors?: SummarizedAttackVector[];
/**
* <p>The counters that describe the details of the attack.</p>
*/
Counters?: SummarizedCounter[];
}
export namespace SubResourceSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SubResourceSummary): any => ({
...obj,
});
}
/**
* <p>The details of a DDoS attack.</p>
*/
export interface AttackDetail {
/**
* <p>The unique identifier (ID) of the attack.</p>
*/
AttackId?: string;
/**
* <p>The ARN (Amazon Resource Name) of the resource that was attacked.</p>
*/
ResourceArn?: string;
/**
* <p>If applicable, additional detail about the resource being attacked, for example, IP address or URL.</p>
*/
SubResources?: SubResourceSummary[];
/**
* <p>The time the attack started, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
StartTime?: Date;
/**
* <p>The time the attack ended, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
EndTime?: Date;
/**
* <p>List of counters that describe the attack for the specified time period.</p>
*/
AttackCounters?: SummarizedCounter[];
/**
* <p>The array of objects that provide details of the Shield event. </p>
* <p>For infrastructure
* layer events (L3 and L4 events) after January 25, 2021, you can view metrics for top contributors in Amazon CloudWatch metrics.
* For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/monitoring-cloudwatch.html#set-ddos-alarms">Shield metrics and alarms</a>
* in the <i>WAF Developer Guide</i>. </p>
*/
AttackProperties?: AttackProperty[];
/**
* <p>List of mitigation actions taken for the attack.</p>
*/
Mitigations?: Mitigation[];
}
export namespace AttackDetail {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackDetail): any => ({
...obj,
});
}
/**
* <p>Statistics objects for the various data types in <a>AttackVolume</a>. </p>
*/
export interface AttackVolumeStatistics {
/**
* <p>The maximum attack volume observed for the given unit.</p>
*/
Max: number | undefined;
}
export namespace AttackVolumeStatistics {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackVolumeStatistics): any => ({
...obj,
});
}
/**
* <p>Information about the volume of attacks during the time period, included in an <a>AttackStatisticsDataItem</a>. If the accompanying <code>AttackCount</code> in the statistics object is zero, this setting might be empty.</p>
*/
export interface AttackVolume {
/**
* <p>A statistics object that uses bits per second as the unit. This is included for network level attacks. </p>
*/
BitsPerSecond?: AttackVolumeStatistics;
/**
* <p>A statistics object that uses packets per second as the unit. This is included for network level attacks. </p>
*/
PacketsPerSecond?: AttackVolumeStatistics;
/**
* <p>A statistics object that uses requests per second as the unit. This is included for application level attacks, and is only available for accounts that are subscribed to Shield Advanced.</p>
*/
RequestsPerSecond?: AttackVolumeStatistics;
}
export namespace AttackVolume {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackVolume): any => ({
...obj,
});
}
/**
* <p>A single attack statistics data record. This is returned by <a>DescribeAttackStatistics</a> along with a time range indicating the time period that the attack statistics apply to. </p>
*/
export interface AttackStatisticsDataItem {
/**
* <p>Information about the volume of attacks during the time period. If the accompanying <code>AttackCount</code> is zero, this setting might be empty.</p>
*/
AttackVolume?: AttackVolume;
/**
* <p>The number of attacks detected during the time period. This is always present, but might be zero. </p>
*/
AttackCount: number | undefined;
}
export namespace AttackStatisticsDataItem {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackStatisticsDataItem): any => ({
...obj,
});
}
/**
* <p>Describes the attack.</p>
*/
export interface AttackVectorDescription {
/**
* <p>The attack type. Valid values:</p>
* <ul>
* <li>
* <p>UDP_TRAFFIC</p>
* </li>
* <li>
* <p>UDP_FRAGMENT</p>
* </li>
* <li>
* <p>GENERIC_UDP_REFLECTION</p>
* </li>
* <li>
* <p>DNS_REFLECTION</p>
* </li>
* <li>
* <p>NTP_REFLECTION</p>
* </li>
* <li>
* <p>CHARGEN_REFLECTION</p>
* </li>
* <li>
* <p>SSDP_REFLECTION</p>
* </li>
* <li>
* <p>PORT_MAPPER</p>
* </li>
* <li>
* <p>RIP_REFLECTION</p>
* </li>
* <li>
* <p>SNMP_REFLECTION</p>
* </li>
* <li>
* <p>MSSQL_REFLECTION</p>
* </li>
* <li>
* <p>NET_BIOS_REFLECTION</p>
* </li>
* <li>
* <p>SYN_FLOOD</p>
* </li>
* <li>
* <p>ACK_FLOOD</p>
* </li>
* <li>
* <p>REQUEST_FLOOD</p>
* </li>
* <li>
* <p>HTTP_REFLECTION</p>
* </li>
* <li>
* <p>UDS_REFLECTION</p>
* </li>
* <li>
* <p>MEMCACHED_REFLECTION</p>
* </li>
* </ul>
*/
VectorType: string | undefined;
}
export namespace AttackVectorDescription {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackVectorDescription): any => ({
...obj,
});
}
/**
* <p>Summarizes all DDoS attacks for a specified time period.</p>
*/
export interface AttackSummary {
/**
* <p>The unique identifier (ID) of the attack.</p>
*/
AttackId?: string;
/**
* <p>The ARN (Amazon Resource Name) of the resource that was attacked.</p>
*/
ResourceArn?: string;
/**
* <p>The start time of the attack, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
StartTime?: Date;
/**
* <p>The end time of the attack, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
EndTime?: Date;
/**
* <p>The list of attacks for a specified time period.</p>
*/
AttackVectors?: AttackVectorDescription[];
}
export namespace AttackSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AttackSummary): any => ({
...obj,
});
}
export enum AutoRenew {
DISABLED = "DISABLED",
ENABLED = "ENABLED",
}
/**
* <p>A tag associated with an Amazon Web Services resource. Tags are key:value pairs that you can use to categorize and manage your resources, for purposes like billing or other management. Typically, the tag key represents a category, such as "environment", and the tag value represents a specific value within that category, such as "test," "development," or "production". Or you might set the tag key to "customer" and the value to the customer name or ID. You can specify one or more tags to add to each Amazon Web Services resource, up to 50 tags for a resource.</p>
*/
export interface Tag {
/**
* <p>Part of the key:value pair that defines a tag. You can use a tag key to describe a category of information, such as "customer." Tag keys are case-sensitive.</p>
*/
Key?: string;
/**
* <p>Part of the key:value pair that defines a tag. You can use a tag value to describe a specific value within a category, such as "companyA" or "companyB." Tag values are case-sensitive.</p>
*/
Value?: string;
}
export namespace Tag {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Tag): any => ({
...obj,
});
}
export interface CreateProtectionRequest {
/**
* <p>Friendly name for the <code>Protection</code> you are creating.</p>
*/
Name: string | undefined;
/**
* <p>The ARN (Amazon Resource Name) of the resource to be protected.</p>
* <p>The ARN should be in one of the following formats:</p>
* <ul>
* <li>
* <p>For an Application Load Balancer: <code>arn:aws:elasticloadbalancing:<i>region</i>:<i>account-id</i>:loadbalancer/app/<i>load-balancer-name</i>/<i>load-balancer-id</i>
* </code>
* </p>
* </li>
* <li>
* <p>For an Elastic Load Balancer (Classic Load Balancer): <code>arn:aws:elasticloadbalancing:<i>region</i>:<i>account-id</i>:loadbalancer/<i>load-balancer-name</i>
* </code>
* </p>
* </li>
* <li>
* <p>For an Amazon CloudFront distribution: <code>arn:aws:cloudfront::<i>account-id</i>:distribution/<i>distribution-id</i>
* </code>
* </p>
* </li>
* <li>
* <p>For an Global Accelerator accelerator: <code>arn:aws:globalaccelerator::<i>account-id</i>:accelerator/<i>accelerator-id</i>
* </code>
* </p>
* </li>
* <li>
* <p>For Amazon Route 53: <code>arn:aws:route53:::hostedzone/<i>hosted-zone-id</i>
* </code>
* </p>
* </li>
* <li>
* <p>For an Elastic IP address: <code>arn:aws:ec2:<i>region</i>:<i>account-id</i>:eip-allocation/<i>allocation-id</i>
* </code>
* </p>
* </li>
* </ul>
*/
ResourceArn: string | undefined;
/**
* <p>One or more tag key-value pairs for the <a>Protection</a> object that is created.</p>
*/
Tags?: Tag[];
}
export namespace CreateProtectionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateProtectionRequest): any => ({
...obj,
});
}
export interface CreateProtectionResponse {
/**
* <p>The unique identifier (ID) for the <a>Protection</a> object that is created.</p>
*/
ProtectionId?: string;
}
export namespace CreateProtectionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateProtectionResponse): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that the resource is invalid. You might not have access to the resource, or the resource might not exist.</p>
*/
export interface InvalidResourceException extends __SmithyException, $MetadataBearer {
name: "InvalidResourceException";
$fault: "client";
message?: string;
}
export namespace InvalidResourceException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidResourceException): any => ({
...obj,
});
}
/**
* <p>Exception indicating the specified resource already exists. If available, this exception includes details in additional properties. </p>
*/
export interface ResourceAlreadyExistsException extends __SmithyException, $MetadataBearer {
name: "ResourceAlreadyExistsException";
$fault: "client";
message?: string;
/**
* <p>The type of resource that already exists.</p>
*/
resourceType?: string;
}
export namespace ResourceAlreadyExistsException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceAlreadyExistsException): any => ({
...obj,
});
}
export enum ProtectionGroupAggregation {
MAX = "MAX",
MEAN = "MEAN",
SUM = "SUM",
}
export enum ProtectionGroupPattern {
ALL = "ALL",
ARBITRARY = "ARBITRARY",
BY_RESOURCE_TYPE = "BY_RESOURCE_TYPE",
}
export enum ProtectedResourceType {
APPLICATION_LOAD_BALANCER = "APPLICATION_LOAD_BALANCER",
CLASSIC_LOAD_BALANCER = "CLASSIC_LOAD_BALANCER",
CLOUDFRONT_DISTRIBUTION = "CLOUDFRONT_DISTRIBUTION",
ELASTIC_IP_ALLOCATION = "ELASTIC_IP_ALLOCATION",
GLOBAL_ACCELERATOR = "GLOBAL_ACCELERATOR",
ROUTE_53_HOSTED_ZONE = "ROUTE_53_HOSTED_ZONE",
}
export interface CreateProtectionGroupRequest {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
/**
* <p>Defines how Shield combines resource data for the group in order to detect, mitigate, and report events.</p>
* <ul>
* <li>
* <p>Sum - Use the total traffic across the group. This is a good choice for most cases. Examples include Elastic IP addresses for EC2 instances that scale manually or automatically.</p>
* </li>
* <li>
* <p>Mean - Use the average of the traffic across the group. This is a good choice for resources that share traffic uniformly. Examples include accelerators and load balancers.</p>
* </li>
* <li>
* <p>Max - Use the highest traffic from each resource. This is useful for resources that don't share traffic and for resources that share that traffic in a non-uniform way. Examples include Amazon CloudFront and origin resources for CloudFront distributions.</p>
* </li>
* </ul>
*/
Aggregation: ProtectionGroupAggregation | string | undefined;
/**
* <p>The criteria to use to choose the protected resources for inclusion in the group. You can include all resources that have protections, provide a list of resource Amazon Resource Names (ARNs), or include all resources of a specified resource type. </p>
*/
Pattern: ProtectionGroupPattern | string | undefined;
/**
* <p>The resource type to include in the protection group. All protected resources of this type are included in the protection group. Newly protected resources of this type are automatically added to the group.
* You must set this when you set <code>Pattern</code> to <code>BY_RESOURCE_TYPE</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
ResourceType?: ProtectedResourceType | string;
/**
* <p>The Amazon Resource Names (ARNs) of the resources to include in the protection group. You must set this when you set <code>Pattern</code> to <code>ARBITRARY</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
Members?: string[];
/**
* <p>One or more tag key-value pairs for the protection group.</p>
*/
Tags?: Tag[];
}
export namespace CreateProtectionGroupRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateProtectionGroupRequest): any => ({
...obj,
});
}
export interface CreateProtectionGroupResponse {}
export namespace CreateProtectionGroupResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateProtectionGroupResponse): any => ({
...obj,
});
}
export interface CreateSubscriptionRequest {}
export namespace CreateSubscriptionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateSubscriptionRequest): any => ({
...obj,
});
}
export interface CreateSubscriptionResponse {}
export namespace CreateSubscriptionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateSubscriptionResponse): any => ({
...obj,
});
}
export interface DeleteProtectionRequest {
/**
* <p>The unique identifier (ID) for the <a>Protection</a> object to be
* deleted.</p>
*/
ProtectionId: string | undefined;
}
export namespace DeleteProtectionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteProtectionRequest): any => ({
...obj,
});
}
export interface DeleteProtectionResponse {}
export namespace DeleteProtectionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteProtectionResponse): any => ({
...obj,
});
}
export interface DeleteProtectionGroupRequest {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
}
export namespace DeleteProtectionGroupRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteProtectionGroupRequest): any => ({
...obj,
});
}
export interface DeleteProtectionGroupResponse {}
export namespace DeleteProtectionGroupResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteProtectionGroupResponse): any => ({
...obj,
});
}
export interface DeleteSubscriptionRequest {}
export namespace DeleteSubscriptionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteSubscriptionRequest): any => ({
...obj,
});
}
export interface DeleteSubscriptionResponse {}
export namespace DeleteSubscriptionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteSubscriptionResponse): any => ({
...obj,
});
}
/**
* <p>You are trying to update a subscription that has not yet completed the 1-year commitment. You can change the <code>AutoRenew</code> parameter during the last 30 days of your subscription. This exception indicates that you are attempting to change <code>AutoRenew</code> prior to that period.</p>
*/
export interface LockedSubscriptionException extends __SmithyException, $MetadataBearer {
name: "LockedSubscriptionException";
$fault: "client";
message?: string;
}
export namespace LockedSubscriptionException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: LockedSubscriptionException): any => ({
...obj,
});
}
export interface DescribeAttackRequest {
/**
* <p>The unique identifier (ID) for the attack that to be described.</p>
*/
AttackId: string | undefined;
}
export namespace DescribeAttackRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeAttackRequest): any => ({
...obj,
});
}
export interface DescribeAttackResponse {
/**
* <p>The attack that is described.</p>
*/
Attack?: AttackDetail;
}
export namespace DescribeAttackResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeAttackResponse): any => ({
...obj,
});
}
export interface DescribeAttackStatisticsRequest {}
export namespace DescribeAttackStatisticsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeAttackStatisticsRequest): any => ({
...obj,
});
}
/**
* <p>The time range. </p>
*/
export interface TimeRange {
/**
* <p>The start time, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
FromInclusive?: Date;
/**
* <p>The end time, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
ToExclusive?: Date;
}
export namespace TimeRange {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TimeRange): any => ({
...obj,
});
}
export interface DescribeAttackStatisticsResponse {
/**
* <p>The time range. </p>
*/
TimeRange: TimeRange | undefined;
/**
* <p>The data that describes the attacks detected during the time period.</p>
*/
DataItems: AttackStatisticsDataItem[] | undefined;
}
export namespace DescribeAttackStatisticsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeAttackStatisticsResponse): any => ({
...obj,
});
}
export interface DescribeDRTAccessRequest {}
export namespace DescribeDRTAccessRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDRTAccessRequest): any => ({
...obj,
});
}
export interface DescribeDRTAccessResponse {
/**
* <p>The Amazon Resource Name (ARN) of the role the SRT used to access your Amazon Web Services account.</p>
*/
RoleArn?: string;
/**
* <p>The list of Amazon S3 buckets accessed by the SRT.</p>
*/
LogBucketList?: string[];
}
export namespace DescribeDRTAccessResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDRTAccessResponse): any => ({
...obj,
});
}
export interface DescribeEmergencyContactSettingsRequest {}
export namespace DescribeEmergencyContactSettingsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeEmergencyContactSettingsRequest): any => ({
...obj,
});
}
export interface DescribeEmergencyContactSettingsResponse {
/**
* <p>A list of email addresses and phone numbers that the Shield Response Team (SRT) can use to contact you if you have proactive engagement enabled, for escalations to the SRT and to initiate proactive customer support.</p>
*/
EmergencyContactList?: EmergencyContact[];
}
export namespace DescribeEmergencyContactSettingsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeEmergencyContactSettingsResponse): any => ({
...obj,
});
}
export interface DescribeProtectionRequest {
/**
* <p>The unique identifier (ID) for the <a>Protection</a> object that is
* described. When submitting the <code>DescribeProtection</code> request you must provide either the <code>ResourceArn</code> or the <code>ProtectionID</code>, but not both.</p>
*/
ProtectionId?: string;
/**
* <p>The ARN (Amazon Resource Name) of the Amazon Web Services resource for the <a>Protection</a> object that is
* described. When submitting the <code>DescribeProtection</code> request you must provide either the <code>ResourceArn</code> or the <code>ProtectionID</code>, but not both.</p>
*/
ResourceArn?: string;
}
export namespace DescribeProtectionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeProtectionRequest): any => ({
...obj,
});
}
/**
* <p>An object that represents a resource that is under DDoS protection.</p>
*/
export interface Protection {
/**
* <p>The unique identifier (ID) of the protection.</p>
*/
Id?: string;
/**
* <p>The name of the protection. For example, <code>My CloudFront distributions</code>.</p>
*/
Name?: string;
/**
* <p>The ARN (Amazon Resource Name) of the Amazon Web Services resource that is protected.</p>
*/
ResourceArn?: string;
/**
* <p>The unique identifier (ID) for the Route 53 health check that's associated with the protection. </p>
*/
HealthCheckIds?: string[];
/**
* <p>The ARN (Amazon Resource Name) of the protection.</p>
*/
ProtectionArn?: string;
}
export namespace Protection {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Protection): any => ({
...obj,
});
}
export interface DescribeProtectionResponse {
/**
* <p>The <a>Protection</a> object that is described.</p>
*/
Protection?: Protection;
}
export namespace DescribeProtectionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeProtectionResponse): any => ({
...obj,
});
}
export interface DescribeProtectionGroupRequest {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
}
export namespace DescribeProtectionGroupRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeProtectionGroupRequest): any => ({
...obj,
});
}
/**
* <p>A grouping of protected resources that you and Shield Advanced can monitor as a collective. This resource grouping improves the accuracy of detection and reduces false positives. </p>
*/
export interface ProtectionGroup {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
/**
* <p>Defines how Shield combines resource data for the group in order to detect, mitigate, and report events.</p>
* <ul>
* <li>
* <p>Sum - Use the total traffic across the group. This is a good choice for most cases. Examples include Elastic IP addresses for EC2 instances that scale manually or automatically.</p>
* </li>
* <li>
* <p>Mean - Use the average of the traffic across the group. This is a good choice for resources that share traffic uniformly. Examples include accelerators and load balancers.</p>
* </li>
* <li>
* <p>Max - Use the highest traffic from each resource. This is useful for resources that don't share traffic and for resources that share that traffic in a non-uniform way. Examples include Amazon CloudFront distributions and origin resources for CloudFront distributions.</p>
* </li>
* </ul>
*/
Aggregation: ProtectionGroupAggregation | string | undefined;
/**
* <p>The criteria to use to choose the protected resources for inclusion in the group. You can include all resources that have protections, provide a list of resource Amazon Resource Names (ARNs), or include all resources of a specified resource type.</p>
*/
Pattern: ProtectionGroupPattern | string | undefined;
/**
* <p>The resource type to include in the protection group. All protected resources of this type are included in the protection group.
* You must set this when you set <code>Pattern</code> to <code>BY_RESOURCE_TYPE</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
ResourceType?: ProtectedResourceType | string;
/**
* <p>The Amazon Resource Names (ARNs) of the resources to include in the protection group. You must set this when you set <code>Pattern</code> to <code>ARBITRARY</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
Members: string[] | undefined;
/**
* <p>The ARN (Amazon Resource Name) of the protection group.</p>
*/
ProtectionGroupArn?: string;
}
export namespace ProtectionGroup {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProtectionGroup): any => ({
...obj,
});
}
export interface DescribeProtectionGroupResponse {
/**
* <p>A grouping of protected resources that you and Shield Advanced can monitor as a collective. This resource grouping improves the accuracy of detection and reduces false positives. </p>
*/
ProtectionGroup: ProtectionGroup | undefined;
}
export namespace DescribeProtectionGroupResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeProtectionGroupResponse): any => ({
...obj,
});
}
export interface DescribeSubscriptionRequest {}
export namespace DescribeSubscriptionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeSubscriptionRequest): any => ({
...obj,
});
}
/**
* <p>Specifies how many protections of a given type you can create.</p>
*/
export interface Limit {
/**
* <p>The type of protection.</p>
*/
Type?: string;
/**
* <p>The maximum number of protections that can be created for the specified <code>Type</code>.</p>
*/
Max?: number;
}
export namespace Limit {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Limit): any => ({
...obj,
});
}
export enum ProactiveEngagementStatus {
DISABLED = "DISABLED",
ENABLED = "ENABLED",
PENDING = "PENDING",
}
/**
* <p>Limits settings on protection groups with arbitrary pattern type. </p>
*/
export interface ProtectionGroupArbitraryPatternLimits {
/**
* <p>The maximum number of resources you can specify for a single arbitrary pattern in a protection group.</p>
*/
MaxMembers: number | undefined;
}
export namespace ProtectionGroupArbitraryPatternLimits {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProtectionGroupArbitraryPatternLimits): any => ({
...obj,
});
}
/**
* <p>Limits settings by pattern type in the protection groups for your subscription. </p>
*/
export interface ProtectionGroupPatternTypeLimits {
/**
* <p>Limits settings on protection groups with arbitrary pattern type. </p>
*/
ArbitraryPatternLimits: ProtectionGroupArbitraryPatternLimits | undefined;
}
export namespace ProtectionGroupPatternTypeLimits {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProtectionGroupPatternTypeLimits): any => ({
...obj,
});
}
/**
* <p>Limits settings on protection groups for your subscription. </p>
*/
export interface ProtectionGroupLimits {
/**
* <p>The maximum number of protection groups that you can have at one time. </p>
*/
MaxProtectionGroups: number | undefined;
/**
* <p>Limits settings by pattern type in the protection groups for your subscription. </p>
*/
PatternTypeLimits: ProtectionGroupPatternTypeLimits | undefined;
}
export namespace ProtectionGroupLimits {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProtectionGroupLimits): any => ({
...obj,
});
}
/**
* <p>Limits settings on protections for your subscription. </p>
*/
export interface ProtectionLimits {
/**
* <p>The maximum number of resource types that you can specify in a protection.</p>
*/
ProtectedResourceTypeLimits: Limit[] | undefined;
}
export namespace ProtectionLimits {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ProtectionLimits): any => ({
...obj,
});
}
/**
* <p>Limits settings for your subscription. </p>
*/
export interface SubscriptionLimits {
/**
* <p>Limits settings on protections for your subscription. </p>
*/
ProtectionLimits: ProtectionLimits | undefined;
/**
* <p>Limits settings on protection groups for your subscription. </p>
*/
ProtectionGroupLimits: ProtectionGroupLimits | undefined;
}
export namespace SubscriptionLimits {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SubscriptionLimits): any => ({
...obj,
});
}
/**
* <p>Information about the Shield Advanced subscription for an account.</p>
*/
export interface Subscription {
/**
* <p>The start time of the subscription, in Unix time in seconds. For more information see <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp</a>.</p>
*/
StartTime?: Date;
/**
* <p>The date and time your subscription will end.</p>
*/
EndTime?: Date;
/**
* <p>The length, in seconds, of the Shield Advanced subscription for the account.</p>
*/
TimeCommitmentInSeconds?: number;
/**
* <p>If <code>ENABLED</code>, the subscription will be automatically renewed at the end of the existing subscription period.</p>
* <p>When you initally create a subscription, <code>AutoRenew</code> is set to <code>ENABLED</code>. You can change this by submitting an <code>UpdateSubscription</code> request. If the <code>UpdateSubscription</code> request does not included a value for <code>AutoRenew</code>, the existing value for <code>AutoRenew</code> remains unchanged.</p>
*/
AutoRenew?: AutoRenew | string;
/**
* <p>Specifies how many protections of a given type you can create.</p>
*/
Limits?: Limit[];
/**
* <p>If <code>ENABLED</code>, the Shield Response Team (SRT) will use email and phone to notify contacts about escalations to the SRT and to initiate proactive customer support.</p>
* <p>If <code>PENDING</code>, you have requested proactive engagement and the request is pending. The status changes to <code>ENABLED</code> when your request is fully processed.</p>
* <p>If <code>DISABLED</code>, the SRT will not proactively notify contacts about escalations or to initiate proactive customer support. </p>
*/
ProactiveEngagementStatus?: ProactiveEngagementStatus | string;
/**
* <p>Limits settings for your subscription. </p>
*/
SubscriptionLimits: SubscriptionLimits | undefined;
/**
* <p>The ARN (Amazon Resource Name) of the subscription.</p>
*/
SubscriptionArn?: string;
}
export namespace Subscription {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Subscription): any => ({
...obj,
});
}
export interface DescribeSubscriptionResponse {
/**
* <p>The Shield Advanced subscription details for an account.</p>
*/
Subscription?: Subscription;
}
export namespace DescribeSubscriptionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeSubscriptionResponse): any => ({
...obj,
});
}
export interface DisableProactiveEngagementRequest {}
export namespace DisableProactiveEngagementRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisableProactiveEngagementRequest): any => ({
...obj,
});
}
export interface DisableProactiveEngagementResponse {}
export namespace DisableProactiveEngagementResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisableProactiveEngagementResponse): any => ({
...obj,
});
}
export interface DisassociateDRTLogBucketRequest {
/**
* <p>The Amazon S3 bucket that contains the logs that you want to share.</p>
*/
LogBucket: string | undefined;
}
export namespace DisassociateDRTLogBucketRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateDRTLogBucketRequest): any => ({
...obj,
});
}
export interface DisassociateDRTLogBucketResponse {}
export namespace DisassociateDRTLogBucketResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateDRTLogBucketResponse): any => ({
...obj,
});
}
export interface DisassociateDRTRoleRequest {}
export namespace DisassociateDRTRoleRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateDRTRoleRequest): any => ({
...obj,
});
}
export interface DisassociateDRTRoleResponse {}
export namespace DisassociateDRTRoleResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateDRTRoleResponse): any => ({
...obj,
});
}
export interface DisassociateHealthCheckRequest {
/**
* <p>The unique identifier (ID) for the <a>Protection</a> object to remove the health check association from. </p>
*/
ProtectionId: string | undefined;
/**
* <p>The Amazon Resource Name (ARN) of the health check that is associated with the protection.</p>
*/
HealthCheckArn: string | undefined;
}
export namespace DisassociateHealthCheckRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateHealthCheckRequest): any => ({
...obj,
});
}
export interface DisassociateHealthCheckResponse {}
export namespace DisassociateHealthCheckResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DisassociateHealthCheckResponse): any => ({
...obj,
});
}
export interface EnableProactiveEngagementRequest {}
export namespace EnableProactiveEngagementRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EnableProactiveEngagementRequest): any => ({
...obj,
});
}
export interface EnableProactiveEngagementResponse {}
export namespace EnableProactiveEngagementResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EnableProactiveEngagementResponse): any => ({
...obj,
});
}
export interface GetSubscriptionStateRequest {}
export namespace GetSubscriptionStateRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSubscriptionStateRequest): any => ({
...obj,
});
}
export enum SubscriptionState {
ACTIVE = "ACTIVE",
INACTIVE = "INACTIVE",
}
export interface GetSubscriptionStateResponse {
/**
* <p>The status of the subscription.</p>
*/
SubscriptionState: SubscriptionState | string | undefined;
}
export namespace GetSubscriptionStateResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetSubscriptionStateResponse): any => ({
...obj,
});
}
export interface ListAttacksRequest {
/**
* <p>The ARN (Amazon Resource Name) of the resource that was attacked. If this is left
* blank, all applicable resources for this account will be included.</p>
*/
ResourceArns?: string[];
/**
* <p>The start of the time period for the attacks. This is a <code>timestamp</code> type. The sample request above indicates a <code>number</code> type because the default used by WAF is Unix time in seconds. However any valid <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp format</a> is allowed. </p>
*/
StartTime?: TimeRange;
/**
* <p>The end of the time period for the attacks. This is a <code>timestamp</code> type. The sample request above indicates a <code>number</code> type because the default used by WAF is Unix time in seconds. However any valid <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#parameter-types">timestamp format</a> is allowed. </p>
*/
EndTime?: TimeRange;
/**
* <p>The <code>ListAttacksRequest.NextMarker</code> value from a previous call to <code>ListAttacksRequest</code>. Pass null if this is the first call.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of <a>AttackSummary</a> objects to return. If you leave this blank,
* Shield Advanced returns the first 20 results.</p>
* <p>This is a maximum value. Shield Advanced might return the results in smaller batches. That is, the number of objects returned could be less than <code>MaxResults</code>, even if there are still more objects yet to return. If there are more objects to return, Shield Advanced returns a value in <code>NextToken</code> that you can use in your next request, to get the next batch of objects.</p>
*/
MaxResults?: number;
}
export namespace ListAttacksRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListAttacksRequest): any => ({
...obj,
});
}
export interface ListAttacksResponse {
/**
* <p>The attack information for the specified time range.</p>
*/
AttackSummaries?: AttackSummary[];
/**
* <p>The token returned by a previous call to indicate that there is more data available.
* If not null, more results are available. Pass this value for the <code>NextMarker</code>
* parameter in a subsequent call to <code>ListAttacks</code> to retrieve the next set of
* items.</p>
* <p>Shield Advanced might return the list of <a>AttackSummary</a> objects in batches smaller than the number specified by MaxResults. If there are more attack summary objects to return, Shield Advanced will always also return a <code>NextToken</code>.</p>
*/
NextToken?: string;
}
export namespace ListAttacksResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListAttacksResponse): any => ({
...obj,
});
}
/**
* <p>Exception that indicates that the NextToken specified in the request is invalid. Submit the request using the NextToken value that was returned in the response.</p>
*/
export interface InvalidPaginationTokenException extends __SmithyException, $MetadataBearer {
name: "InvalidPaginationTokenException";
$fault: "client";
message?: string;
}
export namespace InvalidPaginationTokenException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InvalidPaginationTokenException): any => ({
...obj,
});
}
export interface ListProtectionGroupsRequest {
/**
* <p>The next token value from a previous call to <code>ListProtectionGroups</code>. Pass null if this is the first call.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of <a>ProtectionGroup</a> objects to return. If you leave this blank,
* Shield Advanced returns the first 20 results.</p>
* <p>This is a maximum value. Shield Advanced might return the results in smaller batches. That is, the number of objects returned could be less than <code>MaxResults</code>, even if there are still more objects yet to return. If there are more objects to return, Shield Advanced returns a value in <code>NextToken</code> that you can use in your next request, to get the next batch of objects.</p>
*/
MaxResults?: number;
}
export namespace ListProtectionGroupsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListProtectionGroupsRequest): any => ({
...obj,
});
}
export interface ListProtectionGroupsResponse {
/**
* <p></p>
*/
ProtectionGroups: ProtectionGroup[] | undefined;
/**
* <p>If you specify a value for <code>MaxResults</code> and you have more protection groups than the value of MaxResults, Shield Advanced returns this token that you can use in your next request, to get the next batch of objects. </p>
*/
NextToken?: string;
}
export namespace ListProtectionGroupsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListProtectionGroupsResponse): any => ({
...obj,
});
}
export interface ListProtectionsRequest {
/**
* <p>The <code>ListProtectionsRequest.NextToken</code> value from a previous call to <code>ListProtections</code>. Pass null if this is the first call.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of <a>Protection</a> objects to return. If you leave this blank,
* Shield Advanced returns the first 20 results.</p>
* <p>This is a maximum value. Shield Advanced might return the results in smaller batches. That is, the number of objects returned could be less than <code>MaxResults</code>, even if there are still more objects yet to return. If there are more objects to return, Shield Advanced returns a value in <code>NextToken</code> that you can use in your next request, to get the next batch of objects.</p>
*/
MaxResults?: number;
}
export namespace ListProtectionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListProtectionsRequest): any => ({
...obj,
});
}
export interface ListProtectionsResponse {
/**
* <p>The array of enabled <a>Protection</a> objects.</p>
*/
Protections?: Protection[];
/**
* <p>If you specify a value for <code>MaxResults</code> and you have more Protections than the value of MaxResults, Shield Advanced returns a NextToken value in the response that allows you to list another group of Protections. For the second and subsequent ListProtections requests, specify the value of NextToken from the previous response to get information about another batch of Protections.</p>
* <p>Shield Advanced might return the list of <a>Protection</a> objects in batches smaller than the number specified by MaxResults. If there are more <a>Protection</a> objects to return, Shield Advanced will always also return a <code>NextToken</code>.</p>
*/
NextToken?: string;
}
export namespace ListProtectionsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListProtectionsResponse): any => ({
...obj,
});
}
export interface ListResourcesInProtectionGroupRequest {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
/**
* <p>The next token value from a previous call to <code>ListResourcesInProtectionGroup</code>. Pass null if this is the first call.</p>
*/
NextToken?: string;
/**
* <p>The maximum number of resource ARN objects to return. If you leave this blank,
* Shield Advanced returns the first 20 results.</p>
* <p>This is a maximum value. Shield Advanced might return the results in smaller batches. That is, the number of objects returned could be less than <code>MaxResults</code>, even if there are still more objects yet to return. If there are more objects to return, Shield Advanced returns a value in <code>NextToken</code> that you can use in your next request, to get the next batch of objects.</p>
*/
MaxResults?: number;
}
export namespace ListResourcesInProtectionGroupRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourcesInProtectionGroupRequest): any => ({
...obj,
});
}
export interface ListResourcesInProtectionGroupResponse {
/**
* <p>The Amazon Resource Names (ARNs) of the resources that are included in the protection group.</p>
*/
ResourceArns: string[] | undefined;
/**
* <p>If you specify a value for <code>MaxResults</code> and you have more resources in the protection group than the value of MaxResults, Shield Advanced returns this token that you can use in your next request, to get the next batch of objects. </p>
*/
NextToken?: string;
}
export namespace ListResourcesInProtectionGroupResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListResourcesInProtectionGroupResponse): any => ({
...obj,
});
}
export interface ListTagsForResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource to get tags for.</p>
*/
ResourceARN: string | undefined;
}
export namespace ListTagsForResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({
...obj,
});
}
export interface ListTagsForResourceResponse {
/**
* <p>A list of tag key and value pairs associated with the specified resource.</p>
*/
Tags?: Tag[];
}
export namespace ListTagsForResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({
...obj,
});
}
export interface TagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource that you want to add or update tags for.</p>
*/
ResourceARN: string | undefined;
/**
* <p>The tags that you want to modify or add to the resource.</p>
*/
Tags: Tag[] | undefined;
}
export namespace TagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceRequest): any => ({
...obj,
});
}
export interface TagResourceResponse {}
export namespace TagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceResponse): any => ({
...obj,
});
}
export interface UntagResourceRequest {
/**
* <p>The Amazon Resource Name (ARN) of the resource that you want to remove tags from.</p>
*/
ResourceARN: string | undefined;
/**
* <p>The tag key for each tag that you want to remove from the resource.</p>
*/
TagKeys: string[] | undefined;
}
export namespace UntagResourceRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({
...obj,
});
}
export interface UntagResourceResponse {}
export namespace UntagResourceResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({
...obj,
});
}
export interface UpdateEmergencyContactSettingsRequest {
/**
* <p>A list of email addresses and phone numbers that the Shield Response Team (SRT) can use to contact you if you have proactive engagement enabled, for escalations to the SRT and to initiate proactive customer support.</p>
* <p>If you have proactive engagement enabled, the contact list must include at least one phone number.</p>
*/
EmergencyContactList?: EmergencyContact[];
}
export namespace UpdateEmergencyContactSettingsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateEmergencyContactSettingsRequest): any => ({
...obj,
});
}
export interface UpdateEmergencyContactSettingsResponse {}
export namespace UpdateEmergencyContactSettingsResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateEmergencyContactSettingsResponse): any => ({
...obj,
});
}
export interface UpdateProtectionGroupRequest {
/**
* <p>The name of the protection group. You use this to identify the protection group in lists and to manage the protection group, for example to update, delete, or describe it. </p>
*/
ProtectionGroupId: string | undefined;
/**
* <p>Defines how Shield combines resource data for the group in order to detect, mitigate, and report events.</p>
* <ul>
* <li>
* <p>Sum - Use the total traffic across the group. This is a good choice for most cases. Examples include Elastic IP addresses for EC2 instances that scale manually or automatically.</p>
* </li>
* <li>
* <p>Mean - Use the average of the traffic across the group. This is a good choice for resources that share traffic uniformly. Examples include accelerators and load balancers.</p>
* </li>
* <li>
* <p>Max - Use the highest traffic from each resource. This is useful for resources that don't share traffic and for resources that share that traffic in a non-uniform way. Examples include Amazon CloudFront distributions and origin resources for CloudFront distributions.</p>
* </li>
* </ul>
*/
Aggregation: ProtectionGroupAggregation | string | undefined;
/**
* <p>The criteria to use to choose the protected resources for inclusion in the group. You can include all resources that have protections, provide a list of resource Amazon Resource Names (ARNs), or include all resources of a specified resource type.</p>
*/
Pattern: ProtectionGroupPattern | string | undefined;
/**
* <p>The resource type to include in the protection group. All protected resources of this type are included in the protection group.
* You must set this when you set <code>Pattern</code> to <code>BY_RESOURCE_TYPE</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
ResourceType?: ProtectedResourceType | string;
/**
* <p>The Amazon Resource Names (ARNs) of the resources to include in the protection group. You must set this when you set <code>Pattern</code> to <code>ARBITRARY</code> and you must not set it for any other <code>Pattern</code> setting. </p>
*/
Members?: string[];
}
export namespace UpdateProtectionGroupRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateProtectionGroupRequest): any => ({
...obj,
});
}
export interface UpdateProtectionGroupResponse {}
export namespace UpdateProtectionGroupResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateProtectionGroupResponse): any => ({
...obj,
});
}
export interface UpdateSubscriptionRequest {
/**
* <p>When you initally create a subscription, <code>AutoRenew</code> is set to <code>ENABLED</code>. If <code>ENABLED</code>, the subscription will be automatically renewed at the end of the existing subscription period. You can change this by submitting an <code>UpdateSubscription</code> request. If the <code>UpdateSubscription</code> request does not included a value for <code>AutoRenew</code>, the existing value for <code>AutoRenew</code> remains unchanged.</p>
*/
AutoRenew?: AutoRenew | string;
}
export namespace UpdateSubscriptionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSubscriptionRequest): any => ({
...obj,
});
}
export interface UpdateSubscriptionResponse {}
export namespace UpdateSubscriptionResponse {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateSubscriptionResponse): any => ({
...obj,
});
} | the_stack |
import * as React from 'react'
import { Commit } from '../../models/commit'
import { lookupPreferredEmail } from '../../lib/email'
import {
getGlobalConfigValue,
setGlobalConfigValue,
} from '../../lib/git/config'
import { CommitListItem } from '../history/commit-list-item'
import { Account } from '../../models/account'
import { CommitIdentity } from '../../models/commit-identity'
import { Form } from '../lib/form'
import { Button } from '../lib/button'
import { TextBox } from '../lib/text-box'
import { Row } from '../lib/row'
import {
isConfigFileLockError,
parseConfigLockFilePathFromError,
} from '../../lib/git'
import { ConfigLockFileExists } from './config-lock-file-exists'
import { RadioButton } from './radio-button'
import { Select } from './select'
import { GitEmailNotFoundWarning } from './git-email-not-found-warning'
import { getDotComAPIEndpoint } from '../../lib/api'
interface IConfigureGitUserProps {
/** The logged-in accounts. */
readonly accounts: ReadonlyArray<Account>
/** Called after the user has chosen to save their config. */
readonly onSave?: () => void
/** The label for the button which saves config changes. */
readonly saveLabel?: string
}
interface IConfigureGitUserState {
readonly globalUserName: string | null
readonly globalUserEmail: string | null
readonly manualName: string
readonly manualEmail: string
readonly gitHubName: string
readonly gitHubEmail: string
readonly useGitHubAuthorInfo: boolean
/**
* If unable to save Git configuration values (name, email)
* due to an existing configuration lock file this property
* will contain the (fully qualified) path to said lock file
* such that an error may be presented and the user given a
* choice to delete the lock file.
*/
readonly existingLockFilePath?: string
}
/**
* A component which allows the user to configure their Git user.
*
* Provide `children` elements which will be rendered below the form.
*/
export class ConfigureGitUser extends React.Component<
IConfigureGitUserProps,
IConfigureGitUserState
> {
private readonly globalUsernamePromise = getGlobalConfigValue('user.name')
private readonly globalEmailPromise = getGlobalConfigValue('user.email')
private loadInitialDataPromise: Promise<void> | null = null
public constructor(props: IConfigureGitUserProps) {
super(props)
const account = this.account
this.state = {
globalUserName: null,
globalUserEmail: null,
manualName: '',
manualEmail: '',
useGitHubAuthorInfo: this.account !== null,
gitHubName: account?.name || account?.login || '',
gitHubEmail:
this.account !== null ? lookupPreferredEmail(this.account) : '',
}
}
public async componentDidMount() {
this.loadInitialDataPromise = this.loadInitialData()
}
private async loadInitialData() {
// Capture the current accounts prop because we'll be
// doing a bunch of asynchronous stuff and we can't
// rely on this.props.account to tell us what that prop
// was at mount-time.
const accounts = this.props.accounts
const [globalUserName, globalUserEmail] = await Promise.all([
this.globalUsernamePromise,
this.globalEmailPromise,
])
this.setState(
prevState => ({
globalUserName,
globalUserEmail,
manualName:
prevState.manualName.length === 0
? globalUserName || ''
: prevState.manualName,
manualEmail:
prevState.manualEmail.length === 0
? globalUserEmail || ''
: prevState.manualEmail,
}),
() => {
// Chances are low that we actually have an account at mount-time
// the way things are designed now but in case the app changes around
// us and we do get passed an account at mount time in the future we
// want to make sure that not only was it passed at mount time but also
// that it hasn't been changed since (if it has been then
// componentDidUpdate would be responsible for handling it).
if (accounts === this.props.accounts && accounts.length > 0) {
this.setDefaultValuesFromAccount(accounts[0])
}
}
)
}
public async componentDidUpdate(prevProps: IConfigureGitUserProps) {
if (
this.loadInitialDataPromise !== null &&
this.props.accounts !== prevProps.accounts &&
this.props.accounts.length > 0
) {
if (this.props.accounts[0] !== prevProps.accounts[0]) {
// Wait for the initial data load to finish before updating the state
// with the new account info.
// The problem is we might get the account info before we retrieved the
// global user name and email in `loadInitialData` and updated the state
// with them, so `componentDidUpdate` would get called and override
// whatever the user had in the global git config with the account info.
await this.loadInitialDataPromise
const account = this.props.accounts[0]
this.setDefaultValuesFromAccount(account)
}
}
}
private setDefaultValuesFromAccount(account: Account) {
const preferredEmail = lookupPreferredEmail(account)
this.setState({
useGitHubAuthorInfo: true,
gitHubName: account.name || account.login,
gitHubEmail: preferredEmail,
})
if (this.state.manualName.length === 0) {
this.setState({
manualName: account.name || account.login,
})
}
if (this.state.manualEmail.length === 0) {
this.setState({ manualEmail: preferredEmail })
}
}
private get account(): Account | null {
if (this.props.accounts.length === 0) {
return null
}
return this.props.accounts[0]
}
private dateWithMinuteOffset(date: Date, minuteOffset: number): Date {
const copy = new Date(date.getTime())
copy.setTime(copy.getTime() + minuteOffset * 60 * 1000)
return copy
}
public render() {
const error =
this.state.existingLockFilePath !== undefined ? (
<ConfigLockFileExists
lockFilePath={this.state.existingLockFilePath}
onLockFileDeleted={this.onLockFileDeleted}
onError={this.onLockFileDeleteError}
/>
) : null
return (
<div id="configure-git-user">
{this.renderAuthorOptions()}
{error}
{this.state.useGitHubAuthorInfo
? this.renderGitHubInfo()
: this.renderGitConfigForm()}
{this.renderExampleCommit()}
</div>
)
}
private renderExampleCommit() {
const now = new Date()
let name = this.state.manualName
let email = this.state.manualEmail
if (this.state.useGitHubAuthorInfo) {
name = this.state.gitHubName
email = this.state.gitHubEmail
}
// NB: We're using the name as the commit SHA:
// 1. `Commit` is referentially transparent wrt the SHA. So in order to get
// it to update when we name changes, we need to change the SHA.
// 2. We don't display the SHA so the user won't ever know our secret.
const author = new CommitIdentity(
name,
email,
this.dateWithMinuteOffset(now, -30)
)
const dummyCommit = new Commit(
name,
name.slice(0, 7),
'Fix all the things',
'',
author,
author,
[],
[],
[]
)
const emoji = new Map()
return (
<div id="commit-list" className="commit-list-example">
<div className="header">Example commit</div>
<CommitListItem
commit={dummyCommit}
emoji={emoji}
gitHubRepository={null}
isLocal={false}
showUnpushedIndicator={false}
/>
</div>
)
}
private renderAuthorOptions() {
const account = this.account
if (account === null) {
return
}
const accountTypeSuffix =
account.endpoint === getDotComAPIEndpoint() ? '' : ' Enterprise'
return (
<div>
<RadioButton
label={`Use my GitHub${accountTypeSuffix} account name and email address`}
checked={this.state.useGitHubAuthorInfo}
onSelected={this.onUseGitHubInfoSelected}
value="github-account"
/>
<RadioButton
label="Configure manually"
checked={!this.state.useGitHubAuthorInfo}
onSelected={this.onUseGitConfigInfoSelected}
value="git-config"
/>
</div>
)
}
private renderGitHubInfo() {
if (this.account === null) {
return
}
return (
<Form className="sign-in-form" onSubmit={this.save}>
<TextBox
label="Name"
placeholder="Your Name"
value={this.state.gitHubName}
disabled={true}
/>
<Select
label="Email"
value={this.state.gitHubEmail}
onChange={this.onSelectedGitHubEmailChange}
>
{this.account.emails.map(e => (
<option key={e.email} value={e.email}>
{e.email}
</option>
))}
</Select>
<Row>
<Button type="submit">{this.props.saveLabel || 'Save'}</Button>
{this.props.children}
</Row>
</Form>
)
}
private renderGitConfigForm() {
return (
<Form className="sign-in-form" onSubmit={this.save}>
<TextBox
label="Name"
placeholder="Your Name"
value={this.state.manualName}
onValueChanged={this.onNameChange}
/>
<TextBox
type="email"
label="Email"
placeholder="your-email@example.com"
value={this.state.manualEmail}
onValueChanged={this.onEmailChange}
/>
{this.account !== null && (
<GitEmailNotFoundWarning
accounts={[this.account]}
email={this.state.manualEmail}
/>
)}
<Row>
<Button type="submit">{this.props.saveLabel || 'Save'}</Button>
{this.props.children}
</Row>
</Form>
)
}
private onSelectedGitHubEmailChange = (
event: React.FormEvent<HTMLSelectElement>
) => {
const email = event.currentTarget.value
if (email) {
this.setState({ gitHubEmail: email })
}
}
private onLockFileDeleted = () => {
this.setState({ existingLockFilePath: undefined })
}
private onLockFileDeleteError = (e: Error) => {
log.error('Failed to unlink config lock file', e)
this.setState({ existingLockFilePath: undefined })
}
private onUseGitHubInfoSelected = () => {
this.setState({ useGitHubAuthorInfo: true })
}
private onUseGitConfigInfoSelected = () => {
this.setState({ useGitHubAuthorInfo: false })
}
private onNameChange = (name: string) => {
this.setState({ manualName: name })
}
private onEmailChange = (email: string) => {
this.setState({ manualEmail: email })
}
private save = async () => {
const {
manualName,
manualEmail,
globalUserName,
globalUserEmail,
useGitHubAuthorInfo,
gitHubName,
gitHubEmail,
} = this.state
const name = useGitHubAuthorInfo ? gitHubName : manualName
const email = useGitHubAuthorInfo ? gitHubEmail : manualEmail
try {
if (name.length > 0 && name !== globalUserName) {
await setGlobalConfigValue('user.name', name)
}
if (email.length > 0 && email !== globalUserEmail) {
await setGlobalConfigValue('user.email', email)
}
} catch (e) {
if (isConfigFileLockError(e)) {
const lockFilePath = parseConfigLockFilePathFromError(e.result)
if (lockFilePath !== null) {
this.setState({ existingLockFilePath: lockFilePath })
return
}
}
}
if (this.props.onSave) {
this.props.onSave()
}
}
} | the_stack |
* ---------------------------------------------------------------
* ## THIS FILE WAS GENERATED VIA SWAGGER-TYPESCRIPT-API ##
* ## ##
* ## AUTHOR: acacode ##
* ## SOURCE: https://github.com/acacode/swagger-typescript-api ##
* ---------------------------------------------------------------
*/
export interface User {
id?: number;
username?: string;
posts?: Post[];
}
export interface Post {
id?: number;
title?: string;
content?: string;
user?: User;
}
export interface CreateUser {
username: string | null;
posts?: PostCreateManyWithoutUserInput;
}
export interface UpdateUser {
username?: string | null;
posts?: PostUpdateManyWithoutUserInput;
}
export interface CreatePost {
title: string | null;
content: string | null;
user: UserCreateOneWithoutPostsInput;
}
export interface UpdatePost {
title?: string | null;
content?: string | null;
user?: UserUpdateOneRequiredWithoutPostsInput;
}
export interface PostCreateManyWithoutUserInput {
create?:
| PostCreateWithoutUserInput
| PostCreateWithoutUserInput[]
| (PostCreateWithoutUserInput & PostCreateWithoutUserInput[]);
connect?: PostWhereUniqueInput | PostWhereUniqueInput[] | (PostWhereUniqueInput & PostWhereUniqueInput[]);
connectOrCreate?:
| PostCreateOrConnectWithoutuserInput
| PostCreateOrConnectWithoutuserInput[]
| (PostCreateOrConnectWithoutuserInput & PostCreateOrConnectWithoutuserInput[]);
}
export interface PostCreateWithoutUserInput {
title?: string;
content?: string;
}
export interface PostWhereUniqueInput {
id?: number;
}
export interface PostCreateOrConnectWithoutuserInput {
where?: PostWhereUniqueInput;
create?: PostCreateWithoutUserInput;
}
export interface PostUpdateManyWithoutUserInput {
create?:
| PostCreateWithoutUserInput
| PostCreateWithoutUserInput[]
| (PostCreateWithoutUserInput & PostCreateWithoutUserInput[]);
connect?: PostWhereUniqueInput | PostWhereUniqueInput[] | (PostWhereUniqueInput & PostWhereUniqueInput[]);
set?: PostWhereUniqueInput | PostWhereUniqueInput[] | (PostWhereUniqueInput & PostWhereUniqueInput[]);
disconnect?: PostWhereUniqueInput | PostWhereUniqueInput[] | (PostWhereUniqueInput & PostWhereUniqueInput[]);
delete?: PostWhereUniqueInput | PostWhereUniqueInput[] | (PostWhereUniqueInput & PostWhereUniqueInput[]);
update?:
| PostUpdateWithWhereUniqueWithoutUserInput
| PostUpdateWithWhereUniqueWithoutUserInput[]
| (PostUpdateWithWhereUniqueWithoutUserInput & PostUpdateWithWhereUniqueWithoutUserInput[]);
updateMany?:
| PostUpdateManyWithWhereWithoutUserInput
| PostUpdateManyWithWhereWithoutUserInput[]
| (PostUpdateManyWithWhereWithoutUserInput & PostUpdateManyWithWhereWithoutUserInput[]);
deleteMany?: PostScalarWhereInput | PostScalarWhereInput[] | (PostScalarWhereInput & PostScalarWhereInput[]);
upsert?:
| PostUpsertWithWhereUniqueWithoutUserInput
| PostUpsertWithWhereUniqueWithoutUserInput[]
| (PostUpsertWithWhereUniqueWithoutUserInput & PostUpsertWithWhereUniqueWithoutUserInput[]);
connectOrCreate?:
| PostCreateOrConnectWithoutuserInput
| PostCreateOrConnectWithoutuserInput[]
| (PostCreateOrConnectWithoutuserInput & PostCreateOrConnectWithoutuserInput[]);
}
export interface PostUpdateWithWhereUniqueWithoutUserInput {
where?: PostWhereUniqueInput;
data?: PostUpdateWithoutUserInput;
}
export interface PostUpdateWithoutUserInput {
title?: string | StringFieldUpdateOperationsInput;
content?: string | StringFieldUpdateOperationsInput;
}
export interface StringFieldUpdateOperationsInput {
set?: string;
}
export interface PostUpdateManyWithWhereWithoutUserInput {
where?: PostScalarWhereInput;
data?: PostUpdateManyMutationInput;
}
export interface PostScalarWhereInput {
AND?: PostScalarWhereInput | PostScalarWhereInput[] | (PostScalarWhereInput & PostScalarWhereInput[]);
OR?: PostScalarWhereInput | PostScalarWhereInput[] | (PostScalarWhereInput & PostScalarWhereInput[]);
NOT?: PostScalarWhereInput | PostScalarWhereInput[] | (PostScalarWhereInput & PostScalarWhereInput[]);
id?: IntFilter | number;
title?: StringFilter | string;
content?: StringFilter | string;
userId?: IntFilter | number;
}
export interface IntFilter {
equals?: number;
in?: number[];
notIn?: number[];
lt?: number;
lte?: number;
gt?: number;
gte?: number;
not?: number | NestedIntFilter;
}
export interface NestedIntFilter {
equals?: number;
in?: number[];
notIn?: number[];
lt?: number;
lte?: number;
gt?: number;
gte?: number;
not?: number | NestedIntFilter;
}
export interface StringFilter {
equals?: string;
in?: string[];
notIn?: string[];
lt?: string;
lte?: string;
gt?: string;
gte?: string;
contains?: string;
startsWith?: string;
endsWith?: string;
not?: string | NestedStringFilter;
}
export interface NestedStringFilter {
equals?: string;
in?: string[];
notIn?: string[];
lt?: string;
lte?: string;
gt?: string;
gte?: string;
contains?: string;
startsWith?: string;
endsWith?: string;
not?: string | NestedStringFilter;
}
export interface PostUpdateManyMutationInput {
title?: string | StringFieldUpdateOperationsInput;
content?: string | StringFieldUpdateOperationsInput;
}
export interface PostUpsertWithWhereUniqueWithoutUserInput {
where?: PostWhereUniqueInput;
update?: PostUpdateWithoutUserInput;
create?: PostCreateWithoutUserInput;
}
export interface UserCreateOneWithoutPostsInput {
create?: UserCreateWithoutPostsInput;
connect?: UserWhereUniqueInput;
connectOrCreate?: UserCreateOrConnectWithoutpostsInput;
}
export interface UserCreateWithoutPostsInput {
username?: string;
}
export interface UserWhereUniqueInput {
id?: number;
}
export interface UserCreateOrConnectWithoutpostsInput {
where?: UserWhereUniqueInput;
create?: UserCreateWithoutPostsInput;
}
export interface UserUpdateOneRequiredWithoutPostsInput {
create?: UserCreateWithoutPostsInput;
connect?: UserWhereUniqueInput;
update?: UserUpdateWithoutPostsInput;
upsert?: UserUpsertWithoutPostsInput;
connectOrCreate?: UserCreateOrConnectWithoutpostsInput;
}
export interface UserUpdateWithoutPostsInput {
username?: string | StringFieldUpdateOperationsInput;
}
export interface UserUpsertWithoutPostsInput {
update?: UserUpdateWithoutPostsInput;
create?: UserCreateWithoutPostsInput;
}
export interface PaginationData {
/**
* Total number of elements in the collection
* @min 0
*/
total?: number;
/**
* Total number of pages
* @min 0
*/
pageCount?: number;
/**
* Current page number
* @min 0
*/
page?: number;
}
export interface UserPage {
data?: User[];
pagination?: PaginationData;
}
export interface PostPage {
data?: Post[];
pagination?: PaginationData;
}
export type QueryParamsType = Record<string | number, any>;
export type ResponseFormat = keyof Omit<Body, "body" | "bodyUsed">;
export interface FullRequestParams extends Omit<RequestInit, "body"> {
/** set parameter to `true` for call `securityWorker` for this request */
secure?: boolean;
/** request path */
path: string;
/** content type of request body */
type?: ContentType;
/** query params */
query?: QueryParamsType;
/** format of response (i.e. response.json() -> format: "json") */
format?: ResponseFormat;
/** request body */
body?: unknown;
/** base url */
baseUrl?: string;
/** request cancellation token */
cancelToken?: CancelToken;
}
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
export interface ApiConfig<SecurityDataType = unknown> {
baseUrl?: string;
baseApiParams?: Omit<RequestParams, "baseUrl" | "cancelToken" | "signal">;
securityWorker?: (securityData: SecurityDataType | null) => Promise<RequestParams | void> | RequestParams | void;
customFetch?: typeof fetch;
}
export interface HttpResponse<D extends unknown, E extends unknown = unknown> extends Response {
data: D;
error: E;
}
type CancelToken = Symbol | string | number;
export enum ContentType {
Json = "application/json",
FormData = "multipart/form-data",
UrlEncoded = "application/x-www-form-urlencoded",
}
export class HttpClient<SecurityDataType = unknown> {
public baseUrl: string = "http://localhost:3000/api";
private securityData: SecurityDataType | null = null;
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
private abortControllers = new Map<CancelToken, AbortController>();
private customFetch = (...fetchParams: Parameters<typeof fetch>) => fetch(...fetchParams);
private baseApiParams: RequestParams = {
credentials: "same-origin",
headers: {},
redirect: "follow",
referrerPolicy: "no-referrer",
};
constructor(apiConfig: ApiConfig<SecurityDataType> = {}) {
Object.assign(this, apiConfig);
}
public setSecurityData = (data: SecurityDataType | null) => {
this.securityData = data;
};
private encodeQueryParam(key: string, value: any) {
const encodedKey = encodeURIComponent(key);
return `${encodedKey}=${encodeURIComponent(typeof value === "number" ? value : `${value}`)}`;
}
private addQueryParam(query: QueryParamsType, key: string) {
return this.encodeQueryParam(key, query[key]);
}
private addArrayQueryParam(query: QueryParamsType, key: string) {
const value = query[key];
return value.map((v: any) => this.encodeQueryParam(key, v)).join("&");
}
protected toQueryString(rawQuery?: QueryParamsType): string {
const query = rawQuery || {};
const keys = Object.keys(query).filter((key) => "undefined" !== typeof query[key]);
return keys
.map((key) => (Array.isArray(query[key]) ? this.addArrayQueryParam(query, key) : this.addQueryParam(query, key)))
.join("&");
}
protected addQueryParams(rawQuery?: QueryParamsType): string {
const queryString = this.toQueryString(rawQuery);
return queryString ? `?${queryString}` : "";
}
private contentFormatters: Record<ContentType, (input: any) => any> = {
[ContentType.Json]: (input: any) =>
input !== null && (typeof input === "object" || typeof input === "string") ? JSON.stringify(input) : input,
[ContentType.FormData]: (input: any) =>
Object.keys(input || {}).reduce((formData, key) => {
const property = input[key];
formData.append(
key,
property instanceof Blob
? property
: typeof property === "object" && property !== null
? JSON.stringify(property)
: `${property}`,
);
return formData;
}, new FormData()),
[ContentType.UrlEncoded]: (input: any) => this.toQueryString(input),
};
private mergeRequestParams(params1: RequestParams, params2?: RequestParams): RequestParams {
return {
...this.baseApiParams,
...params1,
...(params2 || {}),
headers: {
...(this.baseApiParams.headers || {}),
...(params1.headers || {}),
...((params2 && params2.headers) || {}),
},
};
}
private createAbortSignal = (cancelToken: CancelToken): AbortSignal | undefined => {
if (this.abortControllers.has(cancelToken)) {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
return abortController.signal;
}
return void 0;
}
const abortController = new AbortController();
this.abortControllers.set(cancelToken, abortController);
return abortController.signal;
};
public abortRequest = (cancelToken: CancelToken) => {
const abortController = this.abortControllers.get(cancelToken);
if (abortController) {
abortController.abort();
this.abortControllers.delete(cancelToken);
}
};
public request = async <T = any, E = any>({
body,
secure,
path,
type,
query,
format,
baseUrl,
cancelToken,
...params
}: FullRequestParams): Promise<HttpResponse<T, E>> => {
const secureParams =
((typeof secure === "boolean" ? secure : this.baseApiParams.secure) &&
this.securityWorker &&
(await this.securityWorker(this.securityData))) ||
{};
const requestParams = this.mergeRequestParams(params, secureParams);
const queryString = query && this.toQueryString(query);
const payloadFormatter = this.contentFormatters[type || ContentType.Json];
const responseFormat = format || requestParams.format;
return this.customFetch(`${baseUrl || this.baseUrl || ""}${path}${queryString ? `?${queryString}` : ""}`, {
...requestParams,
headers: {
...(type && type !== ContentType.FormData ? { "Content-Type": type } : {}),
...(requestParams.headers || {}),
},
signal: cancelToken ? this.createAbortSignal(cancelToken) : void 0,
body: typeof body === "undefined" || body === null ? null : payloadFormatter(body),
}).then(async (response) => {
const r = response as HttpResponse<T, E>;
r.data = null as unknown as T;
r.error = null as unknown as E;
const data = !responseFormat
? r
: await response[responseFormat]()
.then((data) => {
if (r.ok) {
r.data = data;
} else {
r.error = data;
}
return r;
})
.catch((e) => {
r.error = e;
return r;
});
if (cancelToken) {
this.abortControllers.delete(cancelToken);
}
if (!response.ok) throw data;
return data;
});
};
}
/**
* @title My API CRUD
* @baseUrl http://localhost:3000/api
*/
export class Api<SecurityDataType extends unknown> extends HttpClient<SecurityDataType> {
users = {
/**
* No description
*
* @tags Users
* @name UsersList
* @request GET:/users
*/
usersList: (
query?: {
select?: string;
include?: string;
limit?: number;
skip?: number;
where?: string;
orderBy?: string;
page?: number;
distinct?: string;
},
params: RequestParams = {},
) =>
this.request<any[], any>({
path: `/users`,
method: "GET",
query: query,
format: "json",
...params,
}),
/**
* No description
*
* @tags Users
* @name UsersCreate
* @request POST:/users
*/
usersCreate: (data: any, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/users`,
method: "POST",
query: query,
body: data,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*
* @tags Users
* @name UsersDetail
* @request GET:/users/{id}
*/
usersDetail: (id: string, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/users/${id}`,
method: "GET",
query: query,
format: "json",
...params,
}),
/**
* No description
*
* @tags Users
* @name UsersUpdate
* @request PUT:/users/{id}
*/
usersUpdate: (id: string, data: any, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/users/${id}`,
method: "PUT",
query: query,
body: data,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*
* @tags Users
* @name UsersDelete
* @request DELETE:/users/{id}
*/
usersDelete: (id: string, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/users/${id}`,
method: "DELETE",
query: query,
format: "json",
...params,
}),
};
posts = {
/**
* No description
*
* @tags Posts
* @name PostsList
* @request GET:/posts
*/
postsList: (
query?: {
select?: string;
include?: string;
limit?: number;
skip?: number;
where?: string;
orderBy?: string;
page?: number;
distinct?: string;
},
params: RequestParams = {},
) =>
this.request<any[], any>({
path: `/posts`,
method: "GET",
query: query,
format: "json",
...params,
}),
/**
* No description
*
* @tags Posts
* @name PostsCreate
* @request POST:/posts
*/
postsCreate: (data: any, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/posts`,
method: "POST",
query: query,
body: data,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*
* @tags Posts
* @name PostsDetail
* @request GET:/posts/{id}
*/
postsDetail: (id: string, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/posts/${id}`,
method: "GET",
query: query,
format: "json",
...params,
}),
/**
* No description
*
* @tags Posts
* @name PostsUpdate
* @request PUT:/posts/{id}
*/
postsUpdate: (id: string, data: any, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/posts/${id}`,
method: "PUT",
query: query,
body: data,
type: ContentType.Json,
format: "json",
...params,
}),
/**
* No description
*
* @tags Posts
* @name PostsDelete
* @request DELETE:/posts/{id}
*/
postsDelete: (id: string, query?: { select?: string; include?: string }, params: RequestParams = {}) =>
this.request<any, any>({
path: `/posts/${id}`,
method: "DELETE",
query: query,
format: "json",
...params,
}),
};
} | the_stack |
import {DateTime} from '../types';
import {EnumId} from './enum-types';
export enum FactorType {
SEQUENCE = 'sequence',
NUMBER = 'number',
UNSIGNED = 'unsigned', // 0 & positive
TEXT = 'text',
// address
ADDRESS = 'address',
CONTINENT = 'continent',
REGION = 'region',
COUNTRY = 'country',
PROVINCE = 'province',
CITY = 'city',
DISTRICT = 'district',
ROAD = 'road',
COMMUNITY = 'community',
FLOOR = 'floor',
RESIDENCE_TYPE = 'residence-type',
RESIDENTIAL_AREA = 'residential-area',
// contact electronic
EMAIL = 'email',
PHONE = 'phone',
MOBILE = 'mobile',
FAX = 'fax',
// date time related
DATETIME = 'datetime', // YYYY-MM-DD HH:mm:ss
FULL_DATETIME = 'full-datetime', // YYYY-MM-DD HH:mm:ss.SSS
DATE = 'date', // YYYY-MM-DD
TIME = 'time', // HH:mm:ss
YEAR = 'year', // 4 digits
HALF_YEAR = 'half-year', // 1: first half, 2: second half
QUARTER = 'quarter', // 1 - 4
MONTH = 'month', // 1 - 12
HALF_MONTH = 'half-month', // 1: first half, 2: second half
TEN_DAYS = 'ten-days', // 1, 2, 3
WEEK_OF_YEAR = 'week-of-year', // 0 (the partial week that precedes the first Sunday of the year) - 53 (leap year)
WEEK_OF_MONTH = 'week-of-month', // 0 (the partial week that precedes the first Sunday of the year) - 5
HALF_WEEK = 'half-week', // 1: first half, 2: second half
DAY_OF_MONTH = 'day-of-month', // 1 - 31, according to month/year
DAY_OF_WEEK = 'day-of-week', // 1 (Sunday) - 7 (Saturday)
DAY_KIND = 'day-kind', // 1: workday, 2: weekend, 3: holiday
HOUR = 'hour', // 0 - 23
HOUR_KIND = 'hour-kind', // 1: work time, 2: off hours, 3: sleeping time
MINUTE = 'minute', // 0 - 59
SECOND = 'second', // 0 - 59
MILLISECOND = 'millisecond', // 0 - 999
AM_PM = 'am-pm', // 1, 2
// individual
GENDER = 'gender',
OCCUPATION = 'occupation',
DATE_OF_BIRTH = 'date-of-birth', // YYYY-MM-DD
AGE = 'age',
ID_NO = 'id-no',
RELIGION = 'religion',
NATIONALITY = 'nationality',
// organization
BIZ_TRADE = 'biz-trade',
BIZ_SCALE = 'biz-scale',
BOOLEAN = 'boolean',
ENUM = 'enum',
OBJECT = 'object',
ARRAY = 'array',
}
export interface SourceTypes {
includes?: Array<FactorType>;
excludes?: Array<FactorType>;
}
/**
* compatible compatible means types in value can be write into type in key
*/
export const CompatibleTypes: Record<FactorType, SourceTypes> = {
[FactorType.SEQUENCE]: {includes: [FactorType.SEQUENCE, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.NUMBER]: {
includes: [
FactorType.NUMBER, FactorType.UNSIGNED, FactorType.SEQUENCE,
FactorType.FLOOR, FactorType.RESIDENTIAL_AREA,
FactorType.YEAR, FactorType.HALF_YEAR, FactorType.QUARTER, FactorType.MONTH, FactorType.HALF_MONTH,
FactorType.TEN_DAYS, FactorType.WEEK_OF_YEAR, FactorType.WEEK_OF_MONTH, FactorType.HALF_WEEK,
FactorType.DAY_OF_MONTH, FactorType.DAY_OF_WEEK, FactorType.DAY_KIND, FactorType.HOUR, FactorType.HOUR_KIND,
FactorType.MINUTE, FactorType.SECOND, FactorType.MILLISECOND, FactorType.AM_PM
]
},
[FactorType.UNSIGNED]: {
includes: [
FactorType.NUMBER, FactorType.UNSIGNED, FactorType.SEQUENCE,
FactorType.FLOOR, FactorType.RESIDENTIAL_AREA,
FactorType.YEAR, FactorType.HALF_YEAR, FactorType.QUARTER, FactorType.MONTH, FactorType.HALF_MONTH,
FactorType.TEN_DAYS, FactorType.WEEK_OF_YEAR, FactorType.WEEK_OF_MONTH, FactorType.HALF_WEEK,
FactorType.DAY_OF_MONTH, FactorType.DAY_OF_WEEK, FactorType.DAY_KIND, FactorType.HOUR, FactorType.HOUR_KIND,
FactorType.MINUTE, FactorType.SECOND, FactorType.MILLISECOND, FactorType.AM_PM
]
},
// any type can be written to text except object and array
[FactorType.TEXT]: {excludes: [FactorType.OBJECT, FactorType.ARRAY]},
// address
[FactorType.ADDRESS]: {includes: [FactorType.ADDRESS, FactorType.TEXT]},
[FactorType.CONTINENT]: {includes: [FactorType.CONTINENT]},
[FactorType.REGION]: {includes: [FactorType.REGION]},
[FactorType.COUNTRY]: {includes: [FactorType.COUNTRY]},
[FactorType.PROVINCE]: {includes: [FactorType.PROVINCE]},
[FactorType.CITY]: {includes: [FactorType.CITY]},
[FactorType.DISTRICT]: {includes: [FactorType.DISTRICT]},
[FactorType.ROAD]: {includes: [FactorType.ROAD]},
[FactorType.COMMUNITY]: {includes: [FactorType.COMMUNITY]},
[FactorType.FLOOR]: {includes: [FactorType.FLOOR, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.RESIDENCE_TYPE]: {includes: [FactorType.RESIDENCE_TYPE]},
[FactorType.RESIDENTIAL_AREA]: {includes: [FactorType.RESIDENTIAL_AREA, FactorType.NUMBER, FactorType.UNSIGNED]},
// contact electronic
[FactorType.EMAIL]: {includes: [FactorType.EMAIL]},
[FactorType.PHONE]: {includes: [FactorType.PHONE, FactorType.MOBILE, FactorType.FAX]},
[FactorType.MOBILE]: {includes: [FactorType.PHONE, FactorType.MOBILE, FactorType.FAX]},
[FactorType.FAX]: {includes: [FactorType.PHONE, FactorType.MOBILE, FactorType.FAX]},
// date time related
[FactorType.DATETIME]: {includes: [FactorType.DATE, FactorType.DATETIME, FactorType.FULL_DATETIME]},
[FactorType.FULL_DATETIME]: {includes: [FactorType.DATE, FactorType.DATETIME, FactorType.FULL_DATETIME]},
[FactorType.DATE]: {includes: [FactorType.DATE, FactorType.DATETIME, FactorType.FULL_DATETIME]},
[FactorType.TIME]: {includes: [FactorType.TIME, FactorType.DATETIME, FactorType.FULL_DATETIME]},
[FactorType.YEAR]: {includes: [FactorType.YEAR, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.HALF_YEAR]: {includes: [FactorType.HALF_YEAR, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.QUARTER]: {includes: [FactorType.QUARTER, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.MONTH]: {includes: [FactorType.MONTH, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.HALF_MONTH]: {includes: [FactorType.HALF_MONTH, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.TEN_DAYS]: {includes: [FactorType.TEN_DAYS, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.WEEK_OF_YEAR]: {includes: [FactorType.WEEK_OF_YEAR, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.WEEK_OF_MONTH]: {includes: [FactorType.WEEK_OF_MONTH, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.HALF_WEEK]: {includes: [FactorType.HALF_WEEK, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.DAY_OF_MONTH]: {includes: [FactorType.DAY_OF_MONTH, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.DAY_OF_WEEK]: {includes: [FactorType.DAY_OF_WEEK, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.DAY_KIND]: {includes: [FactorType.DAY_KIND, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.HOUR]: {includes: [FactorType.HOUR, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.HOUR_KIND]: {includes: [FactorType.HOUR_KIND, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.MINUTE]: {includes: [FactorType.MINUTE, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.SECOND]: {includes: [FactorType.SECOND, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.MILLISECOND]: {includes: [FactorType.MILLISECOND, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.AM_PM]: {includes: [FactorType.AM_PM, FactorType.NUMBER, FactorType.UNSIGNED]},
// individual
[FactorType.GENDER]: {includes: [FactorType.GENDER]},
[FactorType.OCCUPATION]: {includes: [FactorType.OCCUPATION]},
[FactorType.DATE_OF_BIRTH]: {includes: [FactorType.DATE_OF_BIRTH, FactorType.DATE, FactorType.DATETIME, FactorType.FULL_DATETIME]},
[FactorType.AGE]: {includes: [FactorType.AGE, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.ID_NO]: {includes: [FactorType.ID_NO]},
[FactorType.RELIGION]: {includes: [FactorType.RELIGION]},
[FactorType.NATIONALITY]: {includes: [FactorType.NATIONALITY]},
// organization
[FactorType.BIZ_TRADE]: {includes: [FactorType.BIZ_TRADE]},
[FactorType.BIZ_SCALE]: {includes: [FactorType.BIZ_SCALE, FactorType.NUMBER, FactorType.UNSIGNED]},
[FactorType.BOOLEAN]: {includes: [FactorType.BOOLEAN]},
[FactorType.ENUM]: {includes: [FactorType.ENUM]},
[FactorType.OBJECT]: {includes: [FactorType.OBJECT]},
[FactorType.ARRAY]: {includes: [FactorType.ARRAY]}
};
export enum FactorEncryptMethod {
NONE = 'none',
AES256_PKCS5_PADDING = 'AES256-PKCS5-PADDING',
MD5 = 'MD5',
SHA256 = 'SHA256',
MASK_MAIL = 'MASK-MAIL',
MASK_CENTER_3 = 'MASK-CENTER-3',
MASK_CENTER_5 = 'MASK-CENTER-5',
MASK_LAST_3 = 'MASK-LAST-3',
MASK_LAST_6 = 'MASK-LAST-6',
MASK_DAY = 'MASK-DAY',
MASK_MONTH = 'MASK-MONTH',
MASK_MONTH_DAY = 'MASK-MONTH-DAY'
}
export const CompatibleEncryptMethods: Record<FactorType, Array<FactorEncryptMethod>> = {
[FactorType.SEQUENCE]: [],
[FactorType.NUMBER]: [],
[FactorType.UNSIGNED]: [],
// any type can be written to text except object and array
[FactorType.TEXT]: [],
// address
[FactorType.ADDRESS]: [],
[FactorType.CONTINENT]: [],
[FactorType.REGION]: [],
[FactorType.COUNTRY]: [],
[FactorType.PROVINCE]: [],
[FactorType.CITY]: [],
[FactorType.DISTRICT]: [],
[FactorType.ROAD]: [],
[FactorType.COMMUNITY]: [],
[FactorType.FLOOR]: [],
[FactorType.RESIDENCE_TYPE]: [],
[FactorType.RESIDENTIAL_AREA]: [],
// contact electronic
[FactorType.EMAIL]: [FactorEncryptMethod.MASK_MAIL, FactorEncryptMethod.AES256_PKCS5_PADDING],
[FactorType.PHONE]: [
FactorEncryptMethod.MASK_CENTER_3, FactorEncryptMethod.MASK_CENTER_5,
FactorEncryptMethod.MASK_LAST_3, FactorEncryptMethod.MASK_LAST_6,
FactorEncryptMethod.AES256_PKCS5_PADDING
],
[FactorType.MOBILE]: [
FactorEncryptMethod.MASK_CENTER_3, FactorEncryptMethod.MASK_CENTER_5,
FactorEncryptMethod.MASK_LAST_3, FactorEncryptMethod.MASK_LAST_6,
FactorEncryptMethod.AES256_PKCS5_PADDING
],
[FactorType.FAX]: [
FactorEncryptMethod.MASK_CENTER_3, FactorEncryptMethod.MASK_CENTER_5,
FactorEncryptMethod.MASK_LAST_3, FactorEncryptMethod.MASK_LAST_6,
FactorEncryptMethod.AES256_PKCS5_PADDING
],
// date time related
[FactorType.DATETIME]: [],
[FactorType.FULL_DATETIME]: [],
[FactorType.DATE]: [],
[FactorType.TIME]: [],
[FactorType.YEAR]: [],
[FactorType.HALF_YEAR]: [],
[FactorType.QUARTER]: [],
[FactorType.MONTH]: [],
[FactorType.HALF_MONTH]: [],
[FactorType.TEN_DAYS]: [],
[FactorType.WEEK_OF_YEAR]: [],
[FactorType.WEEK_OF_MONTH]: [],
[FactorType.HALF_WEEK]: [],
[FactorType.DAY_OF_MONTH]: [],
[FactorType.DAY_OF_WEEK]: [],
[FactorType.DAY_KIND]: [],
[FactorType.HOUR]: [],
[FactorType.HOUR_KIND]: [],
[FactorType.MINUTE]: [],
[FactorType.SECOND]: [],
[FactorType.MILLISECOND]: [],
[FactorType.AM_PM]: [],
// individual
[FactorType.GENDER]: [],
[FactorType.OCCUPATION]: [],
[FactorType.DATE_OF_BIRTH]: [FactorEncryptMethod.MASK_DAY, FactorEncryptMethod.MASK_MONTH, FactorEncryptMethod.MASK_MONTH_DAY],
[FactorType.AGE]: [],
[FactorType.ID_NO]: [
FactorEncryptMethod.MASK_CENTER_5,
FactorEncryptMethod.MASK_LAST_3, FactorEncryptMethod.MASK_LAST_6,
FactorEncryptMethod.MD5, FactorEncryptMethod.SHA256,
FactorEncryptMethod.AES256_PKCS5_PADDING
],
[FactorType.RELIGION]: [],
[FactorType.NATIONALITY]: [],
// organization
[FactorType.BIZ_TRADE]: [],
[FactorType.BIZ_SCALE]: [],
[FactorType.BOOLEAN]: [],
[FactorType.ENUM]: [],
[FactorType.OBJECT]: [],
[FactorType.ARRAY]: []
};
export const FactorEncryptMethodLabels = {
[FactorEncryptMethod.NONE]: 'None',
[FactorEncryptMethod.AES256_PKCS5_PADDING]: 'AES256 PKCS5 Padding',
[FactorEncryptMethod.MD5]: 'Md5',
[FactorEncryptMethod.SHA256]: 'SHA256',
[FactorEncryptMethod.MASK_MAIL]: 'Mask Mail',
[FactorEncryptMethod.MASK_CENTER_3]: 'Mask Center 3 Digits',
[FactorEncryptMethod.MASK_CENTER_5]: 'Mask Center 5 Digits',
[FactorEncryptMethod.MASK_LAST_3]: 'Mask Last 3 Digits',
[FactorEncryptMethod.MASK_LAST_6]: 'Mask Last 6 Digits',
[FactorEncryptMethod.MASK_DAY]: 'Mask Day',
[FactorEncryptMethod.MASK_MONTH]: 'Mask Month',
[FactorEncryptMethod.MASK_MONTH_DAY]: 'Mask Month & Day'
};
export type FactorId = string;
export type FactorIndexGroup =
'i-1' | 'i-2' | 'i-3' | 'i-4' | 'i-5' | 'i-6' | 'i-7' | 'i-8' | 'i-9' | 'i-10'
| 'u-1' | 'u-2' | 'u-3' | 'u-4' | 'u-5' | 'u-6' | 'u-7' | 'u-8' | 'u-9' | 'u-10';
export interface Factor {
factorId: FactorId;
name: string;
label: string;
type: FactorType;
enumId?: EnumId;
defaultValue?: string;
indexGroup?: FactorIndexGroup;
// will be flatten to table column or not, only used in raw topic, and must be top level factor
flatten?: boolean;
encrypt?: FactorEncryptMethod;
description?: string;
createTime: DateTime;
lastModified: DateTime;
} | the_stack |
'use strict'
// **Github:** https://github.com/fidm/quic
//
// **License:** MIT
import { promisify } from 'util'
import { EventEmitter } from 'events'
import { ilog } from 'ilog'
import { thunk } from 'thunks'
import { suite, it } from 'tman'
import { ok, equal, deepEqual } from 'assert'
import { createHash } from 'crypto'
import { Client, Server } from '../src'
import { RandDataStream } from './common'
import { RegularPacket } from '../src/internal/packet'
import { BufferVisitor } from '../src/internal/common'
import { kSocket } from '../src/internal/symbol'
const onceEmit = promisify(EventEmitter.prototype.once)
suite('chaos testing', function () {
function echoServer () {
return new Server()
.on('error', (err) => { ilog.error(Object.assign(err, { class: 'server error' })) })
.on('session', (session) => {
session
.on('error', (err) => { ilog.error(Object.assign(err, { class: 'server session error' })) })
.on('stream', (stream) => {
stream
.on('error', (err) => { ilog.error(Object.assign(err, { class: 'server stream error' })) })
.on('data', (data) => {
stream.write(data)
})
.on('end', () => {
stream.end()
})
})
})
}
suite('echo rand readable stream', function () {
for (const i of [1, 2, 3, 4, 5]) {
// random stream & hash stream --(10MB)--> client --> server --(echo)--> client --> hash stream --> hash should equaled
const bytes = 1024 * 1024 * 2 * i // 2MB random data to echo
it(`with bytes ${bytes}`, async function () {
this.timeout(1000 * 20)
const server = echoServer()
await server.listen(0)
const cli1 = new Client()
cli1.on('error', (err) => { ilog(Object.assign(err, { class: 'client error' })) })
await cli1.connect(server.address().port)
const stream1 = cli1.request()
stream1.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream1 = new RandDataStream(bytes)
stream1.on('drain', () => {
dataStream1.resume()
})
// randDataStream.pipe(stream) // use paused mode for large stream
dataStream1
.on('data', (chunk) => {
if (!stream1.write(chunk)) {
dataStream1.pause()
}
})
.on('end', () => stream1.end())
const hash1 = createHash('sha256')
stream1.pipe(hash1)
const cli2 = await cli1.spawn(server.address().port)
const stream2 = cli2.request()
const stream3 = cli2.request()
stream2.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
stream3.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream2 = new RandDataStream(bytes)
stream3.on('drain', () => {
dataStream2.resume()
})
dataStream2
.on('data', (chunk) => {
stream2.write(chunk)
if (!stream3.write(chunk)) {
dataStream2.pause()
}
})
.on('end', () => {
stream2.end()
stream3.end()
})
const hash2 = createHash('sha256')
stream2.pipe(hash2)
const hash3 = createHash('sha256')
stream3.pipe(hash3)
await Promise.all([
onceEmit.call(stream1, 'end'),
onceEmit.call(stream2, 'end'),
onceEmit.call(stream3, 'end'),
])
equal(dataStream1.readBytes, bytes)
equal(dataStream1.totalSize, bytes)
equal(stream1.bytesRead, bytes)
equal(stream1.bytesWritten, bytes)
const ret1 = hash1.read() as Buffer
equal(ret1.toString('hex'), dataStream1.sum)
equal(dataStream2.readBytes, bytes)
equal(dataStream2.totalSize, bytes)
equal(stream2.bytesRead, bytes)
equal(stream2.bytesWritten, bytes)
const ret2 = hash2.read() as Buffer
equal(ret2.toString('hex'), dataStream2.sum)
equal(stream3.bytesRead, bytes)
equal(stream3.bytesWritten, bytes)
const ret3 = hash3.read() as Buffer
equal(ret3.toString('hex'), dataStream2.sum)
await Promise.all([cli1.close(), cli2.close()])
await server.close()
await thunk.promise(thunk.delay(500))
})
}
})
suite('echo rand readable stream when packets out of order', function () {
for (const i of [1, 2, 3, 4, 5]) {
// random stream & hash stream --(10MB)--> client --> server --(echo)--> client --> hash stream --> hash should equaled
const bytes = 1024 * 1024 * 2 * i // 2MB random data to echo
it(`with bytes ${bytes}`, async function () {
this.timeout(1000 * 200)
const server = echoServer()
await server.listen(0)
const serverListener = server[kSocket].listeners('message')[0]
server[kSocket].removeListener('message', serverListener)
server[kSocket].addListener('message', function (msg: Buffer, rinfo: AddressInfo) {
const rand = Math.random()
if (rand < 0.5) {
setTimeout(() => serverListener.call(this, msg, rinfo), rand * 10) // out-of-order
} else {
serverListener.call(this, msg, rinfo)
}
})
const cli1 = new Client()
cli1.setKeepAlive(true)
cli1.on('error', (err) => { ilog(Object.assign(err, { class: 'client error' })) })
await cli1.connect(server.address().port)
const clientListener = cli1[kSocket].listeners('message')[0]
cli1[kSocket].removeListener('message', clientListener)
cli1[kSocket].addListener('message', function (msg: Buffer, rinfo: AddressInfo) {
const rand = Math.random()
if (rand < 0.5) {
setTimeout(() => clientListener.call(this, msg, rinfo), rand * 10) // out-of-order
} else {
clientListener.call(this, msg, rinfo)
}
})
const stream1 = cli1.request()
stream1.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream1 = new RandDataStream(bytes)
stream1.on('drain', () => {
dataStream1.resume()
})
// randDataStream.pipe(stream) // use paused mode for large stream
dataStream1
.on('data', (chunk) => {
if (!stream1.write(chunk)) {
dataStream1.pause()
}
})
.on('end', () => stream1.end())
const hash1 = createHash('sha256')
stream1.pipe(hash1)
const cli2 = await cli1.spawn(server.address().port)
cli2.setKeepAlive(true)
const stream2 = cli2.request()
const stream3 = cli2.request()
stream2.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
stream3.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream2 = new RandDataStream(bytes)
stream3.on('drain', () => {
dataStream2.resume()
})
dataStream2
.on('data', (chunk) => {
stream2.write(chunk)
if (!stream3.write(chunk)) {
dataStream2.pause()
}
})
.on('end', () => {
stream2.end()
stream3.end()
})
const hash2 = createHash('sha256')
stream2.pipe(hash2)
const hash3 = createHash('sha256')
stream3.pipe(hash3)
await Promise.all([
onceEmit.call(stream1, 'end'),
onceEmit.call(stream2, 'end'),
onceEmit.call(stream3, 'end'),
])
equal(dataStream1.readBytes, bytes)
equal(dataStream1.totalSize, bytes)
equal(stream1.bytesRead, bytes)
equal(stream1.bytesWritten, bytes)
const ret1 = hash1.read() as Buffer
equal(ret1.toString('hex'), dataStream1.sum)
equal(dataStream2.readBytes, bytes)
equal(dataStream2.totalSize, bytes)
equal(stream2.bytesRead, bytes)
equal(stream2.bytesWritten, bytes)
const ret2 = hash2.read() as Buffer
equal(ret2.toString('hex'), dataStream2.sum)
equal(stream3.bytesRead, bytes)
equal(stream3.bytesWritten, bytes)
const ret3 = hash3.read() as Buffer
equal(ret3.toString('hex'), dataStream2.sum)
await Promise.all([cli1.close(), cli2.close()])
await server.close()
await thunk.promise(thunk.delay(500))
})
}
})
suite('echo rand readable stream when packets loss and out of order', function () {
for (const i of [1, 2, 3, 4]) {
// random stream & hash stream --(5MB)--> client --> server --(echo)--> client --> hash stream --> hash should equaled
const bytes = 1024 * 1024 * 1 * i
const lossRatio = 0.618 * 0.05 * i
it(`with loss ratio ${lossRatio * 100}%`, async function () {
this.timeout(1000 * 60 * 2)
const server = echoServer()
await server.listen(0)
const serverListener = server[kSocket].listeners('message')[0]
server[kSocket].removeListener('message', serverListener)
server[kSocket].addListener('message', function (msg: Buffer, rinfo: AddressInfo) {
const rand = Math.random()
if (rand < lossRatio) {
return // packet loss
}
if (rand < 0.2) {
setTimeout(() => serverListener.call(this, msg, rinfo), rand * 10) // out-of-order
} else {
serverListener.call(this, msg, rinfo)
}
})
const cli1 = new Client()
cli1.setKeepAlive(true)
cli1.on('error', (err) => { ilog(Object.assign(err, { class: 'client error' })) })
await cli1.connect(server.address().port)
const clientListener = cli1[kSocket].listeners('message')[0]
cli1[kSocket].removeListener('message', clientListener)
cli1[kSocket].addListener('message', function (msg: Buffer, rinfo: AddressInfo) {
const rand = Math.random()
if (rand < lossRatio) {
return // packet loss
}
if (rand < 0.2) {
setTimeout(() => clientListener.call(this, msg, rinfo), rand * 10) // out-of-order
} else {
clientListener.call(this, msg, rinfo)
}
})
const stream1 = cli1.request()
stream1.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream1 = new RandDataStream(bytes)
stream1.on('drain', () => {
dataStream1.resume()
})
// randDataStream.pipe(stream) // use paused mode for large stream
dataStream1
.on('data', (chunk) => {
if (!stream1.write(chunk)) {
dataStream1.pause()
}
})
.on('end', () => stream1.end())
const hash1 = createHash('sha256')
stream1.pipe(hash1)
const cli2 = await cli1.spawn(server.address().port)
cli2.setKeepAlive(true)
const stream2 = cli2.request()
const stream3 = cli2.request()
stream2.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
stream3.on('error', (err) => { throw Object.assign(err, { class: 'client stream error' })})
const dataStream2 = new RandDataStream(bytes)
stream3.on('drain', () => {
dataStream2.resume()
})
dataStream2
.on('data', (chunk) => {
stream2.write(chunk)
if (!stream3.write(chunk)) {
dataStream2.pause()
}
})
.on('end', () => {
stream2.end()
stream3.end()
})
const hash2 = createHash('sha256')
stream2.pipe(hash2)
const hash3 = createHash('sha256')
stream3.pipe(hash3)
await Promise.all([
onceEmit.call(stream1, 'end'),
onceEmit.call(stream2, 'end'),
onceEmit.call(stream3, 'end'),
])
equal(dataStream1.readBytes, bytes)
equal(dataStream1.totalSize, bytes)
equal(stream1.bytesRead, bytes)
equal(stream1.bytesWritten, bytes)
const ret1 = hash1.read() as Buffer
equal(ret1.toString('hex'), dataStream1.sum)
equal(dataStream2.readBytes, bytes)
equal(dataStream2.totalSize, bytes)
equal(stream2.bytesRead, bytes)
equal(stream2.bytesWritten, bytes)
const ret2 = hash2.read() as Buffer
equal(ret2.toString('hex'), dataStream2.sum)
equal(stream3.bytesRead, bytes)
equal(stream3.bytesWritten, bytes)
const ret3 = hash3.read() as Buffer
equal(ret3.toString('hex'), dataStream2.sum)
await Promise.all([cli1.close(), cli2.close()])
await server.close()
await thunk.promise(thunk.delay(500))
})
}
})
}) | the_stack |
import {GitHubQueryParser} from '../Library/GitHub/GitHubQueryParser';
import {GitHubQueryType} from '../Library/Type/GitHubQueryType';
// ---- filter ----
// number:123 number:456
// is:issue is:pr type:issue type:pr
// is:open is:closed
// is:read is:unread
// is:bookmark is:unbookmark
// is:archived is:unarchived
// is:merged is:unmerged
// is:draft is:undraft
// draft:true draft:false -- githubのクエリに合わせるため
// is:private is:unprivate
// author:foo
// assignee:foo
// involves:foo
// mentions:foo
// team:foo
// review-requested:foo
// reviewed-by:foo
// user:foo org:foo
// repo:foo/bar
// label:foo label:bar
// milestone:foo
// project-name:foo
// project-column:foo
// no:label no:milestone no:assignee no:dueon no:project
// have:label have:milestone have:assignee have:dueon have:project
// ---- sort ----
// sort:number
// sort:type
// sort:read
// sort:updated
// sort:created
// sort:closed
// sort:merged
// sort:archived
// sort:bookmark
// sort:author
// sort:user
// sort:repo
// sort:milestone
// sort:dueon
// sort:title
// single syntax `sort:created`
// order syntax `sort:"created desc"
// multi syntax `sort:author,created` (multi column sort does not work database index, so slow query)
// full syntax `sort:"author desc, created asc"`
class _FilterSQLRepo {
getSQL(filter: string): {filter: string; sort: string} {
if (!filter) return {filter: '', sort: ''};
const conditions = [];
const {positive: positiveMap, negative: negativeMap} = GitHubQueryParser.parse(filter);
if (positiveMap.sort) {
const temp = this.buildSortCondition(positiveMap.sort);
positiveMap.sort = temp.sort;
if (temp.filter) conditions.push(temp.filter);
}
conditions.push(...this.buildPositiveFilterCondition(positiveMap));
conditions.push(...this.buildNegativeFilterCondition(negativeMap));
if (positiveMap.keywords.length) {
const tmp = [];
for (let keyword of positiveMap.keywords) {
keyword = keyword.trim();
if (!keyword) continue;
tmp.push(`(
title like "%${keyword}%"
or body like "%${keyword}%"
or user like "%${keyword}%"
or repo like "%${keyword}%"
or author like "%${keyword}%"
or assignees like "%${keyword}%"
or labels like "%${keyword}%"
or milestone like "%${keyword}%"
or involves like "%${keyword}%"
or mentions like "%${keyword}%"
or review_requested like "%${keyword}%"
or reviews like "%${keyword}%"
or project_names like "%${keyword}%"
or project_columns like "%${keyword}%"
)`);
}
if (tmp.length) {
const value = tmp.join(' and ');
conditions.push(`(${value})`);
}
}
return {
filter: conditions.join(' and '),
sort: positiveMap.sort
};
}
private buildPositiveFilterCondition(filterMap: GitHubQueryType) {
const conditions = [];
if (filterMap.is.issue) conditions.push('type = "issue"');
if (filterMap.is.pr) conditions.push('type = "pr"');
if (filterMap.is.open) conditions.push('closed_at is null');
if (filterMap.is.closed) conditions.push('closed_at is not null');
if (filterMap.is.read) conditions.push('(read_at is not null and read_at >= updated_at)');
if (filterMap.is.unread) conditions.push('(read_at is null or read_at < updated_at)');
if (filterMap.is.bookmark) conditions.push('marked_at is not null');
if (filterMap.is.unbookmark) conditions.push('marked_at is null');
if (filterMap.is.archived) conditions.push('archived_at is not null');
if (filterMap.is.unarchived) conditions.push('archived_at is null');
if (filterMap.is.merged) conditions.push('merged_at is not null');
if (filterMap.is.unmerged) conditions.push('merged_at is null');
if (filterMap.is.draft) conditions.push('draft = 1');
if (filterMap.is.undraft) conditions.push('draft = 0');
if (filterMap.is.private) conditions.push('repo_private = 1');
if (filterMap.is.unprivate) conditions.push('repo_private = 0');
if (filterMap.no.label) conditions.push('labels is null');
if (filterMap.no.milestone) conditions.push('milestone is null');
if (filterMap.no.assignee) conditions.push('assignees is null');
if (filterMap.no.dueon) conditions.push('due_on is null');
if (filterMap.no.project) conditions.push('project_names is null');
if (filterMap.have.label) conditions.push('labels is not null');
if (filterMap.have.milestone) conditions.push('milestone is not null');
if (filterMap.have.assignee) conditions.push('assignees is not null');
if (filterMap.have.dueon) conditions.push('due_on is not null');
if (filterMap.have.project) conditions.push('project_names is not null');
if (filterMap.numbers.length) {
conditions.push(`(number is not null and number in (${filterMap.numbers.join(',')}))`);
}
if (filterMap.authors.length) {
const value = filterMap.authors.map((author) => `"${author}"`).join(',');
conditions.push(`(author is not null and lower(author) in (${value}))`);
}
if (filterMap.assignees.length) {
// hack: assignee format
const value = filterMap.assignees.map((assignee)=> `assignees like "%<<<<${assignee}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap.involves.length) {
// hack: involves format
const value = filterMap.involves.map(user => `involves like "%<<<<${user}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap.mentions.length) {
// hack: mentions format
const value = filterMap.mentions.map(user => `mentions like "%<<<<${user}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap.teams.length) {
// hack: mentions format
const value = filterMap.teams.map(user => `mentions like "%<<<<${user}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap['review-requested'].length) {
// hack: review-requested format
const value = filterMap['review-requested'].map(user => `review_requested like "%<<<<${user}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap['reviewed-by'].length) {
// hack: reviews format
const value = filterMap['reviewed-by'].map(user => `reviews like "%<<<<${user}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap['project-names'].length) {
// hack: project-names format
const value = filterMap['project-names'].map(name => `project_names like "%<<<<${name}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap['project-columns'].length) {
// hack: project-columns format
const value = filterMap['project-columns'].map(name => `project_columns like "%<<<<${name}>>>>%"`).join(' or ');
conditions.push(`(${value})`);
}
if (filterMap.milestones.length) {
const value = filterMap.milestones.map((milestone) => `"${milestone}"`).join(',');
conditions.push(`(milestone is not null and lower(milestone) in (${value}))`);
}
if (filterMap.users.length) {
const value = filterMap.users.map((user) => `"${user}"`).join(',');
conditions.push(`(user is not null and lower(user) in (${value}))`);
}
if (filterMap.repos.length) {
const value = filterMap.repos.map((repo) => `"${repo}"`).join(',');
conditions.push(`(repo is not null and lower(repo) in (${value}))`);
}
if (filterMap.labels.length) {
// hack: label format
const value = filterMap.labels.map((label)=> `labels like "%<<<<${label}>>>>%"`).join(' and ');
conditions.push(`(${value})`);
}
return conditions;
}
private buildNegativeFilterCondition(filterMap: GitHubQueryType) {
const conditions = [];
if (filterMap.is.issue) conditions.push('type != "issue"');
if (filterMap.is.pr) conditions.push('type != "pr"');
if (filterMap.is.open) conditions.push('closed_at is not null');
if (filterMap.is.closed) conditions.push('closed_at is null');
if (filterMap.is.read) conditions.push('(read_at is null or read_at < updated_at)');
if (filterMap.is.unread) conditions.push('(read_at is not null and read_at >= updated_at)');
if (filterMap.is.bookmark) conditions.push('marked_at is null');
if (filterMap.is.unbookmark) conditions.push('marked_at is not null');
if (filterMap.is.archived) conditions.push('archived_at is null');
if (filterMap.is.unarchived) conditions.push('archived_at is not null');
if (filterMap.is.merged) conditions.push('merged_at is null');
if (filterMap.is.unmerged) conditions.push('merged_at is not null');
if (filterMap.is.draft) conditions.push('draft = 0');
if (filterMap.is.undraft) conditions.push('draft = 1');
if (filterMap.is.private) conditions.push('repo_private = 0');
if (filterMap.is.unprivate) conditions.push('repo_private = 1');
if (filterMap.no.label) conditions.push('labels is not null');
if (filterMap.no.milestone) conditions.push('milestone is not null');
if (filterMap.no.assignee) conditions.push('assignees is not null');
if (filterMap.no.dueon) conditions.push('due_on is not null');
if (filterMap.no.project) conditions.push('project_names is not null');
if (filterMap.have.label) conditions.push('labels is null');
if (filterMap.have.milestone) conditions.push('milestone is null');
if (filterMap.have.assignee) conditions.push('assignees is null');
if (filterMap.have.dueon) conditions.push('due_on is null');
if (filterMap.have.project) conditions.push('project_names is null');
if (filterMap.numbers.length) {
conditions.push(`number is not null and number not in (${filterMap.numbers.join(',')})`);
}
if (filterMap.authors.length) {
const value = filterMap.authors.map((author) => `"${author}"`).join(',');
conditions.push(`(author is not null and lower(author) not in (${value}))`);
}
if (filterMap.assignees.length) {
// hack: assignee format
const value = filterMap.assignees.map((assignee)=> `assignees not like "%<<<<${assignee}>>>>%"`).join(' and ');
conditions.push(`(assignees is null or (${value}))`);
}
if (filterMap.involves.length) {
// hack: involves format
const value = filterMap.involves.map(user => `involves not like "%<<<<${user}>>>>%"`).join(' and ');
conditions.push(`(involves is null or (${value}))`);
}
if (filterMap.mentions.length) {
// hack: mentions format
const value = filterMap.mentions.map(user => `mentions not like "%<<<<${user}>>>>%"`).join(' and ');
conditions.push(`(mentions is null or (${value}))`);
}
if (filterMap.teams.length) {
// hack: mentions format
const value = filterMap.teams.map(user => `mentions not like "%<<<<${user}>>>>%"`).join(' and ');
conditions.push(`(mentions is null or (${value}))`);
}
if (filterMap['review-requested'].length) {
// hack: review-requested format
const value = filterMap['review-requested'].map(user => `review_requested not like "%<<<<${user}>>>>%"`).join(' and ');
conditions.push(`(review_requested is null or (${value}))`);
}
if (filterMap['reviewed-by'].length) {
// hack: reviews format
const value = filterMap['reviewed-by'].map(user => `reviews not like "%<<<<${user}>>>>%"`).join(' and ');
conditions.push(`(reviews is null or (${value}))`);
}
if (filterMap['project-names'].length) {
// hack: project-names format
const value = filterMap['project-names'].map(name => `project_names not like "%<<<<${name}>>>>%"`).join(' and ');
conditions.push(`(project_names is null or (${value}))`);
}
if (filterMap['project-columns'].length) {
// hack: project-columns format
const value = filterMap['project-columns'].map(name => `project_columns not like "%<<<<${name}>>>>%"`).join(' and ');
conditions.push(`(project_columns is null or (${value}))`);
}
if (filterMap.milestones.length) {
const value = filterMap.milestones.map((milestone) => `"${milestone}"`).join(',');
conditions.push(`(milestone is not null and lower(milestone) not in (${value}))`);
}
if (filterMap.users.length) {
const value = filterMap.users.map((user) => `"${user}"`).join(',');
conditions.push(`(user is not null and lower(user) not in (${value}))`);
}
if (filterMap.repos.length) {
const value = filterMap.repos.map((repo) => `"${repo}"`).join(',');
conditions.push(`(repo is not null and lower(repo) not in (${value}))`);
}
if (filterMap.labels.length) {
// hack: label format
const value = filterMap.labels.map((label)=> `labels not like "%<<<<${label}>>>>%"`).join(' and ');
conditions.push(`(labels is null or (${value}))`);
}
return conditions;
}
// sort:number
// sort:type
// sort:read
// sort:updated
// sort:created
// sort:closed
// sort:merged
// sort:archived
// sort:bookmark
// sort:author
// sort:user
// sort:repo
// sort:milestone
// sort:dueon
// sort:title
// value is 'number desc, updated asc'
private buildSortCondition(value) {
const conditions = [];
const filterConditions = [];
const sortConditions = value.split(',').map((v)=> v.trim());
for (const sortCondition of sortConditions) {
let [column, order] = sortCondition.split(/\s+/);
if (order && order !== 'asc' && order !== 'desc') order = null;
switch (column) {
case 'number': conditions.push(`number ${order ? order : 'desc'}`); break;
case 'type': conditions.push(`type ${order ? order : 'asc'}`); break;
case 'read': conditions.push(`read_at ${order ? order : 'desc'}`); break;
case 'updated': conditions.push(`updated_at ${order ? order : 'desc'}`); break;
case 'created': conditions.push(`created_at ${order ? order : 'desc'}`); break;
case 'closed': conditions.push(`closed_at ${order ? order : 'desc'}`); break;
case 'merged': conditions.push(`merged_at ${order ? order : 'desc'}`); break;
case 'archived': conditions.push(`archived_at ${order ? order : 'desc'}`); break;
case 'bookmark': conditions.push(`marked_at ${order ? order : 'desc'}`); break;
case 'author': conditions.push(`author ${order ? order : 'asc'}`); break;
case 'user': conditions.push(`user ${order ? order : 'asc'}`); break;
case 'repo': conditions.push(`repo ${order ? order : 'asc'}`); break;
case 'milestone': conditions.push(`milestone ${order ? order : 'desc'}`); break;
case 'dueon':
conditions.push(`due_on ${order ? order : 'asc'}`);
filterConditions.push('closed_at is null');
filterConditions.push('due_on is not null');
break;
case 'title': conditions.push(`title ${order ? order : 'asc'}`); break;
}
}
return {
sort: conditions.join(' , '),
filter: filterConditions.join(' and ')
};
}
}
export const FilterSQLRepo = new _FilterSQLRepo(); | the_stack |
import * as cp from 'child_process';
import * as fse from 'fs-extra';
import { PathLike, Stats } from 'fs-extra';
import { normalize, parse } from './path';
export { PathLike, Stats } from 'fs-extra';
// Electron ships with its own patched version of the fs-module
// to be able to browse ASAR files. This highly impacts the performance
// of SnowFS inside an Electron app. Electron still has the original
// filesystem onboard called 'original-fs'. For more information see
// https://github.com/Snowtrack/SnowFS/issues/173
let useOriginalFs = false;
let fs;
if (Object.prototype.hasOwnProperty.call(process.versions, 'electron')) {
// eslint-disable-next-line global-require, import/no-unresolved
fs = require('original-fs');
useOriginalFs = true;
} else {
// eslint-disable-next-line global-require
fs = require('fs');
}
let winattr;
if (process.platform === 'win32') {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies
winattr = require('winattr');
}
/**
* Return true if 'original-fs' is used as the underlying filesystem module.
*/
export function usesOriginalFs(): boolean {
return useOriginalFs;
}
export class DirItem {
/** Absolute path of dir item */
absPath: string;
/** Relative path of dir item */
relPath: string;
stats: fse.Stats;
/** If [[DirItem.isdir]] is `true`, this value indicates if the directory is empty or not. */
isempty: boolean;
}
/** Used in [[osWalk]]. */
export enum OSWALK {
/** Return all directories. [[DirItem.isdir]] will be `true` */
DIRS = 1,
/** Return all files. [[DirItem.isdir]] will be `false` */
FILES = 2,
/** Return all hidden items. */
HIDDEN = 4,
/** Browse Git and/or SnowFS repositories. */
BROWSE_REPOS = 8,
/** Only run over the first level of the directory */
NO_RECURSIVE = 16
}
function darwinZip(src: string, dst: string): Promise<void> {
const p0 = cp.spawn('ditto', ['-c', '-k', '--sequesterRsrc', src, dst]);
return new Promise((resolve, reject) => {
p0.on('exit', (code) => {
if (code === 0) {
resolve();
} else {
reject(code);
}
});
});
}
export function zipFile(src: string, dst: string, opts: {deleteSrc: boolean}): Promise<void> {
if (!dst.endsWith('.zip')) {
throw new Error('destination must be a zip');
}
let promise: Promise<void>;
switch (process.platform) {
case 'darwin':
promise = darwinZip(src, dst);
break;
case 'win32':
default:
throw new Error('zip not yet implemented');
}
return promise.then(() => {
if (opts.deleteSrc) {
return fse.remove(src);
}
});
}
/**
* Hides a given directory or file. If the function failed to hide the item,
* the function doesn't throw an exception.
*
* @param path Path to file or dir to hide.
* @returns
*/
export function hideItem(path: string): Promise<void> {
if (winattr) {
return new Promise<void>((resolve) => {
winattr.set(path, { hidden: true }, () => {
// not being able to hide the directory shouldn't stop us here
// so we ignore the error
resolve();
});
});
}
return Promise.resolve();
}
function checkPath(pth): void {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/u.test(pth.replace(parse(pth).root, ''));
if (pathHasInvalidWinCharacters) {
const error = new Error(`Path contains invalid characters: ${pth}`);
(error as any).code = 'EINVAL';
throw error;
}
}
}
const getMode = (options) => {
const defaults = { mode: 0o777 };
if (typeof options === 'number') return options;
return ({ ...defaults, ...options }).mode;
};
/**
* Ensures that the directory exists. If the directory structure does not exist, it is created.
* Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [pathExists] visit https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
*/
export function ensureDir(dir: string, options?: number | any): Promise<void> {
checkPath(dir);
return new Promise<void>((resolve, reject) => {
try {
fs.mkdir(dir, {
mode: getMode(options),
recursive: true,
}, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} catch (error) {
reject(error);
}
});
}
/**
* Tests a user's permissions for the file or directory specified by path.
* Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [pathExists] visit https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
*/
export function access(path: PathLike, mode: number | undefined): Promise<void> {
return new Promise((resolve, reject) => {
try {
fs.access(path, mode, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} catch (error) {
reject(error);
}
});
}
/**
* Test whether or not the given path exists by checking with the file system.
* Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [pathExists] visit https://nodejs.org/api/fs.html#fs_fs_exists_path_callback
*/
export function pathExists(path: PathLike): Promise<boolean> {
return new Promise((resolve, reject) => {
try {
fs.exists(path, (exists) => {
resolve(exists);
});
} catch (error) {
reject(error);
}
});
}
/**
* Change the file system timestamps of the object referenced by the <FileHandle> then resolves the promise with no arguments upon success.
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [createReadStream] visit https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
*/
export function utimes(path: PathLike, atime: Date, mtime: Date): Promise<void> {
return new Promise((resolve, reject) => {
try {
fs.utimes(path, atime, mtime, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} catch (error) {
reject(error);
}
});
}
export async function rmdir(dir: string): Promise<void> {
return new Promise((resolve, reject) => {
try {
(fs.rmdir || fs.rm)(dir, { recursive: true }, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} catch (error) {
resolve(error);
}
});
}
/**
* Retrieve the statistics about a directory item. Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [stat] visit https://nodejs.org/api/fs.html#fs_fs_fstat_fd_options_callback
*/
export function stat(path: PathLike): Promise<Stats> {
return new Promise((resolve, reject) => {
try {
fs.stat(path, (error, stats: Stats) => {
if (error) {
reject(error);
} else {
resolve(stats);
}
});
} catch (error) {
reject(error);
}
});
}
/**
* Asynchronously copies `src` to `dest`. Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [copyFile] visit https://nodejs.org/api/fs.html#fs_fs_copyfilesync_src_dest_mode
*/
export function copyFile(src: PathLike, dest: PathLike, flags: number): Promise<void> {
return new Promise((resolve, reject) => {
try {
fs.copyFile(src, dest, flags, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} catch (error) {
reject(error);
}
});
}
/**
* Read the contents of a directory. Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [readdir] visit https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback
*/
export function readdir(path: PathLike, callback: (err: Error | null, files: string[]) => void): void {
return fs.readdir(path, callback);
}
/**
* Open a read stream. Preferred usage over 'fs' or 'fs-extra' because it ensures always the
* fastest filesystem module is used inside Electron or inside node.
* For more information check the module import comments above.
* For more information about the API of [createReadStream] visit https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
*/
export function createReadStream(path: PathLike, options?: string | {
flags?: string;
encoding?: unknown;
fd?: number;
mode?: number;
autoClose?: boolean;
/**
* @default false
*/
emitClose?: boolean;
start?: number;
end?: number;
highWaterMark?: number;
}): fse.ReadStream {
return fs.createReadStream(path, options);
}
/**
* Helper function to recursively request information of all files or directories of a given directory.
* @param dirPath The directory in question.
* @param request Specify which elements are of interest.
* @param dirItemRef Only for internal use, must be not set when called.
*/
export function osWalk(dirPath: string, request: OSWALK): Promise<DirItem[]> {
const returnDirs = request & OSWALK.DIRS;
const returnFiles = request & OSWALK.FILES;
const returnHidden = request & OSWALK.HIDDEN;
const browseRepo = request & OSWALK.BROWSE_REPOS;
function internalOsWalk(dirPath: string, request: OSWALK, relPath: string, dirItemRef?: DirItem): Promise<DirItem[]> {
if (dirPath.endsWith('/')) {
// if directory ends with a seperator, we cut it off to ensure
// we don't return a path like /foo/directory//file.jpg
dirPath = dirPath.substr(0, dirPath.length - 1);
}
const dirItems = [];
return new Promise<string[]>((resolve, reject) => {
readdir(dirPath, (error, entries: string[]) => {
if (error) {
// While browsing through a sub-directory, readdir
// might fail if the directory e.g. gets deleted at the same
// time. Therefore sub-directories don't throw an error
if (dirItemRef) {
resolve([]);
} else {
reject(error);
}
return;
}
// normalize all dir items
resolve(entries.map(normalize));
});
})
.then((items: string[]) => {
const promises = [];
for (const item of items) {
if (item === '.DS_Store' || item === 'thumbs.db') {
continue;
} else if (!browseRepo && (item === '.snow' || item === '.git')) {
continue;
} else if (!returnHidden && item.startsWith('.')) {
continue;
}
const absPath = `${dirPath}/${item}`;
promises.push(stat(absPath)
.then((stats: Stats) => {
return {
absPath,
isempty: false,
relPath: relPath.length === 0 ? item : `${relPath}/${item}`,
stats,
};
}).catch(() => null));
}
return Promise.all(promises);
}).then((itemStatArray: DirItem[]) => {
const promises = [];
for (const dirItem of itemStatArray.filter((x) => x)) {
if ((dirItem.stats.isDirectory() && returnDirs) || (!dirItem.stats.isDirectory() && returnFiles)) {
dirItems.push(dirItem);
}
if (dirItem.stats.isDirectory() && !(request & OSWALK.NO_RECURSIVE)) {
promises.push(internalOsWalk(dirItem.absPath, request, dirItem.relPath, dirItem));
}
}
if (dirItemRef) {
dirItemRef.isempty = itemStatArray.length === 0;
}
return Promise.all(promises);
})
.then((dirItemResults: DirItem[]) => dirItems.concat(...dirItemResults));
}
return internalOsWalk(dirPath, request, '');
} | the_stack |
import { SBWorkloadState } from '@saladtechnologies/salad-grpc-salad-bowl/salad/grpc/salad_bowl/v1/salad_bowl_pb'
import { Duration } from 'luxon'
import { action, computed, flow, observable, runInAction } from 'mobx'
import { Subject } from 'rxjs'
import { map, takeUntil } from 'rxjs/operators'
import { RetryConnectingToSaladBowl, SaladBowlState } from '../../services/SaladFork/models/SaladBowlLoginResponse'
import * as Storage from '../../Storage'
import { RootStore } from '../../Store'
import { ErrorPageType } from '../../UIStore'
import { MiningStatus } from '../machine/models'
import { NotificationMessageCategory } from '../notifications/models'
import { PluginInfo, StartActionType, StartReason, StopReason } from './models'
import { PluginStatus } from './models/PluginStatus'
import { SaladBowlStoreInterface } from './SaladBowlStoreInterface'
import { getPreppingPercentage } from './utils'
const CPU_MINING_ENABLED = 'CPU_MINING_ENABLED'
const GPU_MINING_OVERRIDDEN = 'GPU_MINING_OVERRIDDEN'
const CPU_MINING_OVERRIDDEN = 'CPU_MINING_OVERRIDDEN'
export class SaladForkAndBowlStore implements SaladBowlStoreInterface {
private runningTimer?: NodeJS.Timeout
private timeoutTimer?: NodeJS.Timeout
/** The timestamp last time that start was pressed */
private startTimestamp?: Date
/** The total time we have been in the chopping state since the start button was pressed (ms) */
private choppingTime?: number = undefined
private readonly choppingSubscription = new Subject<void>()
private readonly saladBowlSubscription = new Subject<void>()
@observable
public runningTime?: number = undefined
@observable
public cpuMiningEnabled = false
@observable
public cpuMiningUpdatePending = false
@observable
public gpuMiningEnabled = false
@observable
public gpuMiningUpdatePending = false
@observable
public cpuMiningOverridden = false
@observable
public cpuMiningOverriddenUpdatePending = false
@observable
public gpuMiningOverridden = false
@observable
public gpuMiningOverriddenUpdatePending = false
@observable
public plugin = new PluginInfo()
@observable
public saladBowlConnected?: boolean
@observable
public workloadState?: SBWorkloadState.AsObject[]
@action
private destroyChoppingSubscriptions(): void {
this.choppingSubscription.next()
}
@action
private destroySaladBowlSubscriptions(): void {
this.saladBowlSubscription.next()
}
@action
private destroyAllSubscriptions(): void {
this.destroyChoppingSubscriptions()
this.destroySaladBowlSubscriptions()
}
@computed
get canRun() {
return (
this.store.auth.isAuthenticated !== undefined &&
this.store.auth.isAuthenticated &&
this.store.native.isNative &&
this.saladBowlConnected !== undefined &&
this.saladBowlConnected &&
this.store.activeWorkloadsUIStore.hasCompatibleWorkloads
)
}
@computed
get isRunning() {
// Change this
return this.runningTime !== undefined
}
@computed
get isNotCompatible() {
return !this.canRun
}
@computed
get isOverriding() {
return this.gpuMiningOverridden || this.cpuMiningOverridden
}
@computed
get status(): MiningStatus {
switch (this.plugin.status) {
case PluginStatus.Installing:
return MiningStatus.Installing
case PluginStatus.Initializing:
return MiningStatus.Initializing
case PluginStatus.Running:
return MiningStatus.Running
case PluginStatus.Unknown:
default:
return MiningStatus.Stopped
}
}
@computed
get preppingProgress() {
return getPreppingPercentage(this.runningTime)
}
@computed
get runningTimeDisplay():
| {
value: number
unit: 'year' | 'month' | 'week' | 'day' | 'hour' | 'minute' | 'second'
}
| undefined {
if (this.runningTime === undefined) {
return undefined
}
const duration: Duration = Duration.fromMillis(this.runningTime)
const interval = duration.shiftTo('years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds').toObject()
if (interval.years !== undefined && interval.years >= 1) {
return { value: interval.years, unit: 'year' }
} else if (interval.months !== undefined && interval.months >= 1) {
return { value: interval.months, unit: 'month' }
} else if (interval.weeks !== undefined && interval.weeks >= 1) {
return { value: interval.weeks, unit: 'week' }
} else if (interval.days !== undefined && interval.days >= 1) {
return { value: interval.days, unit: 'day' }
} else if (interval.hours !== undefined && interval.hours >= 1) {
return { value: interval.hours, unit: 'hour' }
} else if (interval.minutes !== undefined && interval.minutes >= 1) {
return { value: Math.ceil(interval.minutes), unit: 'minute' }
} else {
return { value: interval.seconds ? Math.ceil(interval.seconds) : 0, unit: 'second' }
}
}
@action private updatePluginStatus = (status: PluginStatus) => {
this.plugin.status = status
}
@action private updatePluginName = (name: string) => {
this.plugin.name = name
}
@action private resetPluginInfo = () => {
this.plugin = new PluginInfo()
}
@action private updateWorkloadState = (workloadState: SBWorkloadState.AsObject[]) => {
this.workloadState = workloadState
}
private streamWorkloadData = () => {
this.store.saladFork
.workloadStatuses$('miner.*.>')
.pipe(map((js) => js.getEvent()))
.pipe(
map((event) => {
if (event !== undefined) {
const topic = event.getTopic()
console.log('topic: ', topic)
console.log('message: ', event.getMessage())
let workloadData: { speed?: number; time?: string; dagCompleted?: number; minerName: string } = {
speed: undefined,
time: undefined,
dagCompleted: undefined,
minerName: topic.split('.')[1],
}
if (topic.includes('speed')) {
const message = event.getMessage()
workloadData.speed = parseInt(message.trim())
}
if (topic.includes('time')) {
const message = event.getMessage()
workloadData.time = message.trim()
}
if (topic.includes('dag.complete')) {
const message = event.getMessage()
workloadData.dagCompleted = parseInt(message.trim())
}
return workloadData
} else {
return undefined
}
}),
)
.pipe(takeUntil(this.choppingSubscription))
.subscribe((workloadData) => {
if (workloadData !== undefined) {
if (this.plugin.name !== undefined && this.plugin.name !== workloadData.minerName) {
this.resetPluginInfo()
} else {
this.updatePluginName(workloadData.minerName)
}
if (
(workloadData.speed && workloadData.speed > 0) ||
(workloadData.time && workloadData.time !== '0:00') ||
workloadData.dagCompleted !== undefined
) {
this.updatePluginStatus(PluginStatus.Running)
} else if (this.plugin.status !== undefined) {
this.updatePluginStatus(PluginStatus.Initializing)
}
}
})
}
private streamWorkloadState = () => {
this.store.saladFork
.workloadState$()
.pipe(map((resp) => resp.toObject()))
.pipe(takeUntil(this.saladBowlSubscription))
.subscribe((workloadState) => {
if (workloadState !== undefined) {
this.updateWorkloadState(workloadState.workloadstatesList)
}
})
}
constructor(private readonly store: RootStore) {}
private start = (reason: StartReason, startTimestamp?: Date, choppingTime?: number) => {
if (this.isRunning) {
return
}
if (!this.canRun) {
if (this.store.auth.isAuthenticated && !this.isOverriding) {
this.store.ui.showErrorPage(ErrorPageType.NotCompatible)
}
console.log('This machine is not able to run.')
return
}
this.store.saladFork
.start()
.then(() => {
// Start Salad Bowl 2.0
runInAction(() => {
this.plugin.status = PluginStatus.Installing
})
this.store.ui.updateViewedAVErrorPage(false)
if (this.timeoutTimer != null) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = undefined
}
if (this.runningTimer) {
clearInterval(this.runningTimer)
this.runningTimer = undefined
this.runningTime = undefined
this.choppingTime = undefined
}
// start streaming workload data
this.streamWorkloadData()
// TODO: This anaytics metric is probably not going to work anymore?
// const gpusNames = this.store.machine.gpus.filter((x) => x && x.model).map((x) => x.model)
// const cpu = this.store.native.machineInfo?.cpu
// const cpuName = `${cpu?.manufacturer} ${cpu?.brand}`
// this.store.analytics.trackStart(
// reason,
// this.gpuMiningEnabled,
// this.cpuMiningEnabled,
// gpusNames,
// cpuName,
// this.gpuMiningOverridden,
// this.cpuMiningOverridden,
// )
//Show a notification reminding chefs to use auto start
if (reason === StartReason.Manual && this.store.autoStart.canAutoStart && !this.store.autoStart.autoStart) {
this.store.notifications.sendNotification({
category: NotificationMessageCategory.AutoStart,
title: 'Salad is best run AFK',
message: "Don't forget to enable auto start in Settings",
id: 123456,
onClick: () => this.store.routing.push('/settings/desktop-settings'),
})
}
runInAction(() => {
this.startTimestamp = startTimestamp || new Date(Date.now())
this.runningTime = 0
this.choppingTime = choppingTime || 0
})
this.runningTimer = setInterval(() => {
runInAction(() => {
if (!this.startTimestamp) {
this.runningTime = 0
} else {
//Calculates the new total time since we started
const totalTime = Date.now() - this.startTimestamp.getTime()
//Checks to see if the miner is confirmed to be running and adds to the chopping time if it is
if (this.status === MiningStatus.Running) {
//Calculates the delta since the last timer
const deltaTime = totalTime - (this.runningTime || 0)
if (this.choppingTime) {
this.choppingTime += deltaTime
} else {
this.choppingTime = deltaTime
}
}
this.runningTime = totalTime
}
})
}, 1000)
})
.catch((err) => console.log('error: ', err)) // TODO: Handle Error - Example Error Message - "Workload MUST Exist in SaladBowl"
}
public login = async (): Promise<void> => {
try {
const response = await this.store.saladFork.login()
if (response === RetryConnectingToSaladBowl.Message) {
await this.login()
} else {
this.setSaladBowlConnected(true)
this.getSaladBowlState(response || undefined)
this.streamWorkloadState()
}
} catch (error: any) {
this.setSaladBowlConnected(false)
this.store.startButtonUI.setStartButtonToolTip(
'We are currently unable to connect to Salad Bowl. Please make sure you are running on the latest version and contact support.',
true,
)
this.store.startButtonUI.setSupportNeeded(true)
}
}
public logout = async (): Promise<void> => {
try {
this.destroyAllSubscriptions()
this.store.saladFork.logout()
} catch (error: any) {
// TODO: Handle errors on logging out
}
}
public stop = (reason: StopReason) => {
if (this.timeoutTimer != null) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = undefined
}
if (this.runningTimer) {
clearInterval(this.runningTimer)
this.runningTimer = undefined
}
this.plugin.name = undefined
this.plugin.version = undefined
this.plugin.algorithm = undefined
this.plugin.status = PluginStatus.Stopped
this.store.saladFork.stop() // this is promise that needs to be handled correctly
this.destroyChoppingSubscriptions()
// should we remove this because it is a mixpanel tracking event
if (this.isRunning) {
this.store.analytics.trackStop(reason, this.runningTime || 0, this.choppingTime || 0)
}
this.startTimestamp = undefined
console.log('Stopping after running for: ' + this.runningTime + ' and chopping for: ' + this.choppingTime)
this.runningTime = undefined
this.choppingTime = undefined
}
public toggleRunning = flow(
function* (this: SaladForkAndBowlStore, startAction: StartActionType) {
if (startAction !== StartActionType.Automatic) {
try {
yield this.store.auth.login()
} catch {
return
}
}
if (
startAction !== StartActionType.StartButton &&
startAction !== StartActionType.StopPrepping &&
this.isRunning
) {
return
}
switch (startAction) {
case StartActionType.StartButton:
if (this.isRunning) {
if (this.status === MiningStatus.Initializing || this.status === MiningStatus.Installing) {
this.store.ui.showModal('/warnings/dont-lose-progress')
return
}
this.stop(StopReason.Manual)
} else {
this.store.analytics.trackButtonClicked('start_button', 'Start Button', 'enabled')
this.start(StartReason.Manual)
}
break
case StartActionType.Override:
this.store.analytics.trackButtonClicked('override_button', 'Override Button', 'enabled')
this.gpuMiningEnabled ? this.setGpuOverride(true) : this.setCpuOverride(true)
this.start(StartReason.Manual)
break
case StartActionType.SwitchMiner:
this.store.analytics.trackButtonClicked('switch_mining_type_button', 'Switch Mining Type Button', 'enabled')
this.setGpuOnly(!this.gpuMiningEnabled)
this.start(StartReason.Manual)
break
case StartActionType.StopPrepping:
this.store.analytics.trackButtonClicked('stop_prepping_button', 'Stop Prepping Button', 'enabled')
this.store.ui.hideModal()
this.stop(StopReason.Manual)
break
case StartActionType.Automatic:
this.start(StartReason.Automatic)
break
}
}.bind(this),
)
@action
public setSaladBowlConnected = (value: boolean) => {
this.saladBowlConnected = value
}
@action.bound
public setGpu = flow(function* (this: SaladForkAndBowlStore, value: boolean) {
let hasError = false
this.gpuMiningUpdatePending = true
try {
yield this.setWorkloadPreferences(
value,
this.cpuMiningEnabled,
this.gpuMiningOverridden,
this.cpuMiningOverridden,
)
} catch (_error: any) {
hasError = true
this.store.notifications.sendNotification({
category: NotificationMessageCategory.Error,
title: 'Unable to update your preference.',
message: 'We were unable to update your preference, please try again.',
type: 'error',
})
} finally {
if (!hasError) {
this.gpuMiningEnabled = value
}
this.gpuMiningUpdatePending = false
}
})
@action.bound
public setCpu = flow(function* (this: SaladForkAndBowlStore, value: boolean) {
let hasError = false
this.cpuMiningUpdatePending = true
try {
yield this.setWorkloadPreferences(
this.gpuMiningEnabled,
value,
this.gpuMiningOverridden,
this.cpuMiningOverridden,
)
} catch (_error: any) {
hasError = true
this.store.notifications.sendNotification({
category: NotificationMessageCategory.Error,
title: 'Unable to update your preference.',
message: 'We were unable to update your preference, please try again.',
type: 'error',
})
} finally {
if (!hasError) {
this.cpuMiningEnabled = value
}
this.cpuMiningUpdatePending = false
}
})
@action.bound
public setCpuOverride = flow(function* (this: SaladForkAndBowlStore, value: boolean) {
let hasError = false
this.cpuMiningOverriddenUpdatePending = true
try {
yield this.setWorkloadPreferences(this.gpuMiningEnabled, this.cpuMiningEnabled, this.gpuMiningOverridden, value)
} catch (_error: any) {
hasError = true
this.store.notifications.sendNotification({
category: NotificationMessageCategory.Error,
title: 'Unable to update your preference.',
message: 'We were unable to update your preference, please try again.',
type: 'error',
})
} finally {
if (!hasError) {
this.cpuMiningOverridden = value
}
this.cpuMiningOverriddenUpdatePending = false
}
})
@action.bound
public setGpuOverride = flow(function* (this: SaladForkAndBowlStore, value: boolean) {
let hasError = false
this.gpuMiningOverriddenUpdatePending = true
try {
yield this.setWorkloadPreferences(this.gpuMiningEnabled, this.cpuMiningEnabled, value, this.cpuMiningOverridden)
} catch (_error: any) {
hasError = true
this.store.notifications.sendNotification({
category: NotificationMessageCategory.Error,
title: 'Unable to update your preference.',
message: 'We were unable to update your preference, please try again.',
type: 'error',
})
} finally {
if (!hasError) {
this.gpuMiningOverridden = value
}
this.gpuMiningOverriddenUpdatePending = false
}
})
// Persist Salad Bowl Store State on refresh
public getSaladBowlState = flow(function* (this: SaladForkAndBowlStore, saladBowlState?: SaladBowlState) {
// Check to see if we have any workload preferences
const preferences = saladBowlState?.preferences
let gpuMining = false
let cpuMining = false
let gpuMiningOverridden = false
let cpuMiningOverridden = false
if (preferences === undefined || (preferences && Object.keys(preferences).length === 0)) {
// should show onboarding page here if this is detected.
const cpuMiningEnabled = Storage.getItem(CPU_MINING_ENABLED) === 'true'
const cpuMiningOverrideEnabled = Storage.getItem(CPU_MINING_OVERRIDDEN) === 'true'
const gpuMiningOverrideEnabled = Storage.getItem(GPU_MINING_OVERRIDDEN) === 'true'
gpuMining = !cpuMiningEnabled
cpuMining = cpuMiningEnabled
gpuMiningOverridden = gpuMiningOverrideEnabled
cpuMiningOverridden = cpuMiningOverrideEnabled
} else {
gpuMining = preferences['mining/gpu']
cpuMining = preferences['mining/cpu']
gpuMiningOverridden = preferences['mining/gpu-override']
cpuMiningOverridden = preferences['mining/cpu-override']
}
let hasError = false
this.gpuMiningUpdatePending = true
this.cpuMiningUpdatePending = true
this.gpuMiningOverriddenUpdatePending = true
this.cpuMiningOverriddenUpdatePending = true
try {
yield this.setWorkloadPreferences(gpuMining, cpuMining, gpuMiningOverridden, cpuMiningOverridden)
} catch (_error: any) {
hasError = true
this.store.notifications.sendNotification({
category: NotificationMessageCategory.Error,
title: 'Unable to update your preference.',
message: 'We were unable to update your preference while logging in.',
type: 'error',
})
} finally {
if (!hasError) {
this.gpuMiningEnabled = gpuMining
this.cpuMiningEnabled = cpuMining
this.gpuMiningOverridden = gpuMiningOverridden
this.cpuMiningOverridden = cpuMiningOverridden
}
this.gpuMiningUpdatePending = false
this.cpuMiningUpdatePending = false
this.gpuMiningOverriddenUpdatePending = false
this.cpuMiningOverriddenUpdatePending = false
}
// TODO: Check to see if we are currently chopping
// if (!this.isRunning) {
// return
// }
// Change this to a run in action
// return {
// isRunning: this.isRunning,
// startTimestamp: this.startTimestamp,
// choppingTime: this.choppingTime,
// }
})
private setWorkloadPreferences = (
gpuMining: boolean,
cpuMining: boolean,
gpuMiningOverridden: boolean,
cpuMiningOverridden: boolean,
): Promise<void> => {
return this.store.saladFork.setPreferences({
'mining/gpu': gpuMining,
'mining/cpu': cpuMining,
'mining/gpu-override': gpuMiningOverridden,
'mining/cpu-override': cpuMiningOverridden,
elevated: false,
})
}
public setGpuOnly = (value: boolean) => {
console.log(value)
}
} | the_stack |
const acorn = require("acorn")
const walk = require("acorn-walk")
import * as et from "estree"
import { CategoriesPriorityQueue } from './utils'
import { BlockChain, IBlock, IFuncBlock } from './block-chain'
export const enum VariableType {
NO_EXIST = -1,
FUNCTION = 1,
VARIABLE = 2,
CLOSURE = 3,
}
interface IScope {
funcName: string, // for debug.
// params: Map<string, any>,
// locals: Map<string, any>,
closureTable?: Map<string, any>,
closureCounter?: number // 只有最外层的函数有
}
interface IFunction {
name: string,
body: et.FunctionExpression | et.ArrowFunctionExpression | et.FunctionDeclaration,
blockChain: BlockChain,
prepare: () => void,
// scopes: IScope[], // 存储作用域链
// params: { [x in string]: 1 }[],
}
interface IState {
tmpVariableName: string,
// globals: any,
// locals: Map<string, any>,
// params: Map<string, any>,
scopes: IScope[],
isGlobal: boolean,
labelIndex: number,
functionIndex: number,
functionTable: any,
functions: IFunction[],
codes: CategoriesPriorityQueue<string | (() => string[])>,
r0: string | null,
r1: string | null,
r2: string | null,
maxRegister: number,
currentFunctionName: string,
funcName: string,
currentScope?: IScope,
blockChain: BlockChain,
// $obj: string,
// $key: string,
// $val: string,
}
interface BlockLabel {
startLabel?: string,
endLabel?: string,
updateLabel?: string,
blockNameStart?: string, // 给 block 起名,这样好 continue 和 break
blockNameBody?: string, // 给 block 起名,这样好 continue 和 break
isForIn?: boolean,
startBlock?: IBlock,
bodyBlock?: IBlock,
}
const codeMap = {
'<': 'LT',
'>': 'GT',
'===': 'EQ',
'!==': 'NE',
'==': 'WEQ',
'!=': 'WNE',
'<=': 'LE',
'>=': 'GE',
'+': 'ADD',
'-': 'SUB',
'*': 'MUL',
'/': 'DIV',
'%': 'MOD',
'&': 'AND',
'|': 'OR',
'^': 'XOR',
'<<': 'SHL',
'>>': 'SHR',
'>>>': 'ZSHR',
"in": "IN",
'instanceof': 'INST_OF',
}
class Codegen {
public parse(code: string): et.Program {
return acorn.parse(code)
}
}
/**
* 为了处理这种情况:
* ```
* i = 1
* var i
* ```
*/
const getVariablesByFunctionAstBody = (ast: any): Map<string, any> => {
const locals = new Map()
walk.recursive(ast, locals, {
VariableDeclaration: (node: et.VariableDeclaration, s: any, c: any): void => {
// console.log("VARIABLE...", node)
s.varKind = node.kind
node.declarations.forEach((n: any): void => c(n, s))
delete s.varKind
},
/** 要处理 (global, local) * (function, other) 的情况 */
VariableDeclarator: (node: et.VariableDeclarator, s: any, c: any): void => {
const kind = s.varKind
// console.log(node)
// let funcName = ''
if (node.id.type === 'Identifier') {
if (kind === 'var') {
locals.set(node.id.name, VariableType.VARIABLE)
}
} else {
throw new Error("Unprocessed node.id.type " + node.id.type + " " + node.id)
}
},
FunctionDeclaration(node: et.FunctionDeclaration, s: any, c: any): any {
if (node.id) {
locals.set(node.id.name, VariableType.VARIABLE)
}
},
FunctionExpression(): any {
},
ArrowFunctionExpression(): any {
},
})
return locals
}
const codegen = new Codegen()
let state: IState
const createNewState = (): IState => {
return {
tmpVariableName: '',
isGlobal: true,
// globals: {},
// locals: new Map(),
currentScope: {
funcName: '',
// params: new Map(),
// locals: new Map(),
closureTable: new Map(),
closureCounter: 0,
},
// params: new Map(),
scopes: [],
labelIndex: 0,
functionIndex: 0,
functions: [],
functionTable: {},
funcName: '',
codes: new CategoriesPriorityQueue(),
r0: '', // 寄存器的名字
r1: '', // 寄存器的名字
r2: '', //
maxRegister: 0,
currentFunctionName: '',
blockChain: new BlockChain([]),
}
}
// tslint:disable-next-line: no-big-function
const parseToCode = (ast: any): void => {
const newFunctionName = (): string => {
state.currentFunctionName = `@@f${state.functionIndex++}`
return state.currentFunctionName
}
const parseFunc = (
node: et.FunctionExpression | et.ArrowFunctionExpression | et.FunctionDeclaration,
s: IState,
prior?: number,
): string => {
const retReg = s.r0
const originalFunctionName = (node as any).id?.name
const isFuntionExpression = node.type === 'FunctionExpression'
if (originalFunctionName && !isFuntionExpression) {
declareVariable(s, originalFunctionName, 'var', true)
}
const funcName = newFunctionName()
// s.globals[funcName] = VariableType.FUNCTION
s.blockChain.newGlobal(funcName, VariableType.FUNCTION)
s.functions.push({
name: funcName,
body: node,
blockChain: s.blockChain.newFuncBlock(),
prepare(): void {
const funcBlock = s.blockChain.getCurrentBlock() as IFuncBlock
const isBlockHasSameName = funcBlock.variables.has(originalFunctionName) ||
funcBlock.params.has(originalFunctionName)
if (isFuntionExpression && originalFunctionName && !isBlockHasSameName) {
declareVariable(s, originalFunctionName, 'var')
cg([`FUNC`, `${originalFunctionName}`, `${funcName}`], { prior })
}
},
// scopes: [...s.scopes, getCurrentScope() || {
// locals: s.locals, params: s.params, closureCounter: 0,
// }],
})
s.functionTable[funcName] = node
// console.log(s.r0, '....', s.functionTable)
if (retReg) {
cg([`FUNC`, `${retReg}`, `${funcName}`], { prior })
}
if (originalFunctionName && !isFuntionExpression) {
cg([`FUNC`, `${originalFunctionName}`, `${funcName}`], { prior })
}
delete s.funcName
return funcName
}
let registerCounter = 0
let maxRegister = 0
const newLabelName = (): string => `_l${state.labelIndex++}_`
const newRegister = (): string => {
const r = `%r${registerCounter++}`
maxRegister = Math.max(maxRegister, registerCounter)
return r
}
const freeRegister = (): number => {
state.r0 = null
return registerCounter--
}
const newRegisterController = (): [any, any] => {
let count = 0
return [(): string => {
count++
return newRegister()
}, (): void => {
state.r0 = null
for (let i = 0; i < count; i++) {
freeRegister()
}
}]
}
// const hasLocalOrParam = (name: string, s: IState): boolean => {
// return s.locals.get(name) || s.params.get(name)
// }
// const hasVars = (name: string, s: any): boolean => {
// if (hasLocalOrParam(name, s)) { return true }
// for (const scope of [...state.scopes]) {
// if (scope.locals.get(name) || scope.params.get(name)) {
// return true
// }
// }
// return !!s.globals.get(name)
// }
// const getCurrentScope = (): IScope => {
// return state.currentScope!
// }
// const allocateClosure = (root: IScope, scope: IScope, reg: string): void => {
// if (!scope.closureTable) {
// scope.closureTable = new Map()
// }
// if (!scope.closureTable.get(reg)) {
// if (root.closureCounter === void 0) {
// throw new Error("Root scope closure counter cannot be 0.")
// } else {
// scope.closureTable.set(reg, `@c${root.closureCounter++}`)
// }
// }
// }
// const touchRegister = (
// reg: string,
// currentScope: IScope,
// scopes: IScope[],
// blockChain: Map<string, VariableType>[]): void => {
// /** 这个变量当前 scope 有了就不管了 */
// const currentBlock = blockChain[blockChain.length - 1]
// // if (currentBlock)
// if (currentScope.locals.get(reg) || currentScope.params.get(reg)) { return }
// let i = 0
// for (const scope of [...scopes].reverse()) {
// if (scope.locals.get(reg)) {
// scope.locals.set(reg, VariableType.CLOSURE)
// allocateClosure(scopes[0], scope, reg)
// return
// }
// if (scope.params.get(reg)) {
// scope.params.set(reg, VariableType.CLOSURE)
// allocateClosure(scopes[0], scope, reg)
// return
// }
// i++
// }
// }
// const getRegisterName = (reg: string, currentScope: IScope, scopes: IScope[], isVar: boolean = false): string => {
// const isClosure = (v: VariableType): boolean => v === VariableType.CLOSURE
// const regType = currentScope.locals.get(reg) || currentScope.params.get(reg)
// if (regType) {
// if (regType === VariableType.CLOSURE) {
// return currentScope.closureTable?.get(reg)
// } else {
// return reg
// }
// }
// for (const scope of [...scopes, currentScope].reverse()) {
// if (
// isClosure(scope.locals.get(reg)) ||
// isClosure(scope.params.get(reg))
// ) {
// if (!scope.closureTable?.get(reg)) {
// throw new Error(`Cannot found clouse variable ${reg} on closure table`)
// }
// return scope.closureTable.get(reg)
// }
// }
// return reg
// }
const cg = (ops: any[], { prior, isForceBlock }: { prior?: number, isForceBlock?: boolean } = {}): any => {
/** 各种动态生成 */
// if (typeof ops[0] === 'function') {
// ops = ops[0]()
// }
let operator = ops[0]
if (!operator || operator ==='undefined') {
throw new Error('Operator cannot be ' + operator)
}
const operants = ops.slice(1)
if (operator === 'MOV' && ops[1] === 'undefined') {
throw new Error('First operant of MOV cannot be undefined' )
}
// if (ops[0] === 'MOV') {
// state.codes.push(createMovCode(ops[1], ops[2], getCurrentScope()))
// } else {
// const currentScope = getCurrentScope()
// const scopes = state.scopes
const blockChain = state.blockChain
// const currentBlock = blockChain[blockChain.length - 1]
// console.log(operants, '--->')
operants.forEach((o: any): void => {
if (typeof o === 'string') {
blockChain.accessName(o)
// if (isMade && o === 't') {
// console.log('--------------------------------------------------')
// console.log(ops)
// for (const c of blockChain.chain) {
// console.log(c)
// }
// }
}
})
/** 这里需要提前一些指令,例如变量声明、全局变量、有名函数声明 */
let priority
if (prior === void 0) {
// if ('VAR' === operator) {
// priority = 1
// } else if ('GLOBAL' === operator) {
// priority = 2
if ('ALLOC' === operator) {
priority = 3
// } else if ('FUNC' === operator && blockChain.hasName(operants[0])) {
// priority = 4
} else {
priority = 100
}
} else {
priority = prior
}
const currentBlock = blockChain.getCurrentBlock()
return state.codes.push((): string[] => {
// console.log(ops, operants)
// console.log(operator, operants)
// TOFIX: 是否要清除 block?还是要再考虑一下
if (
['BLOCK', 'END_BLOCK', 'CLR_BLOCK'].includes(operator) &&
currentBlock.variables.size === 0 &&
!(currentBlock.isForceBlock || isForceBlock)
) {
return []
}
if (typeof operator === 'function') {
operator = operator()
}
const processedOps = operants.map((o): string => {
if (typeof o === 'function') {
o = o()
}
// if (o === 'momentProperties') {
// console.log(blockChain)
// }
return blockChain.getName(o)
// return getRegisterName(o, currentScope, scopes, operator === 'VAR')
})
const ret: any[] = []
const pushCode = (): void => {
const c = [operator, ...processedOps].join(' ')
ret.push(c)
}
if (
['VAR', 'BVAR'].includes(operator) &&
blockChain.getNameType(operants[0]) === VariableType.CLOSURE
) {
operator = 'CLS'
pushCode()
// ret.push(`ALLOC ${processedOps[0]}`)
} else {
pushCode()
}
return ret
}, priority)
// }
}
/** 生成 label */
const lg = (label: string): string => {
return cg([`LABEL ${label}:`])
}
const callIdentifier = (id: string, numArgs: number, s: IState, isExpression: boolean): void => {
// if (s.functionTable[id]) {
// cg('CALL', id, numArgs, isExpression)
// } else
s.blockChain.accessName(id)
// touchRegister(id, getCurrentScope(), state.scopes, s.blockChain)
if (s.blockChain.hasName(id)) {
cg([`CALL_REG`, id, numArgs, isExpression])
} else {
cg([`CALL_CTX`, `'${id}'`, numArgs, isExpression])
}
}
/**
* 所有的操作都是先获取到临时寄存器,操作完以后再写回目标寄存器
* 有四种种目标操作
* 1. Identifier: 局部变量、context、闭包变量
* 2. Member
*/
const setValueToNode = (node: any, reg: string, s: IState, c: any): any => {
if (node.type === 'MemberExpression') {
// s.r0 = newReg()
s.r0 = null
const objReg = s.r1 = newRegister()
const keyReg = s.r2 = newRegister()
c(node, s)
cg([`SET_KEY`, objReg, keyReg, reg])
freeRegister()
freeRegister()
} else if (node.type === 'Identifier') {
if (s.blockChain.hasName(node.name)) {
cg([`MOV`, `${ node.name }`, `${ reg }`])
} else {
cg([`SET_CTX`, `"${node.name}"`, `${ reg }`])
}
} else {
throw new Error('Unprocessed assignment')
}
}
const getValueOfNode = (node: any, reg: string, s: IState, c: any): any => {
if (node.type === 'Identifier') {
if (reg) {
if (s.blockChain.hasName(node.name)) {
cg([`MOV`, `${ reg }`, `${ node.name }`])
} else {
if (node.name === 'arguments') {
cg([`MOV_ARGS`, `${ reg }`])
} else {
cg([`MOV_CTX`, `${ reg }`, `"${node.name}"`])
}
}
}
} else {
s.r0 = reg
s.r1 = null
s.r2 = null
c(node, s)
s.r0 = null
s.r1 = null
s.r2 = null
}
}
const declareVariable = (
s: IState, name: string,
kind: 'let' | 'var' | 'const' = 'var',
isForce: boolean = false,
): void => {
// if (state.isGlobal) {
// cg(`GLOBAL`, name)
// s.globals.set(name, VariableType.VARIABLE)
/* } else */
// if (state.isGlobal) {
// cg(`GLOBAL`, name)
// s.blockChain.newGlobal(name, VariableType.VARIABLE)
// } else
if ((kind === 'let' || kind === 'const') && s.blockChain.chain.length > 1) {
cg(['VAR', `${name}`])
s.blockChain.newName(name, kind, isForce)
} else {
// console.log("nnnnnnnnnnnnnnnnnnnnnnnnnnnn new name", name)
// if (name === 'e') {
// throw new Error('fuck')
// }
cg([`VAR`, `${name}`], { prior: 1 })
s.blockChain.newName(name, kind, isForce)
}
}
/** Label 操作 */
const loopLabels: BlockLabel[] = []
const pushLoopLabels = (label: BlockLabel): any => loopLabels.push(label)
const popLoopLabels = (): BlockLabel | undefined => loopLabels.pop()
const getCurrentLoopLabel = (): BlockLabel => loopLabels[loopLabels.length - 1]
const blockEndLabels: Map<string, BlockLabel> = new Map()
const newBlockChain = (): (() => void) & { blockIndexName: string } => {
// throw new Error('shoud not called ...')
const oldBlockChain = state.blockChain
// state.blockChain = [...oldBlockChain, new Map<string, any>()]
state.blockChain = oldBlockChain.newBlock()
const blockName = state.blockChain.newBlockName()
cg(['BLOCK', blockName])
const ret = (): void => {
// const currentBlock = state.blockChain[state.blockChain.length - 1]
cg(['END_BLOCK', blockName])
state.blockChain = oldBlockChain
// for (const [name] of currentBlock.entries()) {
// cg('FREEBV', name)
// }
}
ret.blockIndexName = blockName
return ret
}
/**
* 表达式结果处理原则:所有没有向下一层传递 s.r0 的都要处理 s.r0
*/
walk.recursive(ast, state, {
Identifier: (node: et.Identifier, s: any, c: any): void => {
if (s.r0) {
getValueOfNode(node, s.r0, s, c)
}
},
VariableDeclaration: (node: et.VariableDeclaration, s: any, c: any): void => {
// console.log("VARIABLE...", node)
s.varKind = node.kind
node.declarations.forEach((n: any): void => c(n, s))
delete s.varKind
},
/** 要处理 (global, local) * (function, other) 的情况 */
VariableDeclarator: (node: et.VariableDeclarator, s: any, c: any): void => {
// console.log(node)
const [newReg, freeReg] = newRegisterController()
let reg
// let funcName = ''
if (node.id.type === 'Identifier') {
// if (isInitFunction) {
// reg = node.id.name // newReg()
// if (state.isGlobal) {
// funcName = node.id.name
// } else {
// s.locals[node.id.name] = VariableType.VARIABLE
// cg(`VAR`, `${node.id.name}`)
// funcName = newFunctionName()
// }
// } else {
declareVariable(s, node.id.name, s.varKind)
reg = node.id.name
// }
} else {
throw new Error("Unprocessed node.id.type " + node.id.type + " " + node.id)
}
if (node.init) {
if (node.init?.type === 'Identifier') {
// if (!state.isGlobal) {
getValueOfNode(node.init, reg, s, c)
// cg([`MOV`, reg, node.init.name])
// }
} else {
s.r0 = reg
// s.funcName = funcName
c(node.init, s)
}
}
freeReg()
delete s.funcName
},
FunctionDeclaration(node: et.FunctionDeclaration, s: any, c: any): any {
if (s.r0 && !state.isGlobal) {
parseFunc(node, s)
} else {
// s.r0 = node.id?.name
// declareVariable(s, s.r0)
parseFunc(node, s, 4)
}
s.r0 = null
},
CallExpression(node: et.CallExpression, s: any, c: any): any {
const retReg = s.r0
const isNewExpression = !!s.isNewExpression
delete s.isNewExpression
const args = [...node.arguments]
// args.reverse()
for (const arg of args) {
const reg = s.r0 = newRegister()
// if (arg.type === 'Identifier') {
getValueOfNode(arg, reg, s, c)
// } else {
// c(arg, s)
// freeRegister()
// }
freeRegister()
cg([`PUSH`, reg])
}
if (node.callee.type === "MemberExpression") {
s.r0 = null
const objReg = s.r1 = newRegister()
const keyReg = s.r2 = newRegister()
c(node.callee, s)
cg([`CALL_VAR`, objReg, keyReg, node.arguments.length, isNewExpression])
freeRegister()
freeRegister()
} else if (node.callee.type === "Identifier") {
callIdentifier(node.callee.name, node.arguments.length, s, isNewExpression)
} else {
const ret = s.r0 = newRegister()
c(node.callee, s)
freeRegister()
/** 这里不能用 callIdentifier */
cg([`CALL_REG`, ret, node.arguments.length, isNewExpression])
}
if (retReg) {
cg([`MOV`, retReg, `$RET`])
}
s.r0 = null
},
Literal: (node: et.Literal, s: any): void => {
const unescape = (ss: string): string => ss.replace(/\\/g, '\\\\').replace(/"/g, '\\"')
if ((node as any).regex) {
const { pattern, flags } = (node as any).regex
cg(['NEW_REG', s.r0, `"${unescape(pattern)}"`, `"${flags}"`])
return
}
let val
if (node.value === true) {
val = true
} else if (node.value === false) {
val = false
} else {
val = node.value
if (typeof val === 'string') {
val = `"${unescape(val)}"`
}
}
if (s.r0) {
cg([`MOV`, s.r0, `${val}`])
}
},
ArrowFunctionExpression(node: et.ArrowFunctionExpression, s: any, c: any): any {
parseFunc(node, s)
},
FunctionExpression(node: et.FunctionExpression, s: any, c: any): any {
parseFunc(node, s)
},
BlockStatement(node: et.BlockStatement, s: any, c: any): void {
const restoreBlockChain = newBlockChain()
node.body.forEach((n: any): void => c(n, s))
restoreBlockChain()
},
MemberExpression(node: et.MemberExpression, s: any, c: any): void {
const [newReg, freeReg] = newRegisterController()
const valReg = s.r0
const objReg = s.r1 || newReg()
const keyReg = s.r2 || newReg()
if (node.object.type === 'MemberExpression') {
s.r0 = objReg
s.r1 = newRegister()
s.r2 = null
c(node.object, s)
freeRegister()
} else if (node.object.type === 'Identifier') {
getValueOfNode(node.object, objReg, s, c)
} else {
// s.r0 = objReg
// c(node.object, s)
getValueOfNode(node.object, objReg, s, c)
}
if (node.property.type === 'MemberExpression') {
s.r0 = keyReg
s.r1 = null
s.r2 = newRegister()
c(node.property, s)
freeRegister()
} else if (node.property.type === 'Identifier') {
// a.b.c.d
if (node.computed) {
cg([`MOV`, keyReg, node.property.name])
} else {
cg([`MOV`, keyReg, `"${node.property.name}"`])
}
} else {
getValueOfNode(node.property, keyReg, s, c)
}
if (valReg) {
cg([`MOV_PROP`, valReg, objReg, keyReg])
}
s.r0 = null
s.r1 = null
s.r2 = null
freeReg()
},
AssignmentExpression(node: et.AssignmentExpression, s: any, c: any): any {
const retReg = s.r0
const left = node.left
const right = node.right
const [newReg, freeReg] = newRegisterController()
let rightReg = newReg()
const isLeftMembership = left.type === 'MemberExpression'
let objReg: any // = newReg()
let keyReg: any // = newReg()
if (isLeftMembership) {
objReg = newReg()
keyReg = newReg()
s.r1 = objReg
s.r2 = keyReg
c(left, s)
}
const getLeftReg = (reg: string): void => {
if (isLeftMembership) {
cg(["MOV_PROP", reg, objReg, keyReg])
} else {
getValueOfNode(left, reg, s, c)
}
}
const setLeftReg = (reg: string): void => {
if (isLeftMembership) {
cg([`SET_KEY`, `${objReg}`, keyReg, `${reg}`])
} else {
setValueToNode(left, reg, s, c)
}
}
getValueOfNode(right, rightReg, s, c)
if (node.operator !== '=') {
const o = node.operator.replace(/\=$/, '')
const cmd = codeMap[o]
if (!cmd) { throw new Error(`Operation ${o} is not implemented.`)}
const leftReg = newReg()
getLeftReg(leftReg)
// getValueOfNode(left, leftReg, s, c)
cg([`${cmd}`, leftReg, rightReg])
rightReg = leftReg
}
setLeftReg(rightReg)
// setValueToNode(left, rightReg, s, c)
if (retReg) {
cg([`MOV`, retReg, rightReg])
}
freeReg()
},
BinaryExpression(node: et.BinaryExpression, s: any, c: any): void {
const [newReg, freeReg] = newRegisterController()
const leftReg = s.r0 || newReg()
s.r0 = null
const rightReg = newReg()
getValueOfNode(node.left, leftReg, s, c)
getValueOfNode(node.right, rightReg, s, c)
// if (node.operator === '') {
// }
const op = codeMap[node.operator]
if (!op) {
throw new Error(`${ node.operator } is not implemented.`)
}
cg([op, leftReg, rightReg])
freeReg()
},
UnaryExpression(node: et.UnaryExpression, s: any, c: any): void {
const op = node.operator
const codesMap = {
'+': 'PLUS',
'-': 'MINUS',
'~': 'NOT',
'!': 'NEG',
'void': 'VOID',
'typeof': 'TYPE_OF',
}
const [newReg, freeReg] = newRegisterController()
const cmd = codesMap[node.operator]
if (op !== 'delete') {
const reg = s.r0 || newReg()
if (!reg) {
console.log((node.argument as any).callee.body.body[0])
throw new Error('! regster should not be null')
}
getValueOfNode(node.argument, reg, s, c)
cg([`${cmd}`, `${reg}`])
} else {
s.r0 = null
const objReg = s.r1 = newReg()
const keyReg = s.r2 = newReg()
c(node.argument, s)
cg([`DEL`, `${objReg}`, `${keyReg}`])
s.r1 = null
s.r2 = null
}
freeReg()
},
IfStatement(node: any, s: any, c: any): void {
// const restoreBlockChain = newBlockChain()
const [newReg, freeReg] = newRegisterController()
const retReg = s.r0
const endLabel = newLabelName()
while (node && (node.type === 'IfStatement' || node.type === 'ConditionalExpression')) {
const testReg = newReg()
const nextLabel = newLabelName()
s.r0 = testReg
c(node.test, s)
cg([`JF`, testReg, nextLabel])
getValueOfNode(node.consequent, retReg, s, c)
cg([`JMP`, endLabel])
cg([`LABEL`, `${ nextLabel }:`])
node = node.alternate
// if (node.alternate) {
// getValueOfNode(node.alternate, retReg, s, c)
// }
}
if (node) {
getValueOfNode(node, retReg, s, c)
}
cg([`LABEL`, `${ endLabel }:`])
freeReg()
// restoreBlockChain()
},
ConditionalExpression(node: et.ConditionalExpression, s: any, c: any): void {
this.IfStatement(node, s, c)
},
LogicalExpression(node: et.LogicalExpression, s: any, c: any): void {
const [newReg, freeReg] = newRegisterController()
const retReg = s.r0
const endLabel = newLabelName()
const leftReg = s.r0 = newReg()
getValueOfNode(node.left, leftReg, s, c)
const op = node.operator
if (retReg) {
cg([`MOV`, `${retReg}`, `${leftReg}`])
}
if (op === '&&') {
cg([`JF`, `${leftReg}`, `${endLabel}`])
} else {
cg([`JIF`, `${leftReg}`, `${endLabel}`])
}
const rightReg = s.r0 = newReg()
getValueOfNode(node.right, rightReg, s, c)
if (retReg) {
cg([op === '&&' ? `LG_AND` : `LG_OR`, `${retReg}`, `${rightReg}`])
}
cg(['LABEL', `${endLabel}:`])
freeReg()
},
ForStatement(node: et.ForStatement, s: any, c: any): any {
const restoreBlockChainInit = newBlockChain()
const [newReg, freeReg] = newRegisterController()
const startLabel = newLabelName()
let endLabel = newLabelName()
const updateLabel = newLabelName()
let labels: BlockLabel
if (s.jsLabel) {
if (!blockEndLabels.has(s.jsLabel)) {
throw new Error('If has `jsLabel`, label information should be set')
}
labels = blockEndLabels.get(s.jsLabel)!
labels.startLabel = startLabel
if (!labels.endLabel) {
throw new Error('Endlabel is not set in label information')
}
endLabel = labels.endLabel
delete s.jsLabel
} else {
labels = { startLabel, endLabel }
}
if (node.update) {
labels.updateLabel = updateLabel
}
labels.startBlock = s.blockChain.getCurrentBlock()
labels.blockNameStart = labels.blockNameBody = restoreBlockChainInit.blockIndexName
pushLoopLabels(labels)
// init
if (node.init) {
// console.log('--- INTI -->', node.init)
c(node.init, s)
}
// if do while
const isDoWhileLoop = node.type as string === 'DoWhileStatement'
const bodyLabel = newLabelName()
if (isDoWhileLoop) {
cg([`JMP`, bodyLabel])
}
cg([`LABEL`, `${ startLabel }:`])
// test
if (node.test) {
const testReg = s.r0 = newReg()
c(node.test, s)
cg([`JF`, `${ testReg }`, `${ endLabel }`])
}
// body
s.forEndLabel = endLabel
s.r0 = null
cg([`LABEL`, `${ bodyLabel }:`])
const restoreBlockChainBody = newBlockChain()
// console.log('for body', node.body)
labels.bodyBlock = s.blockChain.getCurrentBlock()
labels.blockNameBody = restoreBlockChainBody.blockIndexName
c(node.body, s)
restoreBlockChainBody()
// update
if (node.update) {
cg(['LABEL', `${ updateLabel }:`])
s.r0 = null
c(node.update, s)
}
cg([`JMP`, `${ startLabel }`])
// end
cg([`LABEL`, `${ endLabel }:`])
restoreBlockChainInit()
popLoopLabels()
freeReg()
},
ForInStatement(node: et.ForInStatement, s: any, c: any): any {
const restoreBlockChain = newBlockChain()
const left = node.left
const right = node.right
const [newReg, freeReg] = newRegisterController()
let leftReg
if (left.type === 'Identifier') {
leftReg = left.name
} else if (left.type === 'VariableDeclaration') {
const varDecorator = left.declarations[0]
leftReg = (varDecorator.id as et.Identifier).name
declareVariable(s, leftReg, left.kind)
} else {
throw new Error('Cannot process for in statement left type ' + left.type)
}
const rightReg = newReg()
const startLabel = newLabelName()
const endLabel = newLabelName()
getValueOfNode(right, rightReg, s, c)
const labels: BlockLabel = {
startLabel,
endLabel,
updateLabel: startLabel,
isForIn: true,
blockNameStart: restoreBlockChain.blockIndexName,
startBlock: s.blockChain.getCurrentBlock(),
}
pushLoopLabels(labels)
cg(['FORIN', leftReg, rightReg, startLabel, endLabel])
lg(startLabel)
const restoreBlockChainBody = newBlockChain()
labels.blockNameBody = restoreBlockChainBody.blockIndexName
labels.bodyBlock = s.blockChain.getCurrentBlock()
c(node.body, s)
restoreBlockChainBody()
cg(['FORIN_END'])
lg(endLabel)
restoreBlockChain()
freeReg()
popLoopLabels()
},
WhileStatement(node: et.WhileStatement, s: any, c: any): any {
this.ForStatement(node, s, c)
},
DoWhileStatement(node: et.DoWhileStatement, s: any, c: any): any {
this.ForStatement(node, s, c)
},
BreakStatement(node: et.BreakStatement, s: any, c: any): any {
if (node.label) {
const { name } = node.label
if (!blockEndLabels.has(name)) {
throw new Error(`Label ${name} does not exist.`)
}
const lb = blockEndLabels.get(name)!
lb.startBlock!.isForceBlock = true
cg(['CLR_BLOCK', lb.blockNameStart], { isForceBlock: true })
cg(['JMP', lb.endLabel])
return
}
// console.log(loopLabels)
const labels = getCurrentLoopLabel()
// console.log(node)
if (!labels) {
throw new Error("Not available labels, cannot use `break` here.")
}
if (labels.isForIn) {
cg(['BREAK_FORIN'])
return
}
const endLabel = labels.endLabel
if (labels.startBlock) { // for switch case
labels.startBlock.isForceBlock = true
}
if (!labels.blockNameStart) {
throw new Error('No start block name')
}
cg(['CLR_BLOCK', labels.blockNameStart], { isForceBlock: true })
cg([`JMP`, `${endLabel}`])
},
ContinueStatement(node: et.ContinueStatement, s: any, c: any): any {
if (node.label) {
const { name } = node.label
if (!blockEndLabels.has(name)) {
throw new Error(`Label ${name} does not exist.`)
}
const blockLabel = blockEndLabels.get(name)!
// continue label; 语法,如果有 update ,回到 update, 否则回到头
blockLabel.bodyBlock!.isForceBlock = true
cg(['CLR_BLOCK', blockLabel.blockNameBody], { isForceBlock: true })
cg(['JMP', blockLabel.updateLabel || blockLabel.startLabel])
return
}
const labels = getCurrentLoopLabel()
if (!labels) {
throw new Error("Not available labels, cannot use `continue` here.")
}
if (labels.isForIn) {
labels.bodyBlock!.isForceBlock = true
cg(['CLR_BLOCK', labels.blockNameBody], { isForceBlock: true })
cg(['CONT_FORIN'])
return
}
const { startLabel, updateLabel } = labels
// cg(`JMP ${endLabel} (break)`)
labels.bodyBlock!.isForceBlock = true
cg(['CLR_BLOCK', labels.blockNameBody], { isForceBlock: true })
cg([`JMP`, `${updateLabel || startLabel}`])
},
UpdateExpression(node: et.UpdateExpression, s: any, c: any): any {
const op = node.operator
const [newReg, freeReg] = newRegisterController()
const retReg = s.r0
const reg = newReg()
getValueOfNode(node.argument, reg, s, c)
if (retReg && !node.prefix) {
cg([`MOV ${retReg} ${reg}`])
}
if (op === '++') {
cg([`ADD`, `${reg}`, `1`])
} else if (op === '--') {
cg([`SUB`, `${reg}`, `1`])
}
if (retReg && node.prefix) {
cg([`MOV ${retReg} ${reg}`])
}
setValueToNode(node.argument, reg, s, c)
freeReg()
},
ObjectExpression(node: et.ObjectExpression, s: any, c: any): any {
const [newReg, freeReg] = newRegisterController()
const reg = s.r0 || newReg()
cg([`NEW_OBJ`, `${reg}`])
for (const prop of node.properties) {
s.r0 = reg
c(prop, s)
}
freeReg()
},
ArrayExpression(node: et.ArrayExpression, s: any, c: any): any {
const [newReg, freeReg] = newRegisterController()
const reg = s.r0 || newReg()
cg([`NEW_ARR`, `${reg}`])
node.elements.forEach((el: any, i: number): void => {
if (!el) {
return
}
const valReg = newRegister()
getValueOfNode(el, valReg, s, c)
cg([`SET_KEY`, `${reg}`, `${i}`, `${valReg}`])
freeRegister()
})
freeReg()
},
Property(node: et.Property, s: any, c: any): any {
const objReg = s.r0
const [newReg, freeReg] = newRegisterController()
const valReg = newReg()
let key
if (node.key.type === "Identifier") {
key = `'${node.key.name}'`
} else if (node.key.type === "Literal") {
const keyReg = newReg()
getValueOfNode(node.key, keyReg, s, c)
key = keyReg
}
getValueOfNode(node.value, valReg, s, c)
cg([`SET_KEY`, `${objReg}`, key, `${valReg}`])
// cg(`SET_KEY`, `${objReg}`, `"${key}"`, `${valReg}`)
freeReg()
},
ReturnStatement(node: et.ReturnStatement, s: any, c: any): any {
const reg = s.r0 = newRegister()
if (node.argument) {
c(node.argument, s)
cg([`MOV`, `$RET`, `${reg}`])
}
cg(['RET'])
freeRegister()
},
SequenceExpression(node: et.SequenceExpression, s: any, c: any): any {
const r0 = s.r0
delete s.r0
node.expressions.forEach((n, i): void => {
if (i === node.expressions.length - 1) {
s.r0 = r0
}
c(n, s)
})
},
ThisExpression(node: et.ThisExpression, s: any, c: any): any {
if (!s.r0) {
throw new Error('Access `this` without register r0')
}
cg([`MOV_THIS`, `${s.r0}`])
},
NewExpression(node: et.NewExpression, s: any, c: any): any {
s.isNewExpression = true
this.CallExpression(node, s, c)
},
LabeledStatement(node: et.LabeledStatement, s: any, c: any): any {
const restoreBlockChain = newBlockChain()
const labelNode = node.label
const labelName = labelNode.name
const endLabel = newLabelName()
blockEndLabels.set(labelName, {
endLabel,
blockNameStart: restoreBlockChain.blockIndexName,
startBlock: s.blockChain.getCurrentBlock(),
})
if (
node.body.type === 'ForStatement' ||
node.body.type === 'ForInStatement' ||
node.body.type === 'WhileStatement' ||
node.body.type === 'DoWhileStatement'
) {
s.jsLabel = labelName
}
c(node.body, s)
blockEndLabels.delete(labelName)
cg([`LABEL ${endLabel}:`])
restoreBlockChain()
},
SwitchStatement(node: et.SwitchStatement, s: any, c: any): any {
const restoreBlockChain = newBlockChain()
const [newReg, freeReg] = newRegisterController()
const discriminantReg = newReg()
getValueOfNode(node.discriminant, discriminantReg, s, c)
const switchEndLabel = newLabelName()
const label: BlockLabel = {
endLabel: switchEndLabel,
blockNameStart: restoreBlockChain.blockIndexName,
startBlock: s.blockChain.getCurrentBlock(),
}
pushLoopLabels(label)
let caseStartlabel: string = ''
const fetchCaseLabel = (): string => {
if (!caseStartlabel) {
caseStartlabel = newLabelName()
}
return caseStartlabel
}
const useCaseLabel = (): string => {
const ret = caseStartlabel
caseStartlabel = ''
return ret
// caseStartlabel = ''
// caseEndlabel = ''
// return ret
}
node.cases.forEach((cs: et.SwitchCase): void => {
let startLabel = fetchCaseLabel()
const endLabel = newLabelName()
if (cs.test) {
const testReg = newReg()
getValueOfNode(cs.test, testReg, s, c)
cg([`JE`, `${discriminantReg}`, `${testReg}`, `${startLabel}`])
cg([`JMP`, `${endLabel}`])
}
if (cs.consequent && cs.consequent.length > 0) {
startLabel = useCaseLabel()
cg([`LABEL ${startLabel}:`])
cs.consequent.forEach((n: any): void => {
c(n, s)
})
const nextStart = fetchCaseLabel()
cg([`JMP ${nextStart}`])
}
cg([`LABEL ${endLabel}:`])
})
if (caseStartlabel) {
cg([`LABEL ${caseStartlabel}:`])
}
cg([`LABEL ${switchEndLabel}:`])
popLoopLabels()
freeReg()
restoreBlockChain()
},
TryStatement(node: et.TryStatement, s: any, c: any): any {
// const restoreBlockChain = newBlockChain()
const catchLabel: string = newLabelName()
const finalLabel: string = newLabelName()
const endLabel = node.handler ? catchLabel : finalLabel
cg(['TRY', endLabel, finalLabel])
c(node.block, s)
cg(['TRY_END'])
if (node.handler) {
lg(catchLabel)
const restoreBlockChain = newBlockChain()
const handler = node.handler
if (handler.param) {
if (handler.param.type !== 'Identifier') {
throw new Error('cannot process error type ' + handler.param.type)
}
const errName = handler.param.name
declareVariable(s, errName, 'let')
cg(['GET_ERR', errName])
}
c(handler, s)
restoreBlockChain()
}
lg(finalLabel)
if (node.finalizer) {
const finalizer = node.finalizer
c(finalizer, s)
}
// restoreBlockChain()
},
ThrowStatement(node: et.ThrowStatement, s: any, c: any): any {
const reg = newRegister()
getValueOfNode(node.argument, reg, s, c)
cg(['THROW', reg])
freeRegister()
},
})
state.maxRegister = maxRegister
}
const getFunctionDecleration = (func: IFunction): string => {
const name = func.name
const params = func.body.params.map((p: any): string => '.' + p.name).join(', ')
return `func ${name}(${params}) {`
}
export const generateAssemblyFromJs = (jsCode: string): string => {
const ret = codegen.parse(jsCode)
let allCodes: any[] = []
const processFunctionAst = (funcBody: et.Node): void => {
/** () => a + b,无显式 return 的返回表达式 */
if (funcBody.type !== 'BlockStatement') {
// console.log(funcBody, '.....?')
state.r0 = '$RET'
}
parseToCode(funcBody)
for (let i = 0; i < state.maxRegister; i++) {
state.codes.push(`REG %r${i}`, 1)
}
state.codes.push('}')
allCodes = [...allCodes, ...state.codes]
state.codes.clear()
}
state = createNewState()
const globals = getVariablesByFunctionAstBody(ret)
state.blockChain = state.blockChain.newBlock(globals)
state.codes.push('func @@main() {', 0)
processFunctionAst(ret)
while (state.functions.length > 0) {
state.isGlobal = false
state.maxRegister = 0
const funcInfo = state.functions.shift()!
const funcBlockChain = funcInfo.blockChain
const params = funcInfo.body.params.reduce((o, param): any => {
o.set((param as et.Identifier).name, VariableType.VARIABLE)
return o
}, new Map())
const locals = getVariablesByFunctionAstBody(funcInfo.body.body)
if (!funcBlockChain.currentFuncBlock) { throw new Error('Should has function block chain.') }
const currentFuncBlock = funcBlockChain.currentFuncBlock
currentFuncBlock.params = params
currentFuncBlock.variables = locals
state.codes.push(getFunctionDecleration(funcInfo), 0)
state.codes.push((): string[] => {
const paramClosureDeclarations = [...currentFuncBlock.params.keys()].reduce((o: any, param: string): any => {
const paramType = funcBlockChain.getNameType(param)
if (paramType === VariableType.CLOSURE) {
// const closureName = currentFuncBlock.closures.get(param)
// console.log(
// '===========+>', varType, param, funcBlockChain.chain[funcBlockChain.chain.length - 1], currentFuncBlock)
// if (param === VariableType.CLOSURE) {
const name = funcBlockChain.getName(param)
o.push(`CLS ${name}`)
o.push(`MOV ${name} .${param}`)
// }
// if (!closureName) { throw new Error(`Parameter ${param} is closure but not allow name`) }
// o.push(`MOV ${closureName} ${param}`)
}
return o
}, [])
return paramClosureDeclarations.length > 0 ? paramClosureDeclarations : []
})
// state.scopes = funcInfo.scopes
state.blockChain = funcBlockChain
if (funcInfo.prepare) {
funcInfo.prepare()
}
// console.log(funcAst?.name, funcAst?.scopes)
processFunctionAst(funcInfo.body.body)
}
allCodes = allCodes.map((s: string | (() => string[])): string[] => {
const f = (c: string): string => {
if (c.trim() === '') { return ''}
if (c.startsWith('func') || c.startsWith('LABEL') || c.startsWith('}')) {
return c + '\n'
}
return ` ${c};\n`
}
if (typeof s === 'string') {
return [f(s)]
} else {
return s().map(f)
}
}).reduce((cc: string[], c: string[]): string[] => [...cc, ...c], [])
return allCodes.join("")
// tslint:disable-next-line: max-file-line-count
} | the_stack |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons';
import JqxChart, { IChartProps } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxchart';
import JqxDockingLayout, { IDockingLayoutProps } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxdockinglayout';
import JqxTextArea from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtextarea';
import JqxTree from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtree';
class App extends React.PureComponent<{}, IDockingLayoutProps> {
private myDockingLayout = React.createRef<JqxDockingLayout>();
private textArea1 = React.createRef<JqxTextArea>();
private viewServerExplorerBtn = React.createRef<JqxButton>();
constructor(props: {}) {
super(props);
this.viewServerExplorerBtnOnClick = this.viewServerExplorerBtnOnClick.bind(this);
const layout: IDockingLayoutProps['layout'] = [{
items: [{
alignment: 'left',
items: [{
contentContainer: 'ToolboxPanel',
title: 'Toolbox',
type: 'layoutPanel'
}, {
contentContainer: 'HelpPanel',
title: 'Help',
type: 'layoutPanel',
}],
type: 'autoHideGroup',
unpinnedWidth: 200,
width: 80
}, {
items: [{
height: 400,
items: [{
contentContainer: 'Document1Panel',
initContent: () => {
ReactDOM.render(<JqxTextArea ref={this.textArea1} width={'100%'} height={400} />, document.querySelector('#Document1TextArea'), () => {
this.textArea1.current!.val('<!DOCTYPE html>\n<html>\n\t<head>\n\t<title>Page Title</title>\n\t</head>\n\t<body>\n\t\t<h1>This is a Heading</h1>\n\t\t<p>This is a paragraph.</p>\n\t</body>\n</html>');
});
},
title: 'index.htm',
type: 'documentPanel'
}, {
contentContainer: 'Document2Panel',
initContent: () => {
ReactDOM.render(<JqxTextArea width={'100%'} height={400} placeHolder={'Blank document'} />, document.querySelector('#Document2TextArea'));
},
title: 'New Document',
type: 'documentPanel'
}],
minHeight: 200,
type: 'documentGroup'
}, {
height: 200,
items: [{
contentContainer: 'ErrorListPanel',
title: 'Error List',
type: 'layoutPanel',
}, {
contentContainer: 'PerformancePanel',
initContent: () => {
const data = [1, 5, 12, 5, 33, 38, 40, 42, 18, 18, 70, 76, 75, 99, 100, 88, 64, 13, 19, 15];
const padding = { left: 0, top: 10, right: 0, bottom: 0 };
const titlePadding = { left: 0, top: 0, right: 0, bottom: 0 };
const xAxis = { visible: false, valuesOnTicks: false };
const seriesGroups: IChartProps['seriesGroups'] = [{
columnsGapPercent: 0,
columnsMaxWidth: 2,
series: [{
colorFunction(value: any) {
if (value <= 33) {
return '#32CD32';
} else if (value <= 66) {
return '#FFD700';
} else {
return '#AA4643';
}
},
linesUnselectMode: 'click'
}],
type: 'line',
valueAxis: {
minValue: 0,
visible: false
}
}];
ReactDOM.render(
<JqxChart theme={'material-purple'} style={{ width: '100%', height: '100%' }}
title={'CPU Usage'} description={''} enableAnimations={false} showBorderLine={false} showLegend={false}
showToolTips={false} backgroundColor={'transparent'} padding={padding} titlePadding={titlePadding}
source={data} colorScheme={'scheme01'} xAxis={xAxis} seriesGroups={seriesGroups} />,
document.querySelector('#cpuUsage')
);
},
selected: true,
title: 'Performance',
type: 'layoutPanel'
}],
minHeight: 200,
pinnedHeight: 30,
type: 'tabbedGroup'
}],
orientation: 'vertical',
type: 'layoutGroup',
width: 500
}, {
items: [{
contentContainer: 'SolutionExplorerPanel',
initContent: () => {
// initialize a jqxTree inside the Solution Explorer Panel
const source = [{
expanded: true,
icon: 'https://www.jqwidgets.com/react/images/earth.png',
items: [{
expanded: true,
icon: 'https://www.jqwidgets.com/react/images/folder.png',
items: [{
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqx.base.css'
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqx.energyblue.css'
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqx.orange.css'
}],
label: 'css'
}, {
icon: 'https://www.jqwidgets.com/react/images/folder.png',
items: [{
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqxcore.js'
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqxdata.js'
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'jqxgrid.js'
}],
label: 'scripts',
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'index.htm',
selected: true
}],
label: 'Project'
}];
ReactDOM.render(<JqxTree width={'100%'} height={'99%'} source={source} />, document.querySelector('#solutionExplorerTree'));
},
title: 'Solution Explorer',
type: 'layoutPanel'
}, {
contentContainer: 'PropertiesPanel',
title: 'Properties',
type: 'layoutPanel'
}],
minWidth: 200,
type: 'tabbedGroup',
width: 220
}],
orientation: 'horizontal',
type: 'layoutGroup'
}];
this.state = {
layout
}
}
public render() {
return (
<div>
<JqxDockingLayout theme={'material-purple'} Layout ref={this.myDockingLayout}
// @ts-ignore
width={'100%'} height={600} layout={this.state.layout}>
{/* The panel content divs can have a flat structure */}
{/* autoHideGroup */}
<div data-container={'ToolboxPanel'}>
List of tools
</div>
<div data-container={'HelpPanel'}>
Help topics
</div>
{/* documentGroup */}
<div data-container={'Document1Panel'}>
<div style={{ padding: '5px' }}>
<div id="Document1TextArea" style={{ margin: '5px' }} />
</div>
</div>
<div data-container={'Document2Panel'}>
<div style={{ padding: '5px' }}>
<div id="Document2TextArea" style={{ margin: '5px' }} />
</div>
</div>
{/* bottom tabbedGroup */}
<div data-container={'ErrorListPanel'}>
No errors.
</div>
<div data-container={'PerformancePanel'}>
<div id="cpuUsage" style={{ width: '99%', height: '100px' }} />
</div>
{/* right tabbedGroup */}
<div data-container={'SolutionExplorerPanel'}>
<div id="solutionExplorerTree" style={{ border: 'none', width: '99%', height: '100%' }} />
</div>
<div data-container={'PropertiesPanel'}>
List of properties
</div>
</JqxDockingLayout>
<br />
<JqxButton theme={'material-purple'} ref={this.viewServerExplorerBtn} width={160}
onClick={this.viewServerExplorerBtnOnClick}>
View Server Explorer
</JqxButton>
</div>
);
}
private viewServerExplorerBtnOnClick(): void {
this.myDockingLayout.current!.addFloatGroup(300, 200, { x: 500, y: 200 }, 'layoutPanel', 'Server Explorer', '<div id="serverExplorerTree" style="width: 100%; height: 100%" />',
(): void => {
const source = [{
expanded: true,
icon: 'https://www.jqwidgets.com/react/images/dataadapter.png',
items: [{
icon: 'https://www.jqwidgets.com/react/images/validator.png',
label: 'northwinddatabase.mdf'
}],
label: 'Data Connections'
}, {
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
items: [{
icon: 'https://www.jqwidgets.com/react/images/nav1.png',
label: 'WorkStation3-PC'
}, {
icon: 'https://www.jqwidgets.com/react/images/dragdrop.png',
label: 'SharePoint Connections'
}],
label: 'Servers'
}];
ReactDOM.render(<JqxTree width={'99%'} height={'99%'} source={source} />, document.querySelector('#serverExplorerTree'));
}
);
this.viewServerExplorerBtn.current!.setOptions({ disabled: true });
}
}
export default App; | the_stack |
import { StatementTypes } from "../../chef/rust/statements/block";
import { ArgumentList, ClosureExpression, FunctionDeclaration, ReturnStatement } from "../../chef/rust/statements/function";
import { VariableDeclaration } from "../../chef/rust/statements/variable";
import { Expression, Operation } from "../../chef/rust/values/expression";
import { Type, Value, ValueTypes as RustValueTypes, ValueTypes } from "../../chef/rust/values/value";
import { VariableReference } from "../../chef/rust/values/variable";
import { Component } from "../../component";
import { IFinalPrismSettings } from "../../settings";
import { Module } from "../../chef/rust/module";
import { Module as JSModule } from "../../chef/javascript/components/module";
import { ModStatement } from "../../chef/rust/statements/mod";
import { TypeSignature } from "../../chef/rust/statements/struct";
import { UseStatement } from "../../chef/rust/statements/use";
import { ElseStatement, IfStatement } from "../../chef/rust/statements/if";
import { ForStatement } from "../../chef/rust/statements/for";
import { IShellData } from "../template";
import { jsAstToRustAst, typeMap } from "../../chef/rust/utils/js2rust";
import { InterfaceDeclaration as TSInterfaceDeclaration } from "../../chef/javascript/components/types/interface";
import { DynamicStatement } from "../../chef/rust/dynamic-statement";
import { Comment as JSComment } from "../../chef/javascript/components/statements/comments";
import { Value as JSValue } from "../../chef/javascript/components/value/value";
import { VariableReference as JSVariableReference } from "../../chef/javascript/components/value/expression";
import { IType } from "../../chef/javascript/utils/types";
import {
IServerRenderSettings, ServerRenderChunk, ServerRenderedChunks, serverRenderPrismNode
} from "../../templating/builders/server-render";
import {
ImportStatement as JSImportStatement,
ExportStatement as JSExportStatement
} from "../../chef/javascript/components/statements/import-export";
import { dirname, join, relative, basename } from "path";
import { ObjectLiteral } from "../../chef/javascript/components/value/object";
/** The variable which points to the String that is appended to */
const accVariable = new VariableReference("acc");
/**
* Builds a array of rust statements for rendering a component to string
* @param serverChunks The chunks from `/templating/builders/server-render.ts`
* @param includeStringDef Whether to add the `acc` variable declaration and ending
* return statement. Default `true` set false for doing working in `if` or `for` blocks
*/
function statementsFromServerRenderChunks(
serverChunks: ServerRenderedChunks,
module: Module,
jsModule: JSModule,
dataType: IType | null,
): Array<StatementTypes> {
const statements: Array<StatementTypes> = [];
for (const chunk of serverChunks) {
if (typeof chunk === "string") {
statements.push(new Expression(
new VariableReference("push_str", accVariable),
Operation.Call,
new Value(Type.string, chunk)
));
} else if ("value" in chunk) {
const value = serverChunkToValue(chunk, module, jsModule, dataType);
statements.push(new Expression(
new VariableReference("push_str", accVariable),
Operation.Call,
new Expression(value, Operation.Borrow)
));
} else if ("condition" in chunk) {
// TODO null
let value = jsAstToRustAst(chunk.condition, null, module, jsModule) as RustValueTypes;
/* TODO TEMP:
* Convert conditional properties (in rust these are Option<T>) to a boolean
* and check strings are not empty
* TODO does not work for for loop and nested variables...
*/
if (value instanceof VariableReference) {
const name = value.name;
const isOptional = dataType?.properties?.get(name)?.isOptional;
if (isOptional) {
value = new Expression(
new VariableReference("is_some", value),
Operation.Call,
)
}
if (dataType?.properties?.get(name)?.name === "string") {
// TODO should probably do destructured pattern matching with guard
// Prevents .is_some().is_empty() with 'x.is_some() && !x.as_ref().unwrap().is_empty()'
if (isOptional) {
value = new Expression(
value,
Operation.And,
new Expression(
new Expression(
new VariableReference(
"is_empty",
new Expression(
new VariableReference(
"unwrap",
new Expression(
new VariableReference(
"as_ref",
// without the is_some()
((value as Expression).lhs as VariableReference).parent!,
),
Operation.Call
)
),
Operation.Call,
),
),
Operation.Call,
),
Operation.Not
),
);
} else {
value = new Expression(
new Expression(
new VariableReference("is_empty", value),
Operation.Call,
),
Operation.Not
);
}
}
// TODO numbers != 0
}
statements.push(new IfStatement(
value,
statementsFromServerRenderChunks(chunk.truthyRenderExpression, module, jsModule, dataType),
new ElseStatement(null, statementsFromServerRenderChunks(chunk.falsyRenderExpression, module, jsModule, dataType))
));
} else if ("subject" in chunk) {
// TODO null
const expr = jsAstToRustAst(chunk.subject, null, module, jsModule) as RustValueTypes;
statements.push(new ForStatement(
chunk.variable,
new Expression(expr, Operation.Borrow),
statementsFromServerRenderChunks(chunk.childRenderExpression, module, jsModule, dataType)
));
} else if ("component" in chunk) {
statements.push(serverChunkToValue(chunk, module, jsModule, dataType));
}
}
return statements;
}
function serverChunkToValue(
chunk: ServerRenderChunk,
module: Module,
jsModule: JSModule,
dataType: IType | null = null
): RustValueTypes {
if (typeof chunk === "string") {
return new Expression(
new VariableReference("to_string", new Value(Type.string, chunk)),
Operation.Call
);
} else if ("value" in chunk) {
// TODO null
let value = jsAstToRustAst(chunk.value, null, module, jsModule) as RustValueTypes;
/* TODO TEMP:
* Unwrap conditional properties (Option<T> in rust)
*/
if (value instanceof VariableReference && dataType?.properties?.get(value.name)?.isOptional) {
value = new Expression(
new VariableReference(
"unwrap",
new Expression(
new VariableReference("as_ref", value),
Operation.Call
)
),
Operation.Call,
)
}
// TODO for deep properties
const typeIsString =
chunk.value instanceof JSVariableReference &&
dataType?.properties?.get(chunk.value.name)?.name === "string"
if (!typeIsString) {
value = new Expression(
new VariableReference("to_string", value),
Operation.Call
);
}
if (chunk.escape) {
// TODO if text (not a attribute could use "encode_text")
value = new Expression(
new VariableReference("encode_safe"),
Operation.Call,
new Expression(value, Operation.Borrow)
);
}
return value;
} else if ("component" in chunk) {
const useDestructured = chunk.args.has("data") &&
typeof chunk.args.get("data")![0] === "object" &&
"argument" in (chunk.args.get("data")![0] as object) &&
(chunk.args.get("data")![0] as any).argument instanceof ObjectLiteral;
const args: Map<string, RustValueTypes> = new Map([["acc", new VariableReference("acc")]]);
for (const [name, [value, valueType]] of chunk.args) {
if (typeof value === "object" && "argument" in value) {
if (value.argument instanceof ObjectLiteral) {
for (const [olKey, olValue] of value.argument.values) {
args.set(
olKey as string, // TODO catch [Symbol.x] etc
new Expression(
jsAstToRustAst(olValue, valueType, module, jsModule) as RustValueTypes,
Operation.Borrow
)
)
}
} else {
args.set(
name,
new Expression(
jsAstToRustAst(value.argument, valueType, module, jsModule) as RustValueTypes,
Operation.Borrow
)
);
}
} else {
if (Array.isArray(value)) {
if (value.length === 0) {
args.set(
name,
new Expression(
new Expression(
new VariableReference("to_string", new Value(Type.string, "")),
Operation.Call
),
Operation.Borrow
)
);
} else if (value.length === 1) {
const rustValue = serverChunkToValue(value[0], module, jsModule, dataType);
if (typeof value[0] === "string") {
args.set(name, new Expression(rustValue, Operation.Borrow));
} else {
args.set(name, rustValue);
}
} else {
args.set(name, formatExpressionFromServerChunks(value, module, jsModule));
}
} else {
const rustValue = serverChunkToValue(value, module, jsModule, dataType)
if (value instanceof JSValue) {
args.set(name, new Expression(rustValue, Operation.Borrow));
} else {
args.set(name, rustValue);
}
}
}
}
const func = useDestructured ?
chunk.component.destructuredServerRenderFunction! :
chunk.component.serverRenderFunction!;
return new Expression(
new VariableReference(func.actualName!),
Operation.Call,
func.buildArgumentListFromArgumentsMap(args)
);
} else if ("subject" in chunk) {
const mapFunctionOnSubject = new VariableReference("map", new Expression(
new VariableReference("iter", jsAstToRustAst(chunk.subject, null, module, jsModule) as RustValueTypes),
Operation.Call,
));
const serverRenderedIteratorChunk = formatExpressionFromServerChunks(
chunk.childRenderExpression, module, jsModule
);
const mapCall = new Expression(
mapFunctionOnSubject,
Operation.Call,
new ClosureExpression(
[[chunk.variable, null]],
[new ReturnStatement(serverRenderedIteratorChunk)],
true // <- Important environment is captured to allow variables other than the one from the iterator to be accessible
)
)
// Collect the output to a String:
return new Expression(
// Yes <String> is a generic argument which is not the same as a member at the ast level but due to syntactical equivalence when rendering can get away with it here
new VariableReference("<String>",
new VariableReference("collect", mapCall),
true
),
Operation.Call
)
} else {
// TODO conditional expressions with match, will run into the js truthy to rust boolean issue here...?
throw Error(`Not implemented - producing rust expression from chunk "${chunk}" `);
}
}
/** Builds a `format!(...)` expression. Cannot be used for condition and iterator data */
function formatExpressionFromServerChunks(
serverChunks: ServerRenderedChunks,
module: Module,
jsModule: JSModule,
): Expression {
let formatString = "";
const args: Array<RustValueTypes> = [];
for (const chunk of serverChunks) {
if (typeof chunk === "string") {
formatString += chunk;
} else {
formatString += "{}";
args.push(new Expression(
serverChunkToValue(chunk, module, jsModule),
Operation.Borrow
));
}
}
return new Expression(
new VariableReference("format!"),
Operation.Call,
new ArgumentList(
[new Value(Type.string, formatString), ...args]
)
);
}
const jsToRustDecoratorName = "@useRustStatement";
/**
* Builds a rust module that has a public function for rendering a component to js
* @param comp
* @param settings
*/
export function makeRustComponentServerModule(
comp: Component,
settings: IFinalPrismSettings,
ssrSettings: IServerRenderSettings
): void {
comp.serverModule = new Module(
join(settings.absoluteServerOutputPath, comp.relativeFilename.replace(/[.-]/g, "_")) + ".rs"
);
// Use encode_safe from html_escape crate
const useHTMLEscapeStatement = new UseStatement(["html_escape", "encode_safe"]);
comp.serverModule!.statements.push(useHTMLEscapeStatement);
// Transition over statements
for (const statement of comp.clientModule.statements) {
if (
statement instanceof JSExportStatement && (
statement.exported === comp.componentClass) ||
statement === comp.componentClass ||
statement === comp.customElementDefineStatement) {
continue;
} else if (statement instanceof JSImportStatement) {
// If component
if (statement.from.endsWith(".prism.js") || statement.from.endsWith(".prism.ts")) {
const newImports: Array<string> = [];
let importedComponent: Component | null = null;
// If a imports a component class convert it to
for (const key of statement.variable!.entries!.values()) {
if (comp.importedComponents.has(key?.name!)) {
importedComponent = comp.importedComponents.get(key?.name!)!;
if (importedComponent.isLayout) {
newImports.push(
importedComponent.layoutServerRenderFunctions![0].actualName!,
importedComponent.layoutServerRenderFunctions![1].actualName!,
)
} else {
if (importedComponent.destructuredServerRenderFunction) {
newImports.push(importedComponent.destructuredServerRenderFunction!.actualName!)
}
newImports.push(importedComponent.serverRenderFunction!.actualName!)
}
} else {
newImports.push(key?.name!);
}
}
if (importedComponent) {
// TODO does not work where path ~ ../x/comp.prism.js but then I don't think that is possible without knowing crate origin
const path = relative(
comp.serverModule!.filename,
importedComponent.serverModule!.filename
);
const useStatement = new UseStatement([
"super",
...path
.substr(0, path.lastIndexOf('.'))
.split(settings.pathSplitter)
.slice(1),
newImports
]);
comp.serverModule!.statements.push(useStatement);
}
}
// Ignores other imports for now
} else if (
statement instanceof JSComment
) {
/**
* Conditional inject statement if compiling under rust e.g
* /* @useRustStatement use crate_x::{func1};") * /
*
* As this function will not be included into the rust
* function func1() {
* ..js engine dependant logic...
* }
*
* Currently very flexible with `DynamicStatement`
* Expects that the rust code in the argument string introduces a function of the same name
* and parameters into the module / scope
*/
const useRustStatementMatch = statement.comment.match(jsToRustDecoratorName);
if (useRustStatementMatch) {
const rustCode = statement.comment.slice(useRustStatementMatch.index! + jsToRustDecoratorName.length)
comp.serverModule.statements.push(new DynamicStatement(rustCode.trim()));
}
} else if (
statement instanceof TSInterfaceDeclaration ||
statement instanceof JSImportStatement ||
statement instanceof JSExportStatement
) {
const rustStatement = jsAstToRustAst(statement, null, comp.serverModule, comp.clientModule);
if (rustStatement) comp.serverModule.statements.push(rustStatement);
}
}
/**
* May produce 4 statements
* - render_x
* - render_x_from_buffer
* - render_x_page
* - render_x_destructured
*/
const rustRenderParameters: Array<[string, TypeSignature]> = [["acc", new TypeSignature("&mut String")]];
for (const parameter of comp.serverRenderParameters) {
const newTS = jsAstToRustAst(parameter.typeSignature!, null, comp.serverModule!, comp.clientModule) as TypeSignature;
newTS.name = "&" + newTS.name;
rustRenderParameters.push([
parameter.name,
newTS
])
}
const camelCaseComponentName = comp.tagName
.replace(/-/g, "_")
.replace(/[A-Z]/g, (s, i) => i ? `_${s.toLowerCase()}` : s.toLowerCase());
const componentRenderFunctionName = "render_" + camelCaseComponentName + "_component";
const componentRenderFunctionFromBufferName = "render_" + camelCaseComponentName + "_component_from_buffer";
const componentRenderFunctionDestructuredName = componentRenderFunctionFromBufferName + "_destructured";
const pageRenderFunctionName = "render_" + camelCaseComponentName + "_page";
// TODO add clientGlobals
// Used for "passthrough" functions e.g. render page and render (on new buffer)
const renderFunctionArguments = [
new VariableReference("data"),
];
if (!comp.isPage) {
renderFunctionArguments.push(new VariableReference("attributes"))
}
// Component function which initializes string for you. TODO @WithCapacity
const componentRenderFunction = new FunctionDeclaration(
componentRenderFunctionName,
rustRenderParameters.slice(1), // Ignore the acc parameter
new TypeSignature("String"),
[
// Create new string
new VariableDeclaration("acc", true, getNewString(comp.withCapacity)),
// Call the buffer function
new Expression(
new VariableReference(componentRenderFunctionFromBufferName),
Operation.Call,
new ArgumentList([new VariableReference("&mut acc")].concat(renderFunctionArguments))
),
// Return acc
new ReturnStatement(accVariable)
],
true
);
const serverRenderChunks = serverRenderPrismNode(
comp.componentHTMLTag,
comp.templateData.nodeData,
ssrSettings,
comp.globals,
false,
// If destructured method then data is sent down property wise rather than on a struct instance named "data"
!comp.createdUsingDestructured
);
if (comp.isLayout) {
const pageInterpolationIndex = serverRenderChunks
.findIndex((value) => typeof value === "object" &&
"value" in value &&
value.value instanceof JSVariableReference &&
value.value.name === "contentSlot"
);
const prefixChunk = serverRenderChunks.slice(0, pageInterpolationIndex);
const suffixChunk = serverRenderChunks.slice(pageInterpolationIndex + 1);
const renderParameters = rustRenderParameters.filter(([name]) => name !== "contentSlot");
const prefixChunkRenderFunction = new FunctionDeclaration(
"render_" + camelCaseComponentName + "_layout_prefix",
renderParameters,
null,
statementsFromServerRenderChunks(
prefixChunk,
comp.serverModule,
comp.clientModule,
comp.componentDataType,
),
true
);
const suffixChunkRenderFunction = new FunctionDeclaration(
"render_" + camelCaseComponentName + "_layout_suffix",
renderParameters,
null,
statementsFromServerRenderChunks(
suffixChunk,
comp.serverModule,
comp.clientModule,
comp.componentDataType,
),
true
);
comp.layoutServerRenderFunctions = [prefixChunkRenderFunction, suffixChunkRenderFunction];
comp.serverModule.statements.push(prefixChunkRenderFunction, suffixChunkRenderFunction);
return;
}
if (comp.renderFromEndpoint) {
// TODO recomputing chunks slow :(
// Same chunks without component tag
const chunks = comp.componentHTMLTag.children
.flatMap((child) => serverRenderPrismNode(
child,
comp.templateData.nodeData,
ssrSettings,
comp.globals,
false,
true
)
);
comp.serverModule.statements.push(new FunctionDeclaration(
componentRenderFunctionName + "_content",
rustRenderParameters.filter(([paramName]) => !["acc", "attributes"].includes(paramName)),
new TypeSignature("String"),
[
// Create new string
new VariableDeclaration("buf", true, getNewString(comp.withCapacity)),
// buf is owned (mutable) String but many statements require a mutable reference so acc is &mut buf
new VariableDeclaration("acc", false, new VariableReference("&mut buf")),
...statementsFromServerRenderChunks(chunks,
comp.serverModule,
comp.clientModule,
comp.componentDataType
),
// Return acc
new ReturnStatement(new VariableReference("buf"))
],
true
));
}
comp.serverModule.statements.push(componentRenderFunction);
/* For <OtherComponent $data="{x, y, z}"> it cannot generate &OtherComponentData { x, y, z } as OtherComponentData
needs values and x, y, z values are only references. So instead creates a function with a references to
individual properties instead a of instance. Exactly the same statements though
*/
if (!comp.createdUsingDestructured) {
comp.serverRenderFunction = new FunctionDeclaration(
componentRenderFunctionFromBufferName,
rustRenderParameters,
null,
[],
true
);
comp.serverModule.statements.push(comp.serverRenderFunction);
} else {
const destructuredParameters = rustRenderParameters.filter(([propName]) => propName !== "data");
const destructuredArguments: Array<ValueTypes> = [
new VariableReference("acc"),
new VariableReference("attributes")
];
for (const [name, type] of comp.componentDataType?.properties ?? []) {
// TODO deep destructuring
let rustTypeName = typeMap.get(type.name!) ?? type.name!;
if (type.name === "Array") {
rustTypeName += `<${typeMap.get(type.indexed!.name!) ?? type.indexed!.name!}>`;
}
if (type.isOptional) {
rustTypeName = `Option<${rustTypeName}>`;
}
destructuredParameters.push([name, new TypeSignature("&" + rustTypeName)]);
destructuredArguments.push(new Expression(
new VariableReference(name, new VariableReference("data")),
Operation.Borrow
));
}
// TODO add client globals to destructuredParameters
const componentRenderFunctionDestructured = new FunctionDeclaration(
componentRenderFunctionDestructuredName,
destructuredParameters,
null,
[],
true
);
const componentRenderFunction = new FunctionDeclaration(
componentRenderFunctionFromBufferName,
rustRenderParameters,
null,
[
new Expression(
new VariableReference(componentRenderFunctionDestructuredName),
Operation.Call,
new ArgumentList(destructuredArguments)
)
],
true
);
comp.serverRenderFunction = componentRenderFunction;
comp.destructuredServerRenderFunction = componentRenderFunctionDestructured;
comp.serverModule.statements.push(componentRenderFunctionDestructured, componentRenderFunction);
}
// Statements must be set after "comp.serverRenderFunction" is set to allow for recursive components
const statements = statementsFromServerRenderChunks(
serverRenderChunks,
comp.serverModule,
comp.clientModule,
comp.componentDataType,
);
if (comp.createdUsingDestructured) {
comp.destructuredServerRenderFunction!.statements = statements;
} else {
comp.serverRenderFunction.statements = statements;
}
if (comp.usesLayout) {
// TODO imports
const [prefixFunction, suffixFunction] = comp.usesLayout.layoutServerRenderFunctions!;
// Call prefix function
statements.unshift(new Expression(
new VariableReference(prefixFunction.actualName!),
Operation.Call,
new ArgumentList([new VariableReference("acc")]) // TODO client globals
));
// Call suffix function
statements.push(new Expression(
new VariableReference(suffixFunction.actualName!),
Operation.Call,
new ArgumentList([new VariableReference("acc")]) // TODO client globals
));
}
if (comp.isPage) {
let metadataString: RustValueTypes;
if (comp.metaDataChunks.length > 0) {
metadataString = formatExpressionFromServerChunks(comp.metaDataChunks, comp.serverModule, comp.clientModule);
} else {
metadataString = new Expression(
new VariableReference("to_string", new Value(Type.string, "")),
Operation.Call,
);
}
/*
new String
call1
append metadata
call2
append content
call3
return string
*/
const renderPageFunction = new FunctionDeclaration(
pageRenderFunctionName,
rustRenderParameters.slice(1), // Skip &mut acc
new TypeSignature("String"),
[
// Create new string
new VariableDeclaration("acc", true, getNewString(comp.withCapacity)),
new Expression(
new VariableReference(htmlRenderFunctionOne),
Operation.Call,
new ArgumentList([new VariableReference("&mut acc")])
),
new Expression(
new VariableReference("push_str", accVariable),
Operation.Call,
new Expression(metadataString, Operation.Borrow)
),
new Expression(
new VariableReference(htmlRenderFunctionTwo),
Operation.Call,
new ArgumentList([new VariableReference("&mut acc")])
),
// Call the buffer function
new Expression(
new VariableReference(componentRenderFunctionFromBufferName),
Operation.Call,
new ArgumentList([new VariableReference("&mut acc")].concat(renderFunctionArguments))
),
new Expression(
new VariableReference(htmlRenderFunctionThree),
Operation.Call,
new ArgumentList([new VariableReference("&mut acc")])
),
// Return acc
new ReturnStatement(accVariable)
],
true
);
comp.serverModule.statements.push(renderPageFunction);
const pathToPrismModule = relative(
settings.absoluteServerOutputPath,
dirname(comp.serverModule.filename)
).split(settings.pathSplitter).filter(Boolean);
const useStatement = new UseStatement([
"super",
...pathToPrismModule,
"prism", [
"render_html_one",
"render_html_two",
"render_html_three"
]
]);
comp.serverModule!.statements.unshift(useStatement);
}
}
const htmlRenderFunctionOne = "render_html_one";
const htmlRenderFunctionTwo = "render_html_two";
const htmlRenderFunctionThree = "render_html_three";
export function buildPrismServerModule(
template: IShellData,
settings: IFinalPrismSettings,
outputFiles: Array<string>
): Module {
const baseServerModule = new Module(join(settings.absoluteServerOutputPath, "prism.rs"));
// Create a template literal to build the index page. As the template has been parsed it will include slots for rendering slots
const chunks = serverRenderPrismNode(template.document, template.nodeData, {
minify: settings.minify, addDisableToElementWithEvents: false
});
const metaLocation = chunks
.findIndex((value) => typeof value === "object" &&
"value" in value &&
value.value instanceof JSVariableReference &&
value.value.name === "metaSlot"
);
const contentLocation = chunks
.findIndex((value) => typeof value === "object" &&
"value" in value &&
value.value instanceof JSVariableReference &&
value.value.name === "contentSlot"
);
// Create function with content and meta slot parameters
const pageRenderFunctionOne = new FunctionDeclaration(
htmlRenderFunctionOne,
[["acc", new TypeSignature("&mut String")]],
null,
statementsFromServerRenderChunks(chunks.slice(0, metaLocation), baseServerModule, new JSModule(""), null),
true
);
const pageRenderFunctionTwo = new FunctionDeclaration(
htmlRenderFunctionTwo,
[["acc", new TypeSignature("&mut String")]],
null,
statementsFromServerRenderChunks(chunks.slice(metaLocation + 1, contentLocation), baseServerModule, new JSModule(""), null),
true
);
const pageRenderFunctionThree = new FunctionDeclaration(
htmlRenderFunctionThree,
[["acc", new TypeSignature("&mut String")]],
null,
statementsFromServerRenderChunks(chunks.slice(contentLocation + 1), baseServerModule, new JSModule(""), null),
true
);
baseServerModule.statements.push(pageRenderFunctionOne, pageRenderFunctionTwo, pageRenderFunctionThree);
outputFiles.push(baseServerModule.filename);
const directoryModules: Map<string, Module> = new Map();
for (const file of outputFiles) {
const dir = dirname(file);
const base = basename(file, ".rs");
const pubCrateStatement: ModStatement = new ModStatement(base, true);
if (directoryModules.has(dir)) {
directoryModules.get(dir)!.statements.push(pubCrateStatement)
} else {
const dirModule = new Module(join(dir, "mod.rs"), [pubCrateStatement])
directoryModules.set(dir, dirModule);
}
}
directoryModules.forEach(value => value.writeToFile({}))
return baseServerModule;
}
function getNewString(initialBufferCapacity: number): Expression {
if (initialBufferCapacity === 0) {
return new Expression(
new VariableReference("new", new VariableReference("String"), true),
Operation.Call
)
} else {
return new Expression(
new VariableReference("with_capacity", new VariableReference("String"), true),
Operation.Call,
new ArgumentList([
new Value(Type.number, initialBufferCapacity.toString())
])
)
}
} | the_stack |
import { URL } from 'url';
import { Link } from '../node';
import Stats from '../Stats';
import Dirent from '../Dirent';
import { Volume, filenameToSteps, StatWatcher } from '../volume';
import hasBigInt from './hasBigInt';
import { tryGetChild, tryGetChildNode } from './util';
describe('volume', () => {
describe('filenameToSteps(filename): string[]', () => {
it('/ -> []', () => {
expect(filenameToSteps('/')).toEqual([]);
});
it('/test -> ["test"]', () => {
expect(filenameToSteps('/test')).toEqual(['test']);
});
it('/usr/bin/node.sh -> ["usr", "bin", "node.sh"]', () => {
expect(filenameToSteps('/usr/bin/node.sh')).toEqual(['usr', 'bin', 'node.sh']);
});
it('/dir/file.txt -> ["dir", "file.txt"]', () => {
expect(filenameToSteps('/dir/file.txt')).toEqual(['dir', 'file.txt']);
});
it('/dir/./file.txt -> ["dir", "file.txt"]', () => {
expect(filenameToSteps('/dir/./file.txt')).toEqual(['dir', 'file.txt']);
});
it('/dir/../file.txt -> ["file.txt"]', () => {
expect(filenameToSteps('/dir/../file.txt')).toEqual(['file.txt']);
});
});
describe('Volume', () => {
it('.genRndStr()', () => {
const vol = new Volume();
for (let i = 0; i < 100; i++) {
const str = vol.genRndStr();
expect(typeof str === 'string').toBe(true);
expect(str.length).toBe(6);
}
});
describe('.getLink(steps)', () => {
const vol = new Volume();
it('[] - Get the root link', () => {
const link = vol.getLink([]);
expect(link).toBeInstanceOf(Link);
expect(link).toBe(vol.root);
});
it('["child.sh"] - Get a child link', () => {
const link1 = vol.root.createChild('child.sh');
const link2 = vol.getLink(['child.sh']);
expect(link1).toBe(link2);
});
it('["dir", "child.sh"] - Get a child link in a dir', () => {
const dir = vol.root.createChild('dir');
const link1 = dir.createChild('child.sh');
const node2 = vol.getLink(['dir', 'child.sh']);
expect(link1).toBe(node2);
});
});
describe('i-nodes', () => {
it('i-node numbers are unique', () => {
const vol = Volume.fromJSON({
'/1': 'foo',
'/2': 'bar',
});
const stat1 = vol.statSync('/1');
const stat2 = vol.statSync('/2');
expect(stat1.ino === stat2.ino).toBe(false);
});
});
describe('.toJSON()', () => {
it('Single file', () => {
const vol = new Volume();
vol.writeFileSync('/test', 'Hello');
expect(vol.toJSON()).toEqual({ '/test': 'Hello' });
});
it('Multiple files', () => {
const vol = new Volume();
vol.writeFileSync('/test', 'Hello');
vol.writeFileSync('/test2', 'Hello2');
vol.writeFileSync('/test.txt', 'Hello3');
expect(vol.toJSON()).toEqual({
'/test': 'Hello',
'/test2': 'Hello2',
'/test.txt': 'Hello3',
});
});
it('With folders, skips empty folders', () => {
const vol = new Volume();
vol.writeFileSync('/test', 'Hello');
vol.mkdirSync('/dir');
vol.mkdirSync('/dir/dir2');
// Folder `/dir3` will be empty, and should not be in the JSON aoutput.
vol.mkdirSync('/dir3');
vol.writeFileSync('/dir/abc', 'abc');
vol.writeFileSync('/dir/abc2', 'abc2');
vol.writeFileSync('/dir/dir2/hello.txt', 'world');
expect(vol.toJSON()).toEqual({
'/test': 'Hello',
'/dir/abc': 'abc',
'/dir/abc2': 'abc2',
'/dir/dir2/hello.txt': 'world',
'/dir3': null,
});
});
it('Specify export path', () => {
const vol = Volume.fromJSON({
'/foo': 'bar',
'/dir/a': 'b',
});
expect(vol.toJSON('/dir')).toEqual({
'/dir/a': 'b',
});
});
it('Specify multiple export paths', () => {
const vol = Volume.fromJSON({
'/foo': 'bar',
'/dir/a': 'b',
'/dir2/a': 'b',
'/dir2/c': 'd',
});
expect(vol.toJSON(['/dir2', '/dir'])).toEqual({
'/dir/a': 'b',
'/dir2/a': 'b',
'/dir2/c': 'd',
});
});
it('Specify a file export path', () => {
const vol = Volume.fromJSON({
'/foo': 'bar',
'/dir/a': 'b',
'/dir2/a': 'b',
'/dir2/c': 'd',
});
expect(vol.toJSON(['/dir/a'])).toEqual({
'/dir/a': 'b',
});
});
it('Accumulate exports on supplied object', () => {
const vol = Volume.fromJSON({
'/foo': 'bar',
});
const obj = {};
expect(vol.toJSON('/', obj)).toBe(obj);
});
it('Export empty volume', () => {
const vol = Volume.fromJSON({});
expect(vol.toJSON()).toEqual({});
});
it('Exporting non-existing path', () => {
const vol = Volume.fromJSON({});
expect(vol.toJSON('/lol')).toEqual({});
});
it('Serializes empty dirs as null', () => {
const vol = Volume.fromJSON({
'/dir': null,
});
expect(vol.toJSON()).toEqual({
'/dir': null,
});
});
it('Serializes only empty dirs', () => {
const vol = Volume.fromJSON({
'/dir': null,
'/dir/dir2': null,
'/dir/dir2/foo': null,
'/empty': null,
});
expect(vol.toJSON()).toEqual({
'/dir/dir2/foo': null,
'/empty': null,
});
});
});
describe('.fromJSON(json[, cwd])', () => {
it('Files at root', () => {
const vol = new Volume();
const json = {
'/hello': 'world',
'/app.js': 'console.log(123)',
};
vol.fromJSON(json);
expect(vol.toJSON()).toEqual(json);
});
it('Files and directories at root with relative paths', () => {
const vol = new Volume();
const json = {
hello: 'world',
'app.js': 'console.log(123)',
dir: null,
};
vol.fromJSON(json, '/');
expect(vol.toJSON()).toEqual({
'/hello': 'world',
'/app.js': 'console.log(123)',
'/dir': null,
});
});
it('Deeply nested tree', () => {
const vol = new Volume();
const json = {
'/dir/file': '...',
'/dir/dir/dir2/hello.sh': 'world',
'/hello.js': 'console.log(123)',
'/dir/dir/test.txt': 'Windows',
};
vol.fromJSON(json);
expect(vol.toJSON()).toEqual(json);
});
it('Invalid JSON throws error', () => {
try {
const vol = new Volume();
const json = {
'/dir/file': '...',
'/dir': 'world',
};
vol.fromJSON(json);
throw Error('This should not throw');
} catch (error) {
// Check for both errors, because in JavaScript we the `json` map's key order is not guaranteed.
expect(error.code === 'EISDIR' || error.code === 'ENOTDIR').toBe(true);
}
});
it('Invalid JSON throws error 2', () => {
try {
const vol = new Volume();
const json = {
'/dir': 'world',
'/dir/file': '...',
};
vol.fromJSON(json);
throw Error('This should not throw');
} catch (error) {
// Check for both errors, because in JavaScript we the `json` map's key order is not guaranteed.
expect(error.code === 'EISDIR' || error.code === 'ENOTDIR').toBe(true);
}
});
it('creates a folder if value is not a string', () => {
const vol = Volume.fromJSON({
'/dir': null,
});
const stat = vol.statSync('/dir');
expect(stat.isDirectory()).toBe(true);
expect(vol.readdirSync('/dir')).toEqual([]);
});
});
describe('.fromNestedJSON(nestedJSON[, cwd])', () => {
it('Accept a nested dict as input because its nicer to read', () => {
const vol1 = new Volume();
const vol2 = new Volume();
const jsonFlat = {
'/dir/file': '...',
'/emptyDir': null,
'/anotherEmptyDir': null,
'/oneMoreEmptyDir': null,
'/dir/dir/dir2/hello.sh': 'world',
'/hello.js': 'console.log(123)',
'/dir/dir/test.txt': 'File with leading slash',
};
const jsonNested = {
'/dir/': {
file: '...',
dir: {
dir2: {
'hello.sh': 'world',
},
'/test.txt': 'File with leading slash',
},
},
'/emptyDir': {},
'/anotherEmptyDir': null,
'/oneMoreEmptyDir': {
'': null, // this could be considered a glitch, but "" is not a valid filename anyway
// (same as 'file/name' is invalid and would lead to problems)
},
'/hello.js': 'console.log(123)',
};
vol1.fromJSON(jsonFlat);
vol2.fromNestedJSON(jsonNested);
expect(vol1.toJSON()).toEqual(vol2.toJSON());
});
});
describe('.reset()', () => {
it('Remove all files', () => {
const vol = new Volume();
const json = {
'/hello': 'world',
'/app.js': 'console.log(123)',
};
vol.fromJSON(json);
vol.reset();
expect(vol.toJSON()).toEqual({});
});
it('File operations should work after reset', () => {
const vol = new Volume();
const json = {
'/hello': 'world',
};
vol.fromJSON(json);
vol.reset();
vol.writeFileSync('/good', 'bye');
expect(vol.toJSON()).toEqual({
'/good': 'bye',
});
});
});
describe('.openSync(path, flags[, mode])', () => {
const vol = new Volume();
it('Create new file at root (/test.txt)', () => {
const fd = vol.openSync('/test.txt', 'w');
expect(vol.root.getChild('test.txt')).toBeInstanceOf(Link);
expect(typeof fd).toBe('number');
expect(fd).toBeGreaterThan(0);
});
it('Error on file not found', () => {
try {
vol.openSync('/non-existing-file.txt', 'r');
throw Error('This should not throw');
} catch (err) {
expect(err.code).toBe('ENOENT');
}
});
it('Invalid path correct error code', () => {
try {
(vol as any).openSync(123, 'r');
throw Error('This should not throw');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toBe('path must be a string or Buffer');
}
});
it('Invalid flags correct error code', () => {
try {
(vol as any).openSync('/non-existing-file.txt');
throw Error('This should not throw');
} catch (err) {
expect(err.code).toBe('ERR_INVALID_OPT_VALUE');
}
});
it('Invalid mode correct error code', () => {
try {
vol.openSync('/non-existing-file.txt', 'r', 'adfasdf');
throw Error('This should not throw');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toBe('mode must be an int');
}
});
it('Open multiple files', () => {
const fd1 = vol.openSync('/1.json', 'w');
const fd2 = vol.openSync('/2.json', 'w');
const fd3 = vol.openSync('/3.json', 'w');
const fd4 = vol.openSync('/4.json', 'w');
expect(typeof fd1).toBe('number');
expect(fd1 !== fd2).toBe(true);
expect(fd2 !== fd3).toBe(true);
expect(fd3 !== fd4).toBe(true);
});
});
describe('.open(path, flags[, mode], callback)', () => {
const vol = new Volume();
vol.mkdirSync('/test-dir');
it('Create new file at root (/test.txt)', done => {
vol.open('/test.txt', 'w', (err, fd) => {
expect(err).toBe(null);
expect(vol.root.getChild('test.txt')).toBeInstanceOf(Link);
expect(typeof fd).toBe('number');
expect(fd).toBeGreaterThan(0);
done();
});
});
it('Error on file not found', done => {
vol.open('/non-existing-file.txt', 'r', (err, fd) => {
expect(err).toHaveProperty('code', 'ENOENT');
done();
});
});
it('Invalid path correct error code thrown synchronously', done => {
try {
(vol as any).open(123, 'r', (err, fd) => {
throw Error('This should not throw');
});
throw Error('This should not throw');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toBe('path must be a string or Buffer');
done();
}
});
it('Invalid flags correct error code thrown synchronously', done => {
try {
(vol as any).open('/non-existing-file.txt', undefined, () => {
throw Error('This should not throw');
});
throw Error('This should not throw');
} catch (err) {
expect(err.code).toBe('ERR_INVALID_OPT_VALUE');
done();
}
});
it('Invalid mode correct error code thrown synchronously', done => {
try {
(vol as any).openSync('/non-existing-file.txt', 'r', 'adfasdf', () => {
throw Error('This should not throw');
});
throw Error('This should not throw');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toBe('mode must be an int');
done();
}
});
it('Properly sets permissions from mode when creating a new file', done => {
vol.writeFileSync('/a.txt', 'foo');
const stats = vol.statSync('/a.txt');
// Write a new file, copying the mode from the old file
vol.open('/b.txt', 'w', stats.mode, (err, fd) => {
expect(err).toBe(null);
expect(vol.root.getChild('b.txt')).toBeInstanceOf(Link);
expect(typeof fd).toBe('number');
expect(tryGetChildNode(vol.root, 'b.txt').canWrite()).toBe(true);
done();
});
});
it('Error on incorrect flags for directory', done => {
vol.open('/test-dir', 'r+', (err, fd) => {
expect(err).toHaveProperty('code', 'EISDIR');
done();
});
});
it('Properly opens directory as read-only', done => {
vol.open('/test-dir', 'r', (err, fd) => {
expect(err).toBe(null);
expect(typeof fd).toBe('number');
done();
});
});
});
describe('.close(fd, callback)', () => {
const vol = new Volume();
it('Closes file without errors', done => {
vol.open('/test.txt', 'w', (err, fd) => {
expect(err).toBe(null);
vol.close(fd || -1, err => {
expect(err).toBe(null);
done();
});
});
});
});
describe('.read(fd, buffer, offset, length, position, callback)', () => {
xit('...', () => {});
});
describe('.readFileSync(path[, options])', () => {
const vol = new Volume();
const data = 'trololo';
const fileNode = (vol as any).createLink(vol.root, 'text.txt').getNode();
fileNode.setString(data);
it('Read file at root (/text.txt)', () => {
const buf = vol.readFileSync('/text.txt');
const str = buf.toString();
expect(buf).toBeInstanceOf(Buffer);
expect(str).toBe(data);
});
it('Read file with path passed as URL', () => {
const str = vol.readFileSync(new URL('file:///text.txt')).toString();
expect(str).toBe(data);
});
it('Specify encoding as string', () => {
const str = vol.readFileSync('/text.txt', 'utf8');
expect(str).toBe(data);
});
it('Specify encoding in object', () => {
const str = vol.readFileSync('/text.txt', { encoding: 'utf8' });
expect(str).toBe(data);
});
it('Read file deep in tree (/dir1/dir2/test-file)', () => {
const dir1 = (vol as any).createLink(vol.root, 'dir1', true);
const dir2 = (vol as any).createLink(dir1, 'dir2', true);
const fileNode = (vol as any).createLink(dir2, 'test-file').getNode();
const data = 'aaaaaa';
fileNode.setString(data);
const str = vol.readFileSync('/dir1/dir2/test-file').toString();
expect(str).toBe(data);
});
it('Invalid options should throw', () => {
try {
// Expecting this line to throw
vol.readFileSync('/text.txt', 123 as any);
throw Error('This should not throw');
} catch (err) {
expect(err).toBeInstanceOf(TypeError);
// TODO: Check the right error message.
}
});
it('Attempt to read a directory should throw EISDIR', () => {
const vol = new Volume();
vol.mkdirSync('/test');
const fn = () => vol.readFileSync('/test');
expect(fn).toThrowError('EISDIR');
});
it('Attempt to read a non-existing file should throw ENOENT', () => {
const fn = () => vol.readFileSync('/pizza.txt');
expect(fn).toThrowError('ENOENT');
});
});
describe('.readFile(path[, options], callback)', () => {
const vol = new Volume();
const data = 'asdfasdf asdfasdf asdf';
const fileNode = (vol as any).createLink(vol.root, 'file.txt').getNode();
fileNode.setString(data);
it('Read file at root (/file.txt)', done => {
vol.readFile('/file.txt', 'utf8', (err, str) => {
expect(err).toBe(null);
expect(str).toBe(data);
done();
});
});
});
describe('.writeSync(fd, str, position, encoding)', () => {
const vol = new Volume();
it('Simple write to a file descriptor', () => {
const fd = vol.openSync('/test.txt', 'w+');
const data = 'hello';
const bytes = vol.writeSync(fd, data);
vol.closeSync(fd);
expect(bytes).toBe(data.length);
expect(vol.readFileSync('/test.txt', 'utf8')).toBe(data);
});
it('Multiple writes to a file', () => {
const fd = vol.openSync('/multi.txt', 'w+');
const datas = ['hello', ' ', 'world', '!'];
let bytes = 0;
for (const data of datas) {
const b = vol.writeSync(fd, data);
expect(b).toBe(data.length);
bytes += b;
}
vol.closeSync(fd);
const result = datas.join('');
expect(bytes).toBe(result.length);
expect(vol.readFileSync('/multi.txt', 'utf8')).toBe(result);
});
it('Overwrite part of file', () => {
const fd = vol.openSync('/overwrite.txt', 'w+');
vol.writeSync(fd, 'martini');
vol.writeSync(fd, 'Armagedon', 1, 'utf8');
vol.closeSync(fd);
expect(vol.readFileSync('/overwrite.txt', 'utf8')).toBe('mArmagedon');
});
});
describe('.write(fd, buffer, offset, length, position, callback)', () => {
it('Simple write to a file descriptor', done => {
const vol = new Volume();
const fd = vol.openSync('/test.txt', 'w+');
const data = 'hello';
vol.write(fd, Buffer.from(data), (err, bytes, buf) => {
vol.closeSync(fd);
expect(err).toBe(null);
expect(vol.readFileSync('/test.txt', 'utf8')).toBe(data);
done();
});
});
});
describe('.writeFile(path, data[, options], callback)', () => {
const vol = new Volume();
const data = 'asdfasidofjasdf';
it('Create a file at root (/writeFile.json)', done => {
vol.writeFile('/writeFile.json', data, err => {
expect(err).toBe(null);
const str = tryGetChildNode(vol.root, 'writeFile.json').getString();
expect(str).toBe(data);
done();
});
});
it('Throws error when no callback provided', () => {
try {
vol.writeFile('/asdf.txt', 'asdf', 'utf8', undefined as any);
throw Error('This should not throw');
} catch (err) {
expect(err.message).toBe('callback must be a function');
}
});
});
describe('.symlinkSync(target, path[, type])', () => {
const vol = new Volume();
const jquery = (vol as any).createLink(vol.root, 'jquery.js').getNode();
const data = '"use strict";';
jquery.setString(data);
it('Create a symlink', () => {
vol.symlinkSync('/jquery.js', '/test.js');
expect(vol.root.getChild('test.js')).toBeInstanceOf(Link);
expect(tryGetChildNode(vol.root, 'test.js').isSymlink()).toBe(true);
});
it('Read from symlink', () => {
vol.symlinkSync('/jquery.js', '/test2.js');
expect(vol.readFileSync('/test2.js').toString()).toBe(data);
});
describe('Complex, deep, multi-step symlinks get resolved', () => {
it('Symlink to a folder', () => {
const vol = Volume.fromJSON({ '/a1/a2/a3/a4/a5/hello.txt': 'world!' });
vol.symlinkSync('/a1', '/b1');
expect(vol.readFileSync('/b1/a2/a3/a4/a5/hello.txt', 'utf8')).toBe('world!');
});
it('Symlink to a folder to a folder', () => {
const vol = Volume.fromJSON({ '/a1/a2/a3/a4/a5/hello.txt': 'world!' });
vol.symlinkSync('/a1', '/b1');
vol.symlinkSync('/b1', '/c1');
vol.openSync('/c1/a2/a3/a4/a5/hello.txt', 'r');
});
it('Multiple hops to folders', () => {
const vol = Volume.fromJSON({
'/a1/a2/a3/a4/a5/hello.txt': 'world a',
'/b1/b2/b3/b4/b5/hello.txt': 'world b',
'/c1/c2/c3/c4/c5/hello.txt': 'world c',
});
vol.symlinkSync('/a1/a2', '/b1/l');
vol.symlinkSync('/b1/l', '/b1/b2/b3/ok');
vol.symlinkSync('/b1/b2/b3/ok', '/c1/a');
vol.symlinkSync('/c1/a', '/c1/c2/c3/c4/c5/final');
vol.openSync('/c1/c2/c3/c4/c5/final/a3/a4/a5/hello.txt', 'r');
expect(vol.readFileSync('/c1/c2/c3/c4/c5/final/a3/a4/a5/hello.txt', 'utf8')).toBe('world a');
});
});
});
describe('.symlink(target, path[, type], callback)', () => {
xit('...', () => {});
});
describe('.realpathSync(path[, options])', () => {
const vol = new Volume();
const mootools = vol.root.createChild('mootools.js');
const data = 'String.prototype...';
mootools.getNode().setString(data);
const symlink = vol.root.createChild('mootools.link.js');
symlink.getNode().makeSymlink(['mootools.js']);
it('Symlink works', () => {
const resolved = vol.resolveSymlinks(symlink);
expect(resolved).toBe(mootools);
});
it('Basic one-jump symlink resolves', () => {
const path = vol.realpathSync('/mootools.link.js');
expect(path).toBe('/mootools.js');
});
it('Basic one-jump symlink with /./ and /../ in path', () => {
const path = vol.realpathSync('/./lol/../mootools.link.js');
expect(path).toBe('/mootools.js');
});
});
describe('.realpath(path[, options], callback)', () => {
const vol = new Volume();
const mootools = vol.root.createChild('mootools.js');
const data = 'String.prototype...';
mootools.getNode().setString(data);
const symlink = vol.root.createChild('mootools.link.js');
symlink.getNode().makeSymlink(['mootools.js']);
it('Basic one-jump symlink resolves', done => {
vol.realpath('/mootools.link.js', (err, path) => {
expect(path).toBe('/mootools.js');
done();
});
});
it('Basic one-jump symlink with /./ and /../ in path', () => {
vol.realpath('/./lol/../mootools.link.js', (err, path) => {
expect(path).toBe('/mootools.js');
});
});
});
describe('.lstatSync(path)', () => {
const vol = new Volume();
const dojo = vol.root.createChild('dojo.js');
const data = '(function(){})();';
dojo.getNode().setString(data);
it('Returns basic file stats', () => {
const stats = vol.lstatSync('/dojo.js');
expect(stats).toBeInstanceOf(Stats);
expect(stats.size).toBe(data.length);
expect(stats.isFile()).toBe(true);
expect(stats.isDirectory()).toBe(false);
});
it('Returns file stats using BigInt', () => {
if (hasBigInt) {
const stats = vol.lstatSync('/dojo.js', { bigint: true });
expect(typeof stats.ino).toBe('bigint');
} else {
expect(() => vol.lstatSync('/dojo.js', { bigint: true })).toThrowError();
}
});
it('Stats on symlink returns results about the symlink', () => {
vol.symlinkSync('/dojo.js', '/link.js');
const stats = vol.lstatSync('/link.js');
expect(stats.isSymbolicLink()).toBe(true);
expect(stats.isFile()).toBe(false);
expect(stats.size).toBe(0);
});
});
describe('.lstat(path, callback)', () => {
xit('...', () => {});
});
describe('.statSync(path)', () => {
const vol = new Volume();
const dojo = vol.root.createChild('dojo.js');
const data = '(function(){})();';
dojo.getNode().setString(data);
it('Returns basic file stats', () => {
const stats = vol.statSync('/dojo.js');
expect(stats).toBeInstanceOf(Stats);
expect(stats.size).toBe(data.length);
expect(stats.isFile()).toBe(true);
expect(stats.isDirectory()).toBe(false);
});
it('Returns file stats using BigInt', () => {
if (hasBigInt) {
const stats = vol.statSync('/dojo.js', { bigint: true });
expect(typeof stats.ino).toBe('bigint');
} else {
expect(() => vol.statSync('/dojo.js', { bigint: true })).toThrowError();
}
});
it('Stats on symlink returns results about the resolved file', () => {
vol.symlinkSync('/dojo.js', '/link.js');
const stats = vol.statSync('/link.js');
expect(stats.isSymbolicLink()).toBe(false);
expect(stats.isFile()).toBe(true);
expect(stats.size).toBe(data.length);
});
it('Modification new write', done => {
vol.writeFileSync('/mtime.txt', '1');
const stats1 = vol.statSync('/mtime.txt');
setTimeout(() => {
vol.writeFileSync('/mtime.txt', '2');
const stats2 = vol.statSync('/mtime.txt');
expect(stats2.mtimeMs).toBeGreaterThan(stats1.mtimeMs);
done();
}, 2);
});
});
describe('.stat(path, callback)', () => {
xit('...', () => {});
});
describe('.fstatSync(fd)', () => {
const vol = new Volume();
const dojo = vol.root.createChild('dojo.js');
const data = '(function(){})();';
dojo.getNode().setString(data);
it('Returns basic file stats', () => {
const fd = vol.openSync('/dojo.js', 'r');
const stats = vol.fstatSync(fd);
expect(stats).toBeInstanceOf(Stats);
expect(stats.size).toBe(data.length);
expect(stats.isFile()).toBe(true);
expect(stats.isDirectory()).toBe(false);
});
it('Returns file stats using BigInt', () => {
const fd = vol.openSync('/dojo.js', 'r');
if (hasBigInt) {
const stats = vol.fstatSync(fd, { bigint: true });
expect(typeof stats.ino).toBe('bigint');
} else {
expect(() => vol.fstatSync(fd, { bigint: true })).toThrowError();
}
});
});
describe('.fstat(fd, callback)', () => {
xit('...', () => {});
});
describe('.linkSync(existingPath, newPath)', () => {
const vol = new Volume();
it('Create a new link', () => {
const data = '123';
vol.writeFileSync('/1.txt', data);
vol.linkSync('/1.txt', '/2.txt');
expect(vol.readFileSync('/1.txt', 'utf8')).toBe(data);
expect(vol.readFileSync('/2.txt', 'utf8')).toBe(data);
});
it('nlink property of i-node increases when new link is created', () => {
vol.writeFileSync('/a.txt', '123');
vol.linkSync('/a.txt', '/b.txt');
vol.linkSync('/a.txt', '/c.txt');
const stats = vol.statSync('/b.txt');
expect(stats.nlink).toBe(3);
});
});
describe('.link(existingPath, newPath, callback)', () => {
xit('...', () => {});
});
describe('.readdirSync(path)', () => {
it('Returns simple list', () => {
const vol = new Volume();
vol.writeFileSync('/1.js', '123');
vol.writeFileSync('/2.js', '123');
const list = vol.readdirSync('/');
expect(list.length).toBe(2);
expect(list).toEqual(['1.js', '2.js']);
});
it('Returns a Dirent list', () => {
const vol = new Volume();
vol.writeFileSync('/1', '123');
vol.mkdirSync('/2');
const list = vol.readdirSync('/', { withFileTypes: true });
expect(list.length).toBe(2);
expect(list[0]).toBeInstanceOf(Dirent);
const dirent0 = list[0] as Dirent;
expect(dirent0.name).toBe('1');
expect(dirent0.isFile()).toBe(true);
const dirent1 = list[1] as Dirent;
expect(dirent1.name).toBe('2');
expect(dirent1.isDirectory()).toBe(true);
});
});
describe('.readdir(path, callback)', () => {
xit('...', () => {});
});
describe('.readlinkSync(path[, options])', () => {
it('Simple symbolic link to one file', () => {
const vol = new Volume();
vol.writeFileSync('/1', '123');
vol.symlinkSync('/1', '/2');
const res = vol.readlinkSync('/2');
expect(res).toBe('/1');
});
});
describe('.readlink(path[, options], callback)', () => {
it('Simple symbolic link to one file', done => {
const vol = new Volume();
vol.writeFileSync('/1', '123');
vol.symlink('/1', '/2', err => {
vol.readlink('/2', (err, res) => {
expect(res).toBe('/1');
done();
});
});
});
});
describe('.fsyncSync(fd)', () => {
const vol = new Volume();
const fd = vol.openSync('/lol', 'w');
it('Executes without crashing', () => {
vol.fsyncSync(fd);
});
});
describe('.fsync(fd, callback)', () => {
const vol = new Volume();
const fd = vol.openSync('/lol', 'w');
it('Executes without crashing', done => {
vol.fsync(fd, done);
});
});
describe('.ftruncateSync(fd[, len])', () => {
const vol = new Volume();
it('Truncates to 0 single file', () => {
const fd = vol.openSync('/trunky', 'w');
vol.writeFileSync(fd, '12345');
expect(vol.readFileSync('/trunky', 'utf8')).toBe('12345');
vol.ftruncateSync(fd);
expect(vol.readFileSync('/trunky', 'utf8')).toBe('');
});
});
describe('.ftruncate(fd[, len], callback)', () => {
xit('...', () => {});
});
describe('.truncateSync(path[, len])', () => {
const vol = new Volume();
it('Truncates to 0 single file', () => {
const fd = vol.openSync('/trunky', 'w');
vol.writeFileSync(fd, '12345');
expect(vol.readFileSync('/trunky', 'utf8')).toBe('12345');
vol.truncateSync('/trunky');
expect(vol.readFileSync('/trunky', 'utf8')).toBe('');
});
it('Partial truncate', () => {
const fd = vol.openSync('/1', 'w');
vol.writeFileSync(fd, '12345');
expect(vol.readFileSync('/1', 'utf8')).toBe('12345');
vol.truncateSync('/1', 2);
expect(vol.readFileSync('/1', 'utf8')).toBe('12');
});
});
describe('.truncate(path[, len], callback)', () => {
xit('...', () => {});
});
describe('.utimesSync(path, atime, mtime)', () => {
const vol = new Volume();
it('Set times on file', () => {
vol.writeFileSync('/lol', '12345');
vol.utimesSync('/lol', 1234, 12345);
const stats = vol.statSync('/lol');
expect(Math.round(stats.atime.getTime() / 1000)).toBe(1234);
expect(Math.round(stats.mtime.getTime() / 1000)).toBe(12345);
});
});
describe('.utimes(path, atime, mtime, callback)', () => {
xit('...', () => {});
});
describe('.mkdirSync(path[, options])', () => {
it('Create dir at root', () => {
const vol = new Volume();
vol.mkdirSync('/test');
const child = tryGetChild(vol.root, 'test');
expect(child).toBeInstanceOf(Link);
expect(child.getNode().isDirectory()).toBe(true);
});
it('Create 2 levels deep folders', () => {
const vol = new Volume();
vol.mkdirSync('/dir1');
vol.mkdirSync('/dir1/dir2');
const dir1 = tryGetChild(vol.root, 'dir1');
expect(dir1).toBeInstanceOf(Link);
expect(dir1.getNode().isDirectory()).toBe(true);
const dir2 = tryGetChild(dir1, 'dir2');
expect(dir2).toBeInstanceOf(Link);
expect(dir2.getNode().isDirectory()).toBe(true);
expect(dir2.getPath()).toBe('/dir1/dir2');
});
it('Create /dir1/dir2/dir3 recursively', () => {
const vol = new Volume();
vol.mkdirSync('/dir1/dir2/dir3', { recursive: true });
const dir1 = tryGetChild(vol.root, 'dir1');
const dir2 = tryGetChild(dir1, 'dir2');
const dir3 = tryGetChild(dir2, 'dir3');
expect(dir1).toBeInstanceOf(Link);
expect(dir2).toBeInstanceOf(Link);
expect(dir3).toBeInstanceOf(Link);
expect(dir1.getNode().isDirectory()).toBe(true);
expect(dir2.getNode().isDirectory()).toBe(true);
expect(dir3.getNode().isDirectory()).toBe(true);
});
});
describe('.mkdir(path[, mode], callback)', () => {
xit('...', () => {});
xit('Create /dir1/dir2/dir3', () => {});
});
describe('.mkdtempSync(prefix[, options])', () => {
it('Create temp dir at root', () => {
const vol = new Volume();
const name = vol.mkdtempSync('/tmp-');
vol.writeFileSync(name + '/file.txt', 'lol');
expect(vol.toJSON()).toEqual({ [name + '/file.txt']: 'lol' });
});
it('throws when prefix is not a string', () => {
const vol = new Volume();
expect(() => vol.mkdtempSync({} as string)).toThrow(TypeError);
});
it('throws when prefix contains null bytes', () => {
const vol = new Volume();
expect(() => vol.mkdtempSync('/tmp-\u0000')).toThrow(/path.+string.+null bytes/i);
});
});
describe('.mkdtemp(prefix[, options], callback)', () => {
xit('Create temp dir at root', () => {});
it('throws when prefix is not a string', () => {
const vol = new Volume();
expect(() => vol.mkdtemp({} as string, () => {})).toThrow(TypeError);
});
it('throws when prefix contains null bytes', () => {
const vol = new Volume();
expect(() => vol.mkdtemp('/tmp-\u0000', () => {})).toThrow(/path.+string.+null bytes/i);
});
});
describe('.rmdirSync(path)', () => {
it('Remove single dir', () => {
const vol = new Volume();
vol.mkdirSync('/dir');
expect(tryGetChildNode(vol.root, 'dir').isDirectory()).toBe(true);
vol.rmdirSync('/dir');
expect(!!vol.root.getChild('dir')).toBe(false);
});
it('Remove dir /dir1/dir2/dir3 recursively', () => {
const vol = new Volume();
vol.mkdirSync('/dir1/dir2/dir3', { recursive: true });
vol.rmdirSync('/dir1', { recursive: true });
expect(!!vol.root.getChild('dir1')).toBe(false);
});
});
describe('.rmdir(path, callback)', () => {
xit('Remove single dir', () => {});
it('Async remove dir /dir1/dir2/dir3 recursively', done => {
const vol = new Volume();
vol.mkdirSync('/dir1/dir2/dir3', { recursive: true });
vol.rmdir('/dir1', { recursive: true }, () => {
expect(!!vol.root.getChild('dir1')).toBe(false);
done();
});
});
});
describe('.watchFile(path[, options], listener)', () => {
it('Calls listener on .writeFile', done => {
const vol = new Volume();
vol.writeFileSync('/lol.txt', '1');
setTimeout(() => {
vol.watchFile('/lol.txt', { interval: 1 }, (curr, prev) => {
process.nextTick(() => {
vol.unwatchFile('/lol.txt');
done();
});
});
vol.writeFileSync('/lol.txt', '2');
}, 1);
});
xit('Multiple listeners for one file', () => {});
});
describe('.unwatchFile(path[, listener])', () => {
it('Stops watching before .writeFile', done => {
const vol = new Volume();
vol.writeFileSync('/lol.txt', '1');
setTimeout(() => {
let listenerCalled = false;
vol.watchFile('/lol.txt', { interval: 1 }, (curr, prev) => {
listenerCalled = true;
});
vol.unwatchFile('/lol.txt');
vol.writeFileSync('/lol.txt', '2');
setTimeout(() => {
expect(listenerCalled).toBe(false);
done();
}, 10);
}, 1);
});
});
describe('.promises', () => {
it('Have a promises property', () => {
const vol = new Volume();
expect(typeof vol.promises).toBe('object');
});
});
});
describe('StatWatcher', () => {
it('.vol points to current volume', () => {
const vol = new Volume();
expect(new StatWatcher(vol).vol).toBe(vol);
});
});
}); | the_stack |
import test from "ava";
import Client from "ioredis";
import Redlock, { ExecutionError, ResourceLockedError } from "./index.js";
const redis = new Client({ host: "redis-single-instance" });
test.before(async () => {
await redis
.keys("*")
.then((keys) => (keys?.length ? redisA.del(keys) : null));
});
test("acquires, extends, and releases a single lock", async (t) => {
const redlock = new Redlock([redis]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Acquire a lock.
let lock = await redlock.acquire(["a"], duration);
t.is(await redis.get("a"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("a")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
// Extend the lock.
lock = await lock.extend(3 * duration);
t.is(await redis.get("a"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("a")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
// Release the lock.
await lock.release();
t.is(await redis.get("a"), null);
});
test("acquires, extends, and releases a multi-resource lock", async (t) => {
const redlock = new Redlock([redis]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Acquire a lock.
let lock = await redlock.acquire(["a1", "a2"], duration);
t.is(await redis.get("a1"), lock.value, "The lock value was incorrect.");
t.is(await redis.get("a2"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("a1")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redis.pttl("a2")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
// Extend the lock.
lock = await lock.extend(3 * duration);
t.is(await redis.get("a1"), lock.value, "The lock value was incorrect.");
t.is(await redis.get("a2"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("a1")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redis.pttl("a2")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
// Release the lock.
await lock.release();
t.is(await redis.get("a1"), null);
t.is(await redis.get("a2"), null);
});
test("locks fail when redis is unreachable", async (t) => {
const redis = new Client({
host: "127.0.0.1",
maxRetriesPerRequest: 0,
autoResendUnfulfilledCommands: false,
autoResubscribe: false,
retryStrategy: () => null,
reconnectOnError: () => false,
});
redis.on("error", () => {
// ignore redis-generated errors
});
const redlock = new Redlock([redis]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
try {
await redlock.acquire(["b"], duration);
throw new Error("This lock should not be acquired.");
} catch (error) {
if (!(error instanceof ExecutionError)) {
throw error;
}
t.is(
error.attempts.length,
11,
"A failed acquisition must have the configured number of retries."
);
for (const e of await Promise.allSettled(error.attempts)) {
t.is(e.status, "fulfilled");
if (e.status === "fulfilled") {
for (const v of e.value?.votesAgainst?.values()) {
t.is(v.message, "Connection is closed.");
}
}
}
}
});
test("locks automatically expire", async (t) => {
const redlock = new Redlock([redis]);
const duration = 200;
// Acquire a lock.
const lock = await redlock.acquire(["d"], duration);
t.is(await redis.get("d"), lock.value, "The lock value was incorrect.");
// Wait until the lock expires.
await new Promise((resolve) => setTimeout(resolve, 300, undefined));
// Attempt to acquire another lock on the same resource.
const lock2 = await redlock.acquire(["d"], duration);
t.is(await redis.get("d"), lock2.value, "The lock value was incorrect.");
// Release the lock.
await lock2.release();
t.is(await redis.get("d"), null);
});
test("individual locks are exclusive", async (t) => {
const redlock = new Redlock([redis]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Acquire a lock.
const lock = await redlock.acquire(["c"], duration);
t.is(await redis.get("c"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("c")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
// Attempt to acquire another lock on the same resource.
try {
await redlock.acquire(["c"], duration);
throw new Error("This lock should not be acquired.");
} catch (error) {
if (!(error instanceof ExecutionError)) {
throw error;
}
t.is(
error.attempts.length,
11,
"A failed acquisition must have the configured number of retries."
);
for (const e of await Promise.allSettled(error.attempts)) {
t.is(e.status, "fulfilled");
if (e.status === "fulfilled") {
for (const v of e.value?.votesAgainst?.values()) {
t.assert(
v instanceof ResourceLockedError,
"The error must be a ResourceLockedError."
);
}
}
}
}
// Release the lock.
await lock.release();
t.is(await redis.get("c"), null);
});
test("overlapping multi-locks are exclusive", async (t) => {
const redlock = new Redlock([redis]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Acquire a lock.
const lock = await redlock.acquire(["c1", "c2"], duration);
t.is(await redis.get("c1"), lock.value, "The lock value was incorrect.");
t.is(await redis.get("c2"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redis.pttl("c1")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redis.pttl("c2")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
// Attempt to acquire another lock with overlapping resources
try {
await redlock.acquire(["c2", "c3"], duration);
throw new Error("This lock should not be acquired.");
} catch (error) {
if (!(error instanceof ExecutionError)) {
throw error;
}
t.is(
await redis.get("c1"),
lock.value,
"The original lock value must not be changed."
);
t.is(
await redis.get("c2"),
lock.value,
"The original lock value must not be changed."
);
t.is(await redis.get("c3"), null, "The new resource must remain unlocked.");
t.is(
error.attempts.length,
11,
"A failed acquisition must have the configured number of retries."
);
for (const e of await Promise.allSettled(error.attempts)) {
t.is(e.status, "fulfilled");
if (e.status === "fulfilled") {
for (const v of e.value?.votesAgainst?.values()) {
t.assert(
v instanceof ResourceLockedError,
"The error must be a ResourceLockedError."
);
}
}
}
}
// Release the lock.
await lock.release();
t.is(await redis.get("c1"), null);
t.is(await redis.get("c2"), null);
t.is(await redis.get("c3"), null);
});
test("the `using` helper acquires, extends, and releases locks", async (t) => {
const redlock = new Redlock([redis]);
const duration = 300;
await redlock.using(
["x"],
duration,
{
automaticExtensionThreshold: 100,
},
async (signal) => {
const lockValue = await redis.get("x");
t.assert(
typeof lockValue === "string",
"The lock value was not correctly acquired."
);
// Wait to ensure that the lock is extended
await new Promise((resolve) => setTimeout(resolve, 400, undefined));
t.is(signal.aborted, false, "The signal must not be aborted.");
t.is(signal.error, undefined, "The signal must not have an error.");
t.is(
await redis.get("x"),
lockValue,
"The lock value should not have changed."
);
return lockValue;
}
);
t.is(await redis.get("x"), null, "The lock was not released.");
});
test("the `using` helper is exclusive", async (t) => {
const redlock = new Redlock([redis]);
const duration = 300;
let locked = false;
const [lock1, lock2] = await Promise.all([
await redlock.using(
["y"],
duration,
{
automaticExtensionThreshold: 100,
},
async (signal) => {
t.is(locked, false, "The resource must not already be locked.");
locked = true;
const lockValue = await redis.get("y");
t.assert(
typeof lockValue === "string",
"The lock value was not correctly acquired."
);
// Wait to ensure that the lock is extended
await new Promise((resolve) => setTimeout(resolve, 400, undefined));
t.is(signal.error, undefined, "The signal must not have an error.");
t.is(signal.aborted, false, "The signal must not be aborted.");
t.is(
await redis.get("y"),
lockValue,
"The lock value should not have changed."
);
locked = false;
return lockValue;
}
),
await redlock.using(
["y"],
duration,
{
automaticExtensionThreshold: 100,
},
async (signal) => {
t.is(locked, false, "The resource must not already be locked.");
locked = true;
const lockValue = await redis.get("y");
t.assert(
typeof lockValue === "string",
"The lock value was not correctly acquired."
);
// Wait to ensure that the lock is extended
await new Promise((resolve) => setTimeout(resolve, 400, undefined));
t.is(signal.error, undefined, "The signal must not have an error.");
t.is(signal.aborted, false, "The signal must not be aborted.");
t.is(
await redis.get("y"),
lockValue,
"The lock value should not have changed."
);
locked = false;
return lockValue;
}
),
]);
t.not(lock1, lock2, "The locks must be different.");
t.is(await redis.get("y"), null, "The lock was not released.");
});
const redisA = new Client({ host: "redis-multi-instance-a" });
const redisB = new Client({ host: "redis-multi-instance-b" });
const redisC = new Client({ host: "redis-multi-instance-c" });
test.before(async () => {
await Promise.all([
redisA.keys("*").then((keys) => (keys?.length ? redisA.del(keys) : null)),
redisB.keys("*").then((keys) => (keys?.length ? redisB.del(keys) : null)),
redisC.keys("*").then((keys) => (keys?.length ? redisC.del(keys) : null)),
]);
});
test("multi - acquires, extends, and releases a single lock", async (t) => {
const redlock = new Redlock([redisA, redisB, redisC]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Acquire a lock.
let lock = await redlock.acquire(["a"], duration);
t.is(await redisA.get("a"), lock.value, "The lock value was incorrect.");
t.is(await redisB.get("a"), lock.value, "The lock value was incorrect.");
t.is(await redisC.get("a"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redisA.pttl("a")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisB.pttl("a")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisC.pttl("a")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
// Extend the lock.
lock = await lock.extend(3 * duration);
t.is(await redisA.get("a"), lock.value, "The lock value was incorrect.");
t.is(await redisB.get("a"), lock.value, "The lock value was incorrect.");
t.is(await redisC.get("a"), lock.value, "The lock value was incorrect.");
t.is(
Math.floor((await redisA.pttl("a")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisB.pttl("a")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisC.pttl("a")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
// Release the lock.
await lock.release();
t.is(await redisA.get("a"), null);
t.is(await redisB.get("a"), null);
t.is(await redisC.get("a"), null);
});
test("multi - succeeds when a minority of clients fail", async (t) => {
const redlock = new Redlock([redisA, redisB, redisC]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Set a value on redisC so that lock acquisition fails.
await redisC.set("b", "other");
// Acquire a lock.
let lock = await redlock.acquire(["b"], duration);
t.is(await redisA.get("b"), lock.value, "The lock value was incorrect.");
t.is(await redisB.get("b"), lock.value, "The lock value was incorrect.");
t.is(await redisC.get("b"), "other", "The lock value was changed.");
t.is(
Math.floor((await redisA.pttl("b")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisB.pttl("b")) / 100),
Math.floor(duration / 100),
"The lock expiration was off by more than 100ms"
);
t.is(await redisC.pttl("b"), -1, "The lock expiration was changed");
// Extend the lock.
lock = await lock.extend(3 * duration);
t.is(await redisA.get("b"), lock.value, "The lock value was incorrect.");
t.is(await redisB.get("b"), lock.value, "The lock value was incorrect.");
t.is(await redisC.get("b"), "other", "The lock value was changed.");
t.is(
Math.floor((await redisA.pttl("b")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
t.is(
Math.floor((await redisB.pttl("b")) / 100),
Math.floor((3 * duration) / 100),
"The lock expiration was off by more than 100ms"
);
t.is(await redisC.pttl("b"), -1, "The lock expiration was changed");
// Release the lock.
await lock.release();
t.is(await redisA.get("b"), null);
t.is(await redisB.get("b"), null);
t.is(await redisC.get("b"), "other");
await redisC.del("b");
});
test("multi - fails when a majority of clients fail", async (t) => {
const redlock = new Redlock([redisA, redisB, redisC]);
const duration = Math.floor(Number.MAX_SAFE_INTEGER / 10);
// Set a value on redisB and redisC so that lock acquisition fails.
await redisB.set("c", "other1");
await redisC.set("c", "other2");
// Acquire a lock.
try {
await redlock.acquire(["c"], duration);
throw new Error("This lock should not be acquired.");
} catch (error) {
if (!(error instanceof ExecutionError)) {
throw error;
}
t.is(
error.attempts.length,
11,
"A failed acquisition must have the configured number of retries."
);
t.is(await redisA.get("c"), null);
t.is(await redisB.get("c"), "other1");
t.is(await redisC.get("c"), "other2");
for (const e of await Promise.allSettled(error.attempts)) {
t.is(e.status, "fulfilled");
if (e.status === "fulfilled") {
for (const v of e.value?.votesAgainst?.values()) {
t.assert(
v instanceof ResourceLockedError,
"The error was of the wrong type."
);
t.is(
v.message,
"The operation was applied to: 0 of the 1 requested resources."
);
}
}
}
}
await redisB.del("c");
await redisC.del("c");
}); | the_stack |
/// <reference types="node"/>
import * as Request from "request";
import * as Http from "http";
declare class SparkPost {
/** Specifying an inbound domain enables you to customize the address to which inbound messages are sent. */
inboundDomains: {
/**
* List all your inbound domains.
* @param callback The request callback with Domain results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.Domain[]>): void;
/**
* List all your inbound domains.
* @returns Promise The Domain results array
*/
list(): SparkPost.ResultsPromise<SparkPost.Domain[]>;
/**
* Retrieve an inbound domain by specifying its domain name in the URI path.
* @param domain Domain name
* @param callback The request callback with Domain results
*/
get(domain: string, callback: SparkPost.ResultsCallback<SparkPost.Domain>): void;
/**
* Retrieve an inbound domain by specifying its domain name in the URI path.
* @param domain Domain name
* @returns Promise The Domain results
*/
get(domain: string): SparkPost.ResultsPromise<SparkPost.Domain>;
/**
* Create an inbound domain by providing an inbound domains object as the POST request body.
* @param createOpts a hash of [inbound domain attributes]{@link https://developers.sparkpost.com/api/inbound-domains#header-inbound-domains-attributes}
* @param callback The request callback
*/
create(createOpts: SparkPost.CreateOpts, callback: SparkPost.Callback<void>): void;
/**
* Create an inbound domain by providing an inbound domains object as the POST request body.
* @param createOpts a hash of [inbound domain attributes]{@link https://developers.sparkpost.com/api/inbound-domains#header-inbound-domains-attributes}
* @returns Promise void
*/
create(createOpts: SparkPost.CreateOpts): Promise<void>;
/**
* Delete an inbound domain by specifying its domain name in the URI path.
* @param domain Domain name
* @param callback The request callback
*/
delete(domain: string, callback: SparkPost.Callback<void>): void;
/**
* Delete an inbound domain by specifying its domain name in the URI path.
* @param domain Domain name
* @returns Promise void
*/
delete(domain: string): Promise<void>;
};
/** The Message Events API provides the means to search the raw events generated by SparkPost. */
messageEvents: {
/**
* Retrieves list of message events according to given params
* @param parameters Query parameters
* @param callback The request callback with MessageEvent results array
*/
search(parameters: SparkPost.MessageEventParameters, callback: SparkPost.ResultsCallback<SparkPost.MessageEvent[]>): void;
/**
* Retrieves list of message events according to given params
* @param parameters Query parameters
* @returns Promise The MessageEvent results array
*/
search(parameters: SparkPost.MessageEventParameters): SparkPost.ResultsPromise<SparkPost.MessageEvent[]>;
};
/** A recipient list is a collection of recipients that can be used in a transmission. */
recipientLists: {
/**
* List a summary of all recipient lists. The recipients for each list are not included in the results.
* To retrieve recipient details, use the [Retrieve a Recipient List endpoint]{@link https://developers.sparkpost.com/api/recipient-lists.html#recipient-lists-retrieve-get},
* and specify the recipient list.
*
* @param callback The request callback with RecipientList results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.RecipientList[]>): void;
/**
* List a summary of all recipient lists. The recipients for each list are not included in the results.
* To retrieve recipient details, use the [Retrieve a Recipient List endpoint]{@link https://developers.sparkpost.com/api/recipient-lists.html#recipient-lists-retrieve-get},
* and specify the recipient list.
*
* @returns Promise The RecipientList results array
*/
list(): SparkPost.ResultsPromise<SparkPost.RecipientList[]>;
/**
* Retrieve details about a specified recipient list by specifying its id in the URI path.
* To retrieve the recipients contained in a list, the show_recipients parameter must be set to true.
*
* @param specifies whether to retrieve the recipients. Defaults to false
*/
get(id: string, options: { show_recipients?: boolean | undefined }, callback: SparkPost.Callback<SparkPost.RecipientListWithRecipients>): void;
/**
* Retrieve details about a specified recipient list by specifying its id in the URI path.
* To retrieve the recipients contained in a list, the show_recipients parameter must be set to true.
*
*/
get(id: string, callback: SparkPost.Callback<SparkPost.RecipientListWithRecipients>): void;
/**
* Retrieve details about a specified recipient list by specifying its id in the URI path.
* To retrieve the recipients contained in a list, the show_recipients parameter must be set to true.
*
* @param [options] specifies whether to retrieve the recipients. Defaults to false
*/
get(id: string, options?: { show_recipients?: boolean | undefined }): SparkPost.ResultsPromise<SparkPost.RecipientListWithRecipients>;
/**
* Create a recipient list by providing a recipient list object as the POST request body.
* At a minimum, the “recipients” array is required, which must contain a valid “address”.
* If the recipient list “id” is not provided in the POST request body, one will be generated and returned in the results body.
* Use the num_rcpt_errors parameter to limit the number of recipient errors returned.
* @param options The create options
* @param callback The request callback with metadata results
*/
create(options: SparkPost.CreateRecipientList, callback: SparkPost.ResultsCallback<SparkPost.RecipientListMetadata>): void;
/**
* Create a recipient list by providing a recipient list object as the POST request body.
* At a minimum, the “recipients” array is required, which must contain a valid “address”.
* If the recipient list “id” is not provided in the POST request body, one will be generated and returned in the results body.
* Use the num_rcpt_errors parameter to limit the number of recipient errors returned.
* @param options The create options
* @returns Promise metadata results
*/
create(options: SparkPost.CreateRecipientList): SparkPost.ResultsPromise<SparkPost.RecipientListMetadata>;
/**
* Update an existing recipient list by specifying its ID in the URI path and use a recipient list object as the PUT request body.
* Use the num_rcpt_errors parameter to limit the number of recipient errors returned.
*
* @param id Identifier of the recipient list
* @param options The update options
* @param callback The request callback with metadata results
*/
update(id: string, options: SparkPost.UpdateRecipientList, callback: SparkPost.ResultsCallback<SparkPost.RecipientListMetadata>): void;
/**
* Update an existing recipient list by specifying its ID in the URI path and use a recipient list object as the PUT request body.
* Use the num_rcpt_errors parameter to limit the number of recipient errors returned.
*
* @param id Identifier of the recipient list
*/
update(id: string, options: SparkPost.UpdateRecipientList): SparkPost.ResultsPromise<SparkPost.RecipientListMetadata>;
/**
* Permanently delete the specified recipient list.
*
* @param id The list id
* @param callback The request callback
*/
delete(id: string, callback: SparkPost.Callback<void>): void;
/**
* Permanently delete the specified recipient list.
*
* @param id The list id
* @returns Promise void
*/
delete(id: string): Promise<void>;
};
/** Relay Webhooks are a way to instruct SparkPost to accept inbound email on your behalf and forward it to you over HTTP for your own consumption. */
relayWebhooks: {
/**
* List all your relay webhooks.
* @param callback The request callback with RelayWebhook results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.RelayWebhook[]>): void;
/**
* List all your relay webhooks.
* @returns Promise The RelayWebhook results array
*/
list(): SparkPost.ResultsPromise<SparkPost.RelayWebhook[]>;
/**
* Delete a relay webhook by specifying the webhook ID in the URI path.
* @param relayWebhookId The webhook id
* @param callback The request callback with RelayWebhook results
*/
get(relayWebhookId: string, callback: SparkPost.ResultsCallback<SparkPost.RelayWebhook>): void;
/**
* Delete a relay webhook by specifying the webhook ID in the URI path.
* @param relayWebhookId The webhook id
* @returns Promise The RelayWebhook results
*/
get(relayWebhookId: string): SparkPost.ResultsPromise<SparkPost.RelayWebhook>;
/**
* Create a relay webhook by providing a relay webhooks object as the POST request body.
* @param options The create options
* @param callback The request callback with webhook id results
*/
create(options: SparkPost.RelayWebhook, callback: SparkPost.ResultsCallback<{ id: string }>): void;
/**
* Create a relay webhook by providing a relay webhooks object as the POST request body.
* @param options The create options
* @returns Promise The webhook id results
*/
create(options: SparkPost.RelayWebhook): SparkPost.ResultsPromise<{ id: string }>;
/**
* Update a relay webhook by specifying the webhook ID in the URI path.
* @param options The update options
* @param callback The request callback with webhook id results
*/
update(id: string, options: SparkPost.UpdateRelayWebhook, callback: SparkPost.ResultsCallback<{ id: string }>): void;
/**
* Update a relay webhook by specifying the webhook ID in the URI path.
* @param options The update options
* @returns Promise The webhook id results
*/
update(id: string, options: SparkPost.UpdateRelayWebhook): SparkPost.ResultsPromise<{ id: string }>;
/**
* Delete a relay webhook by specifying the webhook ID in the URI path.
* @param relayWebhookId The webhook id
* @param callback The request callback
*/
delete(relayWebhookId: string, callback: SparkPost.Callback<void>): void;
/**
* Delete a relay webhook by specifying the webhook ID in the URI path.
* @param relayWebhookId The webhook id
* @returns Promise void
*/
delete(relayWebhookId: string): Promise<void>;
};
sendingDomains: {
/**
* List an overview of all sending domains in the system.
* @param callback The request callback with SendingDomain results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.SendingDomain[]>): void;
/**
* List an overview of all sending domains in the system.
*
* @returns The SendingDomain results array
*/
list(): SparkPost.ResultsPromise<SparkPost.SendingDomain[]>;
/**
* Retrieve a sending domain by specifying its domain name in the URI path. The response includes details about its DKIM key configuration.
* @param domain The domain
* @param callback The request callback with SendingDomain results
*/
get(domain: string, callback: SparkPost.ResultsCallback<SparkPost.SendingDomain>): void;
/**
* Retrieve a sending domain by specifying its domain name in the URI path. The response includes details about its DKIM key configuration.
*
* @param domain The domain
* @returns Promise The SendingDomain results
*/
get(domain: string): SparkPost.ResultsPromise<SparkPost.SendingDomain>;
/**
* Create a sending domain by providing a sending domain object as the POST request body.
* @param options The create options
* @param callback The request callback with basic info results
*/
create(options: SparkPost.CreateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void;
/**
* Create a sending domain by providing a sending domain object as the POST request body.
*
* @param options The create options
* @returns Promise The basic info results
*/
create(options: SparkPost.CreateSendingDomain): SparkPost.ResultsPromise<{ message: string, domain: string }>;
/**
* Update the attributes of an existing sending domain by specifying its domain name in the URI path and use a sending domain object as the PUT request body.
* @param domain The domain
* @param updateOpts The update options
* @param callback The request callback with basic info results
*/
update(domain: string, updateOpts: SparkPost.UpdateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void;
/**
* Update the attributes of an existing sending domain by specifying its domain name in the URI path and use a sending domain object as the PUT request body.
*
* @param domain The domain
* @param updateOpts The update options
* @returns Promise The basic info results
*/
update(domain: string, updateOpts: SparkPost.UpdateSendingDomain): SparkPost.ResultsPromise<{ message: string, domain: string }>;
/**
* Delete an existing sending domain.
* @param domain The domain
* @param callback The request callback
*/
delete(domain: string, callback: SparkPost.Callback<void>): void;
/**
* Delete an existing sending domain.
*
* @param domain The domain
* @returns Promise void
*/
delete(domain: string): Promise<void>;
/**
* Verify a Sending Domain
* @param domain The domain
* @param options a hash of [verify attributes]{@link https://developers.sparkpost.com/api/sending-domains#header-verify-attributes}
* @param callback The request callback with verify results
*/
verify(domain: string, options: SparkPost.VerifyOptions, callback: SparkPost.ResultsCallback<SparkPost.VerifyResults>): void;
/**
* Verify a Sending Domain
*
* @param domain The domain
* @param options a hash of [verify attributes]{@link https://developers.sparkpost.com/api/sending-domains#header-verify-attributes}
* @returns Promise The verify results
*/
verify(domain: string, options: SparkPost.VerifyOptions): SparkPost.ResultsPromise<SparkPost.VerifyResults>;
};
subaccounts: {
/**
* Endpoint for retrieving a list of your subaccounts.
* This endpoint only returns information about the subaccounts themselves, not the data associated with the subaccount.
* @param callback The request callback with subaccount information results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.SubaccountInformation[]>): void;
/**
* Endpoint for retrieving a list of your subaccounts.
* This endpoint only returns information about the subaccounts themselves, not the data associated with the subaccount.
*
* @returns Promise The subaccount information results array
*/
list(): SparkPost.ResultsPromise<SparkPost.SubaccountInformation[]>;
/**
* Get details about a specified subaccount by its id
*
* @param id the id of the subaccount you want to look up
* @param callback The request callback with subaccount information results
*/
get(id: string | number, callback: SparkPost.ResultsCallback<SparkPost.SubaccountInformation>): void;
/**
* Get details about a specified subaccount by its id
*
* @param id the id of the subaccount you want to look up
* @returns Promise The subaccount information results
*/
get(id: string | number): SparkPost.ResultsPromise<SparkPost.SubaccountInformation>;
/**
* Provisions a new subaccount and an initial subaccount API key.
* @param subaccount The create options
* @param callback The request callback with basic subaccount information results
*/
create(subaccount: SparkPost.CreateSubaccount, callback: SparkPost.ResultsCallback<SparkPost.CreateSubaccountResponse>): void;
/**
* Provisions a new subaccount and an initial subaccount API key.
*
* @param subaccount The create options
* @returns Promise The basic subaccount information results
*/
create(subaccount: SparkPost.CreateSubaccount): SparkPost.ResultsPromise<SparkPost.CreateSubaccountResponse>;
/**
* Update an existing subaccount’s information.
*
* @param id the id of the subaccount you want to update
* @param subaccount an object of [updatable subaccount attributes]{@link https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1}
* @param callback The request callback with webhook id results
*/
update(id: string, subaccount: SparkPost.UpdateSubaccount, callback: SparkPost.ResultsCallback<{ message: string }>): void;
/**
* Update an existing subaccount’s information.
*
* @param id the id of the subaccount you want to update
* @param subaccount an object of [updatable subaccount attributes]{@link https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1}
* @returns Promise The webhook id results
*/
update(id: string, subaccount: SparkPost.UpdateSubaccount): SparkPost.ResultsPromise<{ message: string }>;
};
suppressionList: {
/**
* List all entries in your suppression list, filtered by an optional set of search parameters.
*
* @param callback The request callback with supression lists.
*/
list(callback: SparkPost.ResultsCallback<SparkPost.SupressionListEntry[]>): void;
/**
* List all entries in your suppression list, filtered by an optional set of search parameters.
*
* @param parameters an object of [search parameters]{@link https://developers.sparkpost.com/api/suppression-list#suppression-list-search-get}
* @param callback The request callback with supression lists.
*/
list(parameters: SparkPost.SupressionSearchParameters, callback: SparkPost.ResultsCallback<SparkPost.SupressionListEntry[]>): void;
/**
* List all entries in your suppression list, filtered by an optional set of search parameters.
*
* @param [parameters] an object of [search parameters]{@link https://developers.sparkpost.com/api/suppression-list#suppression-list-search-get}
* @returns Promise The supression lists
*/
list(parameters?: SparkPost.SupressionSearchParameters): SparkPost.ResultsPromise<SparkPost.SupressionListEntry[]>;
/**
* Retrieve an entry by recipient email.
*
* @param email address to check
* @returns void
*/
get(email: string, callback: SparkPost.ResultsCallback<SparkPost.SupressionListEntry[]>): void;
/**
* Retrieve an entry by recipient email.
*
* @param email address to check
* @returns void
*/
get(email: string): SparkPost.ResultsPromise<SparkPost.SupressionListEntry[]>;
/**
* Delete a recipient from the list by specifying the recipient’s email address in the URI path.
*
* @param email Recipient email address
*/
delete(email: string, callback: SparkPost.Callback<void>): void;
/**
* Delete a recipient from the list by specifying the recipient’s email address in the URI path.
*
* @param email Recipient email address
* @returns void
*/
delete(email: string): Promise<void>;
/**
* Insert or update one or many entries.
*
* @param listEntries The suppression entry list
* @param callback The request callback
*/
upsert(listEntries: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[], callback: SparkPost.ResultsCallback<{ message: string }>): void;
/**
* Insert or update one or many entries.
*
* @param listEntries The suppression entry list
*/
upsert(listEntries: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[]): SparkPost.ResultsPromise<{ message: string }>;
};
templates: {
/**
* List a summary of all templates.
* @param callback The request callback with TemplateMeta results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.TemplateMeta[]>): void;
/**
* List a summary of all templates.
*
* @returns The TemplateMeta results array
*/
list(): SparkPost.ResultsPromise<SparkPost.TemplateMeta[]>;
/**
* Retrieve details about a specified template by its id
*
* @param id the id of the template you want to look up
* @param options specifies a draft or published template
* @param callback The request callback with Template results
*/
get(id: string, options: { draft?: boolean | undefined }, callback: SparkPost.ResultsCallback<SparkPost.Template>): void;
/**
* Retrieve details about a specified template by its id
*
* @param id the id of the template you want to look up
* @param callback The request callback with Template results
*/
get(id: string, callback: SparkPost.ResultsCallback<SparkPost.Template>): void;
/**
* Retrieve details about a specified template by its id
*
* @param id the id of the template you want to look up
* @param [options] specifies a draft or published template
* @returns The Template results
*/
get(id: string, options?: { draft?: boolean | undefined }): SparkPost.ResultsPromise<SparkPost.Template>;
/**
* Create a new template
*
* @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes}
* @param callback The request callback with template id results
*/
create(template: SparkPost.CreateTemplate, callback: SparkPost.ResultsCallback<{ id: string }>): void;
/**
* Create a new template
*
* @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes}
* @returns The template id results
*/
create(template: SparkPost.CreateTemplate): SparkPost.ResultsPromise<{ id: string }>;
/**
* Update an existing template
*
* @param id the id of the template you want to update
* @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes}
* @param options The create options. If true, directly overwrite the existing published template. If false, create a new draft
* @param callback The request callback with template id results
*/
update(
id: string,
template: SparkPost.UpdateTemplate,
options: { update_published?: boolean | undefined },
callback: SparkPost.ResultsCallback<{ id: string }>): void;
/**
* Update an existing template
*
* @param id the id of the template you want to update
* @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes}
* @param callback The request callback with template id results
*/
update(
id: string,
template: SparkPost.UpdateTemplate,
callback: SparkPost.ResultsCallback<{ id: string }>): void;
/**
* Update an existing template
*
* @param id the id of the template you want to update
* @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes}
* @param options If true, directly overwrite the existing published template. If false, create a new draft
* @returns The template id results
*/
update(id: string, template: SparkPost.UpdateTemplate, options?: {
update_published?: boolean | undefined;
}): SparkPost.ResultsPromise<{ id: string }>;
/**
* Delete an existing template
* @param id The template id
* @param callback The request callback
*/
delete(id: string, callback: SparkPost.Callback<void>): void;
/**
* Delete an existing template
*
* @param id The template id
* @returns Promise void
*/
delete(id: string): Promise<void>;
/**
* Preview the most recent version of an existing template by id
*
* @param id the id of the template you want to look up
* @param options The preview options
* @param callback The request callback with webhook id results
*/
preview(id: string, options: { substitution_data?: any, draft?: boolean | undefined }, callback: SparkPost.ResultsCallback<SparkPost.TemplateContent>): void;
/**
* Preview the most recent version of an existing template by id
*
* @param id the id of the template you want to look up
* @param callback The request callback with webhook id results
*/
preview(id: string, callback: SparkPost.ResultsCallback<SparkPost.TemplateContent>): void;
/**
* Preview the most recent version of an existing template by id
*
* @param id the id of the template you want to look up
* @returns The webhook id results
*/
preview(id: string, options?: { substitution_data?: any, draft?: boolean | undefined }): SparkPost.ResultsPromise<SparkPost.TemplateContent>;
};
transmissions: {
/**
* List an overview of all transmissions in the account
*
* @param callback The request callback with Transmission results array
*/
list(callback: SparkPost.ResultsCallback<SparkPost.TransmissionSummary[]>): void;
/**
* List an overview of all transmissions in the account
*
* @param callback The request callback with Transmission results array
*/
list(options: { campaign_id?: string | undefined, template_id?: string | undefined }, callback: SparkPost.ResultsCallback<SparkPost.TransmissionSummary[]>): void;
/**
* List an overview of all transmissions in the account
*
* @returns The Transmission results array
*/
list(options?: { campaign_id?: string | undefined, template_id?: string | undefined }): SparkPost.ResultsPromise<SparkPost.TransmissionSummary[]>;
/**
* Retrieve the details about a transmission by its ID
*
* @param id The id of the transmission you want to look up
* @param callback The request callback with Transmission results
*/
get(transmissionID: string, callback: SparkPost.ResultsCallback<SparkPost.Transmission>): void;
/**
* Retrieve the details about a transmission by its ID
*
* @param id The id of the transmission you want to look up
* @returns The Transmission results
*/
get(id: string): SparkPost.ResultsPromise<SparkPost.Transmission>;
/**
* Sends a message by creating a new transmission
*
* @param transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes}
* @param options The create options. Specify maximum number of recipient errors returned
* @param callback The request callback with metadata and id results
*/
send(transmission: SparkPost.CreateTransmission, options: { num_rcpt_errors?: number | undefined }, callback: SparkPost.ResultsCallback<{
total_rejected_recipients: number;
total_accepted_recipients: number;
id: string;
}>): void;
/**
*
*
* @param transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes}
* @param callback The request callback with metadata and id results
*/
send(transmission: SparkPost.CreateTransmission, callback: SparkPost.ResultsCallback<{
total_rejected_recipients: number;
total_accepted_recipients: number;
id: string;
}>): void;
/**
* Sends a message by creating a new transmission
*
* @param transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes}
* @param [options] specify maximum number of recipient errors returned
* @returns The metadata and id results
*/
send(transmission: SparkPost.CreateTransmission, options?: { num_rcpt_errors?: number | undefined }): SparkPost.ResultsPromise<{
total_rejected_recipients: number;
total_accepted_recipients: number;
id: string;
}>;
};
webhooks: {
/**
* List currently existing webhooks.
* @param callback The request callback with RelayWebhook results array
*/
list(callback: SparkPost.ResultsCallback<Array<SparkPost.WebhookLinks & SparkPost.Webhook>>): void;
/**
* List currently existing webhooks.
* @param options Object containing optional timezone
* @param callback The request callback with RelayWebhook results array
*/
list(options: { timezone?: string | undefined }, callback: SparkPost.ResultsCallback<Array<SparkPost.WebhookLinks & SparkPost.Webhook>>): void;
/**
* List currently existing webhooks.the timezone to use for the last_successful and last_failure properties | Default: UTC
*
*/
list(options?: { timezone?: string | undefined }): SparkPost.ResultsPromise<Array<SparkPost.WebhookLinks & SparkPost.Webhook>>;
/**
* Retrieve details about a specified webhook by its id
*
* @param id The id of the webhook to get
* @param options Object containing id and optional timezone
* @param callback The request callback with RelayWebhook results
*/
get(id: string, options: { timezone?: string | undefined }, callback: SparkPost.ResultsCallback<SparkPost.WebhookLinks & SparkPost.Webhook>): void;
/**
* Retrieve details about a specified webhook by its id
*
* @param id The id of the webhook to get
* @param callback The request callback with RelayWebhook results
*/
get(id: string, callback: SparkPost.ResultsCallback<SparkPost.WebhookLinks & SparkPost.Webhook>): void;
/**
* Retrieve details about a specified webhook by its id
*
* @param id The id of the webhook to get
* @param [options] the timezone to use for the last_successful and last_failure properties
* @returns The RelayWebhook results
*/
get(id: string, options?: { timezone?: string | undefined }): SparkPost.ResultsPromise<SparkPost.WebhookLinks & SparkPost.Webhook>;
/**
* Create a new webhook
*
* @param options a hash of [webhook attributes]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties}
* @param callback The request callback with webhook id results
*/
create(options: SparkPost.Webhook, callback: SparkPost.ResultsCallback<SparkPost.WebhookLinks & { id: string }>): void;
/**
* Create a new webhook
*
* @param options a hash of [webhook attributes]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties}
* @returns The webhook id results
*/
create(options: SparkPost.Webhook): SparkPost.ResultsPromise<SparkPost.WebhookLinks & { id: string }>;
/**
* Update an existing webhook
* @param id the id of the webhook to update
* @param options A hash of [webhook attribues]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties}
* @param callback The request callback with webhook id results
*/
update(id: string, options: SparkPost.UpdateWebhook, callback: SparkPost.ResultsCallback<SparkPost.WebhookLinks & { id: string }>): void;
/**
* Update an existing webhook
*
*/
update(id: string, options: SparkPost.UpdateWebhook): SparkPost.ResultsPromise<SparkPost.WebhookLinks & { id: string }>;
/**
* Delete an existing webhook
* @param id The webhook id
* @param callback The request callback
*/
delete(id: string, callback: SparkPost.Callback<void>): void;
/**
* Delete an existing webhook.
*
* @param id The id of the webhook to delete
*/
delete(id: string): Promise<void>;
/**
* Sends an example message event batch from the Webhook API to the target URL
*
* @param id The id of the webhook to validate
* @param options the message (payload) to send to the webhook consumer
* @param callback The request callback with validation results
*/
validate(id: string, options: { message: any }, callback: SparkPost.ResultsCallback<{
msg: string;
response: {
status: number;
headers: any;
body: string;
}
}>): void;
/**
* Sends an example message event batch from the Webhook API to the target URL.
*
* @param id The id of the webhook to validate
* @param options The message (payload) to send to the webhook consumer
* @returns The validation results
*/
validate(id: string, options: { message: any }): SparkPost.ResultsPromise<{
msg: string;
response: {
status: number;
headers: any;
body: string;
}
}>;
/**
* Gets recent status information about a webhook.
*
* @param id The id of the webhook
* @param options An optional limit that specifies the maximum number of results to return. Defaults to 1000
* @param callback The request callback with status results
*/
getBatchStatus(id: string, options: { limit?: number | undefined }, callback: SparkPost.ResultsCallback<Array<{
batch_id: string;
ts: string;
attempts: number;
response_code: number;
}>>): void;
/**
* Gets recent status information about a webhook.
*
* @param id The id of the webhook
* @param callback The request callback with status results
*/
getBatchStatus(id: string, callback: SparkPost.ResultsCallback<Array<{
batch_id: string;
ts: string;
attempts: number;
response_code: number;
}>>): void;
/**
* Gets recent status information about a webhook.
*
* @param id The id of the webhook
* @param Maximum number of results to return. Defaults to 1000
* @returns The status results
*/
getBatchStatus(id: string, options: { limit?: number | undefined }): SparkPost.ResultsPromise<Array<{
batch_id: string;
ts: string;
attempts: number;
response_code: number;
}>>;
/**
* Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL.
* @param callback The request callback containing documentation results
*/
getDocumentation(callback: SparkPost.ResultsCallback<any>): void;
/**
* Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL.
*
* @returns The documentation results
*/
getDocumentation(): SparkPost.ResultsPromise<any>;
/**
* List an example of the event data that will be posted by a Webhook for the specified events.
* @param callback The request callback containing examples
*/
getSamples(callback: SparkPost.Callback<any>): void;
/**
* List an example of the event data that will be posted by a Webhook for the specified events.
* @param options The optional event name
* @param callback The request callback containing examples
*/
getSamples(options: { events?: string | undefined }, callback: SparkPost.Callback<any>): void;
/**
* List an example of the event data that will be posted by a Webhook for the specified events.
*
* @param options [event types]{@link https://support.sparkpost.com/customer/portal/articles/1976204} for which to get a sample payload
* Default: all event types returned
*/
getSamples(options?: { events?: string | undefined }): Promise<SparkPost.Response<any>>;
};
/**
* The official Node.js binding for your favorite SparkPost APIs!
* @param apiKey A passed in apiKey will take precedence over an environment variable
* @param options Additional options
*/
constructor(apiKey?: string, options?: SparkPost.ConstructorOptions);
request(options: Request.Options, callback: SparkPost.Callback<any>): void;
request(options: Request.Options): Promise<SparkPost.Response<any>>;
get(options: Request.Options, callback: SparkPost.Callback<any>): void;
get(options: Request.Options): Promise<SparkPost.Response<any>>;
post(options: Request.Options, callback: SparkPost.Callback<any>): void;
post(options: Request.Options): Promise<SparkPost.Response<any>>;
put(options: Request.Options, callback: SparkPost.Callback<any>): void;
put(options: Request.Options): Promise<SparkPost.Response<any>>;
delete(options: Request.Options, callback: SparkPost.Callback<any>): void;
delete(options: Request.Options): Promise<SparkPost.Response<any>>;
}
declare namespace SparkPost {
interface ErrorWithDescription {
message: string;
code: string;
description: string;
}
interface ErrorWithParam {
message: string;
param: string;
value: string | null;
}
interface SparkPostError extends Error {
name: "SparkPostError";
errors: ErrorWithDescription[] | ErrorWithParam[];
statusCode: number;
}
interface ConstructorOptions {
origin?: string | undefined;
endpoint?: string | undefined;
apiVersion?: string | undefined;
headers?: any;
}
interface Response<T> extends Http.IncomingMessage {
body: T;
}
type Callback<T> = (err: Error | SparkPostError | null, res: Response<T>) => void;
type ResultsCallback<T> = Callback<{ results: T }>;
type ResultsPromise<T> = Promise<{ results: T }>;
interface Domain {
domain: string;
}
interface MessageEvent {
/** Type of event this record describes */
type: string;
/** Classification code for a given message (see [Bounce Classification Codes](https://support.sparkpost.com/customer/portal/articles/1929896)) */
bounce_class: string;
/** Campaign of which this message was a part */
campaign_id: string;
/** SparkPost-customer identifier through which this message was sent */
customer_id: string;
/** Protocol by which SparkPost delivered this message */
delv_method: string;
/** Token of the device / application targeted by this PUSH notification message. Applies only when delv_method is gcm or apn. */
device_token: string;
/** Error code by which the remote server described a failed delivery attempt */
error_code: string;
/** IP address of the host to which SparkPost delivered this message; in engagement events, the IP address of the host where the HTTP request originated */
ip_address: string;
/** SparkPost-cluster-wide unique identifier for this message */
message_id: string;
/** Sender address used on this message"s SMTP envelope */
msg_from: string;
/** Message"s size in bytes */
msg_size: string;
/** Number of failed attempts before this message was successfully delivered; when the first attempt succeeds, zero */
num_retries: string;
/** Metadata describing the message recipient */
rcpt_meta: any;
/** Tags applied to the message which generated this event */
rcpt_tags: string[];
/** Recipient address used on this message"s SMTP envelope */
rcpt_to: string;
/** Indicates that a recipient address appeared in the Cc or Bcc header or the archive JSON array */
rcpt_type: string;
/** Unmodified, exact response returned by the remote server due to a failed delivery attempt */
raw_reason: string;
/** Canonicalized text of the response returned by the remote server due to a failed delivery attempt */
reason: string;
/** Domain receiving this message */
routing_domain: string;
/** Subject line from the email header */
subject: string;
/** Slug of the template used to construct this message */
template_id: string;
/** Version of the template used to construct this message */
template_version: string;
/** Event date and time formatted as: YYYY-MM-DDTHH:MM:SS.SSS±hh:mm */
timestamp: string;
/** Transmission which originated this message */
transmission_id: string;
}
interface MessageEventParameters {
/** delimited list of bounce classification codes to search. (See Bounce Classification Codes.) */
bounce_classes?: Array<string | number> | string | number | undefined;
/** delimited list of campaign ID’s to search (i.e. the campaign id used during creation of a transmission). */
campaign_ids?: string[] | string | undefined;
/** Specifies the delimiter for query parameter lists */
delimiter?: string | undefined;
/** delimited list of event types to search. Defaults to all event types. */
events?: string[] | string | undefined;
/** delimited list of friendly from emails to search. */
friendly_froms?: string[] | string | undefined;
/** Datetime in format of YYYY-MM-DDTHH:MM. */
from?: string | undefined;
/** delimited list of message ID’s to search. */
message_ids?: string[] | string | undefined;
/** The results page number to return. Used with per_page for paging through results. */
page?: number | undefined;
/** Number of results to return per page. Must be between 1 and 10,000 (inclusive). */
per_page?: number | undefined;
/** Bounce/failure/rejection reason that will be matched using a wildcard (e.g., %reason%). */
reason?: string[] | string | undefined;
/** delimited list of recipients to search. */
recipients?: string[] | string | undefined;
/** delimited list of subaccount ID’s to search. */
subaccounts?: number[] | number | undefined;
/** delimited list of template ID’s to search. */
template_ids?: string[] | string | undefined;
/** Standard timezone identification string. */
timezone?: string | undefined;
/** Datetime in format of YYYY-MM-DDTHH:MM. */
to?: string | undefined;
/** delimited list of transmission ID’s to search (i.e. id generated during creation of a transmission). */
transmission_ids?: string[] | string | undefined;
}
interface RecipientListMetadata {
total_rejected_recipients: number;
total_accepted_recipients: number;
id: string;
name: string;
}
interface RecipientList {
/** Short, unique, recipient list identifier */
id: string;
/** Short, pretty/readable recipient list display name, not required to be unique */
name: string;
/** Detailed description of the recipient list */
description: string;
/** Recipient list attribute object */
attributes: any;
/** Number of accepted recipients */
total_accepted_recipients: number;
}
interface RecipientListWithRecipients extends RecipientList {
/** Array of recipient objects */
recipients: Recipient[];
}
interface CreateRecipientList {
/** Short, unique, recipient list identifier */
id?: string | undefined;
/** Short, pretty/readable recipient list display name, not required to be unique */
name?: string | undefined;
/** Detailed description of the recipient list */
description?: string | undefined;
/** Recipient list attribute object */
attributes?: any;
/** limit the number of recipient errors returned. */
num_rcpt_errors?: number | undefined;
/** Array of recipient objects */
recipients: Recipient[];
}
interface UpdateRecipientList {
/** Short, unique, recipient list identifier */
id?: string | undefined;
/** Short, pretty/readable recipient list display name, not required to be unique */
name?: string | undefined;
/** Detailed description of the recipient list */
description?: string | undefined;
/** Recipient list attribute object */
attributes?: any;
/** Array of recipient objects */
recipients: Recipient[];
}
interface BaseRecipient {
/** SparkPost Enterprise API only. Email to use for envelope FROM. */
return_path?: string | undefined;
/** Array of text labels associated with a recipient. */
tags?: string[] | undefined;
/** Key/value pairs associated with a recipient. */
metadata?: any;
/** Key/value pairs associated with a recipient that are provided to the substitution engine. */
substitution_data?: any;
}
interface RecipientWithAddress {
/** Address information for a recipient At a minimum, address or multichannel_addresses is required. */
address: Address | string;
}
interface RecipientWithMultichannelAddresses {
/**
* Address information for a recipient. At a minimum, address or multichannel_addresses is required.
* If both address and multichannel_addresses are specified only multichannel_addresses will be used.
*
*/
address?: Address | string | undefined;
/**
* Array of Multichannel Address objects for a recipient. At a minimum, address or multichannel_addresses is required.
* If both address and multichannel_addresses are specified only multichannel_addresses will be used.
*
*/
multichannel_addresses: MultichannelAddress[];
}
type Recipient = (RecipientWithAddress | RecipientWithMultichannelAddresses) & BaseRecipient;
interface Address {
/** Valid email address */
email: string;
/** User-friendly name for the email address */
name?: string | undefined;
/** Email address to display in the “To” header instead of address.email (for CC and BCC) */
header_to?: string | undefined;
}
interface MultichannelAddress {
/** The communication channel used to reach recipient. Valid values are “email”, “gcm”, “apns”. */
channel: string;
/** Valid email address. Required if channel is “email”. */
email: string;
/** User-friendly name for the email address. Used when channel is “email” */
name: string;
/** Email address to display in the “To” header instead of address.email (for BCC). Used when channel is “email” */
header_to: string;
/** SparkPost Enterprise API only. Required if channel is “gcm” or “apns” */
token: string;
/** SparkPost Enterprise API only. Required if channel is “gcm” or “apns” */
app_id: string;
}
interface RelayWebhook {
/** User-friendly name no example: Inbound Customer Replies */
name?: string | undefined;
/** URL of the target to which to POST relay batches */
target: string;
/** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */
auth_token?: string | undefined;
/** Restrict which inbound messages will be relayed to the target */
match: Match;
}
interface UpdateRelayWebhook {
/** User-friendly name no example: Inbound Customer Replies */
name?: string | undefined;
/** URL of the target to which to POST relay batches */
target: string;
/** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */
auth_token?: string | undefined;
/** Restrict which inbound messages will be relayed to the target */
match?: Match | undefined;
}
interface Match {
/** Inbound messaging protocol associated with this webhook. Defaults to “SMTP” */
protocol?: string | undefined;
/** Inbound domain associated with this webhook. Required when protocol is “SMTP”. */
domain?: string | undefined;
/** ESME address binding associated with this webhook yes, when protocol is “SMPP”. SparkPost Enterprise API only. */
esme_address?: string | undefined;
}
interface SendingDomain {
/** Name of the sending domain. */
domain: string;
/** Associated tracking domain. */
tracking_domain: string;
/** JSON object containing status details, including whether this domain’s ownership has been verified. */
status: Status;
/** JSON object in which DKIM key configuration is defined. */
dkim?: DKIM | undefined;
/** Whether to generate a DKIM keypair on creation. */
generate_dkim?: boolean | undefined;
/** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */
dkim_key_length?: number | undefined;
/** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */
shared_with_subaccounts: boolean;
}
interface CreateSendingDomain {
/** Name of the sending domain. */
domain: string;
/** Associated tracking domain. */
tracking_domain?: string | undefined;
/** JSON object containing status details, including whether this domain’s ownership has been verified. */
status?: Status | undefined;
/** JSON object in which DKIM key configuration is defined. */
dkim?: DKIM | undefined;
/** Whether to generate a DKIM keypair on creation. */
generate_dkim?: boolean | undefined;
/** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */
dkim_key_length?: number | undefined;
/** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */
shared_with_subaccounts?: boolean | undefined;
}
interface UpdateSendingDomain {
/** Associated tracking domain. */
tracking_domain?: string | undefined;
/** JSON object in which DKIM key configuration is defined. */
dkim?: DKIM | undefined;
/** Whether to generate a DKIM keypair on creation. */
generate_dkim?: boolean | undefined;
/** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */
dkim_key_length?: number | undefined;
/** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */
shared_with_subaccounts?: boolean | undefined;
}
interface DKIM {
/** Signing Domain Identifier (SDID). SparkPost Enterprise API only. */
signing_domain?: string | undefined;
/** DKIM private key. */
private?: string | undefined;
/** DKIM public key. */
public: string;
/** DomainKey selector. */
selector: string;
/** Header fields to be included in the DKIM signature. This field is currently ignored. */
headers?: string | undefined;
}
interface Status {
/** Whether domain ownership has been verified */
ownership_verified: boolean;
/** Verification status of SPF configuration */
spf_status: "valid" | "invalid" | "unverified" | "pending";
/** Compliance status */
compliance_status: "valid" | "pending" | "blocked";
/** Verification status of DKIM configuration */
dkim_status: "valid" | "invalid" | "unverified" | "pending";
/** Verification status of abuse@ mailbox */
abuse_at_status: "valid" | "invalid" | "unverified" | "pending";
/** Verification status of postmaster@ mailbox */
postmaster_at_status: "valid" | "invalid" | "unverified" | "pending";
/** Verification status of CNAME configuration */
cname_status: "valid" | "invalid" | "unverified" | "pending";
/** Verification status of MX configuration */
mx_status: "valid" | "invalid" | "unverified" | "pending";
}
interface VerifyOptions {
/**
* Request verification of DKIM record
*
*/
dkim_verify?: boolean | undefined;
/**
* Request verification of SPF record
*
* @deprecated
*/
spf_verify?: boolean | undefined;
/**
* Request an email with a verification link to be sent to the sending domain’s postmaster@ mailbox.
*
*/
postmaster_at_verify?: boolean | undefined;
/**
* Request an email with a verification link to be sent to the sending domain’s abuse@ mailbox.
*
*/
abuse_at_verify?: boolean | undefined;
/**
* A token retrieved from the verification link contained in the postmaster@ verification email.
*
*/
postmaster_at_token?: string | undefined;
/**
* A token retrieved from the verification link contained in the abuse@ verification email.
*
*/
abuse_at_token?: string | undefined;
/**
* Request verification of CNAME record
*/
cname_verify?: boolean | undefined;
}
interface VerifyResults extends Status {
dns?: {
dkim_record: string;
spf_record: string;
} | undefined;
}
interface CreateSubaccount {
/** user-friendly name */
name: string;
/** user-friendly identifier for subaccount API key */
key_label: string;
/** list of grants to give the subaccount API key */
key_grants: string[];
/** list of IPs the subaccount may be used from */
key_valid_ips?: string[] | undefined;
/** id of the default IP pool assigned to subaccount"s transmissions */
ip_pool?: string | undefined;
}
interface CreateSubaccountResponse {
subaccount_id: number;
key: string;
label: string;
short_key: string;
}
interface UpdateSubaccount {
/** user-friendly name */
name: string;
/** status of the subaccount */
status: string;
/** id of the default IP pool assigned to subaccount"s transmissions */
ip_pool?: string | undefined;
}
interface SubaccountInformation {
/** ID of subaccount */
id: number;
/** User friendly identifier for a specific subaccount */
name: string;
/** Status of the account */
status: "active" | "suspended" | "terminated";
/** The ID of the default IP Pool assigned to this subaccount’s transmissions */
ip_pool?: string | undefined;
compliance_status: string;
}
interface CreateSupressionListEntry {
/**
* Email address to be suppressed
*
*/
recipient: string;
/**
* Type of suppression record
*
*/
type?: "transactional" | "non_transactional" | undefined;
/**
* Whether the recipient requested to not receive any non-transactional messages
* Not required if a valid type is passed
*
* @deprecated Available, but deprecated in favor of type
*/
transactional?: boolean | undefined;
/**
* Whether the recipient requested to not receive any non-transactional messages
* Not required if a valid type is passed
*
* @deprecated Available, but deprecated in favor of type
*/
non_transactional?: boolean | undefined;
/**
* Source responsible for inserting the list entry
* no - entries created by the user are marked as Manually Added
*
*/
readonly source?: "Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance" | undefined;
/** Short explanation of the suppression */
description?: string | undefined;
}
interface SupressionListEntry {
/**
* Email address to be suppressed
*
*/
recipient: string;
/**
* Whether the recipient requested to not receive any transactional messages
* Not required if a valid type is passed
*
* @deprecated Available, but deprecated in favor of type
*/
transactional?: boolean | undefined;
/**
* Whether the recipient requested to not receive any non-transactional messages
* Not required if a valid type is passed
*
* @deprecated Available, but deprecated in favor of type
*/
non_transactional?: boolean | undefined;
/** Type of suppression record: transactional or non_transactional */
type?: "transactional" | "non_transactional" | undefined;
/**
* Source responsible for inserting the list entry
*
* no - entries created by the user are marked as Manually Added
*
*/
source?: "Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance" | undefined;
/** Short explanation of the suppression */
description?: string | undefined;
created: string;
updated: string;
}
interface SupressionSearchParameters {
/** Datetime the entries were last updated, in the format of YYYY-MM-DDTHH:mm:ssZ */
to?: string | undefined;
/** Datetime the entries were last updated, in the format YYYY-MM-DDTHH:mm:ssZ */
from?: string | undefined;
/**
* Domain of entries to include in the search. ( Note: SparkPost only)
*
*/
domain?: string | undefined;
/**
* The results cursor location to return, to start paging with cursor, use the value of ‘initial’.
* When cursor is provided the page parameter is ignored. (Note: SparkPost only)
*
*/
cursor?: string | undefined;
/**
* Maximum number of results to return per page. Must be between 1 and 10,000.
* ( Note: SparkPost only)
* @default 1000
*/
per_page?: string | number | undefined;
/**
* The results page number to return. Used with per_page for paging through results.
* The page parameter works up to 10,000 results.
* You must use the cursor parameter and start with cursor=initial to page result sets larger than 10,000
* ( Note: SparkPost only)
*
*/
page?: string | number | undefined;
/** Types of entries to include in the search, i.e. entries with “transactional” and/or “non_transactional” keys set to true */
types?: string | undefined;
/** Sources of the entries to include in the search, i.e. entries that were added by this source */
sources?: string | undefined;
/**
* Description of the entries to include in the search, i.e descriptions that include the text submitted.
* ( Note: SparkPost only)
*
*/
description?: string | undefined;
/**
* Maximum number of results to return per page. Must be between 1 and 10,000.
* @deprecated use per_page instead
*/
limit?: number | undefined;
}
interface TemplateContent {
/** HTML content for the email’s text/html MIME part */
html: string;
/** Text content for the email’s text/plain MIME part */
text: string;
/** Email subject line. */
subject: string;
/**
* Address "from" : "deals@company.com" or JSON object composed of the "name" and "email" fields.
* "from" : { "name" : "My Company", "email" : "deals@company.com" } used to compose the email’s "From" header.
*
*/
from: Address | string;
/** Email address used to compose the email’s “Reply-To” header. */
reply_to?: string | undefined;
/** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To”. */
headers?: any;
}
interface CreateTemplateContent {
/** HTML content for the email’s text/html MIME part */
html?: string | undefined;
/** Text content for the email’s text/plain MIME part */
text?: string | undefined;
/** Email subject line. */
subject: string;
/**
* Address "from" : "deals@company.com" or JSON object composed of the "name" and "email" fields.
* "from" : { "name" : "My Company", "email" : "deals@company.com" } used to compose the email’s "From" header.
*
*/
from: Address | string;
/** Email address used to compose the email’s “Reply-To” header. */
reply_to?: string | undefined;
/** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To”. */
headers?: any;
}
interface TemplateMeta {
/** Unique template ID */
id: string;
/** Template name */
name: string;
/** Published state of the template (true = published, false = draft) */
published: boolean;
/** Template description */
description: string;
}
interface Template {
/**
* Short, unique, alphanumeric ID used to reference the template.
* At a minimum, id or name is required upon creation.
* It is auto generated if not provided.
* After a template has been created, this property cannot be changed. Maximum length - 64 bytes
*
*/
id: string;
/** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */
content: TemplateContent | { email_rfc822: string };
/** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */
published: boolean;
/** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */
name: string;
/** Detailed description of the template no Maximum length - 1024 bytes */
description: string;
/** JSON object in which template options are defined no For a full description, see the Options Attributes. */
options: TemplateOptions;
/** The “last_update_time” is the time the template was last updated, for both draft and published versions */
last_update_time: string;
/** The “last_use” time represents the last time any version of this template was used (draft or published). */
last_use?: string | undefined;
}
interface CreateTemplate {
/**
* Short, unique, alphanumeric ID used to reference the template.
* At a minimum, id or name is required upon creation.
* It is auto generated if not provided.
* After a template has been created, this property cannot be changed. Maximum length - 64 bytes
*
*/
id?: string | undefined;
/** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */
content: CreateTemplateContent | { email_rfc822: string };
/** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */
published?: boolean | undefined;
/** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */
name?: string | undefined;
/** Detailed description of the template no Maximum length - 1024 bytes */
description?: string | undefined;
/** JSON object in which template options are defined no For a full description, see the Options Attributes. */
options?: CreateTemplateOptions | undefined;
}
interface UpdateTemplate {
/** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */
content?: CreateTemplateContent | { email_rfc822: string } | undefined;
/** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */
published?: boolean | undefined;
/** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */
name?: string | undefined;
/** Detailed description of the template no Maximum length - 1024 bytes */
description?: string | undefined;
/** JSON object in which template options are defined no For a full description, see the Options Attributes. */
options?: CreateTemplateOptions | undefined;
}
interface TemplateOptions {
/** Enable or disable open tracking */
open_tracking: boolean;
/** Enable or disable click tracking */
click_tracking: boolean;
/** Distinguish between transactional and non-transactional messages for unsubscribe and suppression purposes */
transactional: boolean;
}
interface CreateTemplateOptions {
/** Enable or disable open tracking */
open_tracking?: boolean | undefined;
/** Enable or disable click tracking */
click_tracking?: boolean | undefined;
/** Distinguish between transactional and non-transactional messages for unsubscribe and suppression purposes */
transactional?: boolean | undefined;
}
interface CreateTransmission {
/** JSON object in which transmission options are defined */
options?: TransmissionOptions | undefined;
/**
* Recipients to receive a carbon copy of the transmission
*
*/
cc?: Recipient[] | undefined;
/**
* Recipients to discreetly receive a carbon copy of the transmission
*
*/
bcc?: Recipient[] | undefined;
/** Inline recipient objects or object containing stored recipient list ID */
recipients?: Recipient[] | { list_id: string } | undefined;
/** Name of the campaign */
campaign_id?: string | undefined;
/** Description of the transmission */
description?: string | undefined;
/** Transmission level metadata containing key/value pairs */
metadata?: any;
/** Key/value pairs that are provided to the substitution engine */
substitution_data?: any;
/** SparkPost Enterprise API only: email to use for envelope FROM */
return_path?: string | undefined;
/** Content that will be used to construct a message */
content: InlineContent | { template_id: string, use_draft_template?: boolean | undefined } | { email_rfc822: string };
}
interface TransmissionSummary {
/** ID of the transmission */
id: string;
/** State of the transmission */
state: "submitted" | "Generating" | "Success" | "Canceled";
/** Description of the transmission */
description: string;
/** Name of the campaign */
campaign_id: string;
/** Content that will be used to construct a message */
content: { template_id: string };
}
interface Transmission {
/** ID of the transmission */
id: string;
/** State of the transmission */
state: "submitted" | "Generating" | "Success" | "Canceled";
/** JSON object in which transmission options are defined */
options: TransmissionOptions;
/** Name of the campaign */
campaign_id: string;
/** Description of the transmission */
description: string;
/** Transmission level metadata containing key/value pairs */
metadata: any;
/** Key/value pairs that are provided to the substitution engine */
substitution_data: any;
/** Content that will be used to construct a message */
content: InlineContent | { template_id: string, use_draft_template?: boolean | undefined } | { email_rfc822: string };
/** Computed total number of messages generated */
num_generated: number;
/** Computed total number of failed messages */
num_failed_generation: number;
/** Number of recipients that failed input validation */
num_invalid_recipients: number;
rcpt_list_chunk_size: number;
rcpt_list_total_chunks: number;
}
interface TransmissionOptions {
/** Delay generation of messages until this datetime. */
start_time?: string | undefined;
/** Whether open tracking is enabled for this transmission */
open_tracking?: boolean | undefined;
/** Whether click tracking is enabled for this transmission */
click_tracking?: boolean | undefined;
/** Whether message is transactional or non-transactional for unsubscribe and suppression purposes */
transactional?: boolean | undefined;
/** Whether or not to use the sandbox sending domain */
sandbox?: boolean | undefined;
/** SparkPost Enterprise API only: Whether or not to ignore customer suppression rules, for this transmission only. Only applicable if your configuration supports this parameter. */
skip_suppression?: boolean | undefined;
/** The ID of a dedicated IP pool associated with your account ( Note: SparkPost only ). */
ip_pool?: string | undefined;
/** Whether or not to perform CSS inlining in HTML content */
inline_css?: boolean | undefined;
}
interface InlineContent {
/** HTML content for the email’s text/html MIME part At a minimum, html, text, or push is required. */
html?: string | undefined;
/** Text content for the email’s text/plain MIME part At a minimum, html, text, or push is required. */
text?: string | undefined;
/** Content of push notifications At a minimum, html, text, or push is required. SparkPost Enterprise API only. */
push?: PushData | undefined;
/** Email subject line required for email transmissions Expected in the UTF-8 charset without RFC2047 encoding. Substitution syntax is supported. */
subject?: string | undefined;
/** "deals@company.com" or JSON object composed of the “name” and “email” fields “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header */
from?: string | { email: string, name: string } | undefined;
/** Email address used to compose the email’s “Reply-To” header */
reply_to?: string | undefined;
/** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To” */
headers?: any;
/** JSON array of attachments. */
attachments?: Attachment[] | undefined;
/** JSON array of inline images. */
inline_images?: Attachment[] | undefined;
}
interface PushData {
/** payload for APNs messages */
apns?: any;
/** payload for GCM messages */
gcm?: any;
}
interface Attachment {
/**
* The MIME type of the attachment; e.g., “text/plain”, “image/jpeg”, “audio/mp3”, “video/mp4”, “application/msword”, “application/pdf”, etc.,
* including the “charset” parameter (text/html; charset=“UTF-8”) if needed.
* The value will apply “as-is” to the “Content-Type” header of the generated MIME part for the attachment.
*
*/
type: string;
/** The filename of the attachment (for example, “document.pdf”). This is inserted into the filename parameter of the Content-Disposition header. */
name: string;
/**
* The content of the attachment as a Base64 encoded string.
* The string should not contain \r\n line breaks.
* The SparkPost systems will add line breaks as necessary to ensure the Base64 encoded lines contain no more than 76 characters each.
*
*/
data: string;
}
interface Webhook {
/** User-friendly name for webhook */
name: string;
/** URL of the target to which to POST event batches */
target: string;
/** Array of event types this webhook will receive */
events: string[];
/**
* Reserved for future use
*
* @default {true}
*/
active?: boolean | undefined;
/** Type of authentication to be used during POST requests to target */
auth_type?: string | undefined;
/** Object containing details needed to request authorization credentials, as necessary */
auth_request_details?: any;
/** Object containing credentials needed to make authorized POST requests to target */
auth_credentials?: any;
/** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */
auth_token?: string | undefined;
}
interface UpdateWebhook {
/** User-friendly name for webhook */
name?: string | undefined;
/** URL of the target to which to POST event batches */
target?: string | undefined;
/** Array of event types this webhook will receive */
events?: string[] | undefined;
active?: boolean | undefined;
/** Type of authentication to be used during POST requests to target */
auth_type?: string | undefined;
/** Object containing details needed to request authorization credentials, as necessary */
auth_request_details?: any;
/** Object containing credentials needed to make authorized POST requests to target */
auth_credentials?: any;
/** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */
auth_token?: string | undefined;
}
interface WebhookLinks {
links: Array<{
href: string;
rel: string;
method: string[];
}>;
}
interface CreateOpts {
/**
* Domain (or subdomain) name for which SparkPost will receive inbound emails
*
*/
domain: string;
}
}
export = SparkPost; | the_stack |
import { Disposable, dom, DomElementArg, Holder, makeTestId, styled, svg } from "grainjs";
import { createPopper, Placement } from '@popperjs/core';
import { FocusLayer } from 'app/client/lib/FocusLayer';
import * as Mousetrap from 'app/client/lib/Mousetrap';
import { bigBasicButton, bigPrimaryButton } from "app/client/ui2018/buttons";
import { colors, vars } from "app/client/ui2018/cssVars";
import range = require("lodash/range");
import {IGristUrlState} from "app/common/gristUrls";
import {urlState} from "app/client/models/gristUrlState";
import {delay} from "app/common/delay";
import {reportError} from "app/client/models/errors";
import {cssBigIcon, cssCloseButton} from "./ExampleCard";
const testId = makeTestId('test-onboarding-');
// Describes an onboarding popup. Each popup is uniquely identified by its id.
export interface IOnBoardingMsg {
// A CSS selector pointing to the reference element
selector: string,
// Title
title: DomElementArg,
// Body
body?: DomElementArg,
// If true show the message as a modal centered on the screen.
showHasModal?: boolean,
// The popper placement.
placement?: Placement,
// Adjusts the popup offset so that it is positioned relative to the content of the reference
// element. This is useful when the reference element has padding and no border (ie: such as
// icons). In which case, and when set to true, it will fill the gap between popups and the UI
// part it's pointing at. If `cropPadding` is falsy otherwise, the popup might look a bit distant.
cropPadding?: boolean,
// The popper offset.
offset?: [number, number],
// Skip the message
skip?: boolean;
// If present, will be passed to urlState().pushUrl() to navigate to the location defined by that state
urlState?: IGristUrlState;
}
// There should only be one tour at a time. Use a holder to dispose the previous tour when
// starting a new one.
const tourSingleton = Holder.create<OnBoardingPopupsCtl>(null);
export function startOnBoarding(messages: IOnBoardingMsg[], onFinishCB: () => void) {
const ctl = OnBoardingPopupsCtl.create(tourSingleton, messages, onFinishCB);
ctl.start().catch(reportError);
}
class OnBoardingError extends Error {
public name = 'OnBoardingError';
constructor(message: string) {
super(message);
}
}
/**
* Current index in the list of messages.
* This allows closing the tour and reopening where you left off.
* Since it's a single global value, mixing unrelated tours
* (e.g. the generic welcome tour and a specific document tour)
* in a single page load won't work well.
*/
let ctlIndex = 0;
class OnBoardingPopupsCtl extends Disposable {
private _openPopupCtl: {close: () => void}|undefined;
private _overlay: HTMLElement;
private _arrowEl = buildArrow();
constructor(private _messages: IOnBoardingMsg[], private _onFinishCB: () => void) {
super();
if (this._messages.length === 0) {
throw new OnBoardingError('messages should not be an empty list');
}
// In case we're reopening after deleting some rows of GristDocTour,
// ensure ctlIndex is still within bounds
ctlIndex = Math.min(ctlIndex, this._messages.length - 1);
this.onDispose(() => {
this._openPopupCtl?.close();
});
}
public async start() {
this._showOverlay();
await this._move(0);
Mousetrap.setPaused(true);
this.onDispose(() => {
Mousetrap.setPaused(false);
});
}
private _finish() {
this._onFinishCB();
this.dispose();
}
private async _move(movement: number, maybeClose = false) {
const newIndex = ctlIndex + movement;
const entry = this._messages[newIndex];
if (!entry) {
if (maybeClose) {
// User finished the tour, close and restart from the beginning if they reopen
ctlIndex = 0;
this._finish();
}
return; // gone out of bounds, probably by keyboard shortcut
}
ctlIndex = newIndex;
if (entry.skip) {
// movement = 0 when starting a tour, make sure we don't get stuck in a loop
await this._move(movement || +1);
return;
}
// close opened popup if any
this._openPopupCtl?.close();
if (entry.urlState) {
await urlState().pushUrl(entry.urlState);
await delay(100); // make sure cursor is in correct place
}
if (entry.showHasModal) {
this._showHasModal();
} else {
await this._showHasPopup(movement);
}
}
private async _showHasPopup(movement: number) {
const content = this._buildPopupContent();
const entry = this._messages[ctlIndex];
const elem = document.querySelector<HTMLElement>(entry.selector);
const {placement} = entry;
// The element the popup refers to is not present. To the user we show nothing and simply skip
// it to the next.
if (!elem) {
console.warn(`On boarding tour: element ${entry.selector} not found!`);
// movement = 0 when starting a tour, make sure we don't get stuck in a loop
return this._move(movement || +1);
}
// Cleanup
function close() {
popper.destroy();
dom.domDispose(content);
content.remove();
}
this._openPopupCtl = {close};
document.body.appendChild(content);
this._addFocusLayer(content);
// Create a popper for positioning the popup content relative to the reference element
const adjacentPadding = entry.cropPadding ? this._getAdjacentPadding(elem, placement) : 0;
const popper = createPopper(elem, content, {
placement,
modifiers: [{
name: 'arrow',
options: {
element: this._arrowEl,
},
}, {
name: 'offset',
options: {
offset: [0, 12 - adjacentPadding],
}
}],
});
}
private _addFocusLayer(container: HTMLElement) {
dom.autoDisposeElem(container, new FocusLayer({
defaultFocusElem: container,
allowFocus: (elem) => (elem !== document.body)
}));
}
// Get the padding length for the side that will be next to the popup.
private _getAdjacentPadding(elem: HTMLElement, placement?: Placement) {
if (placement) {
let padding = '';
if (placement.includes('bottom')) {
padding = getComputedStyle(elem).paddingBottom;
}
else if (placement.includes('top')) {
padding = getComputedStyle(elem).paddingTop;
}
else if (placement.includes('left')) {
padding = getComputedStyle(elem).paddingLeft;
}
else if (placement.includes('right')) {
padding = getComputedStyle(elem).paddingRight;
}
// Note: getComputedStyle return value in pixel, hence no need to handle other unit. See here
// for reference:
// https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle#notes.
if (padding && padding.endsWith('px')) {
return Number(padding.slice(0, padding.length - 2));
}
}
return 0;
}
private _showHasModal() {
const content = this._buildPopupContent();
dom.update(this._overlay, content);
this._addFocusLayer(content);
function close() {
content.remove();
dom.domDispose(content);
}
this._openPopupCtl = {close};
}
private _buildPopupContent() {
return Container(
{tabindex: '-1'},
this._arrowEl,
ContentWrapper(
cssCloseButton(cssBigIcon('CrossBig'),
dom.on('click', () => this._finish()),
testId('close'),
),
cssTitle(this._messages[ctlIndex].title),
cssBody(this._messages[ctlIndex].body),
this._buildFooter(),
testId('popup'),
),
dom.onKeyDown({
Escape: () => this._finish(),
ArrowLeft: () => this._move(-1),
ArrowRight: () => this._move(+1),
Enter: () => this._move(+1, true),
}),
);
}
private _buildFooter() {
const nSteps = this._messages.length;
const isLastStep = ctlIndex === nSteps - 1;
const isFirstStep = ctlIndex === 0;
return Footer(
ProgressBar(
range(nSteps).map((i) => Dot(Dot.cls('-done', i > ctlIndex))),
),
Buttons(
bigBasicButton(
'Previous', testId('previous'),
dom.on('click', () => this._move(-1)),
dom.prop('disabled', isFirstStep),
{style: `margin-right: 8px; visibility: ${isFirstStep ? 'hidden' : 'visible'}`},
),
bigPrimaryButton(
isLastStep ? 'Finish' : 'Next', testId('next'),
dom.on('click', () => this._move(+1, true)),
),
)
);
}
private _showOverlay() {
document.body.appendChild(this._overlay = Overlay());
this.onDispose(() => {
document.body.removeChild(this._overlay);
dom.domDispose(this._overlay);
});
}
}
function buildArrow() {
return ArrowContainer(
svg('svg', { style: 'width: 13px; height: 34px;' },
svg('path', {'d': 'M 2 19 h 13 v 18 Z'}))
);
}
const Container = styled('div', `
align-self: center;
border: 2px solid ${colors.lightGreen};
border-radius: 3px;
z-index: 1000;
max-width: 490px;
position: relative;
background-color: white;
box-shadow: 0 2px 18px 0 rgba(31,37,50,0.31), 0 0 1px 0 rgba(76,86,103,0.24);
outline: unset;
`);
function sideSelectorChunk(side: 'top'|'bottom'|'left'|'right') {
return `.${Container.className}[data-popper-placement^=${side}]`;
}
const ArrowContainer = styled('div', `
position: absolute;
& path {
stroke: ${colors.lightGreen};
stroke-width: 2px;
fill: white;
}
${sideSelectorChunk('top')} > & {
bottom: -26px;
}
${sideSelectorChunk('bottom')} > & {
top: -23px;
}
${sideSelectorChunk('right')} > & {
left: -12px;
}
${sideSelectorChunk('left')} > & {
right: -12px;
}
${sideSelectorChunk('top')} svg {
transform: rotate(-90deg);
}
${sideSelectorChunk('bottom')} svg {
transform: rotate(90deg);
}
${sideSelectorChunk('left')} svg {
transform: scalex(-1);
}
`);
const ContentWrapper = styled('div', `
position: relative;
padding: 32px;
background-color: white;
`);
const Footer = styled('div', `
display: flex;
flex-direction: row;
margin-top: 32px;
justify-content: space-between;
`);
const ProgressBar = styled('div', `
display: flex;
flex-direction: row;
`);
const Buttons = styled('div', `
display: flex;
flex-directions: row;
`);
const Dot = styled('div', `
width: 6px;
height: 6px;
border-radius: 3px;
margin-right: 12px;
align-self: center;
background-color: ${colors.lightGreen};
&-done {
background-color: ${colors.darkGrey};
}
`);
const Overlay = styled('div', `
position: fixed;
display: flex;
flex-direction: column;
justify-content: center;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 999;
overflow-y: auto;
`);
const cssTitle = styled('div', `
font-size: ${vars.xxxlargeFontSize};
font-weight: ${vars.headerControlTextWeight};
color: ${colors.dark};
margin: 0 0 16px 0;
line-height: 32px;
`);
const cssBody = styled('div', `
`); | the_stack |
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Period, ImmutablePeriod } from '../period';
import { Team, ImmutableTeam } from '../team';
import { StorageService } from '../storage.service';
import { MatDialog } from '@angular/material/dialog';
import {
EditPeriodDialogComponent,
EditPeriodDialogData,
} from '../edit-period-dialog/edit-period-dialog.component';
import {
EditTeamDialogComponent,
EditTeamDialogData,
} from '../edit-team-dialog/edit-team-dialog.component';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import {
AddPeriodDialogData,
AddPeriodDialogComponent,
CreateMethod,
} from '../add-period-dialog/add-period-dialog.component';
import { Bucket, ImmutableBucket } from '../bucket';
import { Person } from '../person';
import { Assignment } from '../assignment';
import { Objective } from '../objective';
import { AuthService } from '../services/auth.service';
import { environment } from 'src/environments/environment';
import { NotificationService } from '../services/notification.service';
const DEFAULT_MAX_COMMITTED_PERCENTAGE = 50;
@Component({
selector: 'app-teamperiods',
templateUrl: './teamperiods.component.html',
styleUrls: ['./teamperiods.component.css'],
})
export class TeamPeriodsComponent implements OnInit {
team?: ImmutableTeam;
periods?: readonly ImmutablePeriod[];
userHasEditPermissions = true;
constructor(
private storage: StorageService,
private route: ActivatedRoute,
private dialog: MatDialog,
private notificationService: NotificationService,
public authService: AuthService
) {}
ngOnInit(): void {
this.route.paramMap.subscribe((m) => {
const teamId = m.get('team');
if (teamId) {
this.loadDataFor(teamId);
}
});
}
loadDataFor(teamId: string): void {
this.team = undefined;
this.periods = undefined;
this.storage
.getTeam(teamId)
.pipe(
catchError((error) => {
this.notificationService.error$.next(
'Could not load team "' + teamId + '": ' + JSON.stringify(error)
);
console.log(error);
return of(new Team('', ''));
})
)
.subscribe((team?: Team) => {
if (team) {
this.team = new ImmutableTeam(team);
// TODO(#83) Replace this logic with something determined by the server, like CanAddTeam
if (environment.requireAuth && team.teamPermissions !== undefined) {
const user = this.authService.user$.getValue();
const userEmail = user?.email;
const userDomain = user?.domain;
const principalTypeEmail = 'email';
const principalTypeDomain = 'domain';
this.userHasEditPermissions = false;
team.teamPermissions.write.allow.forEach((permission) => {
if (
(permission.type === principalTypeDomain &&
permission.id.toLowerCase() === userDomain?.toLowerCase()) ||
(permission.type === principalTypeEmail &&
permission.id.toLowerCase() === userEmail?.toLowerCase())
) {
this.userHasEditPermissions = true;
}
});
}
} else {
this.team = undefined;
}
});
this.storage
.getPeriods(teamId)
.pipe(
catchError((error) => {
this.notificationService.error$.next(
'Could not load periods for team "' +
teamId +
'": ' +
JSON.stringify(error)
);
console.log(error);
return of([]);
})
)
.subscribe((periods?: Period[]) => {
if (periods) {
this.periods = periods.map((p) => ImmutablePeriod.fromPeriod(p));
} else {
this.periods = undefined;
}
});
}
isLoaded(): boolean {
return this.team !== undefined && this.periods !== undefined;
}
sortedPeriods(): ImmutablePeriod[] {
const result = this.periods!.slice();
result.sort((a, b) =>
a.displayName < b.displayName ? 1 : a.displayName > b.displayName ? -1 : 0
);
return result;
}
addPeriod(): void {
if (this.periods!.length === 0) {
this.addBlankPeriod();
return;
}
const existingPeriods = this.sortedPeriods();
const dialogData: AddPeriodDialogData = {
period: {
id: '',
displayName: '',
unit: 'person weeks',
secondaryUnits: [],
notesURL: '',
maxCommittedPercentage: DEFAULT_MAX_COMMITTED_PERCENTAGE,
people: [],
buckets: [],
lastUpdateUUID: '',
},
createMethod: CreateMethod.Blank,
existingPeriods,
copyFromPeriodID: existingPeriods[0].id,
copyUnit: true,
copyPeople: true,
copyBuckets: true,
copyObjectives: false,
copyAssignments: false,
};
const dialogRef = this.dialog.open(AddPeriodDialogComponent, {
data: dialogData,
});
dialogRef.afterClosed().subscribe((data) => {
if (!data) {
return;
}
let newPeriod: Period;
if (data.createMethod === CreateMethod.Blank) {
newPeriod = data.period;
} else if (data.createMethod === CreateMethod.Copy) {
const copiedPeriod = this.periods!.find(
(p) => p.id === data.copyFromPeriodID
);
if (!copiedPeriod) {
console.error(
'Cannot find period with ID "' + data.copyFromPeriodID + '"'
);
return;
}
newPeriod = {
id: data.period.id,
displayName: data.period.displayName,
unit: data.copyUnit ? copiedPeriod.unit : data.period.unit,
secondaryUnits: data.copyUnit
? copiedPeriod.secondaryUnits.map((su) => su.toOriginal())
: data.period.secondaryUnits,
notesURL: data.period.notesURL,
maxCommittedPercentage: data.copyUnit
? copiedPeriod.maxCommittedPercentage
: data.period.maxCommittedPercentage,
buckets: data.copyBuckets
? this.copyBuckets(
copiedPeriod.buckets,
data.copyObjectives,
data.copyAssignments
)
: [],
people: data.copyPeople
? copiedPeriod.people.map((p) => p.toOriginal())
: [],
lastUpdateUUID: '',
};
} else {
console.error('Unexpected createMethod "' + data.createMethod + '"');
return;
}
this.storeNewPeriod(newPeriod);
});
}
copyPeople(orig: Person[]): Person[] {
const result = [];
for (const p of orig) {
result.push(new Person(p.id, p.displayName, p.location, p.availability));
}
return result;
}
copyBuckets(
orig: readonly ImmutableBucket[],
copyObjectives: boolean,
copyAssignments: boolean
): Bucket[] {
const result = [];
for (const b of orig) {
const objectives: Objective[] = [];
if (copyObjectives) {
for (const o of b.objectives) {
const assignments = [];
if (copyAssignments) {
for (const a of o.assignments) {
assignments.push(new Assignment(a.personId, a.commitment));
}
}
objectives.push({
name: o.name,
resourceEstimate: o.resourceEstimate,
commitmentType: o.commitmentType,
notes: o.notes,
groups: o.groups.map((g) => g.toOriginal()),
tags: o.tags.map((t) => t.toOriginal()),
assignments,
});
}
}
result.push(
new Bucket(b.displayName, b.allocationPercentage, objectives)
);
}
return result;
}
addBlankPeriod(): void {
const dialogData: EditPeriodDialogData = {
period: {
id: '',
displayName: '',
unit: 'person weeks',
notesURL: '',
maxCommittedPercentage: DEFAULT_MAX_COMMITTED_PERCENTAGE,
people: [],
buckets: [],
secondaryUnits: [],
lastUpdateUUID: '',
},
title: 'New Period',
okAction: 'Add',
allowEditID: true,
};
const dialogRef = this.dialog.open(EditPeriodDialogComponent, {
data: dialogData,
});
dialogRef.afterClosed().subscribe((ok) => {
if (ok) {
this.storeNewPeriod(dialogData.period);
}
});
}
storeNewPeriod(period: Period): void {
this.storage
.addPeriod(this.team!.id, period)
.pipe(
catchError((error) => {
this.notificationService.error$.next(
'Could not save new period: ' + JSON.stringify(error)
);
console.log(error);
return of(undefined);
})
)
.subscribe((updateResponse) => {
if (updateResponse) {
period.lastUpdateUUID = updateResponse.lastUpdateUUID;
this.periods = this.periods!.concat([
ImmutablePeriod.fromPeriod(period),
]);
}
});
}
editTeam(): void {
const dialogData: EditTeamDialogData = {
team: this.team!.toOriginal(),
title: 'Edit Team "' + this.team!.id + '"',
okAction: 'OK',
allowCancel: false,
allowEditID: false,
};
const dialogRef = this.dialog.open(EditTeamDialogComponent, {
data: dialogData,
});
dialogRef.afterClosed().subscribe((team) => {
this.storage
.updateTeam(team)
.pipe(
catchError((error) => {
this.notificationService.error$.next(
'Could not save team: ' + JSON.stringify(error)
);
console.log(error);
return of('error');
})
)
.subscribe((res) => {
if (res !== 'error') {
this.notificationService.notification$.next('Saved');
this.team = new ImmutableTeam(team);
}
});
});
}
} | the_stack |
"use strict";
import { CFG, SESSION_DATA_DIR } from "./config";
import * as fs from "fs";
import { getConnectedDisplaysId, startProgram } from "./otherCmd";
import {
closeWindow,
getX,
initX11,
moveToWorkspace,
restoreWindowPosition
} from "./x11Wrapper";
import {
findDesktopFile,
getActiveWindowListFlow,
goToFirstWorkspace
} from "./metaWrapper";
import { log } from "./log";
import { WinObj } from "./model";
import { exec } from "child_process";
// import * as Store from 'jfs';
const Store = require("jfs");
// create data store
const db = new Store(SESSION_DATA_DIR, {
pretty: CFG.SAVE_SESSION_IN_PRETTY_FORMAT
});
// setup meta wrapper
// EXPORT
// ------
export default {
listSessions,
renameSession,
saveSession,
removeSession,
restoreSession,
getSessions,
getX: getX,
getConnectedDisplaysId,
resetCfg: () => {
const configFilePath = CFG.DATA_DIR + "/config.json";
if (fs.existsSync(configFilePath)) {
fs.unlinkSync(configFilePath);
} else {
console.error("No Config present in " + configFilePath);
}
},
getCfg: () => {
return CFG;
},
getDb: () => {
return db;
}
};
// HELPER
// --------
function _catchGenericErr(err) {
console.error("Generic Error in Main Handler", err, err.stack);
// throw err;
}
function getSessions() {
return db.allSync();
}
// MAIN FUNCTIONS
// --------------
function listSessions() {
let list = Object.keys(getSessions());
list.forEach(name => {
log(name);
});
}
function renameSession(oldName: string, newName: string) {
let obj = db.getSync(oldName);
if (obj.message) {
if (obj.message === "could not load data") {
log(`Error: Could not find a session named '${oldName}'`);
} else {
log(obj.message);
}
return;
}
db.saveSync(newName, obj);
db.delete(oldName);
}
function saveSession(sessionName: string, inputHandlers): Promise<any> {
const sessionToHandle = sessionName || "DEFAULT";
return initX11()
.then(() => {
return getActiveWindowListFlow();
})
.then(windowList => {
// desktop file paths and connected display ids
return _guessAndSetDesktopFilePaths(
windowList,
inputHandlers.desktopFilePath
);
})
.then(windowList => {
const connectedDisplaysId = getConnectedDisplaysId();
console.log("DisplayID: " + connectedDisplaysId);
return saveSessionForDisplayToDb(
sessionToHandle,
connectedDisplaysId,
windowList
);
})
.catch(err => {
console.error("saveSession(): An error occurred", err);
throw err;
});
}
function saveSessionForDisplayToDb(
sessionToHandle: string,
connectedDisplaysId: string,
windowList: WinObj[]
): Promise<void> {
return new Promise((fulfill, reject) => {
// check if entry exists and update
db.get(sessionToHandle, (err, sessionData) => {
if (err) {
// NOTE: we're not failing because, the case is probably that there is no session file yet
log(
`saveSessionForDisplayToDb: no session file present yet for "${sessionToHandle}", creating a new one...`
);
}
if (!sessionData) {
// create new object
sessionData = {
name: sessionToHandle
};
}
if (
!sessionData.displaysCombinations ||
!Array.isArray(sessionData.displaysCombinations)
) {
// create new array
sessionData.displaysCombinations = [];
}
const existingDisplayEntry = sessionData.displaysCombinations.find(
entry => entry.id === connectedDisplaysId
);
if (existingDisplayEntry) {
existingDisplayEntry.windowList = windowList;
} else {
sessionData.displaysCombinations.push({
id: connectedDisplaysId,
windowList
});
}
db.save(sessionToHandle, sessionData, err => {
if (err) {
reject(err);
} else {
log("SAVED SESSION: " + sessionToHandle);
fulfill();
}
});
});
});
}
function restoreSession(
sessionName: string,
isCloseAllOpenWindows: boolean
): Promise<any> {
const sessionToHandle = sessionName || "DEFAULT";
return new Promise((fulfill, reject) => {
db.get(sessionToHandle || "DEFAULT", (err, sessionData) => {
if (err) {
reject(err);
return;
}
let savedWindowList;
initX11()
.then(() => {
return _closeAllWindowsIfSet(isCloseAllOpenWindows);
})
.then(goToFirstWorkspace)
.then(getConnectedDisplaysId)
.then(connectedDisplaysId => {
console.log("DisplayID: " + connectedDisplaysId);
if (!sessionData.displaysCombinations) {
console.error(`no display combinations saved yet`);
return;
}
const displayEntry = sessionData.displaysCombinations.find(
entry => entry.id === connectedDisplaysId
);
if (displayEntry) {
savedWindowList = displayEntry.windowList;
} else {
console.error(
`no data for current display id '${connectedDisplaysId}' saved yet`
);
return;
}
return getActiveWindowListFlow();
})
.then(currentWindowList => {
return _startSessionPrograms(savedWindowList, currentWindowList);
})
.then(() => {
// gets current window list by itself and returns the updated variant
return _waitForAllAppsToStart(savedWindowList);
})
.then(
(updatedCurrentWindowList: WinObj[]) =>
new Promise(resolve =>
setTimeout(() => {
resolve(updatedCurrentWindowList);
}, 250)
)
)
.then((updatedCurrentWindowList: WinObj[]) => {
_updateWindowIds(savedWindowList, updatedCurrentWindowList);
return _restoreWindowPositions(savedWindowList);
})
.then(() => {
log("RESTORED SESSION: " + sessionToHandle);
})
.catch(err => {
console.error("An error occurred", err);
reject(err);
})
.then(fulfill);
});
}).catch(_catchGenericErr);
}
function removeSession(sessionName: string): Promise<unknown> {
return new Promise((fulfill, reject) => {
fs.unlink(CFG.SESSION_DATA_DIR + "/" + sessionName + ".json", error => {
if (error) {
console.error(error);
reject(error);
} else {
fulfill();
}
});
}).catch(_catchGenericErr);
}
function _closeAllWindowsIfSet(isCloseAll: boolean): Promise<unknown> {
return new Promise((fulfill, reject) => {
if (isCloseAll) {
log("Closing opened applications");
getActiveWindowListFlow()
.then((currentWindowList: any[]) => {
currentWindowList.forEach(win => {
closeWindow(win.windowId);
});
_waitForAllAppsToClose()
.then(fulfill)
.catch(reject);
})
.catch(reject);
} else {
fulfill();
}
}).catch(_catchGenericErr);
}
function _waitForAllAppsToClose(): Promise<unknown> {
let totalTimeWaited = 0;
return new Promise((fulfill, reject) => {
function pollAllAppsClosed() {
setTimeout(() => {
getActiveWindowListFlow()
.then((currentWindowList: WinObj[]) => {
totalTimeWaited += CFG.POLL_ALL_APPS_STARTED_INTERVAL;
if (currentWindowList.length !== 0) {
if (totalTimeWaited > CFG.POLL_ALL_MAX_TIMEOUT) {
console.error("POLL_ALL_MAX_TIMEOUT reached");
reject("POLL_ALL_MAX_TIMEOUT reached");
} else {
// call recursively
pollAllAppsClosed();
}
} else {
fulfill(currentWindowList);
}
})
.catch(reject);
}, CFG.POLL_ALL_APPS_STARTED_INTERVAL);
}
// start once initially
pollAllAppsClosed();
}).catch(_catchGenericErr);
}
function _waitForAllAppsToStart(savedWindowList): Promise<WinObj[] | unknown> {
log("Waiting for all applications to start...");
let totalTimeWaited = 0;
let timeout;
return new Promise((fulfill, reject) => {
function pollAllAppsStarted(
savedWindowList: WinObj[],
timeoutDuration = CFG.POLL_ALL_APPS_STARTED_INTERVAL
) {
timeout = setTimeout(() => {
// clear timeout to be save
if (timeout) {
clearTimeout(timeout);
}
getActiveWindowListFlow()
.then(currentWindowList => {
totalTimeWaited += CFG.POLL_ALL_APPS_STARTED_INTERVAL;
if (!_isAllAppsStarted(savedWindowList, currentWindowList)) {
if (totalTimeWaited > CFG.POLL_ALL_MAX_TIMEOUT) {
console.error("POLL_ALL_MAX_TIMEOUT reached");
console.error(
"Unable to start the following apps",
_getNotStartedApps(savedWindowList, currentWindowList)
);
reject("POLL_ALL_MAX_TIMEOUT reached");
} else {
// call recursively
pollAllAppsStarted(savedWindowList);
}
} else {
log("All applications started");
fulfill(currentWindowList);
}
})
.catch(reject);
}, timeoutDuration);
}
// start once initially
pollAllAppsStarted(savedWindowList, 500);
}).catch(_catchGenericErr);
}
function _getNotStartedApps(
savedWindowList: WinObj[],
currentWindowList: WinObj[]
): WinObj[] {
let nonStartedApps = [];
savedWindowList.forEach(win => {
if (!_getMatchingWindowId(win, currentWindowList)) {
nonStartedApps.push(win);
}
});
return nonStartedApps;
}
function _isAllAppsStarted(
savedWindowList: WinObj[],
currentWindowList: WinObj[]
): boolean {
let isAllStarted = true;
const currentWindowListCopy = currentWindowList.slice(0).filter(
// some apps have a splash screen (intellij idea), we want to wait for those
winFromCurrent =>
!winFromCurrent.states?.includes("_NET_WM_STATE_SKIP_TASKBAR")
);
savedWindowList.forEach(win => {
if (!_getMatchingWindowId(win, currentWindowListCopy)) {
isAllStarted = false;
} else {
const index = currentWindowListCopy.findIndex(
winFromCurrent => win.wmClassName === winFromCurrent.wmClassName
);
currentWindowListCopy.splice(index, 1);
}
});
return isAllStarted;
}
async function _guessAndSetDesktopFilePaths(
windowList: WinObj[],
inputHandler
): Promise<WinObj[]> {
const promises = windowList.map(win => _guessFilePath(win, inputHandler));
for (const promise of promises) {
try {
await promise;
} catch (e) {
_catchGenericErr(e);
}
}
return windowList;
}
function _guessFilePath(win: WinObj, inputHandler): Promise<string | unknown> {
return new Promise((fulfill, reject) => {
function callInputHandler(error?, stdout?) {
if (error) {
console.log(
`\n Trying alternative guessing approach for "${win.simpleName}".....`
);
exec(`cat /proc/${win.wmPid}/cmdline`, (error1, stdout1) => {
if (error1 || !stdout1.length) {
console.error("ERR _guessFilePath()", error1);
reject(error1);
} else {
const ent = stdout1.split("\u0000");
console.log(
`\n Alternative guessing approach for "${win.simpleName}" SUCCESS -> ${ent[0]}`
);
win.executableFile = ent[0];
fulfill(win.executableFile);
}
});
} else {
inputHandler(error, win, stdout)
.then(input => {
if (_isDesktopFile(win.executableFile)) {
win.desktopFilePath = input;
fulfill(win.desktopFilePath);
} else {
win.executableFile = input;
fulfill(win.executableFile);
}
})
.catch(reject);
}
}
if (_isDesktopFile(win.executableFile)) {
findDesktopFile(win.executableFile)
.then(stdout => {
callInputHandler(null, stdout);
})
.catch(callInputHandler);
} else {
callInputHandler(true, win.executableFile);
}
}).catch(_catchGenericErr);
}
// TODO check for how many instances there should be running of a program
async function _startSessionPrograms(
windowList: WinObj[],
currentWindowList: WinObj[]
): Promise<void> {
// set instances started to 0
windowList.forEach(win => (win.instancesStarted = 0));
const promises = windowList
.filter(win => {
const numberOfInstancesOfWin = _getNumberOfInstancesToRun(
win,
windowList
);
return !_isProgramAlreadyRunning(
win.wmClassName,
currentWindowList,
numberOfInstancesOfWin,
win.instancesStarted
);
})
.map(win => {
win.instancesStarted += 1;
return startProgram(win.executableFile, win.desktopFilePath);
});
await Promise.all(promises);
}
function _getNumberOfInstancesToRun(
windowToMatch: WinObj,
windowList: WinObj[]
): number {
return windowList.filter(win => {
return win.wmClassName === windowToMatch.wmClassName;
}).length;
}
function _isProgramAlreadyRunning(
wmClassName: string,
currentWindowList: WinObj[],
numberOfInstancesToRun: number,
instancesStarted: number
): boolean {
if (!numberOfInstancesToRun) {
numberOfInstancesToRun = 1;
}
if (!instancesStarted) {
instancesStarted = 0;
}
let instancesRunning = 0;
currentWindowList.forEach(win => {
if (win.wmClassName === wmClassName) {
instancesRunning++;
}
});
log(
'Status: "' + wmClassName + '" is running:',
instancesRunning + instancesStarted >= numberOfInstancesToRun,
numberOfInstancesToRun,
instancesStarted
);
return instancesRunning + instancesStarted >= numberOfInstancesToRun;
}
function _isDesktopFile(executableFile: string): boolean {
return executableFile && !!executableFile.match(/desktop$/);
}
function _updateWindowIds(
savedWindowList: WinObj[],
currentWindowList: WinObj[]
) {
const wmClassNameMap = {};
savedWindowList.forEach(win => {
if (!wmClassNameMap[win.wmClassName]) {
wmClassNameMap[win.wmClassName] = _getMatchingWindows(
win,
currentWindowList
);
}
win.windowId = wmClassNameMap[win.wmClassName][0].windowId;
win.windowIdDec = parseInt(win.windowId, 16);
// remove first entry
wmClassNameMap[win.wmClassName].shift();
});
}
function _getMatchingWindowId(
win: WinObj,
currentWindowList: WinObj[]
): string {
const currentWindow = currentWindowList.find(
winFromCurrent => win.wmClassName === winFromCurrent.wmClassName
);
return currentWindow && currentWindow.windowId;
}
function _getMatchingWindows(
win: WinObj,
currentWindowList: WinObj[]
): WinObj[] {
return currentWindowList.filter(
winFromCurrent => win.wmClassName === winFromCurrent.wmClassName
);
}
async function _restoreWindowPositions(
savedWindowList: WinObj[]
): Promise<void> {
const promises = [];
let last_desktop_nr = 0;
// Sort the window objects based on which workspace they are locate,
// so the windows can be moved workspace by workspace
// This is needed because the window manager just creates an additional workspace when
// the previous one has some window on it.
savedWindowList = savedWindowList.concat().sort((a, b) => {
// NOTE: we need to fallback to zero because otherwise we get NAN for undefined and this
// messes up everything
return (a.wmCurrentDesktopNr || 0) - (b.wmCurrentDesktopNr || 0);
});
for (const win of savedWindowList) {
promises.push(restoreWindowPosition(win));
promises.push(moveToWorkspace(win.windowId, win.wmCurrentDesktopNr));
// The promises are not executed until the last item is reached or
// the desktop_nr is different from the previous entry and which case
// the app waits for those to finish before continuing the process
if (
win.wmCurrentDesktopNr !== last_desktop_nr ||
win === savedWindowList.slice(-1)[0]
) {
for (const promise of promises) {
try {
await promise;
} catch (e) {
_catchGenericErr(e);
}
}
last_desktop_nr = win.wmCurrentDesktopNr;
promises.length = 0;
}
}
} | the_stack |
import * as lodash from 'lodash';
import * as minimist from 'minimist';
import { CommandLineOptions, CommandMetadataOption, HydratedParseArgsOptions, ParsedArg } from '../definitions';
import { Colors, DEFAULT_COLORS } from './colors';
export const parseArgs = minimist;
export { ParsedArgs } from 'minimist';
/**
* Remove options, which are any arguments that starts with a hyphen (-), from
* a list of process args and return the result.
*
* If a double-hyphen separator (--) is encountered, it and the remaining
* arguments are included in the result, as they are not interpreted. This
* behavior can be disabled by setting the `includeSeparated` option to
* `false`.
*/
export function stripOptions(pargv: readonly string[], { includeSeparated = true }: { includeSeparated?: boolean; }): string[] {
const r = /^\-/;
const [ ownArgs, otherArgs ] = separateArgv(pargv);
const filteredArgs = ownArgs.filter(arg => !r.test(arg));
if (!includeSeparated) {
return filteredArgs;
}
if (otherArgs.length > 0) {
otherArgs.unshift('--');
}
return [...filteredArgs, ...otherArgs];
}
/**
* Split a list of process args into own-arguments and other-arguments, which
* are separated by the double-hyphen (--) separator.
*
* For example, `['cmd', 'arg1', '--', 'arg2']` will be split into
* `['cmd', 'arg1']` and `['arg2']`.
*/
export function separateArgv(pargv: readonly string[]): [string[], string[]] {
const ownArgs = [...pargv];
const otherArgs: string[] = [];
const sepIndex = pargv.indexOf('--');
if (sepIndex >= 0) {
otherArgs.push(...ownArgs.splice(sepIndex));
otherArgs.shift(); // strip separator
}
return [ ownArgs, otherArgs ];
}
/**
* Takes a Minimist command option and normalizes its values.
*/
export function hydrateCommandMetadataOption<O extends CommandMetadataOption>(option: O): O {
const type = option.type ? option.type : String;
return lodash.assign({}, option, {
type,
default: typeof option.default !== 'undefined' ? option.default : null,
aliases: Array.isArray(option.aliases) ? option.aliases : [],
});
}
export interface HydratedOptionSpec {
readonly value: string;
}
export function hydrateOptionSpec<O extends CommandMetadataOption>(opt: O): HydratedOptionSpec {
return { ...{ value: opt.type === Boolean ? 'true/false' : opt.name }, ...opt.spec || {} };
}
export interface FormatOptionNameOptions {
readonly showAliases?: boolean;
readonly showValueSpec?: boolean;
readonly colors?: Colors;
}
export function formatOptionName<O extends CommandMetadataOption>(opt: O, { showAliases = true, showValueSpec = true, colors = DEFAULT_COLORS }: FormatOptionNameOptions = {}): string {
const { input, weak } = colors;
const spec = hydrateOptionSpec(opt);
const showInverse = opt.type === Boolean && opt.default === true && opt.name.length > 1;
const valueSpec = opt.type === Boolean ? '' : `=<${spec.value}>`;
const aliasValueSpec = opt.type === Boolean ? '' : '=?';
return (
(showInverse ? input(`--no-${opt.name}`) : input(`-${opt.name.length > 1 ? '-' : ''}${opt.name}`)) +
(showValueSpec ? weak(valueSpec) : '') +
(showAliases ?
(!showInverse && opt.aliases && opt.aliases.length > 0 ? ', ' + opt.aliases
.map(alias => input(`-${alias}`) + (showValueSpec ? weak(aliasValueSpec) : ''))
.join(', ') : '') : '')
);
}
export function metadataOptionsToParseArgsOptions(commandOptions: readonly CommandMetadataOption[]): HydratedParseArgsOptions {
const options: HydratedParseArgsOptions = {
string: ['_'],
boolean: [],
alias: {},
default: {},
'--': true,
};
for (const o of commandOptions) {
const opt = hydrateCommandMetadataOption(o);
if (opt.type === String) {
options.string.push(opt.name);
} else if (opt.type === Boolean) {
options.boolean.push(opt.name);
}
if (typeof opt.default !== 'undefined') {
options.default[opt.name] = opt.default;
}
if (typeof opt.aliases !== 'undefined') {
options.alias[opt.name] = opt.aliases;
}
}
return options;
}
export type OptionPredicate<O extends CommandMetadataOption> = (option: O, value?: ParsedArg) => boolean;
export namespace OptionFilters {
export function includesGroups<O extends CommandMetadataOption>(groups: string | string[]): OptionPredicate<O> {
const g = Array.isArray(groups) ? groups : [groups];
return (option: O) => typeof option.groups !== 'undefined' && lodash.intersection(option.groups, g).length > 0;
}
export function excludesGroups<O extends CommandMetadataOption>(groups: string | string[]): OptionPredicate<O> {
const g = Array.isArray(groups) ? groups : [groups];
return (option: O) => typeof option.groups === 'undefined' || lodash.difference(option.groups, g).length > 0;
}
}
/**
* Given an array of command metadata options and an object of parsed options,
* match each supplied option with its command metadata option definition and
* pass it, along with its value, to a predicate function, which is used to
* return a subset of the parsed options.
*
* Options which are unknown to the command metadata are always excluded.
*
* @param predicate If excluded, `() => true` is used.
*/
export function filterCommandLineOptions<O extends CommandMetadataOption>(options: readonly O[], parsedArgs: CommandLineOptions, predicate: OptionPredicate<O> = () => true): CommandLineOptions {
const initial: CommandLineOptions = { _: parsedArgs._ };
if (parsedArgs['--']) {
initial['--'] = parsedArgs['--'];
}
const mapped = new Map([
...options.map((o): [string, O] => [o.name, o]),
...lodash.flatten(options.map(opt => opt.aliases ? opt.aliases.map((a): [string, O] => [a, opt]) : [])),
]);
const pairs = Object.keys(parsedArgs)
.map((k): [string, O | undefined, ParsedArg | undefined] => [k, mapped.get(k), parsedArgs[k]])
.filter(([ k, opt, value ]) => opt && predicate(opt, value))
.map(([ k, opt, value ]) => [opt ? opt.name : k, value]);
return { ...initial, ...lodash.fromPairs(pairs) };
}
/**
* Given an array of command metadata options and an object of parsed options,
* return a subset of the parsed options whose command metadata option
* definition contains the supplied group(s).
*
* Options which are unknown to the command metadata are always excluded.
*
* @param groups One or more option groups.
*/
export function filterCommandLineOptionsByGroup<O extends CommandMetadataOption>(options: readonly O[], parsedArgs: CommandLineOptions, groups: string | string[]): CommandLineOptions {
return filterCommandLineOptions(options, parsedArgs, OptionFilters.includesGroups(groups));
}
export interface UnparseArgsOptions {
useDoubleQuotes?: boolean;
useEquals?: boolean;
ignoreFalse?: boolean;
allowCamelCase?: boolean;
}
/**
* The opposite of `parseArgs()`. This function takes parsed args and converts
* them back into an argv array of arguments and options.
*
* Based on dargs, by sindresorhus
* @see https://github.com/sindresorhus/dargs/blob/master/license
*
* @param parsedArgs Inputs and options parsed by minimist.
* @param options.useDoubleQuotes For options with values, wrap the value in
* double quotes if it contains a space.
* @param options.useEquals Instead of separating an option and its value with
* a space, use an equals sign.
* @param options.ignoreFalse Optionally ignore flags that equate to false.
* @param options.allowCamelCase Optionally allow camel cased options instead
* of converting to kebab case.
* @param parseArgsOptions To provide more accuracy, specify the options that
* were used to parse the args in the first place.
*/
export function unparseArgs(parsedArgs: minimist.ParsedArgs, { useDoubleQuotes, useEquals = true, ignoreFalse = true, allowCamelCase }: UnparseArgsOptions = {}, parseArgsOptions?: minimist.Opts): string[] {
const args = [...parsedArgs['_'] || []];
const separatedArgs = parsedArgs['--'];
if (useDoubleQuotes) {
useEquals = true;
}
const dashKey = (k: string) => (k.length === 1 ? '-' : '--') + k;
const pushPairs = (...pairs: [string, string | undefined][]) => {
for (const [ k, val ] of pairs) {
const key = dashKey(allowCamelCase ? k : k.replace(/[A-Z]/g, '-$&').toLowerCase());
if (useEquals) {
args.push(key + (val ? `=${useDoubleQuotes && val.includes(' ') ? `"${val}"` : val}` : ''));
} else {
args.push(key);
if (val) {
args.push(val);
}
}
}
};
// Normalize the alias definitions from the options for `parseArgs`.
const aliasDef: { [key: string]: string[]; } = parseArgsOptions && parseArgsOptions.alias
? lodash.mapValues(parseArgsOptions.alias, v => Array.isArray(v) ? v : [v])
: {};
// Construct a mapping of alias to original key name.
const aliases = new Map<string, string>(lodash.flatten(Object.keys(aliasDef).map(k => aliasDef[k].map((a): [string, string] => [a, k]))));
const isKnown = (key: string) => {
if (!parseArgsOptions || !parseArgsOptions.unknown) {
return true;
}
if (
(typeof parseArgsOptions.string !== 'undefined' && (Array.isArray(parseArgsOptions.string) && parseArgsOptions.string.includes(key))) ||
(typeof parseArgsOptions.boolean !== 'undefined' && (Array.isArray(parseArgsOptions.boolean) && parseArgsOptions.boolean.includes(key))) ||
aliases.has(key)
) {
return true;
}
return parseArgsOptions.unknown(key);
};
// Convert the parsed args to an array of 2-tuples of shape [key, value].
// Then, filter out pairs which match any of the following criteria:
// - `_` (positional argument list)
// - `--` (separated args)
// - Aliases whose original key is defined
// - Options not known to the schema, according to
// `parseArgsOptions.unknown` option.
const pairedOptions = lodash.toPairs(parsedArgs).filter(([k]) =>
k !== '_' &&
k !== '--' &&
!(aliases.get(k) && typeof parsedArgs[k] !== 'undefined') &&
isKnown(k)
);
for (const [ key, val ] of pairedOptions) {
if (val === true) {
pushPairs([key, undefined]);
} else if (val === false && !ignoreFalse) {
pushPairs([`no-${key}`, undefined]);
} else if (typeof val === 'string') {
pushPairs([key, val]);
} else if (typeof val === 'number' && !Number.isNaN(val)) {
pushPairs([key, val.toString()]);
} else if (Array.isArray(val)) {
pushPairs(...val.map((v): [string, string] => [key, v]));
}
}
if (separatedArgs && separatedArgs.length > 0) {
args.push('--', ...separatedArgs);
}
return args;
} | the_stack |
import * as test_util from "../test_util";
import { MathTests } from "../test_util";
import * as util from "../util";
import { Array1D, Array2D, Array3D, Scalar } from "./ndarray";
// divide
{
const tests: MathTests = it => {
it("divide", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c = Array2D.new([2, 3], [1, 2, 3, 4, 2, 5]);
const r = math.divide(a, c);
test_util.expectArraysClose(r, [1, 1, 1, 1, 2.5, 6 / 5]);
});
it("divide propagates NaNs", math => {
const a = Array2D.new([2, 1], [1, 2]);
const c = Array2D.new([2, 1], [3, NaN]);
const r = math.divide(a, c);
test_util.expectArraysClose(r, [1 / 3, NaN]);
});
it("divide broadcasting same rank NDArrays different shape", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 1], [2, 3]);
const result = math.divide(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [1 / 2, 1, -1, -4 / 3];
test_util.expectArraysClose(result, expected);
});
it("divide broadcast 2D + 1D", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array1D.new([1, 2]);
const result = math.divide(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [1, 1, -3, -2];
test_util.expectArraysClose(result, expected);
});
it("div throws when passed ndarrays of different shapes", math => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
expect(() => math.divide(a, b)).toThrowError();
expect(() => math.divide(b, a)).toThrowError();
});
it("scalar divided by array", math => {
const c = Scalar.new(2);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const r = math.scalarDividedByArray(c, a);
test_util.expectArraysClose(
r, [2 / 1, 2 / 2, 2 / 3, 2 / 4, 2 / 5, 2 / 6]);
});
it("scalar divided by array propagates NaNs", math => {
const c = Scalar.new(NaN);
const a = Array2D.new([1, 3], [1, 2, 3]);
const r = math.scalarDividedByArray(c, a);
test_util.expectArraysEqual(r, [NaN, NaN, NaN]);
});
it("scalar divided by array throws when passed non scalar", math => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
expect(() => math.scalarDividedByArray(c, a)).toThrowError();
});
it("array divided by scalar", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c = Scalar.new(2);
const r = math.arrayDividedByScalar(a, c);
test_util.expectArraysClose(
r, [1 / 2, 2 / 2, 3 / 2, 4 / 2, 5 / 2, 6 / 2]);
});
it("array divided by scalar propagates NaNs", math => {
const a = Array2D.new([1, 3], [1, 2, NaN]);
const c = Scalar.new(2);
const r = math.arrayDividedByScalar(a, c);
test_util.expectArraysClose(r, [1 / 2, 2 / 2, NaN]);
});
it("array divided by scalar throws when passed non scalar", math => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
expect(() => math.arrayDividedByScalar(a, c)).toThrowError();
});
it("scalar times ndarray", math => {
const a = Array2D.new([3, 2], [2, -5, 1, 1, 4, 0]);
const c = Scalar.new(2);
const expected = [4, -10, 2, 2, 8, 0];
const result = math.scalarTimesArray(c, a);
expect(result.shape).toEqual([3, 2]);
test_util.expectArraysClose(result, expected);
});
it("scalar times ndarray throws when passed non-scalar", math => {
const a = Array2D.new([3, 2], [2, -5, 1, 1, 4, 0]);
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3, 4]);
expect(() => math.scalarTimesArray(c, a)).toThrowError();
});
};
test_util.describeMathCPU("divide", [tests]);
test_util.describeMathGPU("divide", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// multiply
{
const tests: MathTests = it => {
it("elementWiseMul same-shaped ndarrays", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
const expected = [5, 6, -12, 28];
const result = math.elementWiseMul(a, b);
expect(result.shape).toEqual([2, 2]);
test_util.expectArraysClose(result, expected);
});
it("elementWiseMul propagates NaNs", math => {
const a = Array2D.new([2, 2], [1, 3, 4, 0]);
const b = Array2D.new([2, 2], [NaN, 3, NaN, 3]);
const result = math.elementWiseMul(a, b);
test_util.expectArraysClose(result, [NaN, 9, NaN, 0]);
});
it("elementWiseMul throws when passed ndarrays of different shapes",
math => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
expect(() => math.elementWiseMul(a, b)).toThrowError();
expect(() => math.elementWiseMul(b, a)).toThrowError();
});
it("same-shaped ndarrays", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 2], [5, 3, 4, -7]);
const expected = [5, 6, -12, 28];
const result = math.multiply(a, b);
expect(result.shape).toEqual([2, 2]);
test_util.expectArraysClose(result, expected);
});
it("broadcasting ndarrays", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Scalar.new(2);
const expected = [2, 4, -6, -8];
const result = math.multiply(a, b);
expect(result.shape).toEqual([2, 2]);
test_util.expectArraysClose(result, expected);
});
it("broadcasting same rank NDArrays different shape", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 1], [2, 3]);
const result = math.multiply(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [2, 4, -9, -12];
test_util.expectArraysClose(result, expected);
});
it("broadcast 2D + 1D", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array1D.new([1, 2]);
const result = math.multiply(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [1, 4, -3, -8];
test_util.expectArraysClose(result, expected);
});
};
test_util.describeMathCPU("multiply", [tests]);
test_util.describeMathGPU("multiply", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// pow
{
const tests: MathTests = it => {
it("same-shaped ndarrays", math => {
const a = Array2D.new([2, 3], [1, -2, -3, 0, 7, 1]);
const b = Array2D.new([2, 3], [5, 3, 4, 5, 2, -3], "int32");
const expected = [1, -8, 81, 0, 49, 1];
const result = math.pow(a, b);
expect(result.shape).toEqual([2, 3]);
test_util.expectArraysClose(result, expected, 0.01);
});
it("int32^int32 returns int32", math => {
const a = Array1D.new([1, 2, 3], "int32");
const exp = Scalar.new(2, "int32");
const result = math.pow(a, exp);
expect(result.shape).toEqual([3]);
expect(result.dtype).toBe("int32");
test_util.expectArraysEqual(result, [1, 4, 9]);
});
it("different-shaped ndarrays", math => {
const a = Array2D.new([2, 3], [1, -2, -3, 0, 7, 1]);
const b = Scalar.new(2, "int32");
const expected = [1, 4, 9, 0, 49, 1];
const result = math.pow(a, b);
expect(result.shape).toEqual([2, 3]);
test_util.expectArraysClose(result, expected, 0.05);
});
it("propagates NaNs", math => {
const a = Array2D.new([2, 2], [NaN, 3, NaN, 0]);
const b = Array2D.new([2, 2], [1, 3, 2, 3], "int32");
const result = math.pow(a, b);
test_util.expectArraysClose(result, [NaN, 27, NaN, 0], 0.05);
});
it("throws when passed non int32 exponent param", math => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7], "float32");
// tslint:disable-next-line
expect(() => math.pow(a, b as any)).toThrowError();
});
it("broadcasting same rank NDArrays different shape", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 1], [2, 1], "int32");
const result = math.pow(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [1, 4, -3, -4];
test_util.expectArraysClose(result, expected);
});
it("broadcast 2D + 1D", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array1D.new([1, 2], "int32");
const result = math.pow(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [1, 4, -3, 16];
test_util.expectArraysClose(result, expected);
});
it("powStrict same-shaped ndarrays", math => {
const a = Array2D.new([2, 3], [1, -2, -3, 0, 7, 1]);
const b = Array2D.new([2, 3], [5, 3, 4, 5, 2, -3], "int32");
const expected = [1, -8, 81, 0, 49, 1];
const result = math.powStrict(a, b);
expect(result.shape).toEqual([2, 3]);
test_util.expectArraysClose(result, expected, 0.01);
});
it("powStrict throws when passed ndarrays of different shapes", math => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7], "int32");
expect(() => math.powStrict(a, b)).toThrowError();
});
it("powStrict throws when passed non int32 exponent param", math => {
const a = Array2D.new([2, 3], [1, 2, -3, -4, 5, 6]);
const b = Array2D.new([2, 2], [5, 3, 4, -7], "float32");
// tslint:disable-next-line
expect(() => math.powStrict(a, b as any)).toThrowError();
});
};
test_util.describeMathCPU("pow", [tests]);
test_util.describeMathGPU("pow", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise add / sub
{
const tests: MathTests = it => {
it("c + A", math => {
const c = Scalar.new(5);
const a = Array1D.new([1, 2, 3]);
const result = math.scalarPlusArray(c, a);
test_util.expectArraysClose(result, [6, 7, 8]);
});
it("c + A propagates NaNs", math => {
const c = Scalar.new(NaN);
const a = Array1D.new([1, 2, 3]);
const res = math.scalarPlusArray(c, a);
test_util.expectArraysEqual(res, [NaN, NaN, NaN]);
});
it("c + A throws when passed non scalar", math => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.scalarPlusArray(c, a)).toThrowError();
});
it("A + B broadcasting same rank NDArrays different shape", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 1], [2, 3]);
const result = math.add(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [3, 4, 0, -1];
test_util.expectArraysClose(result, expected);
});
it("A + B broadcast 2D + 1D", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array1D.new([1, 2]);
const result = math.add(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [2, 4, -2, -2];
test_util.expectArraysClose(result, expected);
});
it("A + B", math => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, 2, -1]);
const result = math.add(a, b);
const expected = [6, 7, 0];
test_util.expectArraysClose(result, expected);
});
it("A + B propagates NaNs", math => {
const a = Array1D.new([2, 5, NaN]);
const b = Array1D.new([4, 2, -1]);
const res = math.add(a, b);
test_util.expectArraysClose(res, [6, 7, NaN]);
});
it("A + B throws when passed ndarrays with different shape", math => {
const a = Array1D.new([2, 5, 1, 5]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.add(a, b)).toThrowError();
expect(() => math.add(b, a)).toThrowError();
});
it("2D+scalar broadcast", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const b = Scalar.new(2);
const res = math.add(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [3, 4, 5, 6, 7, 8]);
});
it("scalar+1D broadcast", math => {
const a = Scalar.new(2);
const b = Array1D.new([1, 2, 3, 4, 5, 6]);
const res = math.add(a, b);
expect(res.shape).toEqual([6]);
test_util.expectArraysClose(res, [3, 4, 5, 6, 7, 8]);
});
it("2D+2D broadcast each with 1 dim", math => {
const a = Array2D.new([1, 3], [1, 2, 5]);
const b = Array2D.new([2, 1], [7, 3]);
const res = math.add(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [8, 9, 12, 4, 5, 8]);
});
it("2D+2D broadcast inner dim of b", math => {
const a = Array2D.new([2, 3], [1, 2, 5, 4, 5, 6]);
const b = Array2D.new([2, 1], [7, 3]);
const res = math.add(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [8, 9, 12, 7, 8, 9]);
});
it("3D+scalar", math => {
const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, 6]);
const b = Scalar.new(-1);
const res = math.add(a, b);
expect(res.shape).toEqual([2, 3, 1]);
test_util.expectArraysClose(res, [0, 1, 2, 3, 4, 5]);
});
};
test_util.describeMathCPU("add", [tests]);
test_util.describeMathGPU("add", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// subtract
{
const tests: MathTests = it => {
it("c - A", math => {
const c = Scalar.new(5);
const a = Array1D.new([7, 2, 3]);
const result = math.scalarMinusArray(c, a);
test_util.expectArraysClose(result, [-2, 3, 2]);
});
it("c - A throws when passed non scalar", math => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.scalarMinusArray(c, a)).toThrowError();
});
it("A - c", math => {
const a = Array1D.new([1, 2, -3]);
const c = Scalar.new(5);
const result = math.arrayMinusScalar(a, c);
test_util.expectArraysClose(result, [-4, -3, -8]);
});
it("A - c propagates NaNs", math => {
const a = Array1D.new([1, NaN, 3]);
const c = Scalar.new(5);
const res = math.arrayMinusScalar(a, c);
test_util.expectArraysClose(res, [-4, NaN, -2]);
});
it("A - c throws when passed non scalar", math => {
// tslint:disable-next-line:no-any
const c: any = Array1D.new([1, 2, 3]);
const a = Array1D.new([1, 2, 3]);
expect(() => math.arrayMinusScalar(a, c)).toThrowError();
});
it("A - B", math => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, 2, -1]);
const result = math.subtract(a, b);
const expected = [-2, 3, 2];
test_util.expectArraysClose(result, expected);
});
it("A - B propagates NaNs", math => {
const a = Array1D.new([2, 5, 1]);
const b = Array1D.new([4, NaN, -1]);
const res = math.subtract(a, b);
test_util.expectArraysClose(res, [-2, NaN, 2]);
});
it("A - B throws when passed ndarrays with different shape", math => {
const a = Array1D.new([2, 5, 1, 5]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.subtract(a, b)).toThrowError();
expect(() => math.subtract(b, a)).toThrowError();
});
it("A - B broadcasting same rank NDArrays different shape", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array2D.new([2, 1], [2, 3]);
const result = math.subtract(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [-1, 0, -6, -7];
test_util.expectArraysClose(result, expected);
});
it("A - B broadcast 2D + 1D", math => {
const a = Array2D.new([2, 2], [1, 2, -3, -4]);
const b = Array1D.new([1, 2]);
const result = math.subtract(a, b);
expect(result.shape).toEqual([2, 2]);
const expected = [0, 0, -4, -6];
test_util.expectArraysClose(result, expected);
});
it("2D-scalar broadcast", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const b = Scalar.new(2);
const res = math.subtract(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [-1, 0, 1, 2, 3, 4]);
});
it("scalar-1D broadcast", math => {
const a = Scalar.new(2);
const b = Array1D.new([1, 2, 3, 4, 5, 6]);
const res = math.subtract(a, b);
expect(res.shape).toEqual([6]);
test_util.expectArraysClose(res, [1, 0, -1, -2, -3, -4]);
});
it("2D-2D broadcast each with 1 dim", math => {
const a = Array2D.new([1, 3], [1, 2, 5]);
const b = Array2D.new([2, 1], [7, 3]);
const res = math.subtract(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [-6, -5, -2, -2, -1, 2]);
});
it("2D-2D broadcast inner dim of b", math => {
const a = Array2D.new([2, 3], [1, 2, 5, 4, 5, 6]);
const b = Array2D.new([2, 1], [7, 3]);
const res = math.subtract(a, b);
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysClose(res, [-6, -5, -2, 1, 2, 3]);
});
it("3D-scalar", math => {
const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, 6]);
const b = Scalar.new(-1);
const res = math.subtract(a, b);
expect(res.shape).toEqual([2, 3, 1]);
test_util.expectArraysClose(res, [2, 3, 4, 5, 6, 7]);
});
};
test_util.describeMathCPU("subtract", [tests]);
test_util.describeMathGPU("subtract", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// math.scaledArrayAdd
{
const tests: MathTests = it => {
it("Scaled ndarray add", math => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
const c1 = Scalar.new(3);
const c2 = Scalar.new(2);
const result = math.scaledArrayAdd<Array2D>(c1, a, c2, b);
expect(result.shape).toEqual([2, 3]);
test_util.expectArraysClose(result, [8, 16, 24, 32, 40, 48]);
// Different sizes throws an error.
const wrongSizeMat = Array2D.new([2, 2], [1, 2, 3, 4]);
expect(() => math.scaledArrayAdd<Array2D>(c1, wrongSizeMat, c2, b))
.toThrowError();
});
it("throws when passed non-scalars", math => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 3], [1, 2, 3, 4, 5, 6]);
// tslint:disable-next-line:no-any
const c1: any = Array1D.randNormal([10]);
const c2 = Scalar.new(2);
expect(() => math.scaledArrayAdd(c1 as Scalar, a, c2, b)).toThrowError();
expect(() => math.scaledArrayAdd(c2, a, c1 as Scalar, b)).toThrowError();
});
it("throws when NDArrays are different shape", math => {
const a = Array2D.new([2, 3], [2, 4, 6, 8, 10, 12]);
const b = Array2D.new([2, 4], [1, 2, 3, 4, 5, 6, 7, 8]);
const c1 = Scalar.new(3);
const c2 = Scalar.new(2);
expect(() => math.scaledArrayAdd<Array2D>(c1, a, c2, b)).toThrowError();
});
};
test_util.describeMathCPU("scaledArrayAdd", [tests]);
test_util.describeMathGPU("scaledArrayAdd", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise equal
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([2, 5, NaN]);
const b = Array1D.new([4, 5, -1]);
const res = math.equal(a, b);
expect(res.dtype).toBe("bool");
test_util.expectArraysEqual(res, [0, 1, util.NAN_BOOL]);
});
it("strict version throws when x and y are different shape", math => {
const a = Array1D.new([2]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.equalStrict(a, b)).toThrowError();
expect(() => math.equalStrict(b, a)).toThrowError();
});
it("2D and scalar broadcast", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 2, 5, 6]);
const b = Scalar.new(2);
const res = math.equal(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysEqual(res, [0, 1, 0, 1, 0, 0]);
});
it("scalar and 1D broadcast", math => {
const a = Scalar.new(2);
const b = Array1D.new([1, 2, 3, 4, 5, 2]);
const res = math.equal(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([6]);
test_util.expectArraysEqual(res, [0, 1, 0, 0, 0, 1]);
});
it("2D and 2D broadcast each with 1 dim", math => {
const a = Array2D.new([1, 3], [1, 2, 5]);
const b = Array2D.new([2, 1], [5, 1]);
const res = math.equal(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysEqual(res, [0, 0, 1, 1, 0, 0]);
});
it("3D and scalar", math => {
const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, -1]);
const b = Scalar.new(-1);
const res = math.equal(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3, 1]);
test_util.expectArraysEqual(res, [0, 0, 0, 0, 0, 1]);
});
};
test_util.describeMathCPU("equal", [tests]);
test_util.describeMathGPU("equal", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise not equal
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([2, 5, NaN]);
const b = Array1D.new([4, 5, -1]);
const res = math.notEqual(a, b);
expect(res.dtype).toBe("bool");
test_util.expectArraysEqual(res, [1, 0, util.NAN_BOOL]);
});
it("strict version throws when x and y are different shape", math => {
const a = Array1D.new([2]);
const b = Array1D.new([4, 2, -1]);
expect(() => math.notEqualStrict(a, b)).toThrowError();
expect(() => math.notEqualStrict(b, a)).toThrowError();
});
it("2D and scalar broadcast", math => {
const a = Array2D.new([2, 3], [1, 2, 3, 2, 5, 6]);
const b = Scalar.new(2);
const res = math.notEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysEqual(res, [1, 0, 1, 0, 1, 1]);
});
it("scalar and 1D broadcast", math => {
const a = Scalar.new(2);
const b = Array1D.new([1, 2, 3, 4, 5, 2]);
const res = math.notEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([6]);
test_util.expectArraysEqual(res, [1, 0, 1, 1, 1, 0]);
});
it("2D and 2D broadcast each with 1 dim", math => {
const a = Array2D.new([1, 3], [1, 2, 5]);
const b = Array2D.new([2, 1], [5, 1]);
const res = math.notEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3]);
test_util.expectArraysEqual(res, [1, 1, 0, 0, 1, 1]);
});
it("3D and scalar", math => {
const a = Array3D.new([2, 3, 1], [1, 2, 3, 4, 5, -1]);
const b = Scalar.new(-1);
const res = math.notEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.shape).toEqual([2, 3, 1]);
test_util.expectArraysEqual(res, [1, 1, 1, 1, 1, 0]);
});
};
test_util.describeMathCPU("notEqual", [tests]);
test_util.describeMathGPU("notEqual", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise greater
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([1, 5, 1, 5, NaN]);
const b = Array1D.new([4, 1, 2, 5, -1]);
const res = math.greater(a, b);
expect(res.dtype).toBe("bool");
expect(res.dataSync()).toEqual(
new Uint8Array([0, 1, 0, 0, util.NAN_BOOL]));
a.dispose();
b.dispose();
});
};
test_util.describeMathCPU("greater", [tests]);
test_util.describeMathGPU("greater", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise greater equal
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([1, 5, 1, 5, NaN]);
const b = Array1D.new([4, 1, 2, 5, -1]);
const res = math.greaterEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.dataSync()).toEqual(
new Uint8Array([0, 1, 0, 1, util.NAN_BOOL]));
a.dispose();
b.dispose();
});
};
test_util.describeMathCPU("greaterEqual", [tests]);
test_util.describeMathGPU("greaterEqual", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise less
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([1, 5, 1, 5, NaN]);
const b = Array1D.new([4, 1, 2, 5, -1]);
const res = math.less(a, b);
expect(res.dtype).toBe("bool");
expect(res.dataSync()).toEqual(
new Uint8Array([1, 0, 1, 0, util.NAN_BOOL]));
a.dispose();
b.dispose();
});
};
test_util.describeMathCPU("less", [tests]);
test_util.describeMathGPU("less", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// element-wise less equal
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([1, 5, 1, 5, NaN]);
const b = Array1D.new([4, 1, 2, 5, -1]);
const res = math.lessEqual(a, b);
expect(res.dtype).toBe("bool");
expect(res.dataSync()).toEqual(
new Uint8Array([1, 0, 1, 1, util.NAN_BOOL]));
a.dispose();
b.dispose();
});
};
test_util.describeMathCPU("lessEqual", [tests]);
test_util.describeMathGPU("lessEqual", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
}
// select
{
const tests: MathTests = it => {
it("propagates NaNs", math => {
const a = Array1D.new([1, 5, 1, 5, NaN]);
const b = Array1D.new([4, 1, 2, 5, -1]);
const cond = Array1D.new([
false, true, true, false, false], "bool");
const res = math.select(cond, a, b);
expect(res.dtype).toBe("float32");
test_util.expectArraysClose(res.dataSync(),
new Float32Array([4, 5, 1, 5, -1]));
a.dispose();
b.dispose();
cond.dispose();
});
it("handles rank 0", math => {
const a = Scalar.new(1);
const b = Scalar.new(4);
const cond = Scalar.new(false, "bool");
const res = math.select(cond, a, b);
expect(res.dtype).toBe("float32");
test_util.expectArraysClose(res.dataSync(),
new Float32Array([4]));
a.dispose();
b.dispose();
cond.dispose();
});
};
test_util.describeMathCPU("select", [tests]);
test_util.describeMathGPU("select", [tests], [
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 2, "WEBGL_FLOAT_TEXTURE_ENABLED": true},
{"WEBGL_VERSION": 1, "WEBGL_FLOAT_TEXTURE_ENABLED": false}
]);
} | the_stack |
import { EventEmitter } from 'events';
import * as net from 'net';
import { Readable } from 'stream';
import * as tls from 'tls';
import * as shared from '../shared';
import MimeNode = require('../mime-node');
import XOAuth2 = require('../xoauth2');
type ms = number;
declare namespace SMTPConnection {
interface Credentials {
/** the username */
user: string;
/** then password */
pass: string;
}
type OAuth2 = XOAuth2.Options;
interface AuthenticationTypeCustom extends Credentials {
/** indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’ or ‘custom’ */
type: 'custom' | 'Custom' | 'CUSTOM';
method: string;
}
interface AuthenticationTypeLogin extends Credentials {
/** indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’ or ‘custom’ */
type?: 'login' | 'Login' | 'LOGIN' | undefined;
}
interface AuthenticationTypeOAuth2 extends OAuth2 {
/** indicates the authetication type, defaults to ‘login’, other option is ‘oauth2’ or ‘custom’ */
type?: 'oauth2' | 'OAuth2' | 'OAUTH2' | undefined;
}
type AuthenticationType = AuthenticationTypeCustom | AuthenticationTypeLogin | AuthenticationTypeOAuth2;
interface AuthenticationCredentials {
/** normal authentication object */
credentials: Credentials;
}
interface AuthenticationOAuth2 {
/** if set then forces smtp-connection to use XOAuth2 for authentication */
oauth2: OAuth2;
}
interface CustomAuthenticationResponse {
command: string;
response: string;
status: number;
text: string;
code?: number | undefined;
}
interface CustomAuthenticationContext {
auth: AuthenticationCredentials;
authMethod: string;
extensions: string[];
authMethods: string[];
maxAllowedSize: number | false;
sendCommand(cmd: string): Promise<CustomAuthenticationResponse>;
sendCommand(cmd: string, done: (err: Error | null, data: CustomAuthenticationResponse) => void): void;
resolve(): unknown;
reject(err: Error | string): unknown;
}
interface CustomAuthenticationHandlers {
[method: string]: (ctx: CustomAuthenticationContext) => Promise<boolean> | unknown;
}
type DSNOption = 'NEVER' | 'SUCCESS' | 'FAILURE' | 'DELAY';
interface DSNOptions {
/** return either the full message ‘FULL’ or only headers ‘HDRS’ */
ret?: 'Full' | 'HDRS' | undefined;
/** sender’s ‘envelope identifier’ for tracking */
envid?: string | undefined;
/** when to send a DSN. Multiple options are OK - array or comma delimited. NEVER must appear by itself. */
notify?: DSNOption | DSNOption[] | undefined;
/** original recipient */
orcpt?: string | undefined;
}
interface Envelope {
/** includes an address object or is set to false */
from: string | false;
/** the recipient address or an array of addresses */
to: string | string[];
/** an optional value of the predicted size of the message in bytes. This value is used if the server supports the SIZE extension (RFC1870) */
size?: number | undefined;
/** if true then inform the server that this message might contain bytes outside 7bit ascii range */
use8BitMime?: boolean | undefined;
/** the dsn options */
dsn?: DSNOptions | undefined;
}
interface SMTPError extends NodeJS.ErrnoException {
/** string code identifying the error, for example ‘EAUTH’ is returned when authentication */
code?: string | undefined;
/** the last response received from the server (if the error is caused by an error response from the server) */
response?: string | undefined;
/** the numeric response code of the response string (if available) */
responseCode?: number | undefined;
/** command which provoked an error */
command?: string | undefined;
}
interface SentMessageInfo {
/** an array of accepted recipient addresses. Normally this array should contain at least one address except when in LMTP mode. In this case the message itself might have succeeded but all recipients were rejected after sending the message. */
accepted: string[];
/** an array of rejected recipient addresses. This array includes both the addresses that were rejected before sending the message and addresses rejected after sending it if using LMTP */
rejected: string[];
/** if some recipients were rejected then this property holds an array of error objects for the rejected recipients */
rejectedErrors?: SMTPError[] | undefined;
/** the last response received from the server */
response: string;
/** how long was envelope prepared */
envelopeTime: number;
/** how long was send stream prepared */
messageTime: number;
/** how many bytes were streamed */
messageSize: number;
}
interface Options {
/** the hostname or IP address to connect to (defaults to ‘localhost’) */
host?: string | undefined;
/** the port to connect to (defaults to 25 or 465) */
port?: number | undefined;
/** defines authentication data */
auth?: AuthenticationType | undefined;
/** defines if the connection should use SSL (if true) or not (if false) */
secure?: boolean | undefined;
/** turns off STARTTLS support if true */
ignoreTLS?: boolean | undefined;
/** forces the client to use STARTTLS. Returns an error if upgrading the connection is not possible or fails. */
requireTLS?: boolean | undefined;
/** tries to use STARTTLS and continues normally if it fails */
opportunisticTLS?: boolean | undefined;
/** optional hostname of the client, used for identifying to the server */
name?: string | undefined;
/** the local interface to bind to for network connections */
localAddress?: string | undefined;
/** how many milliseconds to wait for the connection to establish */
connectionTimeout?: ms | undefined;
/** how many milliseconds to wait for the greeting after connection is established */
greetingTimeout?: ms | undefined;
/** how many milliseconds of inactivity to allow */
socketTimeout?: ms | undefined;
/** optional bunyan compatible logger instance. If set to true then logs to console. If value is not set or is false then nothing is logged */
logger?: shared.Logger | boolean | undefined;
/** if set to true, then logs SMTP traffic without message content */
transactionLog?: boolean | undefined;
/** if set to true, then logs SMTP traffic and message content, otherwise logs only transaction events */
debug?: boolean | undefined;
/** defines preferred authentication method, e.g. ‘PLAIN’ */
authMethod?: string | undefined;
/** defines additional options to be passed to the socket constructor, e.g. {rejectUnauthorized: true} */
tls?: tls.ConnectionOptions | undefined;
/** initialized socket to use instead of creating a new one */
socket?: net.Socket | undefined;
/** connected socket to use instead of creating and connecting a new one. If secure option is true, then socket is upgraded from plaintext to ciphertext */
connection?: net.Socket | undefined;
customAuth?: CustomAuthenticationHandlers | undefined;
}
}
declare class SMTPConnection extends EventEmitter {
options: SMTPConnection.Options;
logger: shared.Logger;
id: string;
stage: 'init' | 'connected';
secureConnection: boolean;
alreadySecured: boolean;
port: number;
host: string;
name: string;
/** Expose version nr, just for the reference */
version: string;
/** If true, then the user is authenticated */
authenticated: boolean;
/** If set to true, this instance is no longer active */
destroyed: boolean;
/** Defines if the current connection is secure or not. If not, STARTTLS can be used if available */
secure: boolean;
lastServerResponse: string | false;
/** The socket connecting to the server */
_socket: net.Socket;
constructor(options?: SMTPConnection.Options);
/** Creates a connection to a SMTP server and sets up connection listener */
connect(callback: (err?: SMTPConnection.SMTPError) => void): void;
/** Sends QUIT */
quit(): void;
/** Closes the connection to the server */
close(): void;
/** Authenticate user */
login(auth: SMTPConnection.AuthenticationCredentials | SMTPConnection.AuthenticationOAuth2 | SMTPConnection.Credentials, callback: (err?: SMTPConnection.SMTPError) => void): void;
/** Sends a message */
send(envelope: SMTPConnection.Envelope, message: string | Buffer | Readable, callback: (err: SMTPConnection.SMTPError | null, info: SMTPConnection.SentMessageInfo) => void): void;
/** Resets connection state */
reset(callback: (err?: SMTPConnection.SMTPError) => void): void;
addListener(event: 'connect' | 'end', listener: () => void): this;
addListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
emit(event: 'connect' | 'end'): boolean;
emit(event: 'error', error: Error): boolean;
listenerCount(event: 'connect' | 'end' | 'error'): number;
listeners(event: 'connect' | 'end'): Array<() => void>;
listeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>;
off(event: 'connect' | 'end', listener: () => void): this;
off(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
on(event: 'connect' | 'end', listener: () => void): this;
on(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
once(event: 'connect' | 'end', listener: () => void): this;
once(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
prependListener(event: 'connect' | 'end', listener: () => void): this;
prependListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
prependOnceListener(event: 'connect' | 'end', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
rawListeners(event: 'connect' | 'end'): Array<() => void>;
rawListeners(event: 'error'): Array<(err: SMTPConnection.SMTPError) => void>;
removeAllListener(event: 'connect' | 'end' | 'error'): this;
removeListener(event: 'connect' | 'end', listener: () => void): this;
removeListener(event: 'error', listener: (err: SMTPConnection.SMTPError) => void): this;
}
export = SMTPConnection; | the_stack |
import { Sparkline, SparklineTooltip } from '../../src/sparkline/index';
import { createElement } from '@syncfusion/ej2-base';
import { removeElement, getIdElement, TextOption } from '../../src/sparkline/utils/helper';
import { ISparklineLoadedEventArgs, ISparklineResizeEventArgs } from '../../src/sparkline/model/interface';
import {profile , inMB, getMemoryProfile} from '../common.spec';
import { DataManager } from '@syncfusion/ej2-data';
Sparkline.Inject(SparklineTooltip);
/**
* Sparkline Test case file
*/
describe('Sparkline Component Base Spec', () => {
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('Sparkline Testing spec', () => {
let element: Element;
let sparkline: Sparkline;
let id: string = 'spark-container';
let ele: Element;
let d: string[];
let dataManager: DataManager = new DataManager({
url: 'https://ej2services.syncfusion.com/production/web-services/api/Orders'
});
beforeAll(() => {
element = createElement('div', { id: id });
(element as HTMLDivElement).style.width = '400px';
(element as HTMLDivElement).style.height = '100px';
document.body.appendChild(element);
sparkline = new Sparkline({
height: '40%',
width: '20%',
containerArea: {
background: 'green',
border: { color: 'yellow', width: 3},
},
tooltipSettings: { visible: true }
});
});
afterAll(() => {
sparkline.destroy();
sparkline.sparklineResize(null);
removeElement(id);
});
it('Sparkline height and width percentage checking', () => {
sparkline.loaded = () => {
ele = getIdElement(id + '_SparklineBorder');
d = ele.getAttribute('d').split(' ');
let x: number = Number(d[1]);
let y: number = Number(d[2]);
let width: number = Number(d[9]) - x;
let height: number = Number(d[18]) - y;
expect(x).toBe(1.5);
expect(y).toBe(1.5);
expect(width).toBe(77);
expect(height).toBe(37);
removeElement('nothing');
};
sparkline.appendTo('#' + id);
});
it('Sparkline background and border checking', () => {
let fill: string = ele.getAttribute('fill');
expect(fill).toBe('#FFFFFF');
let stroke: string = ele.getAttribute('stroke');
expect(stroke).toBe('yellow');
let strwid: string = ele.getAttribute('stroke-width');
expect(strwid).toBe('3');
});
it('Sparkline height and width pixel checking', () => {
sparkline.loaded = () => {
ele = getIdElement(id + '_SparklineBorder');
d = ele.getAttribute('d').split(' ');
let x: number = Number(d[1]);
let y: number = Number(d[2]);
let width: number = Number(d[9]) - x;
let height: number = Number(d[18]) - y;
expect(x).toBe(1.5);
expect(y).toBe(1.5);
expect(width).toBe(117);
expect(height).toBe(57);
};
sparkline.height = '60px';
sparkline.width = '120px';
sparkline.refresh();
});
it('Sparkline height and width default checking', () => {
sparkline.loaded = () => {
ele = getIdElement(id + '_SparklineBorder');
d = ele.getAttribute('d').split(' ');
let x: number = Number(d[1]);
let y: number = Number(d[2]);
let width: number = Number(d[9]) - x;
let height: number = Number(d[18]) - y;
expect(x).toBe(1.5);
expect(y).toBe(1.5);
expect(width).toBe(397);
expect(height).toBe(97);
};
sparkline.height = null;
sparkline.width = null;
sparkline.refresh();
});
it('Sparkline tooltip module checking', () => {
sparkline.sparklineRenderer.processData();
expect(sparkline.sparklineTooltipModule).not.toBe(null);
expect(sparkline.sparklineTooltipModule).not.toBe(undefined);
});
it('Sparkline tooltip module checking', () => {
sparkline.dataSource = dataManager;
sparkline.sparklineRenderer.processDataManager();
});
});
describe('Sparkline other scenario spec', () => {
let element: Element;
let sparkline: Sparkline;
let id: string = 'spark-container';
let ele: Element;
let d: string[];
beforeAll(() => {
element = createElement('div', { id: id });
(element as HTMLDivElement).style.width = '400px';
(element as HTMLDivElement).style.height = '100px';
document.body.appendChild(element);
sparkline = new Sparkline({
containerArea: {
background: 'blue',
border: { color: 'orange', width: 1},
},
dataSource: [
{xDate: new Date(2017, 1, 1), yval: 2900 },
{xDate: new Date(2017, 1, 2), yval: 3900 },
{xDate: new Date(2017, 1, 3), yval: 3500 },
{xDate: new Date(2017, 1, 4), yval: 3800 },
{xDate: new Date(2017, 1, 5), yval: 2500 },
{xDate: new Date(2017, 1, 6), yval: 3200 }
], yName: 'yval',
});
});
afterAll(() => {
sparkline.destroy();
removeElement(id);
});
it('Sparkline height and width parent size checking', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
ele = getIdElement(id + '_SparklineBorder');
d = ele.getAttribute('d').split(' ');
let x: number = Number(d[1]);
let y: number = Number(d[2]);
let width: number = Number(d[9]) - x;
let height: number = Number(d[18]) - y;
expect(x).toBe(0.5);
expect(y).toBe(0.5);
expect(width).toBe(399);
expect(height).toBe(99);
args.sparkline.loaded = null;
};
sparkline.appendTo('#' + id);
sparkline.getPersistData();
});
it('Sparkline value type Category and series type Pie coverage', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Category');
expect(args.sparkline.type).toBe('Pie');
};
sparkline.valueType = 'Category';
sparkline.type = 'Pie';
sparkline.refresh();
});
it('Sparkline value type DateTime and series type WinLoss coverage', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('DateTime');
expect(args.sparkline.type).toBe('WinLoss');
};
sparkline.valueType = 'DateTime';
sparkline.type = 'WinLoss';
sparkline.xName = 'xDate';
sparkline.refresh();
});
it('Sparkline value type Numeric and series type Pie coverage array data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('Pie');
};
sparkline.valueType = 'Numeric';
sparkline.type = 'Pie';
sparkline.dataSource = [5, 6, 7, 8, 3];
sparkline.refresh();
});
it('Sparkline value type Numeric and series type Column coverage array data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('Column');
};
sparkline.valueType = 'Numeric';
sparkline.type = 'Column';
sparkline.dataSource = [1, 0, 1, -1, 0, -1, 1];
sparkline.refresh();
});
it('Sparkline single array data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('Column');
};
sparkline.dataSource = [5];
sparkline.refresh();
});
it('Sparkline Column array minus data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('Column');
};
sparkline.dataSource = [-5, -4, -7, -9];
sparkline.refresh();
});
it('Sparkline WinLoss array minus data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('WinLoss');
};
sparkline.type = 'WinLoss';
sparkline.refresh();
});
it('Sparkline WinLoss array tristate data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('WinLoss');
};
sparkline.dataSource = [-5, -4, 0, 7, -9];
sparkline.refresh();
});
it('Sparkline Line with single data', () => {
sparkline.loaded = (args: ISparklineLoadedEventArgs) => {
args.sparkline.loaded = null;
expect(args.sparkline.valueType).toBe('Numeric');
expect(args.sparkline.type).toBe('Line');
new TextOption('sdad', 0, 0, 'middle', 'coverage', 'middle', 'translate(90, 0)');
};
sparkline.dataSource = [5];
sparkline.type = 'Line';
sparkline.refresh();
});
it('Sparkline resize event checking', (done: Function) => {
sparkline.sparklineResize(null);
sparkline.resize = (args: ISparklineResizeEventArgs) => {
expect(args.name).toBe('resize');
sparkline.resize = null;
done();
};
sparkline.sparklineResize(null);
});
});
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);
});
}); | the_stack |
import * as chai from 'chai';
import {Server} from '../../src/server';
import {FixtureLoader} from '../../fixtures/FixtureLoader';
import {JwtUtils} from '../../src/security/JwtUtils';
import {User} from '../../src/models/User';
import {Course, ICourseModel} from '../../src/models/Course';
import {ICourse} from '../../../shared/models/ICourse';
import {ICourseView} from '../../../shared/models/ICourseView';
import {IUserSubCourseView} from '../../../shared/models/IUserSubCourseView';
import {IUser} from '../../../shared/models/IUser';
import {FixtureUtils} from '../../fixtures/FixtureUtils';
import chaiHttp = require('chai-http');
import {readFileSync} from 'fs';
import {BreakpointSize} from '../../src/models/BreakpointSize';
import {Picture} from '../../src/models/mediaManager/File';
chai.use(chaiHttp);
const should = chai.should();
const app = new Server().app;
const BASE_URL = '/api/courses';
const fixtureLoader = new FixtureLoader();
describe('Course', () => {
// Before each test we reset the database
beforeEach(async () => {
await fixtureLoader.load();
});
describe(`GET ${BASE_URL}`, () => {
it('should return all active courses', async () => {
const courses = await Course.find({active: true});
const student = await FixtureUtils.getRandomStudent();
const res = await chai.request(app)
.get(BASE_URL)
.set('Cookie', `token=${JwtUtils.generateToken(student)}`);
res.status.should.be.equal(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(courses.length);
res.body.forEach((course: any) => {
course._id.should.be.a('string');
course.name.should.be.a('string');
course.active.should.be.a('boolean');
course.active.should.be.equal(true);
});
});
it('should return all courses', async () => {
const courses = await Course.find();
const teacher = await FixtureUtils.getRandomTeacher();
const res = await chai.request(app)
.get(BASE_URL)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`);
res.status.should.be.equal(200);
res.body.should.be.a('array');
res.body.length.should.be.eql(courses.length);
res.body.forEach((course: any) => {
course._id.should.be.a('string');
course.name.should.be.a('string');
course.active.should.be.a('boolean');
course.active.should.be.oneOf([true, false]);
});
});
it('should fail with wrong authorization', async () => {
const res = await chai.request(app)
.get(BASE_URL)
.set('Authorization', 'JWT asdf')
.catch(err => err.response);
res.status.should.be.equal(401);
});
it('should have a course fixture with "accesskey" enrollType', async () => {
const course = await Course.findOne({enrollType: 'accesskey'});
should.exist(course);
});
it('should not leak access keys to students', async () => {
const student = await FixtureUtils.getRandomStudent();
const res = await chai.request(app)
.get(BASE_URL)
.set('Cookie', `token=${JwtUtils.generateToken(student)}`);
res.status.should.be.equal(200);
res.body.forEach((course: any) => {
should.equal(course.accessKey, undefined);
});
});
});
describe(`POST ${BASE_URL}`, () => {
it('should add a new course', async () => {
const teacher = await FixtureUtils.getRandomTeacher();
const testData = {
name: 'Test Course',
description: 'Test description'
};
const res = await chai.request(app)
.post(BASE_URL)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`)
.send(testData);
res.status.should.be.equal(200);
res.body.name.should.equal(testData.name);
res.body.description.should.equal(testData.description);
});
});
describe(`GET ${BASE_URL} :id`, () => {
async function prepareTestCourse() {
const teachers = await FixtureUtils.getRandomTeachers(2, 2);
const teacher = teachers[0];
const unauthorizedTeacher = teachers[1];
const student = await FixtureUtils.getRandomStudent();
const testData = new Course({
name: 'Test Course',
description: 'Test description',
active: true,
courseAdmin: teacher,
teachers: [teacher],
enrollType: 'accesskey',
accessKey: 'accessKey1234',
freeTextStyle: 'theme1',
students: [student]
});
const savedCourse = await testData.save();
return {teacher, unauthorizedTeacher, student, testData, savedCourse};
}
async function testUnauthorizedGetCourseEdit(savedCourse: ICourseModel, user: IUser) {
const res = await chai.request(app)
.get(`${BASE_URL}/${savedCourse._id}/edit`)
.set('Cookie', `token=${JwtUtils.generateToken(user)}`);
res.should.not.have.status(200);
return res;
}
function assertUserCourseViewEquality(actual: IUserSubCourseView, expected: IUserSubCourseView) {
actual._id.should.be.equal(expected._id.toString());
actual.profile.firstName.should.be.equal(expected.profile.firstName);
actual.profile.lastName.should.be.equal(expected.profile.lastName);
actual.email.should.be.equal(expected.email);
}
it('should get view info for course with given id', async () => {
const {student, testData, savedCourse} = await prepareTestCourse();
const res = await chai.request(app)
.get(`${BASE_URL}/${savedCourse._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(student)}`);
res.should.have.status(200);
const body: ICourseView = res.body;
body.name.should.be.equal(testData.name);
body.description.should.be.equal(testData.description);
assertUserCourseViewEquality(body.courseAdmin, testData.courseAdmin);
for (const [index, actual] of body.teachers.entries()) {
assertUserCourseViewEquality(actual, testData.teachers[index]);
}
should.equal(res.body.accessKey, undefined);
});
it('should get edit info for course with given id', async () => {
const {teacher, testData, savedCourse} = await prepareTestCourse();
const res = await chai.request(app)
.get(`${BASE_URL}/${savedCourse._id}/edit`)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`);
res.should.have.status(200);
const body: ICourse = res.body;
body.name.should.be.equal(testData.name);
body.description.should.be.equal(testData.description);
body.active.should.be.equal(testData.active);
body.enrollType.should.be.equal(testData.enrollType);
body.accessKey.should.be.equal(testData.accessKey);
body.freeTextStyle.should.be.equal(testData.freeTextStyle);
});
it('should not get edit info for course as student', async () => {
const {savedCourse, student} = await prepareTestCourse();
const res = await testUnauthorizedGetCourseEdit(savedCourse, student);
res.body.name.should.be.equal('AccessDeniedError');
res.body.should.have.property('message');
res.body.should.have.property('stack');
});
it('should not get edit info for course as unauthorized teacher', async () => {
const {savedCourse, unauthorizedTeacher} = await prepareTestCourse();
const res = await testUnauthorizedGetCourseEdit(savedCourse, unauthorizedTeacher);
res.body.name.should.be.oneOf(['NotFoundError', 'ForbiddenError']);
res.body.should.have.property('stack');
});
it('should not get course not a teacher of course', async () => {
const teacher = await FixtureUtils.getRandomTeachers(2, 2);
const testData = new Course({
name: 'Test Course',
description: 'Test description',
active: true,
courseAdmin: teacher[0]._id
});
const savedCourse = await testData.save();
const res = await chai.request(app)
.get(`${BASE_URL}/${savedCourse._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(teacher[1])}`)
.catch(err => err.response);
res.should.have.status(404);
});
});
describe(`PUT ${BASE_URL} :id`, () => {
it('change added course', async () => {
const teacher = await FixtureUtils.getRandomTeacher();
const testDataUpdate = new Course(
{
name: 'Test Course Update',
description: 'Test description update',
active: true,
courseAdmin: teacher._id,
freeTextStyle: 'theme1'
});
const testData = new Course(
{
name: 'Test Course',
description: 'Test description',
active: false,
courseAdmin: teacher._id
});
const savedCourse = await testData.save();
testDataUpdate._id = savedCourse._id;
let res = await chai.request(app)
.put(`${BASE_URL}/${testDataUpdate._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`)
.send(testDataUpdate);
res.should.have.status(200);
res.body.name.should.be.eq(testDataUpdate.name);
res.body._id.should.be.eq(testDataUpdate.id);
res = await chai.request(app)
.get(`${BASE_URL}/${res.body._id}/edit`)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`);
res.should.have.status(200);
res.body.name.should.be.eq(testDataUpdate.name);
res.body.description.should.be.eq(testDataUpdate.description);
res.body.active.should.be.eq(testDataUpdate.active);
res.body.freeTextStyle.should.be.eq(testDataUpdate.freeTextStyle);
});
it('should not change course not a teacher of course', async () => {
const teacher = await FixtureUtils.getRandomTeacher();
const testData = new Course(
{
name: 'Test Course',
description: 'Test description',
active: false
});
const savedCourse = await testData.save();
const res = await chai.request(app)
.put(`${BASE_URL}/${savedCourse._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(teacher)}`)
.send(savedCourse)
.catch(err => err.response);
res.should.have.status(404);
});
});
describe(`POST PICTURE ${BASE_URL}`, () => {
it('should update the course image', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({ breakpoints:
[ { screenSize: BreakpointSize.MOBILE, imageSize: { width: 284, height: 190} }] }));
res.should.have.status(200);
res.body.breakpoints.length.should.be.eq(1);
});
it('should update the course image with only the width set', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({ breakpoints:
[ { screenSize: BreakpointSize.MOBILE, imageSize: { width: 284 } }] }));
res.should.have.status(200);
res.body.breakpoints.length.should.be.eq(1);
});
it('should update the course image with only the height set', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({ breakpoints:
[ { screenSize: BreakpointSize.MOBILE, imageSize: { height: 190 } }] }));
res.should.have.status(200);
res.body.breakpoints.length.should.be.eq(1);
});
it('should not update the course image (wrong file type)', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/wrong-format.rtf'), 'test.rtf')
.field('imageData', JSON.stringify({ breakpoints:
[ { screenSize: BreakpointSize.MOBILE, imageSize: { width: 284, height: 190} }] }));
res.should.not.have.status(200);
});
it('should update course image when old picture object missing', async () => {
// https://github.com/geli-lms/geli/issues/1053
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const resAddCourseImage = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({
breakpoints:
[{screenSize: BreakpointSize.MOBILE, imageSize: {width: 284, height: 190}}]
}));
resAddCourseImage.should.have.status(200);
resAddCourseImage.body.breakpoints.length.should.be.eq(1);
// delete picture object without api
await Picture.findByIdAndDelete(resAddCourseImage.body._id);
const resAddAnotherCourseImage = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({ breakpoints:
[ { screenSize: BreakpointSize.MOBILE, imageSize: { width: 284, height: 190} }] }));
resAddAnotherCourseImage.should.have.status(200);
resAddAnotherCourseImage.body.breakpoints.length.should.be.eq(1);
});
it('should not update course image when user not authorized', async () => {
const course = await FixtureUtils.getRandomCourse();
const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(unauthorizedTeacher)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({
breakpoints:
[{screenSize: BreakpointSize.MOBILE, imageSize: {width: 284, height: 190}}]
}));
res.should.not.have.status(200);
});
});
describe(`DELETE PICTURE ${BASE_URL}`, () => {
it('should update and remove the course image', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
let res = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({
breakpoints:
[{screenSize: BreakpointSize.MOBILE, imageSize: {width: 284, height: 190}}]
}));
res.should.have.status(200);
res.body.breakpoints.length.should.be.eq(1);
res = await chai.request(app)
.del(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.send();
res.should.have.status(200);
const updatedCourse = await Course.findById(course._id);
should.not.exist(updatedCourse.image);
});
it('should remove course image when picture object missing', async () => {
// https://github.com/geli-lms/geli/issues/1053
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const resAddCourseImage = await chai.request(app)
.post(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.attach('file', readFileSync('test/resources/test.png'), 'test.png')
.field('imageData', JSON.stringify({
breakpoints:
[{screenSize: BreakpointSize.MOBILE, imageSize: {width: 284, height: 190}}]
}));
resAddCourseImage.should.have.status(200);
resAddCourseImage.body.breakpoints.length.should.be.eq(1);
// delete picture object without api
await Picture.findByIdAndDelete(resAddCourseImage.body._id);
const resDeleteCourseImage = await chai.request(app)
.del(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`)
.send();
resDeleteCourseImage.should.have.status(200);
const updatedCourse = await Course.findById(course._id);
should.not.exist(updatedCourse.image);
});
it('should not delete course image when user not authorized', async () => {
const course = await FixtureUtils.getRandomCourse();
const unauthorizedTeacher = await FixtureUtils.getUnauthorizedTeacherForCourse(course);
const res = await chai.request(app)
.del(`${BASE_URL}/picture/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(unauthorizedTeacher)}`)
.send();
res.should.not.have.status(200);
});
});
describe(`DELETE ${BASE_URL}`, () => {
it('should delete the Course', async () => {
const course = await FixtureUtils.getRandomCourse();
const courseAdmin = await User.findOne({_id: course.courseAdmin});
const res = await chai.request(app)
.del(`${BASE_URL}/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(courseAdmin)}`);
res.status.should.be.equal(200);
const deletedCourse = await Course.findById(course._id);
should.not.exist(deletedCourse, 'Course does still exist');
});
it('should fail because the user is not authorized', async () => {
const course = await FixtureUtils.getRandomCourse();
const res = await chai.request(app)
.del(`${BASE_URL}/${course._id}`)
.catch(err => err.response);
res.status.should.be.equal(401);
});
it('should fail because the teacher is not in the course', async () => {
const course = await FixtureUtils.getRandomCourse();
const allTeachersAndAdmins = course.teachers;
allTeachersAndAdmins.push(course.courseAdmin);
const user = await User.findOne({
$and: [
{role: 'teacher'},
{_id: {$nin: allTeachersAndAdmins}}
]
});
const res = await chai.request(app)
.del(`${BASE_URL}/${course._id}`)
.set('Cookie', `token=${JwtUtils.generateToken(user)}`)
.catch(err => err.response);
res.status.should.be.equal(403);
});
});
}); | the_stack |
import * as React from 'react';
import { render, fireEvent, act, screen } from '@testing-library/react';
import { cssClasses, waitForUseEffectCleanup } from '../helpers';
import { Toast, ToastContainer } from '../../src/components';
import { ToastProps } from '../../src/types';
const REQUIRED_PROPS = {
...ToastContainer.defaultProps,
isIn: true,
closeToast: () => {},
type: 'default',
toastId: 'id',
key: 'key'
} as ToastProps;
function getProgressBar() {
const progressBar = screen.getByRole('progressbar');
return {
isRunning: () =>
expect(progressBar.style.animationPlayState).toBe('running'),
isPaused: () => expect(progressBar.style.animationPlayState).toBe('paused'),
isControlled: (progress: number) => {
expect(document.querySelector(cssClasses.progressBarController)).not.toBe(
null
);
expect(progressBar.style.transform).toMatch(`scaleX(${progress})`);
}
};
}
const documentHasFocus = jest
.spyOn(document, 'hasFocus')
.mockImplementation(() => true);
const defaultEvents = [document.addEventListener, document.removeEventListener];
beforeEach(() => {
const [add, remove] = defaultEvents;
document.addEventListener = add;
document.removeEventListener = remove;
});
afterAll(() => {
documentHasFocus.mockRestore();
});
describe('Toast Component', () => {
it('Should merge container and body className', () => {
render(
<Toast
{...REQUIRED_PROPS}
autoClose={false}
className="container-class"
bodyClassName="body-class"
>
FooBar
</Toast>
);
expect(document.querySelector('.container-class')).not.toBe(null);
expect(document.querySelector('.body-class')).not.toBe(null);
});
it('Should merge container and body className when functional', () => {
render(
<Toast
{...REQUIRED_PROPS}
autoClose={false}
className={() => 'container-class'}
bodyClassName={() => 'body-class'}
>
FooBar
</Toast>
);
expect(document.querySelector('.container-class')).not.toBe(null);
expect(document.querySelector('.body-class')).not.toBe(null);
});
it('Should support Rtl display', () => {
render(
<Toast {...REQUIRED_PROPS} autoClose={false} rtl>
FooBar
</Toast>
);
expect(document.querySelector(cssClasses.rtl)).not.toBeNull();
});
it('Should not render ProgressBar if autoClose prop is set to false', () => {
render(
<Toast {...REQUIRED_PROPS} autoClose={false}>
FooBar
</Toast>
);
expect(screen.queryByRole('progressbar')).toBe(null);
});
it('Should not render closeButton if closeButton prop is set to false', () => {
render(
<Toast {...REQUIRED_PROPS} closeButton={false}>
FooBar
</Toast>
);
expect(screen.queryByLabelText('close')).toBe(null);
});
it('Can call onOpen callback when toast is displayed', () => {
const onOpen = jest.fn();
render(
<Toast {...REQUIRED_PROPS} onOpen={onOpen}>
FooBar
</Toast>
);
expect(onOpen).toHaveBeenCalled();
});
it('Can call onClose callback when toast is removed', async done => {
const onClose = jest.fn();
const { unmount } = render(
<Toast {...REQUIRED_PROPS} onClose={onClose}>
FooBar
</Toast>
);
unmount();
waitForUseEffectCleanup(() => {
expect(onClose).toHaveBeenCalled();
done();
});
});
it('Can pause toast delay on mouse enter', () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const progressBar = getProgressBar();
progressBar.isRunning();
fireEvent.mouseOver(screen.getByRole('alert') as HTMLElement);
progressBar.isPaused();
});
it('Can keep runing on mouse enter', () => {
render(
<Toast {...REQUIRED_PROPS} pauseOnHover={false}>
FooBar
</Toast>
);
const progressBar = getProgressBar();
progressBar.isRunning();
fireEvent.mouseEnter(screen.getByRole('alert'));
progressBar.isRunning();
});
it('Should resume toast delay on mouse leave', () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const progressBar = getProgressBar();
const notification = screen.getByRole('alert');
progressBar.isRunning();
fireEvent.mouseEnter(notification);
progressBar.isPaused();
fireEvent.mouseLeave(notification);
progressBar.isRunning();
});
it('Should pause Toast on window blur and resume Toast on focus', () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const progressBar = getProgressBar();
progressBar.isRunning();
let ev = new Event('blur');
act(() => {
window.dispatchEvent(ev);
});
progressBar.isPaused();
ev = new Event('focus');
act(() => {
window.dispatchEvent(ev);
});
progressBar.isRunning();
});
it('Should bind or unbind dom events when `pauseOnFocusLoss` and `draggable` props are updated', () => {
const { rerender } = render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
document.removeEventListener = jest.fn();
window.removeEventListener = jest.fn();
rerender(
<Toast {...REQUIRED_PROPS} draggable={false} pauseOnFocusLoss={false}>
FooBar
</Toast>
);
expect(document.removeEventListener).toHaveBeenCalled();
expect(window.removeEventListener).toHaveBeenCalled();
document.addEventListener = jest.fn();
window.addEventListener = jest.fn();
rerender(
<Toast {...REQUIRED_PROPS} draggable={true} pauseOnFocusLoss={true}>
FooBar
</Toast>
);
expect(document.addEventListener).toHaveBeenCalled();
expect(window.addEventListener).toHaveBeenCalled();
});
it('Should render toast with controlled progress bar', () => {
render(
<Toast {...REQUIRED_PROPS} progress={0.3}>
FooBar
</Toast>
);
const progressBar = getProgressBar();
progressBar.isControlled(0.3);
});
it('Should render toast with controlled progress bar even if autoClose is false', () => {
render(
<Toast {...REQUIRED_PROPS} progress={0.3} autoClose={false}>
FooBar
</Toast>
);
const progressBar = getProgressBar();
progressBar.isControlled(0.3);
});
it('Should close the toast when progressBar animation end', () => {
const closeToast = jest.fn();
render(
<Toast {...REQUIRED_PROPS} closeToast={closeToast}>
FooBar
</Toast>
);
fireEvent.animationEnd(screen.getByRole('progressbar'));
expect(closeToast).toHaveBeenCalled();
});
it('Should close the toast if progress value is >= 1 when the progress bar is controlled', () => {
const closeToast = jest.fn();
render(
<Toast {...REQUIRED_PROPS} closeToast={closeToast} progress={1}>
FooBar
</Toast>
);
const progressBar = getProgressBar();
progressBar.isControlled(1);
fireEvent.transitionEnd(screen.getByRole('progressbar'));
expect(closeToast).toHaveBeenCalled();
});
it('Should add the role attribute to the toast body', () => {
render(
<Toast {...REQUIRED_PROPS} role="status">
FooBar
</Toast>
);
expect(screen.queryByRole('status')).not.toBe(null);
});
it('Should use toastId as node id', () => {
render(
<Toast {...REQUIRED_PROPS} toastId="foo">
FooBar
</Toast>
);
expect(document.getElementById('foo')).not.toBe(null);
});
it('Should support style attribute', () => {
const style: React.CSSProperties = {
background: 'purple'
};
const bodyStyle: React.CSSProperties = {
fontWeight: 'bold'
};
const { queryByRole } = render(
<Toast {...REQUIRED_PROPS} style={style} bodyStyle={bodyStyle}>
FooBar
</Toast>
);
const notification = queryByRole('alert') as HTMLElement;
expect((notification.parentNode as HTMLElement).style.background).toBe(
'purple'
);
expect(notification.style.fontWeight).toBe('bold');
});
describe('Drag event', () => {
// target parent node due to text selection disabling drag event
it('Should handle drag start on mousedown', () => {
const mockClientRect = jest.fn();
Element.prototype.getBoundingClientRect = mockClientRect;
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
expect(mockClientRect).not.toHaveBeenCalled();
fireEvent.mouseDown(screen.getByRole('alert').parentNode!);
expect(mockClientRect).toHaveBeenCalled();
});
it('Should handle drag start on touchstart', () => {
const mockClientRect = jest.fn();
Element.prototype.getBoundingClientRect = mockClientRect;
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
expect(mockClientRect).not.toHaveBeenCalled();
fireEvent.touchStart(screen.getByRole('alert').parentNode!);
expect(mockClientRect).toHaveBeenCalled();
});
it('Should pause toast duration on drag move', async () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const progressBar = getProgressBar();
const notification = screen.getByRole('alert').parentNode!;
progressBar.isRunning();
fireEvent.mouseDown(notification);
fireEvent.mouseMove(notification);
progressBar.isPaused();
});
it('Should prevent the timer from running on drag end if the mouse hover the toast', () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const notification = screen.getByRole('alert').parentNode!;
// BoundingClientRect for Position top right
Element.prototype.getBoundingClientRect = () => {
return {
top: 20,
right: 846,
bottom: 84,
left: 534
} as DOMRect;
};
const progressBar = getProgressBar();
progressBar.isRunning();
fireEvent.mouseDown(notification);
// Cursor inside the toast
fireEvent.mouseMove(notification, {
clientX: 600,
clientY: 30
});
progressBar.isPaused();
fireEvent.mouseUp(notification);
progressBar.isPaused();
});
it('Should resume the timer on drag end if the mouse is not hovering the toast', () => {
render(<Toast {...REQUIRED_PROPS}>FooBar</Toast>);
const notification = screen.getByRole('alert').parentNode!;
// BoundingClientRect for Position top right
Element.prototype.getBoundingClientRect = () => {
return {
top: 20,
right: 846,
bottom: 84,
left: 534
} as DOMRect;
};
const progressBar = getProgressBar();
progressBar.isRunning();
fireEvent.mouseDown(notification);
// Cursor inside the toast
fireEvent.mouseMove(notification, {
clientX: 400,
clientY: 30
});
progressBar.isPaused();
fireEvent.mouseUp(notification);
progressBar.isRunning();
});
});
}); | the_stack |
import * as ts from 'typescript';
import * as Lint from 'tslint';
import {
isParameterDeclaration, isParameterProperty, isFunctionWithBody, isExpressionValueUsed,
collectVariableUsage, VariableInfo, VariableUse, UsageDomain, isAssignmentKind,
} from 'tsutils';
const OPTION_FUNCTION_EXPRESSION_NAME = 'unused-function-expression-name';
const OPTION_CLASS_EXPRESSION_NAME = 'unused-class-expression-name';
const OPTION_CATCH_BINDING = 'unused-catch-binding';
const OPTION_IGNORE_PARAMETERS = 'ignore-parameters';
const OPTION_IGNORE_IMPORTS = 'ignore-imports';
export class Rule extends Lint.Rules.AbstractRule {
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new UnusedWalker(sourceFile, this.ruleName, {
functionExpressionName: this.ruleArguments.indexOf(OPTION_FUNCTION_EXPRESSION_NAME) !== -1,
classExpressionName: this.ruleArguments.indexOf(OPTION_CLASS_EXPRESSION_NAME) !== -1,
ignoreParameters: this.ruleArguments.indexOf(OPTION_IGNORE_PARAMETERS) !== -1,
ignoreImports: this.ruleArguments.indexOf(OPTION_IGNORE_IMPORTS) !== -1,
catchBinding: this.ruleArguments.indexOf(OPTION_CATCH_BINDING) !== -1,
}));
}
}
interface IOptions {
functionExpressionName: boolean;
classExpressionName: boolean;
ignoreParameters: boolean;
ignoreImports: boolean;
catchBinding: boolean;
}
const enum ExpressionKind {
Function = 'Function',
Class = 'Class',
}
class UnusedWalker extends Lint.AbstractWalker<IOptions> {
public walk(sourceFile: ts.SourceFile) {
const usage = collectVariableUsage(sourceFile);
usage.forEach((variable, identifier) => {
if (isExcluded(variable, sourceFile, usage, this.options))
return;
switch (identifier.parent!.kind) {
case ts.SyntaxKind.FunctionExpression:
if (variable.uses.length === 0 && this.options.functionExpressionName)
this._failNamedExpression(identifier, ExpressionKind.Function);
return;
case ts.SyntaxKind.ClassExpression:
if (variable.uses.length === 0 && this.options.classExpressionName)
this._failNamedExpression(identifier, ExpressionKind.Class);
return;
}
if (variable.uses.length === 0) {
if (identifier.text === 'React' && this.sourceFile.languageVariant === ts.LanguageVariant.JSX &&
isImportFromExternal(identifier) && containsJsx(this.sourceFile))
return; // special case for 'React' import implicitly used by JSX
return this._fail(identifier, 'unused');
}
let uses = filterWriteOnly(variable.uses, identifier);
if (uses.length === 0)
return this._fail(identifier, 'only written and never read');
const filtered = uses.length !== variable.uses.length;
uses = filterUsesInDeclaration(uses, variable.declarations);
if (uses.length === 0)
return this._fail(identifier, `only ${filtered ? 'written or ' : ''}used inside of its declaration`);
// TODO error for classes / functions only used mutually recursive
});
}
private _fail(identifier: ts.Identifier, error: string) {
return this.addFailureAtNode(
identifier,
`${showKind(identifier)} '${identifier.text}' is ${error}.`,
);
}
private _failNamedExpression(identifier: ts.Identifier, kind: ExpressionKind) {
this.addFailureAtNode(
identifier,
`${kind} '${identifier.text}' is never used by its name. Convert it to an anonymous ${kind.toLocaleLowerCase()} expression.`,
Lint.Replacement.deleteFromTo(identifier.pos, identifier.end),
);
}
}
function containsJsx(node: ts.Node): boolean | undefined {
switch (node.kind) {
case ts.SyntaxKind.JsxElement:
case ts.SyntaxKind.JsxSelfClosingElement:
case ts.SyntaxKind.JsxFragment:
return true;
default:
return ts.forEachChild(node, containsJsx);
}
}
function filterUsesInDeclaration(uses: VariableUse[], declarations: ts.Identifier[]): VariableUse[] {
const result = [];
outer: for (const use of uses) {
for (const declaration of declarations) {
const parent = declaration.parent!;
if (use.location.pos > parent.pos && use.location.pos < parent.end &&
(parent.kind !== ts.SyntaxKind.VariableDeclaration ||
initializerHasNoSideEffect(<ts.VariableDeclaration>parent, use.location)))
continue outer;
}
result.push(use);
}
return result;
}
function initializerHasNoSideEffect(declaration: ts.VariableDeclaration, use: ts.Identifier): boolean {
if (declaration.initializer === undefined)
return true;
const enum Result {
HasSideEffect = 1,
NoSideEffect = 2,
}
return (function cb(node): Result | undefined {
if (node.pos > use.pos)
return Result.NoSideEffect;
if (node.end <= use.pos)
return;
switch (node.kind) {
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NewExpression:
case ts.SyntaxKind.TaggedTemplateExpression:
return Result.HasSideEffect;
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ClassExpression:
return Result.NoSideEffect;
}
return ts.forEachChild(node, cb);
})(declaration.initializer) !== Result.HasSideEffect;
}
function filterWriteOnly(uses: VariableUse[], identifier: ts.Identifier): VariableUse[] {
const result = [];
for (const use of uses)
if (use.domain & (UsageDomain.Type | UsageDomain.TypeQuery) ||
isExpressionValueUsed(use.location) && !isUpdate(use.location, identifier))
result.push(use);
return result;
}
// handle foo = foo + 1;
function isUpdate(use: ts.Expression, identifier: ts.Identifier): boolean {
while (true) {
const parent = use.parent!;
switch (parent.kind) {
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.NonNullExpression:
case ts.SyntaxKind.TypeAssertionExpression:
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.PrefixUnaryExpression:
case ts.SyntaxKind.PostfixUnaryExpression:
case ts.SyntaxKind.TypeOfExpression:
case ts.SyntaxKind.ConditionalExpression:
case ts.SyntaxKind.SpreadElement:
case ts.SyntaxKind.SpreadAssignment:
case ts.SyntaxKind.ObjectLiteralExpression:
case ts.SyntaxKind.ArrayLiteralExpression:
use = <ts.Expression>parent;
break;
case ts.SyntaxKind.PropertyAssignment:
case ts.SyntaxKind.ShorthandPropertyAssignment:
case ts.SyntaxKind.TemplateSpan:
use = <ts.Expression>parent.parent;
break;
case ts.SyntaxKind.BinaryExpression:
if (isAssignmentKind((<ts.BinaryExpression>parent).operatorToken.kind))
return (<ts.BinaryExpression>parent).right === use &&
(<ts.BinaryExpression>parent).left.kind === ts.SyntaxKind.Identifier &&
(<ts.Identifier>(<ts.BinaryExpression>parent).left).text === identifier.text;
use = <ts.Expression>parent;
break;
default:
return false;
}
}
}
function isExcluded(variable: VariableInfo, sourceFile: ts.SourceFile, usage: Map<ts.Identifier, VariableInfo>, opts: IOptions): boolean {
if (variable.exported || variable.inGlobalScope)
return true;
for (const declaration of variable.declarations) {
const parent = declaration.parent!;
if (declaration.text.startsWith('_')) {
switch (parent.kind) {
case ts.SyntaxKind.Parameter:
return true;
case ts.SyntaxKind.VariableDeclaration:
if (parent.parent!.parent!.kind === ts.SyntaxKind.ForInStatement ||
parent.parent!.parent!.kind === ts.SyntaxKind.ForOfStatement)
return true;
break;
case ts.SyntaxKind.BindingElement:
if ((<ts.BindingElement>parent).dotDotDotToken !== undefined)
break;
const pattern = <ts.BindingPattern>parent.parent;
if (pattern.kind === ts.SyntaxKind.ObjectBindingPattern &&
pattern.elements[pattern.elements.length - 1].dotDotDotToken !== undefined)
return true;
}
}
if (isParameterDeclaration(parent) &&
(opts.ignoreParameters || isParameterProperty(parent) || !isFunctionWithBody(parent.parent!)) ||
!opts.catchBinding && parent.kind === ts.SyntaxKind.VariableDeclaration && parent.parent!.kind === ts.SyntaxKind.CatchClause ||
parent.kind === ts.SyntaxKind.TypeParameter && parent.parent!.kind === ts.SyntaxKind.MappedType ||
parent.kind === ts.SyntaxKind.TypeParameter && typeParameterMayBeRequired(<ts.TypeParameterDeclaration>parent, usage))
return true;
// exclude imports in TypeScript files, because is may be used implicitly by the declaration emitter
if (/\.tsx?$/.test(sourceFile.fileName) && !sourceFile.isDeclarationFile && opts.ignoreImports && isImportFromExternal(declaration))
return true;
}
return false;
}
function isImportFromExternal(node: ts.Identifier) {
switch (node.parent!.kind) {
case ts.SyntaxKind.ImportEqualsDeclaration:
if ((<ts.ImportEqualsDeclaration>node.parent).moduleReference.kind === ts.SyntaxKind.ExternalModuleReference)
return true;
break;
case ts.SyntaxKind.NamespaceImport:
case ts.SyntaxKind.ImportSpecifier:
case ts.SyntaxKind.ImportClause:
return true;
default:
return false;
}
}
function typeParameterMayBeRequired(parameter: ts.TypeParameterDeclaration, usage: Map<ts.Identifier, VariableInfo>): boolean {
let parent: ts.Node = parameter.parent!;
switch (parent.kind) {
default:
return false;
case ts.SyntaxKind.InterfaceDeclaration:
case ts.SyntaxKind.ClassDeclaration:
if (typeParameterIsUsed(parameter, usage))
return true;
if ((<ts.NamedDeclaration>parent).name === undefined)
return false;
const variable = usage.get(<ts.Identifier>(<ts.NamedDeclaration>parent).name)!;
if (!variable.exported)
return variable.inGlobalScope;
}
parent = parent.parent!;
while (true) {
switch (parent.kind) {
case ts.SyntaxKind.ModuleBlock:
parent = parent.parent!;
break;
case ts.SyntaxKind.ModuleDeclaration:
if ((<ts.ModuleDeclaration>parent).name.kind !== ts.SyntaxKind.Identifier)
return ts.isExternalModule(parent.getSourceFile());
if (parent.flags & ts.NodeFlags.GlobalAugmentation)
return true;
const variable = usage.get(<ts.Identifier>(<ts.ModuleDeclaration>parent).name)!;
if (!variable.exported)
return variable.inGlobalScope;
parent = parent.parent!;
break;
default:
return false;
}
}
}
/** Check if TypeParameter is used in any of the merged declarations. */
function typeParameterIsUsed(parameter: ts.TypeParameterDeclaration, usage: Map<ts.Identifier, VariableInfo>): boolean {
if (usage.get(parameter.name)!.uses.length !== 0)
return true;
const parent = <ts.ClassDeclaration | ts.InterfaceDeclaration>parameter.parent;
if (parent.name === undefined)
return false;
const index = parent.typeParameters!.indexOf(parameter);
for (const declaration of usage.get(parent.name)!.declarations) {
const declarationParent = <ts.DeclarationWithTypeParameters>declaration.parent;
if (declarationParent === parent)
continue;
switch (declarationParent.kind) {
case ts.SyntaxKind.ClassDeclaration:
case ts.SyntaxKind.InterfaceDeclaration:
if (declarationParent.typeParameters !== undefined &&
declarationParent.typeParameters.length > index &&
usage.get(declarationParent.typeParameters[index].name)!.uses.length !== 0)
return true;
}
}
return false;
}
function showKind(node: ts.Identifier): string {
switch (node.parent!.kind) {
case ts.SyntaxKind.BindingElement:
case ts.SyntaxKind.VariableDeclaration:
return 'Variable';
case ts.SyntaxKind.Parameter:
return 'Parameter';
case ts.SyntaxKind.FunctionDeclaration:
return 'Function';
case ts.SyntaxKind.ClassDeclaration:
return 'Class';
case ts.SyntaxKind.InterfaceDeclaration:
return 'Interface';
case ts.SyntaxKind.ImportClause:
case ts.SyntaxKind.NamespaceImport:
case ts.SyntaxKind.ImportSpecifier:
case ts.SyntaxKind.ImportEqualsDeclaration:
return 'Import';
case ts.SyntaxKind.EnumDeclaration:
return 'Enum';
case ts.SyntaxKind.ModuleDeclaration:
return 'Namespace';
case ts.SyntaxKind.TypeAliasDeclaration:
return 'TypeAlias';
case ts.SyntaxKind.TypeParameter:
return 'TypeParameter';
default:
throw new Error(`Unhandled kind ${node.parent!.kind}: ${ts.SyntaxKind[node.parent!.kind]}`);
}
} | the_stack |
import './mocks/matchMedia'
import {
checkNodeUrlValidity,
cleanNodeAuth,
ensureSinglePrimaryNode,
getDefaultClientOptions,
getNetworkById,
getNodeCandidates,
getOfficialNetwork,
getOfficialNodes,
isNodeAuthValid,
isOfficialNetwork,
} from '../network'
import { Network, NetworkConfig, NetworkType } from '../typings/network'
import type { ClientOptions } from '../typings/client'
import type { Node, NodeAuth } from '../typings/node'
describe('File: network.ts', () => {
const _buildNode = (
url: string,
network: Network,
isPrimary: boolean = false,
isDisabled: boolean = false
): Node => ({
url,
network,
auth: { username: '', password: '' },
isPrimary,
isDisabled,
})
const MAINNET: Network = {
id: 'chrysalis-mainnet',
name: 'Chrysalis Mainnet',
type: NetworkType.ChrysalisMainnet,
bech32Hrp: 'iota',
}
const MAINNET_URLS = ['https://chrysalis-nodes.iota.org', 'https://chrysalis-nodes.iota.cafe']
const MAINNET_NODES = [0, 1].map((i) => _buildNode(MAINNET_URLS[i], MAINNET))
const MAINNET_CONFIG: NetworkConfig = {
network: MAINNET,
nodes: MAINNET_NODES,
includeOfficialNodes: false,
automaticNodeSelection: true,
localPow: true,
}
const DEVNET: Network = {
id: 'chrysalis-devnet',
name: 'Chrysalis Devnet',
type: NetworkType.ChrysalisDevnet,
bech32Hrp: 'atoi',
}
const DEVNET_URLS = [
'https://api.lb-0.h.chrysalis-devnet.iota.cafe',
'https://api.lb-1.h.chrysalis-devnet.iota.cafe',
]
const DEVNET_NODES = [0, 1].map((i) => _buildNode(DEVNET_URLS[i], DEVNET))
const DEVNET_CONFIG: NetworkConfig = {
network: DEVNET,
nodes: DEVNET_NODES,
includeOfficialNodes: true,
automaticNodeSelection: false,
localPow: true,
}
const EMPTY_NODE_AUTH = { username: '', password: '' }
const FAKE_NODE_AUTH = <NodeAuth>{
username: 'theUser',
password: 'mY-rEaLlY-sEcUrE-pAsSwOrD',
}
const FAKE_NODE_AUTH_JWT = <NodeAuth>{
jwt: 'SOME JWT',
username: 'theUser',
password: 'mY-rEaLlY-sEcUrE-pAsSwOrD',
}
describe('Function: getClientOptions', () => {
it('should return the client options of the active profile if present', () => {
const clientOpts = getDefaultClientOptions()
expect(clientOpts).toEqual(<ClientOptions>{
network: 'chrysalis-mainnet',
automaticNodeSelection: true,
includeOfficialNodes: true,
localPow: true,
node: _buildNode(MAINNET_URLS[0], MAINNET, true, false),
nodes: [_buildNode(MAINNET_URLS[0], MAINNET, true, false), _buildNode(MAINNET_URLS[1], MAINNET)],
})
})
})
describe('Function: getOfficialNetwork', () => {
it('should return the correct official network metadata given a valid network type', () => {
expect(getOfficialNetwork(NetworkType.ChrysalisMainnet)).toEqual(MAINNET)
expect(getOfficialNetwork(NetworkType.ChrysalisDevnet)).toEqual(DEVNET)
expect(getOfficialNetwork(NetworkType.PrivateNet)).toEqual(<Network>{ type: NetworkType.PrivateNet })
})
it('should return an empty network given an invalid network type', () => {
expect(getOfficialNetwork(undefined)).toEqual(<Network>{})
})
})
describe('Function: getOfficialNodes', () => {
it('should return the correct official nodes given a valid network type', () => {
expect(getOfficialNodes(NetworkType.ChrysalisMainnet)).toEqual([
_buildNode(MAINNET_URLS[0], MAINNET),
_buildNode(MAINNET_URLS[1], MAINNET),
])
expect(getOfficialNodes(NetworkType.ChrysalisDevnet)).toEqual([
_buildNode(DEVNET_URLS[0], DEVNET),
_buildNode(DEVNET_URLS[1], DEVNET),
])
expect(getOfficialNodes(NetworkType.PrivateNet)).toEqual([])
})
it('should return no official nodes given an invalid network type', () => {
expect(getOfficialNodes(undefined)).toEqual([])
})
})
describe('Function: isOfficialNetwork', () => {
it('should return the correct values given a valid network type', () => {
expect(isOfficialNetwork(NetworkType.ChrysalisMainnet)).toBe(true)
expect(isOfficialNetwork(NetworkType.ChrysalisDevnet)).toBe(true)
expect(isOfficialNetwork(NetworkType.PrivateNet)).toBe(false)
})
it('should return false given an invalid network type', () => {
expect(isOfficialNetwork(undefined)).toBe(false)
})
})
describe('Function: getNetworkById', () => {
it('should return all metadata for official networks', () => {
expect(getNetworkById(MAINNET.id)).toEqual(MAINNET)
expect(getNetworkById(DEVNET.id)).toEqual(DEVNET)
})
it('should return partial metadata for unofficial networks', () => {
expect(getNetworkById('another-tangle')).toEqual(<Network>{
id: 'another-tangle',
name: 'Private Net',
type: NetworkType.PrivateNet,
})
})
it('should return nothing given an invalid network ID', () => {
expect(getNetworkById(undefined)).toEqual(<Network>{})
})
})
describe('Function: cleanNodeAuth', () => {
it('should return an empty basic auth configuration given nothing', () => {
expect(cleanNodeAuth(<NodeAuth>{})).toEqual(EMPTY_NODE_AUTH)
expect(cleanNodeAuth(undefined)).toEqual(EMPTY_NODE_AUTH)
})
it('should return a basic auth configuration if given that', () => {
expect(cleanNodeAuth(FAKE_NODE_AUTH)).toEqual(FAKE_NODE_AUTH)
})
it('should return the entire auth configuration if the JWT exists', () => {
expect(cleanNodeAuth(<NodeAuth>{ jwt: 'SOME JWT' })).toEqual(<NodeAuth>{ jwt: 'SOME JWT' })
expect(cleanNodeAuth(FAKE_NODE_AUTH_JWT)).toEqual(FAKE_NODE_AUTH_JWT)
})
})
describe('Function: isNodeAuthValid', () => {
it('should return correct result for any auth configuration', () => {
expect(isNodeAuthValid(<NodeAuth>{})).toBe(false)
expect(isNodeAuthValid(undefined)).toBe(false)
expect(isNodeAuthValid(EMPTY_NODE_AUTH)).toBe(false)
expect(isNodeAuthValid(FAKE_NODE_AUTH)).toBe(true)
expect(isNodeAuthValid(FAKE_NODE_AUTH_JWT)).toBe(true)
})
})
describe('Function: checkNodeUrlValidity', () => {
enum UrlError {
Invalid = 'error.node.invalid',
Insecure = 'error.node.https',
Duplicate = 'error.node.duplicate',
}
const _check = (url: string, allowInsecure: boolean = false): string | undefined =>
checkNodeUrlValidity(MAINNET_NODES, url, allowInsecure)
it('should return undefined for valid node URLs', () => {
expect(_check('https://mainnet.tanglebay.com')).toBeUndefined()
expect(_check(DEVNET_URLS[0])).toBeUndefined()
})
it('should catch generally invalid URLs', () => {
expect(_check('htps://mainnet.tanglebay.com')).toEqual(UrlError.Invalid)
expect(_check('https:/mainnet.tanglebay.com')).toEqual(UrlError.Invalid)
expect(_check('https://mainnet.tanglebay.com')).toBeUndefined()
})
it('should catch duplicate node URLs', () => {
expect(_check(MAINNET_URLS[0])).toEqual(UrlError.Duplicate)
expect(_check(MAINNET_URLS[1])).toEqual(UrlError.Duplicate)
expect(_check(DEVNET_URLS[0])).toBeUndefined()
})
it('may or may NOT catch insecure URLs', () => {
expect(_check('http://mainnet.tanglebay.com')).toEqual(UrlError.Insecure)
// TODO: Enable this test when HTTP support has been audited
// expect(_check('http://mainnet.tanglebay.com', true)).toBeUndefined()
})
})
describe('Function: getNodeCandidates', () => {
it('should return nothing if passed invalid configuration', () => {
expect(getNodeCandidates(undefined)).toEqual([])
})
it('should ensure that at least one node candidate is primary', () => {
expect(getNodeCandidates(MAINNET_CONFIG).find((n) => n.isPrimary)).toBeDefined()
})
it('should use official nodes if no nodes exist', () => {
let nodes = getNodeCandidates({ ...MAINNET_CONFIG, nodes: [] })
expect(nodes.find((n) => n.isPrimary)).toBeDefined()
nodes.forEach((n) => {
expect(MAINNET_NODES.map((_n) => _n.url).includes(n.url)).toBe(true)
})
nodes = getNodeCandidates({ ...DEVNET_CONFIG, nodes: [] })
expect(nodes.find((n) => n.isPrimary)).toBeDefined()
nodes.forEach((n) => {
expect(DEVNET_NODES.map((_n) => _n.url).includes(n.url)).toBe(true)
})
})
it('should return official nodes if using automatic selection', () => {
let nodes = getNodeCandidates(MAINNET_CONFIG)
expect(nodes.find((n) => n.isPrimary)).toBeDefined()
nodes.forEach((n) => {
expect(MAINNET_NODES.map((_n) => _n.url).includes(n.url)).toBe(true)
})
})
it('may return ONLY unofficial nodes OR both', () => {
const unofficialNodes: Node[] = [
{ url: 'https://mainnet.tanglebay.com', network: MAINNET },
{ url: 'https://other.mainnet.tanglebay.com', network: MAINNET },
]
let nodes = getNodeCandidates({
...MAINNET_CONFIG,
nodes: unofficialNodes,
includeOfficialNodes: false,
automaticNodeSelection: false,
})
nodes.forEach((n) => {
expect(unofficialNodes.map((_n) => _n.url).includes(n.url)).toBe(true)
})
nodes = getNodeCandidates({
...MAINNET_CONFIG,
nodes: unofficialNodes,
includeOfficialNodes: true,
automaticNodeSelection: false,
})
nodes.forEach((n) => {
const isOfficial = MAINNET_NODES.map((_n) => _n.url).includes(n.url)
const isUnofficial = unofficialNodes.map((_n) => _n.url).includes(n.url)
expect(isOfficial || isUnofficial).toBe(true)
})
})
})
describe('Function: ensureSinglePrimaryNode', () => {
const _hasOnePrimary = (nodes: Node[]): boolean => nodes.filter((n) => n.isPrimary).length === 1
it('should maintain the primary node if it exists', () => {
const nodes = MAINNET_NODES.map((n, idx) => ({ ...n, isPrimary: idx === 0 }))
expect(ensureSinglePrimaryNode(nodes)).toEqual(nodes)
expect(_hasOnePrimary(ensureSinglePrimaryNode(nodes))).toBe(true)
})
it('should randomly select a primary node if one does not exist', () => {
expect(_hasOnePrimary(MAINNET_NODES)).toBe(false)
expect(_hasOnePrimary(ensureSinglePrimaryNode(MAINNET_NODES))).toBe(true)
})
it('should handle empty or invalid node arrays', () => {
expect(ensureSinglePrimaryNode([])).toEqual([])
expect(ensureSinglePrimaryNode(undefined)).toBeUndefined()
})
it('should ensure ONLY one primary node exists', () => {
const nodes = MAINNET_NODES.map((n) => ({ ...n, isPrimary: true }))
expect(ensureSinglePrimaryNode(nodes) === nodes).toBe(false)
expect(_hasOnePrimary(ensureSinglePrimaryNode(nodes))).toBe(true)
})
})
}) | the_stack |
import localVarRequest from 'request';
import http from 'http';
/* tslint:disable:no-unused-locals */
import { BatchInputJsonNode } from '../model/batchInputJsonNode';
import { BatchInputString } from '../model/batchInputString';
import { BatchInputTag } from '../model/batchInputTag';
import { BatchResponseTagWithErrors } from '../model/batchResponseTagWithErrors';
import { CollectionResponseWithTotalTagForwardPaging } from '../model/collectionResponseWithTotalTagForwardPaging';
import { Tag } from '../model/tag';
import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models';
import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models';
import { HttpError, RequestFile } from './apis';
let defaultBasePath = 'https://api.hubapi.com';
// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================
export enum TagApiApiKeys {
hapikey,
}
export class TagApi {
protected _basePath = defaultBasePath;
protected _defaultHeaders : any = {};
protected _useQuerystring : boolean = false;
protected authentications = {
'default': <Authentication>new VoidAuth(),
'hapikey': new ApiKeyAuth('query', 'hapikey'),
'oauth2': new OAuth(),
}
protected interceptors: Interceptor[] = [];
constructor(basePath?: string);
constructor(basePathOrUsername: string, password?: string, basePath?: string) {
if (password) {
if (basePath) {
this.basePath = basePath;
}
} else {
if (basePathOrUsername) {
this.basePath = basePathOrUsername
}
}
}
set useQuerystring(value: boolean) {
this._useQuerystring = value;
}
set basePath(basePath: string) {
this._basePath = basePath;
}
set defaultHeaders(defaultHeaders: any) {
this._defaultHeaders = defaultHeaders;
}
get defaultHeaders() {
return this._defaultHeaders;
}
get basePath() {
return this._basePath;
}
public setDefaultAuthentication(auth: Authentication) {
this.authentications.default = auth;
}
public setApiKey(key: TagApiApiKeys, value: string) {
(this.authentications as any)[TagApiApiKeys[key]].apiKey = value;
}
set accessToken(token: string) {
this.authentications.oauth2.accessToken = token;
}
public addInterceptor(interceptor: Interceptor) {
this.interceptors.push(interceptor);
}
/**
* Delete the Blog Tag object identified by the id in the path.
* @summary Delete a Blog Tag
* @param objectId The Blog Tag id.
* @param archived Whether to return only results that have been archived.
*/
public async archive (objectId: string, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/{objectId}'
.replace('{' + 'objectId' + '}', encodeURIComponent(String(objectId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'objectId' is not null or undefined
if (objectId === null || objectId === undefined) {
throw new Error('Required parameter objectId was null or undefined when calling archive.');
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'DELETE',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Delete the Blog Tag objects identified in the request body. Note: This is not the same as the in-app `archive` function.
* @summary Archive a batch of Blog Tags
* @param batchInputString The JSON array of Blog Tag ids.
*/
public async archiveBatch (batchInputString: BatchInputString, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/batch/archive';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'batchInputString' is not null or undefined
if (batchInputString === null || batchInputString === undefined) {
throw new Error('Required parameter batchInputString was null or undefined when calling archiveBatch.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(batchInputString, "BatchInputString")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Create a new Blog Tag.
* @summary Create a new Blog Tag
* @param tag The JSON representation of a new Blog Tag.
*/
public async create (tag: Tag, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Tag; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'tag' is not null or undefined
if (tag === null || tag === undefined) {
throw new Error('Required parameter tag was null or undefined when calling create.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(tag, "Tag")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Tag; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "Tag");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Create the Blog Tag objects detailed in the request body.
* @summary Create a batch of Blog Tags
* @param batchInputTag The JSON array of new Blog Tags to create.
*/
public async createBatch (batchInputTag: BatchInputTag, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: object; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/batch/create';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'batchInputTag' is not null or undefined
if (batchInputTag === null || batchInputTag === undefined) {
throw new Error('Required parameter batchInputTag was null or undefined when calling createBatch.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(batchInputTag, "BatchInputTag")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: object; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "object");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Retrieve the Blog Tag object identified by the id in the path.
* @summary Retrieve a Blog Tag
* @param objectId The Blog Tag id.
* @param archived Specifies whether to return archived Blog Tags. Defaults to `false`.
*/
public async getById (objectId: string, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Tag; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/{objectId}'
.replace('{' + 'objectId' + '}', encodeURIComponent(String(objectId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'objectId' is not null or undefined
if (objectId === null || objectId === undefined) {
throw new Error('Required parameter objectId was null or undefined when calling getById.');
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Tag; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "Tag");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Get the list of blog tags. Supports paging and filtering. This method would be useful for an integration that examined these models and used an external service to suggest edits.
* @summary Get all Blog Tags
* @param createdAt Only return Blog Tags created at exactly the specified time.
* @param createdAfter Only return Blog Tags created after the specified time.
* @param createdBefore Only return Blog Tags created before the specified time.
* @param updatedAt Only return Blog Tags last updated at exactly the specified time.
* @param updatedAfter Only return Blog Tags last updated after the specified time.
* @param updatedBefore Only return Blog Tags last updated before the specified time.
* @param sort Specifies which fields to use for sorting results. Valid fields are `name`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy`. `createdAt` will be used by default.
* @param after The cursor token value to get the next set of results. You can get this from the `paging.next.after` JSON property of a paged response containing more results.
* @param limit The maximum number of results to return. Default is 100.
* @param archived Specifies whether to return archived Blog Tags. Defaults to `false`.
*/
public async getPage (createdAt?: Date, createdAfter?: Date, createdBefore?: Date, updatedAt?: Date, updatedAfter?: Date, updatedBefore?: Date, sort?: Array<string>, after?: string, limit?: number, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: CollectionResponseWithTotalTagForwardPaging; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
if (createdAt !== undefined) {
localVarQueryParameters['createdAt'] = ObjectSerializer.serialize(createdAt, "Date");
}
if (createdAfter !== undefined) {
localVarQueryParameters['createdAfter'] = ObjectSerializer.serialize(createdAfter, "Date");
}
if (createdBefore !== undefined) {
localVarQueryParameters['createdBefore'] = ObjectSerializer.serialize(createdBefore, "Date");
}
if (updatedAt !== undefined) {
localVarQueryParameters['updatedAt'] = ObjectSerializer.serialize(updatedAt, "Date");
}
if (updatedAfter !== undefined) {
localVarQueryParameters['updatedAfter'] = ObjectSerializer.serialize(updatedAfter, "Date");
}
if (updatedBefore !== undefined) {
localVarQueryParameters['updatedBefore'] = ObjectSerializer.serialize(updatedBefore, "Date");
}
if (sort !== undefined) {
localVarQueryParameters['sort'] = ObjectSerializer.serialize(sort, "Array<string>");
}
if (after !== undefined) {
localVarQueryParameters['after'] = ObjectSerializer.serialize(after, "string");
}
if (limit !== undefined) {
localVarQueryParameters['limit'] = ObjectSerializer.serialize(limit, "number");
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: CollectionResponseWithTotalTagForwardPaging; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "CollectionResponseWithTotalTagForwardPaging");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Retrieve the Blog Tag objects identified in the request body.
* @summary Retrieve a batch of Blog Tags
* @param batchInputString The JSON array of Blog Tag ids.
* @param archived Specifies whether to return archived Blog Tags. Defaults to `false`.
*/
public async readBatch (batchInputString: BatchInputString, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: object; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/batch/read';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'batchInputString' is not null or undefined
if (batchInputString === null || batchInputString === undefined) {
throw new Error('Required parameter batchInputString was null or undefined when calling readBatch.');
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(batchInputString, "BatchInputString")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: object; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "object");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Sparse updates a single Blog Tag object identified by the id in the path. All the column values need not be specified. Only the that need to be modified can be specified.
* @summary Update a Blog Tag
* @param objectId The Blog Tag id.
* @param tag The JSON representation of the updated Blog Tag.
* @param archived Specifies whether to update archived Blog Tags. Defaults to `false`.
*/
public async update (objectId: string, tag: Tag, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Tag; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/{objectId}'
.replace('{' + 'objectId' + '}', encodeURIComponent(String(objectId)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'objectId' is not null or undefined
if (objectId === null || objectId === undefined) {
throw new Error('Required parameter objectId was null or undefined when calling update.');
}
// verify required parameter 'tag' is not null or undefined
if (tag === null || tag === undefined) {
throw new Error('Required parameter tag was null or undefined when calling update.');
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'PATCH',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(tag, "Tag")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Tag; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "Tag");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
* Update the Blog Tag objects identified in the request body.
* @summary Update a batch of Blog Tags
* @param batchInputJsonNode A JSON array of the JSON representations of the updated Blog Tags.
* @param archived Specifies whether to update archived Blog Tags. Defaults to `false`.
*/
public async updateBatch (batchInputJsonNode: BatchInputJsonNode, archived?: boolean, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: object; }> {
const localVarPath = this.basePath + '/cms/v3/blogs/tags/batch/update';
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/json', '*/*'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'batchInputJsonNode' is not null or undefined
if (batchInputJsonNode === null || batchInputJsonNode === undefined) {
throw new Error('Required parameter batchInputJsonNode was null or undefined when calling updateBatch.');
}
if (archived !== undefined) {
localVarQueryParameters['archived'] = ObjectSerializer.serialize(archived, "boolean");
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'POST',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
body: ObjectSerializer.serialize(batchInputJsonNode, "BatchInputJsonNode")
};
let authenticationPromise = Promise.resolve();
if (this.authentications.hapikey.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.hapikey.applyToRequest(localVarRequestOptions));
}
if (this.authentications.oauth2.accessToken) {
authenticationPromise = authenticationPromise.then(() => this.authentications.oauth2.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: object; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
body = ObjectSerializer.deserialize(body, "object");
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
} | the_stack |
require("source-map-support").install()
import { BatchCluster, Log, logger, setLogger } from "batch-cluster"
import fs from "fs"
import globule from "globule"
import os from "os"
import path from "path"
import process from "process"
import { compact, filterInPlace, times, uniq } from "../Array"
import { ExifTool } from "../ExifTool"
import { map, Maybe } from "../Maybe"
import { isNumber } from "../Number"
import { nullish } from "../ReadTask"
import { blank, isString, leftPad } from "../String"
import ProgressBar = require("progress")
// ☠☠ THIS IS GRISLY, NASTY CODE. SCROLL DOWN AT YOUR OWN PERIL ☠☠
// Avoid error TS2590: Expression produces a union type that is too complex to represent
const MAX_TAGS = 2500 // TypeScript 4.2 crashes with 3100+
// ☠☠ HEY! YOU! I SAID STOP SCROLLING! ☠☠
const RequiredTags: Record<string, { t: string; grp: string }> = {
ApertureValue: { t: "number", grp: "EXIF" },
AvgBitrate: { t: "string", grp: "Composite" },
BodySerialNumber: { t: "string", grp: "MakerNotes" },
BurstID: { t: "string", grp: "XMP" },
BurstUUID: { t: "string", grp: "MakerNotes" },
CameraID: { t: "string", grp: "MakerNotes" },
CameraOrientation: { t: "string", grp: "MakerNotes" },
CameraSerialNumber: { t: "number", grp: "APP1" },
"Caption-Abstract": { t: "string", grp: "IPTC" },
Compass: { t: "string", grp: "APP5" },
Copyright: { t: "string", grp: "EXIF" },
Country: { t: "string", grp: "XMP" },
CountryCode: { t: "string", grp: "XMP" },
CreateDate: { t: "ExifDateTime | string", grp: "EXIF" },
CreationTime: { t: "ExifDateTime | string", grp: "XMP" },
DateCreated: { t: "ExifDateTime | string", grp: "XMP" },
DateTime: { t: "ExifDateTime | string", grp: "XMP" },
DateTimeCreated: { t: "ExifDateTime | string", grp: "Composite" },
DateTimeDigitized: { t: "ExifDateTime | string", grp: "XMP" },
DateTimeGenerated: { t: "ExifDateTime | string", grp: "APP1" },
DateTimeOriginal: { t: "ExifDateTime | string", grp: "EXIF" },
DateTimeUTC: { t: "ExifDateTime | string", grp: "MakerNotes" },
Description: { t: "string", grp: "XMP" },
Error: { t: "string", grp: "ExifTool" },
ExifImageHeight: { t: "number", grp: "EXIF" },
ExifImageWidth: { t: "number", grp: "EXIF" },
ExposureTime: { t: "string", grp: "EXIF" },
FileName: { t: "string", grp: "File" },
FileSize: { t: "string", grp: "File" },
FileType: { t: "string", grp: "File" },
FileTypeExtension: { t: "string", grp: "File" },
FNumber: { t: "number", grp: "EXIF" },
Fnumber: { t: "string", grp: "APP12" },
FocalLength: { t: "string", grp: "EXIF" },
GPSAltitude: { t: "number", grp: "EXIF" },
GPSDateTime: { t: "ExifDateTime | string", grp: "Composite" },
GPSLatitude: { t: "number", grp: "EXIF" },
GPSLongitude: { t: "number", grp: "EXIF" },
History: { t: "ResourceEvent[] | ResourceEvent | string", grp: "XMP" },
ImageDescription: { t: "string", grp: "EXIF" },
ImageHeight: { t: "number", grp: "File" },
ImageNumber: { t: "number", grp: "XMP" },
ImageSize: { t: "string", grp: "Composite" },
ImageWidth: { t: "number", grp: "File" },
InternalSerialNumber: { t: "string", grp: "MakerNotes" },
ISO: { t: "number", grp: "EXIF" },
ISOSpeed: { t: "number", grp: "EXIF" },
Keywords: { t: "string | string[]", grp: "IPTC" },
Lens: { t: "string", grp: "Composite" },
LensID: { t: "string", grp: "Composite" },
LensInfo: { t: "string", grp: "EXIF" },
LensMake: { t: "string", grp: "EXIF" },
LensModel: { t: "string", grp: "EXIF" },
LensSerialNumber: { t: "string", grp: "EXIF" },
LensSpec: { t: "string", grp: "MakerNotes" },
LensType: { t: "string", grp: "MakerNotes" },
LensType2: { t: "string", grp: "MakerNotes" },
LensType3: { t: "string", grp: "MakerNotes" },
Make: { t: "string", grp: "EXIF" },
MaxDataRate: { t: "string", grp: "RIFF" },
MediaCreateDate: { t: "ExifDateTime | string", grp: "QuickTime" },
Megapixels: { t: "number", grp: "Composite" },
MetadataDate: { t: "ExifDateTime | string", grp: "XMP" },
MIMEType: { t: "string", grp: "File" },
Model: { t: "string", grp: "EXIF" },
ModifyDate: { t: "ExifDateTime | string", grp: "EXIF" },
ObjectName: { t: "string", grp: "IPTC" },
Orientation: { t: "number", grp: "EXIF" },
OriginalCreateDateTime: { t: "ExifDateTime | string", grp: "XMP" },
Rating: { t: "number", grp: "XMP" },
RegistryID: { t: "Struct[]", grp: "XMP" },
Rotation: { t: "number", grp: "Composite" },
RunTimeValue: { t: "number", grp: "MakerNotes" },
SerialNumber: { t: "string", grp: "MakerNotes" },
ShutterCount: { t: "number", grp: "MakerNotes" },
ShutterCount2: { t: "number", grp: "MakerNotes" },
ShutterCount3: { t: "number", grp: "MakerNotes" },
ShutterSpeed: { t: "string", grp: "Composite" },
SonyExposureTime: { t: "string", grp: "MakerNotes" },
SonyFNumber: { t: "number", grp: "MakerNotes" },
SonyISO: { t: "number", grp: "MakerNotes" },
SubSecCreateDate: { t: "ExifDateTime | string", grp: "Composite" },
SubSecDateTimeOriginal: { t: "ExifDateTime | string", grp: "Composite" },
SubSecMediaCreateDate: { t: "ExifDateTime | string", grp: "Composite" },
SubSecTime: { t: "number", grp: "EXIF" },
SubSecTimeDigitized: { t: "number", grp: "EXIF" },
TimeZone: { t: "string", grp: "MakerNotes" },
TimeZoneOffset: { t: "number | string", grp: "EXIF" },
Title: { t: "string", grp: "XMP" },
Versions: { t: "Version[] | Version | string", grp: "XMP" },
Warning: { t: "string", grp: "ExifTool" },
XPComment: { t: "string", grp: "EXIF" },
XPKeywords: { t: "string", grp: "EXIF" },
XPSubject: { t: "string", grp: "EXIF" },
XPTitle: { t: "string", grp: "EXIF" },
}
// ☠☠ NO REALLY THIS IS BAD CODE PLEASE STOP SCROLLING ☠☠
// If we don't do tag pruning, TypeScript fails with
// error TS2590: Expression produces a union type that is too complex to represent.
// This is a set of regexp patterns that match tags that are (probably)
// ignorable:
const ExcludedTagRe = new RegExp(
[
"_",
"A[ab]{3,}",
"AEC",
"AFR",
"AFS",
"AFStatus_",
"AFTrace",
"AFV",
"ASF\\d",
"AtmosphericTrans",
"AWB",
"CAM\\d",
"CameraTemperature",
"ChroSupC",
"DayltConv",
"DefConv",
"DefCor",
"Face\\d",
"FCS\\d",
"HJR",
"IM[a-z]",
"IncandConv",
"Kelvin_?WB",
"Label\\d",
"Value\\d",
"Mask_",
"MODE",
"MTR",
"O[a-f]+Revision",
"PF\\d\\d",
"PictureWizard",
"PiP",
"Planck",
"PF\\d",
"R2[A-Z]",
"STB\\d",
"Tag[\\d_]+",
"TL84",
"WB[_\\d]",
"YhiY",
"\\w{6,}\\d{1,2}$",
].join("|")
)
function sortBy<T>(
arr: T[],
f: (t: T, index: number) => Maybe<string | number>
): T[] {
return (
arr
.filter((ea) => ea != null)
.map((item, idx) => ({
item,
cmp: map(f(item, idx), (ea) => [ea, idx]),
}))
.filter((ea) => ea.cmp != null)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.sort((a, b) => cmp(a.cmp!, b.cmp!))
.map((ea) => ea.item)
)
}
// Benchmark on 3900X: 53s for 10778 files with defaults
// 23s for 10778 files with these overrides:
const exiftool = new ExifTool({
maxProcs: os.cpus().length,
// if we use straight defaults, we're load-testing those defaults.
streamFlushMillis: 2,
minDelayBetweenSpawnMillis: 0,
// maxTasksPerProcess: 100, // < uncomment to verify proc wearing works
})
function ellipsize(str: string, max: number) {
str = "" + str
return str.length < max ? str : str.substring(0, max - 1) + "…"
}
// ☠☠ NO SRSLY STOP SCROLLING IT REALLY IS BAD ☠☠
setLogger(
Log.withLevels(
Log.withTimestamps(
Log.filterLevels(
{
trace: console.log,
debug: console.log,
info: console.log,
warn: console.warn,
error: console.error,
},
(process.env.LOG as any) ?? "info"
)
)
)
)
process.on("uncaughtException", (error: any) => {
console.error("Ack, caught uncaughtException: " + error.stack)
})
process.on("unhandledRejection", (reason: any) => {
console.error(
"Ack, caught unhandledRejection: " + (reason.stack ?? reason.toString)
)
})
function usage() {
console.log("Usage: `yarn run mktags IMG_DIR`")
console.log("\nRebuilds src/Tags.ts from tags found in IMG_DIR.")
// eslint-disable-next-line no-process-exit
process.exit(1)
}
function cmp(a: any, b: any): number {
return a > b ? 1 : a < b ? -1 : 0
}
const roots = process.argv.slice(2)
if (roots.length === 0)
throw new Error("USAGE: mktags <path to image directory>")
const pattern = "**/*.+(3fr|avi|jpg|mov|mp4|cr2|cr3|nef|orf|raf|arw|rw2|dng)"
const files = roots
.map((root) => {
logger().info("Scanning " + root + "/" + pattern + "...")
return globule.find(pattern, {
srcBase: root,
nocase: true,
nodir: true,
absolute: true,
})
})
.reduce((prev, curr) => prev.concat(curr))
if (files.length === 0) {
console.error(`No files found in ${roots}`)
usage()
}
logger().info("Found " + files.length + " files...", files.slice(0, 7))
function valueType(value: any): Maybe<string> {
if (value == null) return
if (Array.isArray(value)) {
const types = uniq(compact(value.map((ea) => valueType(ea))))
return (types.length === 1 ? types[0] : "any") + "[]"
}
if (typeof value === "object") {
const ctor = value.constructor.name
if (ctor === "Object") {
return "Struct"
}
if (ctor.startsWith("ExifDate") || ctor.startsWith("ExifTime")) {
return ctor + " | string"
}
return ctor
} else {
return typeof value
}
}
// except CountingMap. Isn't it cute? Not ashamed of you, little guy!
class CountingMap<T> {
private size = 0
private readonly m = new Map<T, number>()
add(...arr: T[]) {
this.size += arr.length
for (const ea of arr) {
this.m.set(ea, 1 + (this.m.get(ea) ?? 0))
}
}
byCountDesc(): T[] {
return Array.from(this.m.keys()).sort((a, b) =>
cmp(this.m.get(b), this.m.get(a))
)
}
topN(n: number) {
return this.byCountDesc().slice(0, n)
}
/**
* @param p [0,1]
* @return the values found in the top p of values
*/
byP(p: number): T[] {
const min = p * this.size
return this.byCountDesc().filter((ea) => (this.m.get(ea) ?? 0) > min)
}
}
function sigFigs(i: number, digits: number): number {
if (i === 0 || digits === 0) return 0
const pow = Math.pow(
10,
digits - Math.round(Math.ceil(Math.log10(Math.abs(i))))
)
return Math.round(i * pow) / pow
}
function toStr(o: any): any {
if (o == null) return ""
if (isString(o)) return `"${ellipsize(o, 65)}"`
else if (o["toISOString"] != null) return o.toISOString()
else if (isNumber(o)) return sigFigs(o, 8)
else return ellipsize(JSON.stringify(o), 65)
}
function exampleToS(examples: any[]): string {
return examples.length > 1
? "Examples: " + toStr(examples)
: "Example: " + toStr(examples[0])
}
function getOrSet<K, V>(m: Map<K, V>, k: K, valueThunk: () => V): V {
const prior = m.get(k)
if (prior != null) {
return prior
} else {
const v = valueThunk()
m.set(k, v)
return v
}
}
class Tag {
values: any[] = []
important = false
constructor(readonly tag: string) {}
toString() {
return JSON.stringify(this.toJSON())
}
toJSON() {
return {
group: this.group,
base: this.base,
important: this.important,
valueTypes: this.valueTypes,
values: [...new Set(this.values)].slice(0, 3),
}
}
get group(): string {
return this.tag.split(":")[0] ?? this.tag
}
get base(): string {
return this.tag.split(":")[1] ?? this.tag
}
get valueTypes(): string[] {
const cm = new CountingMap<string>()
compact(this.values)
.map((ea) => valueType(ea))
.forEach((ea) => {
if (!nullish(ea)) cm.add(ea)
})
return cm.byP(0.5).sort()
}
get valueType(): string {
return (
RequiredTags[this.base as any]?.t ??
(this.valueTypes.length === 0 ? "string" : this.valueTypes.join(" | "))
)
}
get sortBy() {
return (
-(this.required ? 1e8 : this.important ? 1e4 : 1) * this.values.length
)
}
get required() {
return this.base in RequiredTags
}
vacuumValues() {
return filterInPlace(this.values, (ea) => !nullish(ea))
}
keep(minValues: number): boolean {
this.vacuumValues()
// If it's a tag from an "important" camera, always include the tag.
// Otherwise, if we never get a valid value for the tag, skip it.
return (
this.required ||
(!blank(this.valueType) &&
(this.important || this.values.length >= minValues))
)
}
popIcon(totalValues: number): string {
const f = this.values.length / totalValues
// kid: dad srsly stop with the emojicode no one likes it
// dad: ur not the boss of me
// As of 20180814, 4300 unique tags, 2713 of which were found in at least 2
// cameras, and only 700 were found in at least 1% of cameras, so this looks
// like a power law, long-tail distribution, so lets make the cutoffs more
// exponentialish rather than linearish.
// 22 at 99%, 64 at 50%, 87 at 25%, 120 at 10%, 230 at 5%, so if we make the
// four star cutoff too high, nothing will have four stars.
// Read 4311 unique tags from 6526 files.
// missing files:
// Parsing took 20075ms (3.1ms / file)
// Distribution of tags:
// 0%: 2714:#################################
// 1%: 700:########
// 2%: 389:####
// 3%: 323:###
// 4%: 265:###
// 5%: 236:##
// 6%: 207:##
// 7%: 188:##
// 8%: 173:##
// 9%: 142:#
// 10%: 130:#
// 11%: 125:#
// 12%: 118:#
// 13%: 108:#
// 14%: 103:#
// 15%: 102:#
// 16%: 101:#
// 17%: 96:#
// 18%: 93:#
// 19%: 92:#
// 20%: 91:#
// 21%: 90:#
// 22%: 89:#
// 23%: 88:#
// 24%: 86:#
// 25%: 85:#
// 26%: 81:
// 27%: 80:
// 28%: 80:
// 29%: 79:
// 30%: 77:
// 31%: 76:
// 32%: 75:
// 33%: 75:
// 34%: 74:
// 35%: 74:
// 36%: 72:
// 37%: 71:
// 38%: 70:
// 39%: 70:
// 40%: 70:
// 41%: 70:
const stars =
f > 0.5
? "★★★★"
: f > 0.2
? "★★★☆"
: f > 0.1
? "★★☆☆"
: f > 0.05
? "★☆☆☆"
: "☆☆☆☆"
const important = this.important ? "✔" : " "
return `${stars} ${important}`
}
example(): string {
// There are a bunch of tag values that have people's actual names or
// contact information. Replace those values with stub values:
if (this.tag.endsWith("GPSLatitude")) return exampleToS([48.8577484])
if (this.tag.endsWith("GPSLongitude")) return exampleToS([2.2918888])
if (this.tag.endsWith("Comment")) return exampleToS(["This is a comment."])
if (this.tag.endsWith("Directory"))
return exampleToS(["/home/username/pictures"])
if (this.tag.endsWith("Copyright"))
return exampleToS(["© Chuckles McSnortypants, Inc."])
if (this.tag.endsWith("CopyrightNotice"))
return exampleToS(["Creative Commons Attribution 4.0 International"])
if (this.tag.endsWith("OwnerName")) return exampleToS(["Itsa Myowna"])
if (this.tag.endsWith("Artist")) return exampleToS(["Arturo DeImage"])
if (this.tag.endsWith("Author")) return exampleToS(["Nom De Plume"])
if (this.tag.endsWith("Contact")) return exampleToS(["Donna Ringmanumba"])
if (this.tag.endsWith("Software") || this.tag.endsWith("URL"))
return exampleToS(["https://PhotoStructure.com/"])
if (this.tag.endsWith("Credit"))
return exampleToS(["photo by Jenny Snapsalot"])
const byValueType = new Map<string, any[]>()
// Shove boring values to the end:
this.vacuumValues()
uniq(this.values)
.sort()
.reverse()
.forEach((ea) => {
getOrSet(byValueType, valueType(ea), () => []).push(ea)
})
// If there are multiple types, try to show one of each type:
return exampleToS(
this.valueTypes
.map((key) => map(byValueType.get(key), (ea) => ea[0]))
.filter((ea) => !nullish(ea))
)
}
}
// const minOccurrences = 2
class TagMap {
readonly map = new Map<string, Tag>()
private maxValueCount = 0
private _finished = false
groupedTags = new Map<string, Tag[]>()
readonly tags: Tag[] = []
constructor() {
// Seed with required tags
for (const ea of Object.entries(RequiredTags)) {
this.tag(ea[1].grp + ":" + ea[0])
}
}
tag(tag: string) {
const prevTag = this.map.get(tag)
if (prevTag != null) {
return prevTag
} else {
const t = new Tag(tag)
this.map.set(tag, t)
return t
}
}
add(tagName: string, value: any, important: boolean) {
if (
tagName == null ||
value == null ||
tagName.match(ExcludedTagRe) != null
) {
return
}
const tag = this.tag(tagName)
if (important) {
tag.important = true
}
if (value != null) {
const values = tag.values
values.push(value)
this.maxValueCount = Math.max(values.length, this.maxValueCount)
}
}
finish() {
if (this._finished) return
this._finished = true
this.tags.length = 0
const arr = [...this.map.values()]
this.tags.push(...arr.filter((ea) => ea.required))
console.log("TagMap.finish(): required tag count:" + this.tags.length)
const optional = sortBy(
arr.filter((ea) => !ea.required && ea.keep(2)),
(ea) => ea.sortBy
)
this.tags.push(...optional.slice(0, MAX_TAGS - this.tags.length))
console.log(
"TagMap.finish(): final tag count:" +
this.tags.length +
" from " +
arr.length +
" raw tags."
)
// console.log(
// `Skipping the following tags due to < ${minOccurrences} occurrences:`
// )
// console.log(
// allTags
// .filter((a) => !a.keep(minOccurrences))
// .map((t) => t.tag)
// .join(", ")
// )
this.groupedTags.clear()
this.tags.forEach((tag) => {
getOrSet(this.groupedTags, tag.group, () => []).push(tag)
})
}
}
const tagMap = new TagMap()
const saneTagRe = /^[a-z0-9_]+:[a-z0-9_]+$/i
const bar = new ProgressBar(
"reading tags [:bar] :current/:total files, :tasks pending @ :rate files/sec w/:procs procs :etas",
{
complete: "=",
incomplete: " ",
width: 40,
total: files.length,
renderThrottle: 100,
}
)
let nextTick = Date.now()
let ticks = 0
const failedFiles: string[] = []
const seenFiles: string[] = []
async function readAndAddToTagMap(file: string) {
try {
if (file.includes("metadesert")) return
const tags: any = await exiftool.read(file, ["-G"])
seenFiles.push(file)
const importantFile = file.toString().toLowerCase().includes("important")
Object.keys(tags).forEach((key) => {
if (null != saneTagRe.exec(key)) {
tagMap.add(key, tags[key], importantFile)
}
})
if (tags.errors?.length > 0) {
bar.interrupt(`Error from ${file}: ${tags.errors}`)
}
} catch (err) {
bar.interrupt(`Error from ${file}: ${err}`)
failedFiles.push(file)
}
ticks++
if (nextTick <= Date.now()) {
nextTick = Date.now() + 50
bar.tick(ticks, {
tasks: exiftool.pendingTasks,
procs: exiftool.busyProcs,
})
ticks = 0
}
return
}
const start = Date.now()
process.on("unhandledRejection", (reason: any) => {
console.error(
"Ack, caught unhandled rejection: " + (reason.stack ?? reason.toString)
)
})
function escapeKey(s: string): string {
return s.match(/[^0-9a-z_]/i) != null ? JSON.stringify(s) : s
}
Promise.all(files.map((file) => readAndAddToTagMap(file)))
.then(async () => {
bar.terminate()
tagMap.finish()
console.log(
`\nRead ${tagMap.map.size} unique tags from ${seenFiles.length} files.`
)
const missingFiles = files.filter((ea) => seenFiles.indexOf(ea) === -1)
console.log("missing files: " + missingFiles.join("\n"))
const elapsedMs = Date.now() - start
console.log(
`Parsing took ${elapsedMs}ms (${(elapsedMs / files.length).toFixed(
1
)}ms / file)`
)
const version = await exiftool.version()
const destFile = path.resolve(__dirname, "../../src/Tags.ts")
const tagWriter = fs.createWriteStream(destFile)
tagWriter.write(
[
'import { ApplicationRecordTags } from "./ApplicationRecordTags"',
'import { ExifDate } from "./ExifDate"',
'import { ExifDateTime } from "./ExifDateTime"',
'import { ExifTime } from "./ExifTime"',
'import { ICCProfileTags } from "./ICCProfileTags"',
'import { ResourceEvent } from "./ResourceEvent"',
'import { Struct } from "./Struct"',
'import { Version } from "./Version"',
"",
"/* eslint-disable @typescript-eslint/no-explicit-any */",
"",
].join("\n")
)
const groupedTags = tagMap.groupedTags
const tagGroups: string[] = []
const seenTagNames = new Set<string>()
// Pick from the "APP###" groups last.
const DesiredOrder = [
"exiftool",
"file",
"composite",
"exif",
"iptc",
"jfif",
"makernotes",
"xmp",
]
const unsortedGroupNames = [...groupedTags.keys()].sort()
const groupNames = sortBy(unsortedGroupNames, (ea, index) => {
const indexOf = DesiredOrder.indexOf(ea.toLowerCase())
return indexOf >= 0 ? indexOf : index + unsortedGroupNames.length
})
for (const group of groupNames) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const tagsForGroup = groupedTags.get(group)!
const filteredTags = sortBy(tagsForGroup, (ea) => ea.tag)
// First group with a tag name wins. Other group's colliding tag names
// are omitted:
.filter((tag) => !seenTagNames.has(tag.base))
if (filteredTags.length > 0) {
tagGroups.push(group)
tagWriter.write(`\nexport interface ${group}Tags {\n`)
for (const tag of filteredTags) {
tagWriter.write(
` /** ${tag.popIcon(files.length)} ${tag.example()} */\n`
)
tagWriter.write(` ${escapeKey(tag.base)}?: ${tag.valueType}\n`)
seenTagNames.add(tag.base)
}
tagWriter.write(`}\n`)
}
}
const interfaceNames = [
...tagGroups.map((s) => s + "Tags"),
"ApplicationRecordTags",
"ICCProfileTags",
].sort()
tagWriter.write(
[
"",
`/**`,
` * This is a partial list of fields returned by {@link ExifTool.read}.`,
` *`,
` * To prevent error TS2590: (Expression produces a union type that is too`,
` * complex to represent) only the most common 2874 tags are retained in this`,
` * interface.`,
` *`,
` * Comments by each tag include popularity (★★★★ is found in > 50% of samples,`,
` * and ☆☆☆☆ is rare), followed by a checkmark if the tag is used by popular`,
` * devices (like iPhones) An example value, JSON stringified, follows the`,
` * popularity ratings.`,
` *`,
` * Autogenerated by "yarn mktags" by ExifTool ${version} on ${new Date().toDateString()}.`,
` * ${tagMap.map.size} unique tags were found in ${files.length} photo and video files.`,
` */`,
"export interface Tags",
` extends ${interfaceNames.join(",\n ")} {`,
" errors?: string[]",
` /** ☆☆☆☆ ✔ Example: "File is empty" */`,
" Error?: string",
` /** ☆☆☆☆ ✔ Example: "Unrecognized IPTC record 0 (ignored)" */`,
" Warning?: string",
" SourceFile?: string",
" /** Either an offset, like `UTC-7`, or an actual timezone, like `America/Los_Angeles` */",
" tz?: string",
" /** Description of where and how `tz` was extracted */",
" tzSource?: string",
"}",
"",
].join("\n")
)
tagWriter.end()
// Let's look at tag distributions:
const tags = tagMap.tags
const tagsByPctPop = times(
25,
(pct) =>
tags.filter((tag) => tag.values.length / files.length > pct / 100.0)
.length
)
const scale = 80 / files.length
console.log("Distribution of tags: \n")
tagsByPctPop.forEach((cnt, pct) =>
console.log(
leftPad(pct, 2, " ") +
"%: " +
leftPad(cnt, 4, " ") +
":" +
times(Math.floor(cnt * scale), () => "#").join("")
)
)
await exiftool.end()
const bc: BatchCluster = exiftool["batchCluster"]
console.log("Final batch cluster stats", bc.stats())
return
})
.catch((err) => {
console.error(err)
}) | the_stack |
///<reference path="./typings/bundle.d.ts"/>
export namespace gcode {
export class Motion {
type: string;
prevMotion: Motion;
x: number = 0;
y: number = 0;
z: number = 0;
// mm/min
feedRate: number;
constructor(prevMotion: Motion) {
this.prevMotion = prevMotion;
}
get distance():number {
if (!this.prevMotion) {
return 0;
}
var x = this.prevMotion.x - this.x;
var y = this.prevMotion.y - this.y;
var z = this.prevMotion.z - this.z;
return Math.sqrt(x * x + y * y + z * z);
}
// return second
get duration():number {
var distance = this.distance;
if (distance) {
return this.distance / this.feedRate * 60;
} else {
return 0;
}
}
}
export class Context {
prevState: State;
state: State;
code: Code;
motions: Array<Motion>;
blockSub: Function;
rapidFeedRate: number;
get lastMotion():Motion {
if (this.motions.length) {
return this.motions[ this.motions.length - 1];
} else {
return null;
}
}
handlers: { [letter: string]: Function } = {
'F' : () => {
this.state.set(States.F, this.code.value);
},
'G' : () => {
var handler = this.handlers[this.code.name];
if (!handler) {
console.log('unsupported G-code ' + this.code.name);
return;
}
handler();
},
'G0' : () => {
this.state.set(States.MOTION, MotionMode.G0);
this.blockSub = () => {
this.drawLine(
"G0",
this.lastMotion.x,
this.lastMotion.y,
this.lastMotion.z,
this.state.get(States.X),
this.state.get(States.Y),
this.state.get(States.Z),
this.rapidFeedRate || Infinity
);
};
},
'G1' : () => {
this.state.set(States.MOTION, MotionMode.G1);
this.blockSub = () => {
this.drawLine(
"G1",
this.lastMotion.x,
this.lastMotion.y,
this.lastMotion.z,
this.state.get(States.X),
this.state.get(States.Y),
this.state.get(States.Z),
this.state.get(States.F)
);
};
},
'G2' : () => {
this.state.set(States.MOTION, MotionMode.G2);
this.blockSub = () => {
this.drawArc(
"G2",
this.state.get(States.PLANE),
this.lastMotion.x,
this.lastMotion.y,
this.lastMotion.z,
this.state.get(States.X),
this.state.get(States.Y),
this.state.get(States.Z),
this.state.get(States.I),
this.state.get(States.J),
this.state.get(States.K),
this.state.get(States.R),
this.state.get(States.F)
);
};
},
'G3' : () => {
this.state.set(States.MOTION, MotionMode.G3);
this.blockSub = () => {
this.drawArc(
"G3",
this.state.get(States.PLANE),
this.lastMotion.x,
this.lastMotion.y,
this.lastMotion.z,
this.state.get(States.X),
this.state.get(States.Y),
this.state.get(States.Z),
this.state.get(States.I),
this.state.get(States.J),
this.state.get(States.K),
this.state.get(States.R),
this.state.get(States.F)
);
};
},
'G4' : () => {
this.blockSub = () => {
var sleep = 0;
var P = this.state.get(States.P);
if (P) {
sleep = P * 1000;
} else {
sleep = this.state.get(States.X);
}
console.log('sleep', sleep);
}
},
'G10' : () => {
this.blockSub = () => {};
},
'G17' : () => {
this.state.set(States.PLANE, PlaneMode.XY);
},
'G18' : () => {
this.state.set(States.PLANE, PlaneMode.XZ);
},
'G19' : () => {
this.state.set(States.PLANE, PlaneMode.YZ);
},
'G20' : () => {
// throw "does not support inch";
this.state.set(States.UNIT_MODE, UnitMode.INCH);
this.blockSub = () => {};
},
'G21' : () => {
this.state.set(States.UNIT_MODE, UnitMode.MM);
this.blockSub = () => {};
},
'G28' : () => {
this.blockSub = () => {};
},
'G28.1' : () => {
this.blockSub = () => {};
},
'G30' : () => {
this.blockSub = () => {};
},
'G38.1' : () => {
this.blockSub = () => {};
},
'G38.2' : () => {
this.blockSub = () => {};
},
'G38.3' : () => {
this.blockSub = () => {};
},
'G38.4' : () => {
this.blockSub = () => {};
},
'G38.5' : () => {
this.blockSub = () => {};
},
'G40' : () => {
this.blockSub = () => {};
},
'G43.1' : () => {
this.blockSub = () => {};
},
'G49' : () => {
this.blockSub = () => {};
},
'G53' : () => {
this.blockSub = () => {};
},
'G54' : () => {
this.blockSub = () => {};
},
'G55' : () => {
this.blockSub = () => {};
},
'G56' : () => {
this.blockSub = () => {};
},
'G57' : () => {
this.blockSub = () => {};
},
'G58' : () => {
this.blockSub = () => {};
},
'G59' : () => {
this.blockSub = () => {};
},
'G61' : () => {
this.blockSub = () => {};
},
'G80' : () => {
this.state.set(States.MOTION, MotionMode.UNDEFINED);
this.blockSub = () => {};
},
'G90' : () => {
this.state.set(States.DISTANCE_MODE, DistanceMode.ABSOLUTE);
},
'G91' : () => {
this.state.set(States.DISTANCE_MODE, DistanceMode.RELATIVE);
},
'G91.1' : () => {
this.blockSub = () => {};
},
'G92' : () => {
this.blockSub = () => {};
},
'G92.1' : () => {
this.blockSub = () => {};
},
'G93' : () => {
// TODO not supported yet
this.state.set(States.FEED_RATE_MODE, FeedRateMode.INVERSE_TIME);
},
'G94' : () => {
this.state.set(States.FEED_RATE_MODE, FeedRateMode.UNITS_PER_MINUTE);
},
'I' : () => {
this.state.setLengthValue(States.I, this.code.value);
},
'J' : () => {
this.state.setLengthValue(States.J, this.code.value);
},
'K' : () => {
this.state.setLengthValue(States.K, this.code.value);
},
'M' : () => {
var handler = this.handlers[this.code.name];
if (!handler) {
console.log('unsupported M-code ' + this.code.name);
return;
}
handler();
},
'M0' : () => {
this.blockSub = () => {};
},
'M1' : () => {
this.blockSub = () => {};
},
'M2' : () => {
this.blockSub = () => {};
},
'M3' : () => {
this.blockSub = () => {};
},
'M4' : () => {
this.blockSub = () => {};
},
'M5' : () => {
this.blockSub = () => {};
},
'M6' : () => {
this.blockSub = () => {};
},
'M7' : () => {
this.blockSub = () => {};
},
'M8' : () => {
this.blockSub = () => {};
},
'M9' : () => {
this.blockSub = () => {};
},
'M10' : () => {
this.blockSub = () => {};
},
'M11' : () => {
this.blockSub = () => {};
},
'M30' : () => {
this.blockSub = () => {};
},
'N' : () => {
this.state.set(States.LINE_NUMBER, this.code.value);
},
'P' : () => {
this.state.set(States.P, this.code.value);
},
'R' : () => {
this.state.setLengthValue(States.R, this.code.value);
},
'S' : () => {
this.state.set(States.S, this.code.value);
},
'T' : () => {
this.state.set(States.T, this.code.value);
},
'X' : () => {
this.state.setAxisValue(States.X, this.code.value);
},
'Y' : () => {
this.state.setAxisValue(States.Y, this.code.value);
},
'Z' : () => {
this.state.setAxisValue(States.Z, this.code.value);
},
};
constructor() {
this.state = new State(null);
this.motions = [ new Motion(null) ];
}
executeBlock(block: Block):Array<Motion> {
var motionIndex = this.motions.length;
this.prevState = this.state;
this.state = new State(this.prevState);
this.blockSub = null;
for (let i = 0, it: Code; (it = block.codes[i]); i++) {
var handler = this.handlers[it.letter];
if (!handler) {
console.log('warning ' + it.letter + ' handler is missing');
continue;
}
this.code = it;
handler();
}
// implicit move
if (!this.blockSub) {
var implicitHandler = this.handlers[this.state.get(States.MOTION)];
if (implicitHandler) {
implicitHandler();
}
}
if (this.blockSub) {
this.blockSub();
this.blockSub = null;
}
this.state.clearModeless();
return this.motions.slice(motionIndex);
}
drawLine(
type: string,
x1:number, y1:number, z1:number,
x2:number, y2:number, z2:number,
feedRate: number
) {
var line = new Motion(this.lastMotion);
line.type = type;
line.x = x2;
line.y = y2;
line.z = z2;
line.feedRate = feedRate;
this.motions.push(line);
}
drawArc(
type: string,
plain: PlaneMode,
x1:number, y1:number, z1:number,
x2:number, y2:number, z2:number,
xOffset:number, yOffset:number, zOffset:number,
radius:number,
feedRate: number
) {
var isClockWise = type === 'G2';
var drawLine : ( type: string, x1:number, y1:number, z1:number, x2:number, y2:number, z2:number, feedRate: number )=> void;
if (plain === PlaneMode.XZ) {
[x1, y1, z1] = [x1, z1, y1];
[x2, y2, z2] = [x2, z2, y2];
[xOffset, yOffset, zOffset] = [xOffset, zOffset, yOffset];
drawLine = (type, xx, yy, zz, x, y, z, feedRate) => {
this.drawLine( type, xx, zz, yy, x, z, y, feedRate );
};
} else
if (plain === PlaneMode.YZ) {
[x1, y1, z1] = [y1, z1, x1];
[x2, y2, z2] = [y2, z2, x2];
[xOffset, yOffset, zOffset] = [yOffset, zOffset, xOffset];
drawLine = (type, xx, yy, zz, x, y, z, feedRate) => {
this.drawLine( type, zz, xx, yy, z, x, y, feedRate );
};
} else {
// PlaneMode.XY
drawLine = (type, xx, yy, zz, x, y, z, feedRate) => {
this.drawLine( type, xx, yy, zz, x, y, z, feedRate );
};
}
if (radius) {
var x = x2 - x1;
var y = y2 - y1;
// calculate offset
var distance = Math.sqrt(x * x + y * y);
var height = Math.sqrt(4 * radius * radius - x * x - y * y) / 2;
if (isClockWise) {
height = -height;
}
if (radius < 0) {
height = -height;
}
xOffset = x / 2 - y / distance * height;
yOffset = y / 2 + x / distance * height;
}
var centerX = x1 + xOffset;
var centerY = y1 + yOffset;
var radius = Math.sqrt(Math.pow(centerX - x1, 2) + Math.pow(centerY - y1, 2));
var angle1 = (Math.atan2( (y1 - centerY), (x1 - centerX) ) + Math.PI * 2) % (Math.PI * 2);
var angle2 = (Math.atan2( (y2 - centerY), (x2 - centerX) ) + Math.PI * 2) % (Math.PI * 2);
if (angle2 <= angle1) {
angle2 += Math.PI * 2;
}
// calculate ccw angle
var angleDelta = angle2 - angle1;
// and consider cw
if (isClockWise) {
angleDelta = -Math.PI * 2 + angleDelta;
}
var xx = x1, yy = y1, zz = z1;
for (let i = 0, points = 30; i < points; i++) {
let angle = angle1 + (angleDelta / points * i);
var x = Math.cos(angle) * radius + centerX;
var y = Math.sin(angle) * radius + centerY;
var z = (z2 - z1) / points * i + z1;
drawLine( type, xx, yy, zz, x, y, z, feedRate );
xx = x, yy = y, zz = z;
}
drawLine( type, xx, yy, zz, x2, y2, z2, feedRate );
}
}
enum States {
MOTION = <any>'MOTION',
UNIT_MODE = <any>'UNIT_MODE',
DISTANCE_MODE = <any>'DISTANCE_MODE',
LINE_NUMBER = <any>'LINE_NUMBER',
FEED_RATE_MODE = <any>'FEED_RATE_MODE',
PLANE = <any>'PLANE',
F = <any>'F',
I = <any>'I',
J = <any>'J',
K = <any>'K',
L = <any>'L',
N = <any>'N',
P = <any>'P',
R = <any>'R',
S = <any>'S',
T = <any>'T',
X = <any>'X',
Y = <any>'Y',
Z = <any>'Z',
}
enum MotionMode {
UNDEFINED = <any>'UNDEFINED',
G0 = <any>'G0',
G1 = <any>'G1',
G2 = <any>'G2',
G3 = <any>'G3',
}
enum UnitMode {
MM = <any>'MM',
INCH = <any>'INCH',
}
enum DistanceMode {
ABSOLUTE = <any>'ABSOLUTE',
RELATIVE = <any>'RELATIVE',
}
enum PlaneMode {
XY = <any>'XY',
XZ = <any>'XZ',
YZ = <any>'YZ',
}
enum FeedRateMode {
INVERSE_TIME = <any>'INVERSE_TIME',
UNITS_PER_MINUTE = <any>'UNITS_PER_MINUTE',
}
export class State {
_values : { [name: string]: any };
_updated : { [name: string]: boolean };
constructor(state: State) {
this._values = {};
if (state) {
// copy values
for (var key in state._values) if (state._values.hasOwnProperty(key)) {
this._values[key] = state._values[key];
}
} else {
this._values[States.I] = 0;
this._values[States.J] = 0;
this._values[States.K] = 0;
this._values[States.X] = 0;
this._values[States.Y] = 0;
this._values[States.Z] = 0;
this._values[States.MOTION] = MotionMode.UNDEFINED;
this._values[States.UNIT_MODE] = UnitMode.MM;
this._values[States.DISTANCE_MODE] = DistanceMode.ABSOLUTE;
this._values[States.PLANE] = PlaneMode.XY;
this._values[States.FEED_RATE_MODE] = FeedRateMode.UNITS_PER_MINUTE;
}
this._updated = {};
}
set(name: States, value: any) {
if (this._updated[name]) {
throw name + " is already updated";
}
this._values[name] = value;
this._updated[name] = true;
}
setAxisValue(name: States, value: number) {
if (this.get(States.DISTANCE_MODE) === DistanceMode.RELATIVE) {
value += this.get(name);
}
this.setLengthValue(name, value);
}
setLengthValue(name: States, value: number) {
if (this.get(States.UNIT_MODE) === UnitMode.INCH) {
value = value * 25.4;
}
this.set(name, value);
}
get(name: States):any {
return this._values[name];
}
clearModeless() {
delete this._values[States.P];
delete this._values[States.R];
}
}
export class Code {
letter: string;
value: number;
constructor(letter: string, value: number) {
this.letter = letter;
this.value = value;
}
get name():string {
return this.letter + String(this.value);
}
}
export class Block {
codes: Array<Code>;
static parse(str: string):Block {
str = str.replace(/\([^)]+\)/g, '');
str = str.replace(/;.*/g, '');
str = str.replace(/\s+/g, '');
str = str.replace(/%/g, '');
str = str.toUpperCase();
var block = new Block();
str = str.replace(/([A-Z])(-?[0-9.]+)/g, (_:string, letter: string, value: string) => {
block.addCode(new Code(letter, +value));
return '';
});
if (str) throw "unexpected token in this line: " + str;
return block;
}
constructor() {
this.codes = [];
}
addCode(code: Code) {
this.codes.push(code);
}
}
} | the_stack |
import {
AfterContentChecked,
AfterViewInit,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
HostBinding,
HostListener,
Input,
OnDestroy,
Output,
QueryList,
Renderer2,
RendererStyleFlags2,
TemplateRef,
ViewChild,
ViewChildren,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ButtonComponent } from '../button/button.component';
import { CardComponent } from '../card/card.component';
import { ItemComponent } from '../item/item.component';
import { ListItemTemplateDirective } from '../list/list.directive';
import { HorizontalDirection, PopoverComponent } from '../popover/popover.component';
import { OpenState, VerticalDirection } from './dropdown.types';
import { KeyboardHandlerService } from './keyboard-handler.service';
@Component({
selector: 'kirby-dropdown',
templateUrl: './dropdown.component.html',
styleUrls: ['./dropdown.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DropdownComponent),
multi: true,
},
],
})
export class DropdownComponent
implements AfterContentChecked, AfterViewInit, OnDestroy, ControlValueAccessor {
static readonly OPEN_DELAY_IN_MS = 100;
private state = OpenState.closed;
private hasConfiguredSlottedItems = false;
private horizontalDirection = HorizontalDirection.right;
private verticalDirection = VerticalDirection.down;
private _items: string[] | any[] = [];
get items(): string[] | any[] {
return this._items;
}
@Input() set items(value: string[] | any[]) {
this._items = value;
this._value = this.items[this.selectedIndex] || null;
}
private _selectedIndex: number = -1;
get selectedIndex(): number {
return this._selectedIndex;
}
@Input() set selectedIndex(value: number) {
if (this._selectedIndex != value) {
this._selectedIndex = value;
this._value = this.items[this.selectedIndex] || null;
}
}
@Input()
itemTextProperty = 'text';
@Input()
placeholder = 'Please select:';
@Input() set popout(direction: HorizontalDirection) {
this.horizontalDirection = direction || HorizontalDirection.right;
}
get popout() {
return this.horizontalDirection;
}
@Input()
attentionLevel: '1' | '2' | '3' | '4' = '3';
readonly attentionLevelOpen = '2';
@Input()
expand?: 'block';
@Input()
disabled = false;
@HostBinding('attr.disabled')
get _isDisabled() {
return this.disabled ? 'disabled' : null;
}
@HostBinding('class.error')
@Input()
hasError: boolean;
@Input()
size: 'sm' | 'md' = 'md';
@Input()
tabindex = 0;
@HostBinding('class.with-popover')
@Input()
usePopover = false;
@HostBinding('attr.tabindex')
get _tabindex() {
return this.disabled ? -1 : this.tabindex;
}
// Prevent Ionic blur on scroll
@HostBinding('attr.no-blur')
get _noBlurOnScroll() {
return true;
}
/**
* Emitted when an item is selected (tap on mobile, click/keypress on web)
*/
@Output() change: EventEmitter<string | any> = new EventEmitter<string | any>();
private _value: string | any = null;
get value(): string | any {
return this._value;
}
get selectedText(): string {
return this.getTextFromItem(this.value);
}
@HostBinding('class.expand')
get _isBlockLevel() {
return this.expand === 'block';
}
@HostBinding('attr.role')
_role = 'listbox';
@HostBinding('class.is-opening')
get _isOpening(): boolean {
return this.state === OpenState.opening;
}
@HostBinding('class.is-open')
get isOpen(): boolean {
return this.state === OpenState.open;
}
@HostBinding('class.popout-left')
get _popoutLeft() {
return this.horizontalDirection === HorizontalDirection.left;
}
@HostBinding('class.popout-up')
get _popoutUp() {
return this.verticalDirection === VerticalDirection.up;
}
@ContentChild(ListItemTemplateDirective, { static: true, read: TemplateRef })
itemTemplate: TemplateRef<any>;
@ContentChildren(ListItemTemplateDirective, { read: ElementRef })
slottedItems: QueryList<ElementRef<HTMLElement>>;
@ViewChild(CardComponent, { read: ElementRef })
cardElement: ElementRef<HTMLElement>;
@ViewChild(PopoverComponent)
popover?: PopoverComponent;
@ViewChild(ButtonComponent, { static: true, read: ElementRef })
buttonElement: ElementRef<HTMLElement>;
@ViewChildren(ItemComponent, { read: ElementRef })
kirbyItemsDefault: QueryList<ElementRef<HTMLElement>>;
@ContentChildren(ItemComponent, { read: ElementRef })
kirbyItemsSlotted: QueryList<ElementRef<HTMLElement>>;
private itemClickUnlisten: (() => void)[] = [];
private intersectionObserverRef: IntersectionObserver;
private showDropdownTimeoutId: ReturnType<typeof setTimeout>;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef<HTMLElement>,
private changeDetectorRef: ChangeDetectorRef,
private keyboardHandlerService: KeyboardHandlerService
) {}
onToggle(event: MouseEvent) {
event.stopPropagation();
if (!this.isOpen) {
this.elementRef.nativeElement.focus();
}
this.toggle();
}
toggle() {
if (this.disabled) {
return;
}
this.isOpen ? this.close() : this.open();
}
onButtonMouseEvent(event: Event) {
// Prevent button focus;
event.preventDefault();
}
ngAfterContentChecked() {
if (!this.hasConfiguredSlottedItems && this.kirbyItemsSlotted.length) {
this.kirbyItemsSlotted.forEach((kirbyItem, index) => {
this.renderer.setAttribute(kirbyItem.nativeElement, 'role', 'option');
const unlisten = this.renderer.listen(kirbyItem.nativeElement, 'click', () => {
this.onItemSelect(index);
});
this.itemClickUnlisten.push(unlisten);
});
this.hasConfiguredSlottedItems = true;
}
}
/* Utility that makes it easier to set styles on card element
when using popover*/
private setPopoverCardStyle(style: string, value: string) {
if (!this.usePopover) return;
this.renderer.setStyle(
this.cardElement.nativeElement,
style,
value,
RendererStyleFlags2.DashCase
);
}
ngAfterViewInit() {
if (this.usePopover && this.expand === 'block') {
const { width } = this.elementRef.nativeElement.getBoundingClientRect();
this.setPopoverCardStyle('--kirby-card-width', `${width}px`);
this.setPopoverCardStyle('max-width', 'initial');
this.setPopoverCardStyle('min-width', 'initial');
}
this.initializeAlignment();
}
private initializeAlignment() {
if (this.usePopover) return;
if (!this.intersectionObserverRef) {
const options = {
rootMargin: '0px',
};
const callback: IntersectionObserverCallback = (entries) => {
// Only apply alignment when opening:
if (this.state !== OpenState.opening) {
return;
}
// Cancel any pending timer to show dropdown:
clearTimeout(this.showDropdownTimeoutId);
const entry = entries[0];
const isVisible = entry.boundingClientRect.width > 0;
if (isVisible && entry.intersectionRatio < 1) {
this.setHorizontalDirection(entry);
this.setVerticalDirection(entry);
}
this.showDropdown();
this.changeDetectorRef.detectChanges();
};
this.intersectionObserverRef = new IntersectionObserver(callback, options);
this.intersectionObserverRef.observe(this.cardElement.nativeElement);
}
}
private setHorizontalDirection(entry: IntersectionObserverEntry) {
// If popout direction is set to right, and the entry is cut off to the right by ${entry.boundingClientRect.right - entry.intersectionRect.right}px
// it is set to popout left instead, and vice versa for popout direction left
if (this.horizontalDirection === HorizontalDirection.right) {
if (entry.boundingClientRect.right > entry.rootBounds.right) {
this.horizontalDirection = HorizontalDirection.left;
}
} else {
if (entry.boundingClientRect.left < entry.rootBounds.left) {
this.horizontalDirection = HorizontalDirection.right;
}
}
}
private setVerticalDirection(entry: IntersectionObserverEntry) {
if (entry.boundingClientRect.top < 0) {
// entry is cut off at the top by ${entry.boundingClientRect.top}px
// open downwards:
this.verticalDirection = VerticalDirection.down;
}
if (entry.boundingClientRect.bottom > entry.rootBounds.bottom) {
// entry is cut off at the bottom by ${entry.boundingClientRect.bottom - entry.intersectionRect.bottom}px
const containerOffsetTop = this.elementRef.nativeElement.getBoundingClientRect().top;
const SPACING = 5; //TODO: Get from SCSS
// Check if the card can fit on top of button:
if (containerOffsetTop > entry.target.clientHeight + SPACING) {
// open upwards:
this.verticalDirection = VerticalDirection.up;
}
}
}
open() {
if (this.disabled) {
return;
}
if (!this.isOpen) {
this.state = OpenState.opening;
// ensures that the dropdown is opened in case the IntersectionObserverCallback isn't invoked
this.showDropdownTimeoutId = setTimeout(
() => this.showDropdown(),
DropdownComponent.OPEN_DELAY_IN_MS
);
}
}
private showDropdown() {
if (this.state === OpenState.opening) {
this.state = OpenState.open;
this.popover?.show();
this.scrollItemIntoView(this.selectedIndex);
this.changeDetectorRef.markForCheck();
}
}
close() {
if (this.disabled) {
return;
}
if (this.isOpen) {
this.state = OpenState.closed;
// Reset vertical direction to default
this.verticalDirection = VerticalDirection.down;
this.popover?.hide();
}
}
onItemSelect(index: number) {
this.selectItem(index);
this.close();
}
private _onChange: (value: any) => void = () => {};
private _onTouched = () => {};
/**
* Sets the select's value. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param value New value to be written to the model.
*/
writeValue(value: any): void {
this._selectItemByValue(value);
}
/**
* Saves a callback function to be invoked when the select's value
* changes from user input. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the value changes.
*/
registerOnChange(fn: any): void {
this._onChange = fn;
}
/**
* Saves a callback function to be invoked when the select is blurred
* by the user. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the component has been touched.
*/
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
private selectItem(index: number) {
if (index != this.selectedIndex) {
this.selectedIndex = index;
this.change.emit(this.value);
this._onChange(this.value);
this.scrollItemIntoView(index);
}
}
private _selectItemByValue(value: string | any) {
this.selectedIndex = this.items.indexOf(value);
}
getTextFromItem(item: string | any) {
if (!item) {
return null;
}
return typeof item === 'string' ? item : item[this.itemTextProperty];
}
scrollItemIntoView(index: number) {
const kirbyItems =
this.kirbyItemsSlotted && this.kirbyItemsSlotted.length
? this.kirbyItemsSlotted
: this.kirbyItemsDefault;
if (kirbyItems && kirbyItems.length) {
const selectedKirbyItem = kirbyItems.toArray()[index];
if (selectedKirbyItem && selectedKirbyItem.nativeElement) {
const itemElement = selectedKirbyItem.nativeElement;
const scrollContainer = this.cardElement.nativeElement;
const itemTop = itemElement.offsetTop;
const itemBottom = itemElement.offsetTop + itemElement.offsetHeight;
const containerVisibleTop = scrollContainer.scrollTop;
const containerVisibleBottom = scrollContainer.clientHeight + scrollContainer.scrollTop;
if (itemTop < containerVisibleTop) {
scrollContainer.scrollTop = itemTop;
} else if (itemBottom > containerVisibleBottom) {
scrollContainer.scrollTop = itemBottom - scrollContainer.clientHeight;
}
}
}
}
@HostListener('keydown.tab', ['$event'])
_onTab(event: KeyboardEvent) {
if (this.isOpen) {
event.preventDefault();
this.close();
}
}
@HostListener('mousedown', ['$event'])
_onMouseDown(event: MouseEvent) {
if (this.disabled) {
event.preventDefault();
event.stopImmediatePropagation();
}
}
@HostListener('focus')
_onFocus() {
if (this.disabled) {
this.elementRef.nativeElement.blur();
}
}
_onPopoverWillHide() {
this.state = OpenState.closed;
this.elementRef.nativeElement.focus();
}
@HostListener('keydown.enter')
@HostListener('keydown.escape')
@HostListener('blur', ['$event'])
_onBlur(event?: FocusEvent) {
if (this.disabled) return;
if (this.isOpen) {
if (!this.cardElement.nativeElement.contains(event?.relatedTarget as HTMLElement)) {
this.close();
}
}
this._onTouched();
}
@HostListener('keydown.space', ['$event'])
_onSpace(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
if (!this.isOpen) {
this.open();
}
}
@HostListener('keydown.enter', ['$event'])
_onEnter(event: KeyboardEvent) {
event.preventDefault();
event.stopPropagation();
this.toggle();
}
@HostListener('keydown.arrowup', ['$event'])
@HostListener('keydown.arrowdown', ['$event'])
@HostListener('keydown.arrowleft', ['$event'])
@HostListener('keydown.arrowright', ['$event'])
_onArrowKeys(event: KeyboardEvent) {
if (this.disabled) return;
// Mirror default HTML5 select behaviour - prevent left/right arrows when open:
if (this.isOpen && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
return;
}
const newIndex = this.keyboardHandlerService.handle(event, this.items, this.selectedIndex);
if (newIndex > -1) {
this.selectItem(newIndex);
}
return false;
}
@HostListener('keydown.home', ['$event'])
@HostListener('keydown.end', ['$event'])
_onHomeEndKeys(event: KeyboardEvent) {
if (this.disabled) return;
const newIndex = this.keyboardHandlerService.handle(event, this.items, this.selectedIndex);
if (newIndex > -1) {
this.selectItem(newIndex);
}
return false;
}
ngOnDestroy(): void {
let unlisten: () => void;
while ((unlisten = this.itemClickUnlisten.pop()) !== undefined) {
unlisten();
}
if (this.intersectionObserverRef) {
this.intersectionObserverRef.disconnect();
}
}
} | the_stack |
import * as React from "react";
import pnp from "sp-pnp-js";
import { Web } from "sp-pnp-js";
import * as _ from "lodash";
import utils from "../../shared/utils";
import DisplayProp from "../../shared/DisplayProp";
import { SearchQuery, SearchResults } from "sp-pnp-js";
import { css } from "office-ui-fabric-react";
//import styles from "./PropertyBagDisplay.module.scss";
import { IPropertyBagDisplayProps } from "./IPropertyBagDisplayProps";
import { CommandBar } from "office-ui-fabric-react/lib/CommandBar";
import { Label } from "office-ui-fabric-react/lib/Label";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { Toggle } from "office-ui-fabric-react/lib/Toggle";
import { Button, ButtonType } from "office-ui-fabric-react/lib/Button";
import { MessageBar, MessageBarType } from "office-ui-fabric-react/lib/MessageBar";
import * as md from "../../shared/MessageDisplay";
import MessageDisplay from "../../shared/MessageDisplay";
import {
DetailsList, DetailsListLayoutMode, IColumn, IGroupedList, SelectionMode, CheckboxVisibility, IGroup
} from "office-ui-fabric-react/lib/DetailsList";
import {
GroupedList
} from "office-ui-fabric-react/lib/GroupedList";
import {
IViewport
} from "office-ui-fabric-react/lib/utilities/decorators/withViewport";
import {
Panel, PanelType
} from "office-ui-fabric-react/lib/Panel";
import { IContextualMenuItem, } from "office-ui-fabric-react/lib/ContextualMenu";
export interface IPropertyBagDisplayState {
selectedIndex: number; // the currently selected site
managedToCrawedMapping?: Array<ManagedToCrawledMappingEntry>;// Determines which Carwled propeties are mapped to which Managed Properties
errorMessages: Array<md.Message>; // a list of error massages displayed on the page
isediting?: boolean; //Determines if the edit panel is displayed
sites: Array<any>; // the list of sites displayed in the component
workingStorage?: DisplaySite;// A working copy of the site being edited
managedPropNames?: Array<string>; // the list of managed properties to be displayed
columns: Array<IColumn>; // the columns to show in the display
}
export class ManagedToCrawledMappingEntry {
constructor(
public crawledPropertyName: string,
public managedPropertyName: string,
) { }
}
export class DisplaySite {
/**
* Creates an instance of DisplaySite to be used in workingStorage when editing a site
* @param {string} Title
* @param {string} Url
* @param {string} SiteTemplate
* @param {Array<md.Message>} errorMessages
* @param {Array<DisplayProp>} [DisplayProps]
* @param {Array<string>} [searchableProps]
* @param {boolean} [forceCrawl]
*
* @memberOf DisplaySite
*/
constructor(
public Title: string,
public Url: string,
public SiteTemplate: string,
public errorMessages: Array<md.Message>,
public DisplayProps?: Array<DisplayProp>,
public searchableProps?: Array<string>,
public forceCrawl?: boolean,
) { }
}
export default class PropertyBagDisplay extends React.Component<IPropertyBagDisplayProps, IPropertyBagDisplayState> {
public constructor(props) {
super(props);
this.state = { sites: [], selectedIndex: -1, columns: [], errorMessages: [] };
}
/**Accessors */
/**
* Get's the commands to be displayed in the CommandBar. There is only one command (Edit).
* If no item is selected the command is disabled
*
*
* @readonly
* @type {Array<IContextualMenuItem>}
* @memberOf PropertyBagDisplay
*/
get CommandItems(): Array<IContextualMenuItem> {
return [
{
key: "Edit",
name: "Edit",
disabled: !(this.ItemIsSelected),
title: "Edit",
onClick: this.onEditItemClicked.bind(this),
icon: "Edit",
}];
};
get ItemIsSelected(): boolean {
if (!this.state) { return false; }
return (this.state.selectedIndex !== -1);
}
/** Utility Functions */
/**
* Renders the Panel used to edit a site's properties
*
* @returns
*
* @memberOf PropertyBagDisplay
*/
public renderPopup() {
if (!this.state.workingStorage) {
return (<div />);
}
else {
return (
<Panel
isOpen={this.state.isediting} type={PanelType.medium}
onDismiss={this.stopediting.bind(this)}
>
<MessageDisplay messages={this.state.workingStorage.errorMessages}
hideMessage={this.removePanelMessage.bind(this)} />
<div> <Label >Site Title</Label> {this.state.workingStorage.Title}</div>
<span> <Label label="" >Site Url</Label> {this.state.workingStorage.Url}</span>
<table>
<thead>
<tr>
<td>Managed Property Name</td>
<td>Value in Search Index</td>
<td>Crawled Property Name</td>
<td>Web Property Value</td>
<td>Searchable</td>
</tr>
</thead>
<tbody>
{this.state.workingStorage.DisplayProps.map((dp, i) => {
return (<tr>
<td>{dp.managedPropertyName}</td>
<td>{this.state.workingStorage[dp.managedPropertyName]}</td>
<td>{dp.crawledPropertyName}</td>
<td>
<TextField
data-crawledPropertyName={dp.crawledPropertyName}
value={dp.value}
onBlur={this.onPropertyValueChanged.bind(this)}
/>
</td>
<td>
<Toggle label=""
checked={dp.searchable}
onChanged={this.createSearcheableOnChangedHandler(dp.crawledPropertyName)}
/>
</td>
</tr>);
})}
</tbody>
</table>
<Toggle label="Force Crawl"
checked={this.state.workingStorage.forceCrawl}
onChanged={this.onForceCrawlChange.bind(this)}
/>
<Button default={true} icon="Save" buttonType={ButtonType.hero} value="Save" onClick={this.onSave.bind(this)} >Save</Button>
<Button icon="Cancel" buttonType={ButtonType.normal} value="Cancel" onClick={this.onCancel.bind(this)} >Cancel</Button>
</Panel>
);
}
}
/**
* Removes a message from the MessageDIsplay when the user click the 'x'
*
* @param {Array<md.Message>} messageList The list to remove the masseg from (the 'main' window of the Panel)
* @param {string} messageId The Id of the massge to remove
*
* @memberOf PropertyBagDisplay
*/
public removeMessage(messageList: Array<md.Message>, messageId: string) {
_.remove(messageList, {
Id: messageId
});
this.setState(this.state);
}
/**
* Removes a massage from the main windo
*
* @param {string} messageId
*
* @memberOf PropertyBagDisplay
*/
public removeMainMessage(messageId: string) {
this.removeMessage(this.state.errorMessages, messageId);
}
/**
* removes a message from the popup Panel
*
* @param {string} messageId
*
* @memberOf PropertyBagDisplay
*/
public removePanelMessage(messageId: string) {
this.removeMessage(this.state.workingStorage.errorMessages, messageId);
}
/**
* Makes the specified property either searchable or non-searchable in sharepoint
*
* @param {string} siteUrl The site to se it on
* @param {string} propname the managed property to set
* @param {boolean} newValue Searchable or not
* @returns {Promise<any>}
*
* @memberOf PropertyBagDisplay
*/
public changeSearchable(siteUrl: string, propname: string, newValue: boolean): Promise<any> {
if (newValue) {//make prop searchable
if (_.indexOf(this.state.workingStorage.searchableProps, propname) === -1) {// wasa not searchable, mpw it is
console.log(propname + "was not searchable, now it is ");
this.state.workingStorage.searchableProps.push(propname);
return utils.saveSearchablePropertiesToSharePoint(siteUrl, this.state.workingStorage.searchableProps);
}
else {
console.log(propname + "was not searchable, still is not ");
return Promise.resolve();
}
}
else { // make prop not searchablke
if (_.indexOf(this.state.workingStorage.searchableProps, propname) !== -1) {// wasa not searchable, mpw it is
console.log(propname + "was searchable, now it is not");
_.remove(this.state.workingStorage.searchableProps, p => { return p === propname; });
return utils.saveSearchablePropertiesToSharePoint(siteUrl, this.state.workingStorage.searchableProps);
}
else {
console.log(propname + "was searchable, still it is");
return Promise.resolve();
}
}
}
/**
* Switches component out of edit mode
*
*
* @memberOf PropertyBagDisplay
*/
public stopediting() {
this.state.isediting = false;
this.setState(this.state);
}
/**
* Caled by the Details list to render a column as a URL rather than text
*
* @private
* @param {*} [item]
* @param {number} [index]
* @param {IColumn} [column]
* @returns {*}
*
* @memberOf PropertyBagDisplay
*/
private renderSiteUrl(item?: any, index?: number, column?: IColumn): any {
return (<a href={item[column.fieldName]}>{item[column.fieldName]} </a>);
}
/**
* Sets the columns to be displayed in the list.
* These are SiteTemplate, Title and Url, plus any properties specified in
* the propertypane
*
* @private
* @returns {Array<IColumn>}
*
* @memberOf PropertyBagDisplay
*/
private setupColumns(): Array<IColumn> {
const columns: Array<IColumn> = [
{
fieldName: "SiteTemplate",
key: "SiteTemplate",
name: "SiteTemplate",
minWidth: 20,
maxWidth: 100,
},
{
fieldName: "Title",
key: "Title",
name: "Title",
minWidth: 20,
maxWidth: 220,
isSorted: false,
isSortedDescending: false
},
{
fieldName: "Url",
key: "Url",
name: "Url",
minWidth: 20,
maxWidth: 220,
onRender: this.renderSiteUrl
},
];
const displayProps: Array<string> = this.props.propertiesToDisplay.map(item => {
return item.split("|")[1];
});
for (const dp of displayProps) {
columns.push(
{
fieldName: dp,
key: dp,
name: dp,
minWidth: 20,
maxWidth: 220,
isSorted: false,
isSortedDescending: false
});
}
return columns;
}
/** react lifecycle */
/**
* Called when the componet loads.
* Builds the query to search sharepoint for the list of sites to display and formates
* the results to be displayed in the list
*
*
* @memberOf PropertyBagDisplay
*/
public componentWillMount() {
this.state.columns = this.setupColumns();
this.state.managedToCrawedMapping = [];
this.state.managedPropNames = [];
for (const prop of this.props.propertiesToDisplay) {
const names: Array<string> = prop.split('|');// crawledpropety/managed property
this.state.managedToCrawedMapping.push(new ManagedToCrawledMappingEntry(names[0], names[1]));
this.state.managedPropNames.push(names[1]);
}
this.state.managedPropNames.unshift("Title");
this.state.managedPropNames.unshift("Url");
this.state.managedPropNames.unshift("SiteTemplate");
this.state.managedPropNames.unshift("SiteTemplateId");
let querytext = "contentclass:STS_Site ";
if (this.props.siteTemplatesToInclude) {
if (this.props.siteTemplatesToInclude.length > 0) {
querytext += " AND (";
for (const siteTemplate of this.props.siteTemplatesToInclude) {
const siteTemplateParts = siteTemplate.split("#");
if (!siteTemplateParts[1]) {
querytext += "SiteTemplate=" + siteTemplateParts[0];
}
else {
querytext += "(SiteTemplate=" + siteTemplateParts[0] + " AND SiteTemplateId=" + siteTemplateParts[1] + ")";
}
if (this.props.siteTemplatesToInclude.indexOf(siteTemplate) !== this.props.siteTemplatesToInclude.length - 1)
{ querytext += " OR "; }
}
querytext += " )";
}
}
console.log("Using Query " + querytext);
const q: SearchQuery = {
Querytext: querytext,
SelectProperties: this.state.managedPropNames,
RowLimit: 999,
TrimDuplicates: false
};
pnp.sp.search(q).then((results: SearchResults) => {
for (const r of results.PrimarySearchResults) {
const obj: any = {};
for (const dp of this.state.managedPropNames) {
obj[dp] = r[dp];
}
obj.SiteTemplate = obj.SiteTemplate + "#" + obj.SiteTemplateId;
this.state.sites.push(obj);
}
debugger;
this.state.errorMessages.push(new md.Message("Items Recieved"));
this.setState(this.state);
}).catch(err => {
debugger;
this.state.errorMessages.push(new md.Message(err));
this.setState(this.state);
});
}
/** Event Handlers */
/**
* Changes the selected item
*
* @param {*} [item]
* @param {number} [index]
*
* @memberOf PropertyBagDisplay
*/
public onActiveItemChanged(item?: any, index?: number) {
this.state.selectedIndex = index;
this.setState(this.state);
}
/**
* Saves the item in workingStorage back to SharePoint
*
* @param {MouseEvent} [e]
*
* @memberOf PropertyBagDisplay
*/
public onSave(e?: MouseEvent): void {
const promises: Array<Promise<any>> = [];
for (const prop of this.state.workingStorage.DisplayProps) {
const promise = utils.setSPProperty(prop.crawledPropertyName, prop.value, this.state.workingStorage.Url)
.then(value => {
this.changeSearchable(this.state.workingStorage.Url, prop.crawledPropertyName, prop.searchable);
});
promises.push(promise);
}
Promise.all(promises)
.then((results: Array<any>) => {
if (this.state.workingStorage.forceCrawl) {
utils.forceCrawl(this.state.workingStorage.Url);
}
this.state.workingStorage = null;
this.state.isediting = false;
this.setState(this.state);
}).catch((err) => {
debugger;
this.state.workingStorage.errorMessages.push(new md.Message(err));
this.setState(this.state);
console.log(err);
});
}
/**
* Clears workingStorage and exits edit mode
*
* @param {MouseEvent} [e]
*
* @memberOf PropertyBagDisplay
*/
public onCancel(e?: MouseEvent): void {
this.state.isediting = false;
this.state.workingStorage = null;
this.setState(this.state);
}
/**
* Set the ForceCrawl Value in working storage which can be used to force a crawl of the site
* after the item is saved
*
* @param {boolean} newValue
*
* @memberOf PropertyBagDisplay
*/
public onForceCrawlChange(newValue: boolean) {
this.state.workingStorage.forceCrawl = newValue;
this.setState(this.state);
}
/**
* Called when the value of a property i schanged in the display.
* Saves the new value in workingStarage,
*
* @param {React.FormEvent<HTMLInputElement>} event
*
* @memberOf PropertyBagDisplay
*/
public onPropertyValueChanged(event: React.FormEvent<HTMLInputElement>) {
const selectedProperty = event.currentTarget.attributes["data-crawledpropertyname"].value;
const dp: DisplayProp = _.find(this.state.workingStorage.DisplayProps, p => { return p.crawledPropertyName === selectedProperty; });
dp.value = event.currentTarget.value;
this.setState(this.state);
}
public createSearcheableOnChangedHandler = (managedPropertyName) => (value) => {
const dp: DisplayProp = _.find(this.state.workingStorage.DisplayProps, p => { return p.crawledPropertyName === managedPropertyName; });
dp.searchable = value;
this.setState(this.state);
}
/**
* Called when user wishes to edit an item.
* The List displayes the values from the search index.
* This method gets the values from the actual PropertyBag so that they can be edited.
*
* @param {MouseEvent} [e]
*
* @memberOf PropertyBagDisplay
*/
public onEditItemClicked(e?: MouseEvent): void {
console.log("in onEditItemClicked");
const selectedSite = this.state.sites[this.state.selectedIndex];
const web = new Web(selectedSite.Url);
web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
const crawledProps: Array<string> = this.props.propertiesToDisplay.map(item => {
return item.split("|")[0];
});
this.state.workingStorage = _.clone(this.state.sites[this.state.selectedIndex]);
this.state.workingStorage.searchableProps = utils.decodeSearchableProps(r.AllProperties["vti_x005f_indexedpropertykeys"]);
this.state.workingStorage.DisplayProps = utils.SelectProperties(r.AllProperties, crawledProps, this.state.workingStorage.searchableProps);
this.state.workingStorage.errorMessages = new Array<md.Message>();
// now add in the managed Prop
for (const dp of this.state.workingStorage.DisplayProps) {
dp.managedPropertyName =
_.find(this.state.managedToCrawedMapping, mtc => { return mtc.crawledPropertyName === dp.crawledPropertyName; }).managedPropertyName;
}
this.state.isediting = true;
this.setState(this.state);
});
console.log("out onEditItemClicked");
}
/**
* Sorts a column when the user clicks on the header
*
* @private
* @param {*} event
* @param {IColumn} column
*
* @memberOf PropertyBagDisplay
*/
private _onColumnClick(event: any, column: IColumn) {
column = _.find(this.state.columns, c => c.fieldName === column.fieldName);// find the object in state
// If we've sorted this column, flip it.
if (column.isSorted) {
column.isSortedDescending = !column.isSortedDescending;
}
else {
column.isSorted = true;
column.isSortedDescending = false;
}
// Sort the items.
this.state.sites = _.orderBy(this.state.sites, [(site, x, y, z) => {
if (site[column.fieldName]) {
return site[column.fieldName].toLowerCase();
}
else {
return "";
}
}], [column.isSortedDescending ? "desc" : "asc"]);
this.setState(this.state);
}
/**
* Renders the component
*
* @returns {React.ReactElement<IPropertyBagDisplayProps>}
*
* @memberOf PropertyBagDisplay
*/
public render(): React.ReactElement<IPropertyBagDisplayProps> {
return (
<div >
<CommandBar items={this.CommandItems} />
<MessageDisplay
messages={this.state.errorMessages}
hideMessage={this.removeMainMessage.bind(this)}
/>
<DetailsList
key="Url"
onColumnHeaderClick={this._onColumnClick.bind(this)}
items={this.state.sites}
layoutMode={DetailsListLayoutMode.fixedColumns}
columns={this.state.columns}
selectionMode={SelectionMode.single}
checkboxVisibility={CheckboxVisibility.hidden}
onActiveItemChanged={this.onActiveItemChanged.bind(this)
}
>
</DetailsList>
{this.renderPopup.bind(this)()}
</div >
);
}
} | the_stack |
import {expect, match, restore, spy, stub} from '../test';
import EventObject from '../../src/tabris/EventObject';
import NativeObject from '../../src/tabris/NativeObject';
import Listeners from '../../src/tabris/Listeners';
import ChangeListeners from '../../src/tabris/ChangeListeners';
import {SinonStub} from 'sinon';
import {from} from 'rxjs';
import Observable from '../../src/tabris/Observable';
describe('Listeners', function() {
class MyExtendedEvent extends EventObject { }
const type = 'myEventType';
const fooType = 'myFooEventType';
const UntypedListeners: any = Listeners;
let target;
let fooTarget;
let myListeners: Listeners;
let myFooListeners: Listeners;
let listener: SinonStub;
beforeEach(function() {
target = {targetType: true};
fooTarget = {targetType: 'foo'};
myListeners = new Listeners(target, type);
myFooListeners = new Listeners(fooTarget, fooType);
listener = stub();
});
afterEach(restore);
describe('constructor', function() {
it('throws for wrong target', function() {
expect(() => new UntypedListeners()).to.throw('Missing target instance');
expect(() => new UntypedListeners(null)).to.throw('Target null is not an object');
expect(() => new UntypedListeners(true)).to.throw('Target true is not an object');
});
it('throws for wrong type', function() {
expect(() => new UntypedListeners({})).to.throw('Missing event type string');
expect(() => new UntypedListeners({}, true)).to.throw('Event type true is not a string');
expect(() => new Listeners({}, '')).to.throw('Missing event type string');
});
it('throws for types starting with on[UpperCase]', function() {
const ok = new Listeners(fooTarget, 'onion');
expect(ok.type).to.equal('onion');
expect(() => new Listeners(fooTarget, 'onIon')).to.throw(
'Invalid event type string, did you mean "ion"?'
);
});
});
describe('instance', function() {
it('exposes target and type', function() {
expect(myListeners.type).to.equal(type);
expect(myListeners.target).to.equal(target);
expect(myFooListeners.target).to.equal(fooTarget);
});
it('exposes original', function() {
myListeners.original.addListener(listener);
myListeners.trigger();
expect(myListeners.original).to.be.instanceOf(Listeners);
expect(listener).to.have.been.called;
});
it('can be called as function and returns target', function() {
expect(myListeners(listener)).to.equal(target);
expect(myFooListeners(listener)).to.equal(fooTarget);
});
it('exposes methods returning target', function() {
expect(myListeners.once(listener)).to.equal(target);
expect(myListeners.addListener(listener)).to.equal(target);
expect(myListeners.removeListener(listener)).to.equal(target);
expect(myListeners.trigger(listener)).to.equal(target);
});
});
describe('trigger()', function() {
it('notifies directly registered listener', function() {
myListeners.addListener(listener);
myListeners.trigger();
expect(listener).to.have.been.called;
});
it('notifies directly registered listener with data', function() {
myListeners.addListener(listener);
myListeners.trigger({foo: 'bar'});
expect(listener).to.have.been.calledWithMatch({foo: 'bar'});
});
it('initializes event object with type, timeStamp and target', function() {
myListeners.addListener(listener);
myListeners.trigger({foo: 'bar'});
expect(listener).to.have.been.calledWithMatch({foo: 'bar', target, type, timeStamp: match.number});
});
it('ignores type, timeStamp and target in event data', function() {
myListeners.addListener(listener);
myListeners.trigger({foo: 'bar', target: {}, type: 'not the type', timeStamp: 0});
expect(listener).to.have.been.calledWithMatch({foo: 'bar', target, type, timeStamp: match.number});
});
it('passes through uninitialized EventObject', function() {
myListeners.addListener(listener);
const ev = Object.assign(new EventObject(), {foo: 'bar'});
myListeners.trigger(ev);
expect(listener).to.have.been.calledWith(ev);
});
it('passes through uninitialized custom EventObject', function() {
myFooListeners.addListener(listener);
const ev = Object.assign(new MyExtendedEvent(), {ext: 'bar'});
myFooListeners.trigger(ev);
expect(listener).to.have.been.calledWith(ev);
});
it('copies initialized EventObject', function() {
const ev = Object.assign(new EventObject(), {foo: 'bar'});
const events = [];
myListeners.addListener(event => events.push(event));
myFooListeners.addListener(event => events.push(event));
myListeners.trigger(ev);
myFooListeners.trigger(events[0]);
expect(events.length).to.equal(2);
expect(events[0]).to.equal(ev);
expect(events[0].target).to.equal(target);
expect(events[1]).not.to.equal(ev);
expect(events[1].foo).to.equal('bar');
expect(events[1].target).to.equal(fooTarget);
});
it('notifies listener with unbound trigger', function() {
myListeners.addListener(listener);
const trigger = myListeners.trigger;
trigger();
expect(listener).to.have.been.called;
});
it('notifies shorthand registered listener', function() {
myListeners(listener);
myListeners.trigger();
expect(listener).to.have.been.called;
});
it('notifies typed shorthand registered listener', function() {
myListeners(listener);
myListeners.trigger({foo: 'bar'});
expect(listener).to.have.been.calledWithMatch({foo: 'bar'});
});
it('notifies listener only once', function() {
myListeners(listener);
myListeners(listener);
myListeners.trigger();
expect(listener).to.have.been.calledOnce;
});
it('does not notify removed listener', function() {
myListeners(listener);
myListeners.removeListener(listener);
myListeners.trigger();
expect(listener).not.to.have.been.called;
});
it('notifies listeners once ', function() {
myListeners.once(listener);
myListeners.trigger();
myListeners.trigger();
expect(listener).to.have.been.calledOnce;
});
it('shares listener storage', function() {
myFooListeners(listener);
const myFooListeners2 = new Listeners(fooTarget, fooType);
myFooListeners2.trigger({foo: 'bar'});
expect(listener).to.have.been.calledWithMatch({foo: 'bar'});
});
it('prints error of async listeners', done => {
// eslint-disable-next-line @typescript-eslint/promise-function-async
function asyncListener() {
return Promise.reject('someError');
}
const errorSpy = spy(console, 'error');
myListeners(asyncListener);
myListeners.trigger();
setTimeout(function() {
errorSpy.restore();
expect(errorSpy).to.have.been.calledWithMatch(/someError/);
done();
}, 100);
});
describe('with NativeObject target', function() {
// eslint-disable-next-line @typescript-eslint/no-empty-function
const PseudoNativeObject: typeof NativeObject = function(/* noop */) {} as any;
PseudoNativeObject.prototype = NativeObject.prototype;
class MyNativeObject extends PseudoNativeObject {
public onMyEvent: Listeners;
constructor() {
super();
this.onMyEvent = new Listeners(this, 'myEvent');
}
}
it('synthesizes tabris events on NativeObjects', function() {
const object = new MyNativeObject();
object.on({myEvent: listener});
object.onMyEvent.trigger({});
expect(listener).to.have.been.calledOnce;
});
it('triggers events on NativeObjects', function() {
const object = new MyNativeObject();
object.onMyEvent(listener);
object.trigger('myEvent', {foo: 'bar'});
expect(listener).to.have.been.calledOnce;
expect(listener).to.have.been.calledWithMatch({foo: 'bar'});
});
it('forwards given event object to tabris event', function() {
const object = new MyNativeObject();
object.on({myEvent: listener});
const eventData = {target: object, type: 'myEvent', foo: 'bar'};
object.onMyEvent.trigger(eventData);
expect(listener).to.have.been.calledWithMatch({target: object, type: 'myEvent', foo: 'bar'});
});
it('adjusts target and type on forwarded event', function() {
const object = new MyNativeObject();
object.on({myEvent: listener});
const eventData = {target: new Date(), type: 'baz', foo: 'bar'};
object.onMyEvent.trigger(eventData);
expect(listener).to.have.been.calledWithMatch({target: object, type: 'myEvent', foo: 'bar'});
});
});
});
describe('triggerAsync()', function() {
it('returns Promise waiting for other Promise returned by listener', async function() {
let resolver = null;
let result = null;
myListeners.addListener(() => new Promise(resolve => resolver = resolve));
myListeners.triggerAsync().then(arg => result = arg);
return new Promise(resolve => setTimeout(resolve, 50)).then(() => {
expect(resolver).to.be.instanceOf(Function);
expect(result).to.be.null;
resolver();
return new Promise(resolve => setTimeout(resolve, 50));
}).then(() => {
expect(result).to.equal(target);
});
});
});
describe('promise()', function() {
it('resolves previous promises', async function() {
const promise1 = myListeners.promise();
const promise2 = myListeners.promise();
myListeners.trigger();
return Promise.all([promise1, promise2]).then(
([ev1, ev2]) => {
expect(ev1).to.be.instanceof(EventObject);
expect(ev2).to.be.instanceof(EventObject);
}
);
});
it('resolves previous typed promises', async function() {
const promise1 = myListeners.promise();
const promise2 = myListeners.promise();
myListeners.trigger({foo: 'bar'});
return Promise.all([promise1, promise2]).then(
([ev1, ev2]) => {
expect(ev1).to.be.instanceof(EventObject);
expect(ev2).to.be.instanceof(EventObject);
expect(ev1).contains({foo: 'bar'});
expect(ev2).contains({foo: 'bar'});
}
);
});
it('does not resolve new promise', done => {
myListeners.trigger({foo: 'bar'});
myListeners.promise().then(
() => new Error('Should not resolve'),
() => new Error('Should not reject')
);
setTimeout(done, 100);
});
});
describe('as observable', function() {
it('forwards events to subscriber', function() {
myListeners.subscribe(listener);
myListeners.trigger({foo: 'bar'});
expect(listener).to.have.been.calledOnce;
expect(listener.args[0][0]).to.be.instanceOf(EventObject);
expect(listener.args[0][0].foo).to.equal('bar');
});
it('completes on dispose', function() {
myListeners.subscribe(null, null, listener);
new Listeners(target, 'dispose').trigger();
expect(listener).to.have.been.calledOnce;
});
it('supports RxJS', function() {
from(myListeners).subscribe(null, null, listener);
new Listeners(target, 'dispose').trigger();
expect(listener).to.have.been.calledOnce;
});
});
describe('created via ChangeListeners constructor', function() {
let changeListeners: ChangeListeners<{foo: string}, 'foo'>;
beforeEach(function() {
target = {foo: 'bar'};
changeListeners = new ChangeListeners(target, 'foo');
});
it('sets type and target', function() {
expect(changeListeners.target).to.equal(target);
expect(changeListeners.type).to.equal('fooChanged');
});
it('sets original with correct prototype', function() {
expect(changeListeners.original).to.be.instanceOf(ChangeListeners);
});
it('throws if property is missing', function() {
expect(() => new ChangeListeners(target, 'bar2')).to.throw('Target has no property "bar2"');
});
it('creates delegate function', function() {
changeListeners(listener);
changeListeners.trigger({value: 'x'});
expect(listener).to.have.been.called;
expect(listener).to.have.been.calledWithMatch({value: 'x'});
});
it('makes trigger throw when property value is missing', function() {
changeListeners(listener);
expect(() => changeListeners.trigger({notthevalue: 'x'} as any)).to.throw(
'Can not trigger change event without "value" property in event data'
);
});
describe('values', function() {
it('is Observable instance', function() {
expect(changeListeners.values).to.be.instanceOf(Observable);
expect(changeListeners.values).to.equal(changeListeners.values);
});
it('provides current value', function() {
changeListeners.values.subscribe(listener);
expect(listener).to.have.been.calledOnce;
expect(listener).to.have.been.calledWith('bar');
});
it('provides future values', function() {
changeListeners.values.subscribe(listener);
changeListeners.trigger({value: 'baz'});
expect(listener).to.have.been.calledWith('bar');
expect(listener).to.have.been.calledWith('baz');
});
it('completes on dispose', function() {
changeListeners.values.subscribe(null, null, listener);
new Listeners(target, 'dispose').trigger();
expect(listener).to.have.been.calledOnce;
});
});
});
}); | the_stack |
import {DirectiveFn} from '../lib/directive.js';
import {createMarker, directive, NodePart, Part, removeNodes, reparentNodes} from '../lit-html.js';
export type KeyFn<T> = (item: T, index: number) => unknown;
export type ItemTemplate<T> = (item: T, index: number) => unknown;
// Helper functions for manipulating parts
// TODO(kschaaf): Refactor into Part API?
const createAndInsertPart =
(containerPart: NodePart, beforePart?: NodePart): NodePart => {
const container = containerPart.startNode.parentNode as Node;
const beforeNode = beforePart === undefined ? containerPart.endNode :
beforePart.startNode;
const startNode = container.insertBefore(createMarker(), beforeNode);
container.insertBefore(createMarker(), beforeNode);
const newPart = new NodePart(containerPart.options);
newPart.insertAfterNode(startNode);
return newPart;
};
const updatePart = (part: NodePart, value: unknown) => {
part.setValue(value);
part.commit();
return part;
};
const insertPartBefore =
(containerPart: NodePart, part: NodePart, ref?: NodePart) => {
const container = containerPart.startNode.parentNode as Node;
const beforeNode = ref ? ref.startNode : containerPart.endNode;
const endNode = part.endNode.nextSibling;
if (endNode !== beforeNode) {
reparentNodes(container, part.startNode, endNode, beforeNode);
}
};
const removePart = (part: NodePart) => {
removeNodes(
part.startNode.parentNode!, part.startNode, part.endNode.nextSibling);
};
// Helper for generating a map of array item to its index over a subset
// of an array (used to lazily generate `newKeyToIndexMap` and
// `oldKeyToIndexMap`)
const generateMap = (list: unknown[], start: number, end: number) => {
const map = new Map();
for (let i = start; i <= end; i++) {
map.set(list[i], i);
}
return map;
};
// Stores previous ordered list of parts and map of key to index
const partListCache = new WeakMap<NodePart, (NodePart | null)[]>();
const keyListCache = new WeakMap<NodePart, unknown[]>();
/**
* A directive that repeats a series of values (usually `TemplateResults`)
* generated from an iterable, and updates those items efficiently when the
* iterable changes based on user-provided `keys` associated with each item.
*
* Note that if a `keyFn` is provided, strict key-to-DOM mapping is maintained,
* meaning previous DOM for a given key is moved into the new position if
* needed, and DOM will never be reused with values for different keys (new DOM
* will always be created for new keys). This is generally the most efficient
* way to use `repeat` since it performs minimum unnecessary work for insertions
* amd removals.
*
* IMPORTANT: If providing a `keyFn`, keys *must* be unique for all items in a
* given call to `repeat`. The behavior when two or more items have the same key
* is undefined.
*
* If no `keyFn` is provided, this directive will perform similar to mapping
* items to values, and DOM will be reused against potentially different items.
*/
export const repeat =
directive(
<T>(items: Iterable<T>,
keyFnOrTemplate: KeyFn<T>|ItemTemplate<T>,
template?: ItemTemplate<T>):
DirectiveFn => {
let keyFn: KeyFn<T>;
if (template === undefined) {
template = keyFnOrTemplate;
} else if (keyFnOrTemplate !== undefined) {
keyFn = keyFnOrTemplate as KeyFn<T>;
}
return (containerPart: Part): void => {
if (!(containerPart instanceof NodePart)) {
throw new Error('repeat can only be used in text bindings');
}
// Old part & key lists are retrieved from the last update
// (associated with the part for this instance of the directive)
const oldParts = partListCache.get(containerPart) || [];
const oldKeys = keyListCache.get(containerPart) || [];
// New part list will be built up as we go (either reused from
// old parts or created for new keys in this update). This is
// saved in the above cache at the end of the update.
const newParts: NodePart[] = [];
// New value list is eagerly generated from items along with a
// parallel array indicating its key.
const newValues: unknown[] = [];
const newKeys: unknown[] = [];
let index = 0;
for (const item of items) {
newKeys[index] = keyFn ? keyFn(item, index) : index;
newValues[index] = template !(item, index);
index++;
}
// Maps from key to index for current and previous update; these
// are generated lazily only when needed as a performance
// optimization, since they are only required for multiple
// non-contiguous changes in the list, which are less common.
let newKeyToIndexMap!: Map<unknown, number>;
let oldKeyToIndexMap!: Map<unknown, number>;
// Head and tail pointers to old parts and new values
let oldHead = 0;
let oldTail = oldParts.length - 1;
let newHead = 0;
let newTail = newValues.length - 1;
// Overview of O(n) reconciliation algorithm (general approach
// based on ideas found in ivi, vue, snabbdom, etc.):
//
// * We start with the list of old parts and new values (and
// arrays of
// their respective keys), head/tail pointers into each, and
// we build up the new list of parts by updating (and when
// needed, moving) old parts or creating new ones. The initial
// scenario might look like this (for brevity of the diagrams,
// the numbers in the array reflect keys associated with the
// old parts or new values, although keys and parts/values are
// actually stored in parallel arrays indexed using the same
// head/tail pointers):
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [ , , , , , , ]
// newKeys: [0, 2, 1, 4, 3, 7, 6] <- reflects the user's new
// item order
// newHead ^ ^ newTail
//
// * Iterate old & new lists from both sides, updating,
// swapping, or
// removing parts at the head/tail locations until neither
// head nor tail can move.
//
// * Example below: keys at head pointers match, so update old
// part 0 in-
// place (no need to move it) and record part 0 in the
// `newParts` list. The last thing we do is advance the
// `oldHead` and `newHead` pointers (will be reflected in the
// next diagram).
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , ] <- heads matched: update 0
// and newKeys: [0, 2, 1, 4, 3, 7, 6] advance both oldHead
// & newHead
// newHead ^ ^ newTail
//
// * Example below: head pointers don't match, but tail pointers
// do, so
// update part 6 in place (no need to move it), and record
// part 6 in the `newParts` list. Last, advance the `oldTail`
// and `oldHead` pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , 6] <- tails matched: update 6
// and newKeys: [0, 2, 1, 4, 3, 7, 6] advance both oldTail
// & newTail
// newHead ^ ^ newTail
//
// * If neither head nor tail match; next check if one of the
// old head/tail
// items was removed. We first need to generate the reverse
// map of new keys to index (`newKeyToIndexMap`), which is
// done once lazily as a performance optimization, since we
// only hit this case if multiple non-contiguous changes were
// made. Note that for contiguous removal anywhere in the
// list, the head and tails would advance from either end and
// pass each other before we get to this case and removals
// would be handled in the final while loop without needing to
// generate the map.
//
// * Example below: The key at `oldTail` was removed (no longer
// in the
// `newKeyToIndexMap`), so remove that part from the DOM and
// advance just the `oldTail` pointer.
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , 6] <- 5 not in new map; remove
// 5 and newKeys: [0, 2, 1, 4, 3, 7, 6] advance oldTail
// newHead ^ ^ newTail
//
// * Once head and tail cannot move, any mismatches are due to
// either new or
// moved items; if a new key is in the previous "old key to
// old index" map, move the old part to the new location,
// otherwise create and insert a new part. Note that when
// moving an old part we null its position in the oldParts
// array if it lies between the head and tail so we know to
// skip it when the pointers get there.
//
// * Example below: neither head nor tail match, and neither
// were removed;
// so find the `newHead` key in the `oldKeyToIndexMap`, and
// move that old part's DOM into the next head position
// (before `oldParts[oldHead]`). Last, null the part in the
// `oldPart` array since it was somewhere in the remaining
// oldParts still to be scanned (between the head and tail
// pointers) so that we know to skip that old part on future
// iterations.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, , , , , 6] <- stuck; update & move 2
// into place newKeys: [0, 2, 1, 4, 3, 7, 6] and advance
// newHead
// newHead ^ ^ newTail
//
// * Note that for moves/insertions like the one above, a part
// inserted at
// the head pointer is inserted before the current
// `oldParts[oldHead]`, and a part inserted at the tail
// pointer is inserted before `newParts[newTail+1]`. The
// seeming asymmetry lies in the fact that new parts are moved
// into place outside in, so to the right of the head pointer
// are old parts, and to the right of the tail pointer are new
// parts.
//
// * We always restart back from the top of the algorithm,
// allowing matching
// and simple updates in place to continue...
//
// * Example below: the head pointers once again match, so
// simply update
// part 1 and record it in the `newParts` array. Last,
// advance both head pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, , , , 6] <- heads matched; update 1
// and newKeys: [0, 2, 1, 4, 3, 7, 6] advance both oldHead
// & newHead
// newHead ^ ^ newTail
//
// * As mentioned above, items that were moved as a result of
// being stuck
// (the final else clause in the code below) are marked with
// null, so we always advance old pointers over these so we're
// comparing the next actual old value on either end.
//
// * Example below: `oldHead` is null (already placed in
// newParts), so
// advance `oldHead`.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6] // old head already used;
// advance newParts: [0, 2, 1, , , , 6] // oldHead newKeys:
// [0, 2, 1, 4, 3, 7, 6]
// newHead ^ ^ newTail
//
// * Note it's not critical to mark old parts as null when they
// are moved
// from head to tail or tail to head, since they will be
// outside the pointer range and never visited again.
//
// * Example below: Here the old tail key matches the new head
// key, so
// the part at the `oldTail` position and move its DOM to the
// new head position (before `oldParts[oldHead]`). Last,
// advance `oldTail` and `newHead` pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, , , 6] <- old tail matches new
// head: update newKeys: [0, 2, 1, 4, 3, 7, 6] & move 4,
// advance oldTail & newHead
// newHead ^ ^ newTail
//
// * Example below: Old and new head keys match, so update the
// old head
// part in place, and advance the `oldHead` and `newHead`
// pointers.
//
// oldHead v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, 3, ,6] <- heads match: update 3
// and advance newKeys: [0, 2, 1, 4, 3, 7, 6] oldHead &
// newHead
// newHead ^ ^ newTail
//
// * Once the new or old pointers move past each other then all
// we have
// left is additions (if old list exhausted) or removals (if
// new list exhausted). Those are handled in the final while
// loops at the end.
//
// * Example below: `oldHead` exceeded `oldTail`, so we're done
// with the
// main loop. Create the remaining part and insert it at the
// new head position, and the update is complete.
//
// (oldHead > oldTail)
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, 3, 7 ,6] <- create and insert 7
// newKeys: [0, 2, 1, 4, 3, 7, 6]
// newHead ^ newTail
//
// * Note that the order of the if/else clauses is not important
// to the
// algorithm, as long as the null checks come first (to ensure
// we're always working on valid old parts) and that the final
// else clause comes last (since that's where the expensive
// moves occur). The order of remaining clauses is is just a
// simple guess at which cases will be most common.
//
// * TODO(kschaaf) Note, we could calculate the longest
// increasing
// subsequence (LIS) of old items in new position, and only
// move those not in the LIS set. However that costs O(nlogn)
// time and adds a bit more code, and only helps make rare
// types of mutations require fewer moves. The above handles
// removes, adds, reversal, swaps, and single moves of
// contiguous items in linear time, in the minimum number of
// moves. As the number of multiple moves where LIS might help
// approaches a random shuffle, the LIS optimization becomes
// less helpful, so it seems not worth the code at this point.
// Could reconsider if a compelling case arises.
while (oldHead <= oldTail && newHead <= newTail) {
if (oldParts[oldHead] === null) {
// `null` means old part at head has already been used
// below; skip
oldHead++;
} else if (oldParts[oldTail] === null) {
// `null` means old part at tail has already been used
// below; skip
oldTail--;
} else if (oldKeys[oldHead] === newKeys[newHead]) {
// Old head matches new head; update in place
newParts[newHead] =
updatePart(oldParts[oldHead]!, newValues[newHead]);
oldHead++;
newHead++;
} else if (oldKeys[oldTail] === newKeys[newTail]) {
// Old tail matches new tail; update in place
newParts[newTail] =
updatePart(oldParts[oldTail]!, newValues[newTail]);
oldTail--;
newTail--;
} else if (oldKeys[oldHead] === newKeys[newTail]) {
// Old head matches new tail; update and move to new tail
newParts[newTail] =
updatePart(oldParts[oldHead]!, newValues[newTail]);
insertPartBefore(
containerPart,
oldParts[oldHead]!,
newParts[newTail + 1]);
oldHead++;
newTail--;
} else if (oldKeys[oldTail] === newKeys[newHead]) {
// Old tail matches new head; update and move to new head
newParts[newHead] =
updatePart(oldParts[oldTail]!, newValues[newHead]);
insertPartBefore(
containerPart, oldParts[oldTail]!, oldParts[oldHead]!);
oldTail--;
newHead++;
} else {
if (newKeyToIndexMap === undefined) {
// Lazily generate key-to-index maps, used for removals &
// moves below
newKeyToIndexMap = generateMap(newKeys, newHead, newTail);
oldKeyToIndexMap = generateMap(oldKeys, oldHead, oldTail);
}
if (!newKeyToIndexMap.has(oldKeys[oldHead])) {
// Old head is no longer in new list; remove
removePart(oldParts[oldHead]!);
oldHead++;
} else if (!newKeyToIndexMap.has(oldKeys[oldTail])) {
// Old tail is no longer in new list; remove
removePart(oldParts[oldTail]!);
oldTail--;
} else {
// Any mismatches at this point are due to additions or
// moves; see if we have an old part we can reuse and move
// into place
const oldIndex = oldKeyToIndexMap.get(newKeys[newHead]);
const oldPart =
oldIndex !== undefined ? oldParts[oldIndex] : null;
if (oldPart === null) {
// No old part for this value; create a new one and
// insert it
const newPart = createAndInsertPart(
containerPart, oldParts[oldHead]!);
updatePart(newPart, newValues[newHead]);
newParts[newHead] = newPart;
} else {
// Reuse old part
newParts[newHead] =
updatePart(oldPart, newValues[newHead]);
insertPartBefore(
containerPart, oldPart, oldParts[oldHead]!);
// This marks the old part as having been used, so that
// it will be skipped in the first two checks above
oldParts[oldIndex as number] = null;
}
newHead++;
}
}
}
// Add parts for any remaining new values
while (newHead <= newTail) {
// For all remaining additions, we insert before last new
// tail, since old pointers are no longer valid
const newPart = createAndInsertPart(
containerPart, newParts[newTail + 1]!);
updatePart(newPart, newValues[newHead]);
newParts[newHead++] = newPart;
}
// Remove any remaining unused old parts
while (oldHead <= oldTail) {
const oldPart = oldParts[oldHead++];
if (oldPart !== null) {
removePart(oldPart);
}
}
// Save order of new parts for next round
partListCache.set(containerPart, newParts);
keyListCache.set(containerPart, newKeys);
};
}) as
<T>(items: Iterable<T>,
keyFnOrTemplate: KeyFn<T>|ItemTemplate<T>,
template?: ItemTemplate<T>) => DirectiveFn; | the_stack |
import {ExtraGlamorousProps} from './glamorous-component'
import {
CSSPropertiesCompleteSingle,
CSSPropertiesPseudo,
} from './css-properties'
import {SVGPropertiesCompleteSingle} from './svg-properties'
// The file `./named-built-in-glamorous-components.d.ts` is based off this file
// and should get any updates this file does.
/*
* FIXME:
* Since TypeScript doesn't have
* HTMLDetailsElement, HTMLDialogElement,
* HTMLKeygenElement, HTMLMenuItemElement
* Those components currently has wrong type.
* After TypeScript add those types, plz fix this.
* Reference: https://github.com/Microsoft/TypeScript/issues/17828
*/
export interface HTMLComponent {
A: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLAnchorElement>
>
Abbr: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Address: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Area: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLAreaElement>
>
Article: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Aside: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Audio: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLAudioElement>
>
B: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Base: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLBaseElement>
>
Bdi: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Bdo: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Big: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Blockquote: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLQuoteElement>
>
Body: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLBodyElement>
>
Br: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLBRElement>
>
Button: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLButtonElement>
>
Canvas: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLCanvasElement>
>
Caption: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableCaptionElement>
>
Cite: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Code: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Col: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableColElement>
>
Colgroup: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableColElement>
>
Data: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLDataElement>
>
Datalist: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLDataListElement>
>
Dd: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Del: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLModElement>
>
// TypeScript doesn't have HTMLDetailsElement
Details: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Dfn: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
// TypeScript doesn't have HTMLDialogElement
Dialog: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Div: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLDivElement>
>
Dl: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLDListElement>
>
Dt: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Em: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Embed: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLEmbedElement>
>
Fieldset: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLFieldSetElement>
>
Figcaption: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Figure: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Footer: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Form: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLFormElement>
>
H1: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
H2: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
H3: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
H4: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
H5: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
H6: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadingElement>
>
Head: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHeadElement>
>
Header: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Hgroup: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Hr: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHRElement>
>
Html: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLHtmlElement>
>
I: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Iframe: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLIFrameElement>
>
Img: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLImageElement>
>
Input: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLInputElement>
>
Ins: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLModElement>
>
Kbd: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
// TypeScript doesn't have HTMLKeygenElement
Keygen: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Label: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLLabelElement>
>
Legend: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLLegendElement>
>
Li: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLLIElement>
>
Link: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLLinkElement>
>
Main: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Map: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLMapElement>
>
Mark: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Menu: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLMenuElement>
>
// TypeScript doesn't have HTMLMenuItemElement
Menuitem: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Meta: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLMetaElement>
>
Meter: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLMeterElement>
>
Nav: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Noscript: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Object: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLObjectElement>
>
Ol: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLOListElement>
>
Optgroup: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLOptGroupElement>
>
Option: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLOptionElement>
>
Output: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLOutputElement>
>
P: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLParagraphElement>
>
Param: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLParamElement>
>
Picture: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLPictureElement>
>
Pre: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLPreElement>
>
Progress: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLProgressElement>
>
Q: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLQuoteElement>
>
Rp: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Rt: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Ruby: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
S: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Samp: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Script: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLScriptElement>
>
Section: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Select: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLSelectElement>
>
Small: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Source: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLSourceElement>
>
Span: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLSpanElement>
>
Strong: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Style: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLStyleElement>
>
Sub: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Summary: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Sup: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Table: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableElement>
>
Tbody: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableSectionElement>
>
Td: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableDataCellElement>
>
Textarea: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTextAreaElement>
>
Tfoot: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableSectionElement>
>
Th: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableHeaderCellElement>
>
Thead: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableSectionElement>
>
Time: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTimeElement>
>
Title: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTitleElement>
>
Tr: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTableRowElement>
>
Track: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLTrackElement>
>
U: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Ul: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLUListElement>
>
Var: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
Video: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLVideoElement>
>
Wbr: React.StatelessComponent<
CSSPropertiesCompleteSingle &
CSSPropertiesPseudo &
ExtraGlamorousProps &
React.HTMLProps<HTMLElement>
>
}
export interface SVGComponent {
Circle: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGCircleElement>
>
ClipPath: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGClipPathElement>
>
Defs: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGDefsElement>
>
Ellipse: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGEllipseElement>
>
G: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGGElement>
>
Image: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGImageElement>
>
Line: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGLineElement>
>
LinearGradient: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGLinearGradientElement>
>
Mask: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGMaskElement>
>
Path: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGPathElement>
>
Pattern: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGPatternElement>
>
Polygon: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGPolygonElement>
>
Polyline: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGPolylineElement>
>
RadialGradient: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGRadialGradientElement>
>
Rect: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGRectElement>
>
Stop: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGStopElement>
>
Svg: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGSVGElement>
>
Text: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGTextElement>
>
Tspan: React.StatelessComponent<
SVGPropertiesCompleteSingle &
ExtraGlamorousProps &
React.SVGAttributes<SVGTSpanElement>
>
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../../types";
import * as utilities from "../../utilities";
/**
* CSIStorageCapacity stores the result of one CSI GetCapacity call. For a given StorageClass, this describes the available capacity in a particular topology segment. This can be used when considering where to instantiate new PersistentVolumes.
*
* For example this can express things like: - StorageClass "standard" has "1234 GiB" available in "topology.kubernetes.io/zone=us-east1" - StorageClass "localssd" has "10 GiB" available in "kubernetes.io/hostname=knode-abc123"
*
* The following three cases all imply that no capacity is available for a certain combination: - no object exists with suitable topology and storage class name - such an object exists, but the capacity is unset - such an object exists, but the capacity is zero
*
* The producer of these objects can decide which approach is more suitable.
*
* They are consumed by the kube-scheduler if the CSIStorageCapacity beta feature gate is enabled there and a CSI driver opts into capacity-aware scheduling with CSIDriver.StorageCapacity.
*/
export class CSIStorageCapacity extends pulumi.CustomResource {
/**
* Get an existing CSIStorageCapacity resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): CSIStorageCapacity {
return new CSIStorageCapacity(name, undefined as any, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'kubernetes:storage.k8s.io/v1beta1:CSIStorageCapacity';
/**
* Returns true if the given object is an instance of CSIStorageCapacity. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is CSIStorageCapacity {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === CSIStorageCapacity.__pulumiType;
}
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
*/
public readonly apiVersion!: pulumi.Output<"storage.k8s.io/v1beta1">;
/**
* Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
*
* The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
*/
public readonly capacity!: pulumi.Output<string>;
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
*/
public readonly kind!: pulumi.Output<"CSIStorageCapacity">;
/**
* MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
*
* This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
*/
public readonly maximumVolumeSize!: pulumi.Output<string>;
/**
* Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
*
* Objects are namespaced.
*
* More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
*/
public readonly metadata!: pulumi.Output<outputs.meta.v1.ObjectMeta>;
/**
* NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
*/
public readonly nodeTopology!: pulumi.Output<outputs.meta.v1.LabelSelector>;
/**
* The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
*/
public readonly storageClassName!: pulumi.Output<string>;
/**
* Create a CSIStorageCapacity resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: CSIStorageCapacityArgs, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (!opts.id) {
if ((!args || args.storageClassName === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageClassName'");
}
inputs["apiVersion"] = "storage.k8s.io/v1beta1";
inputs["capacity"] = args ? args.capacity : undefined;
inputs["kind"] = "CSIStorageCapacity";
inputs["maximumVolumeSize"] = args ? args.maximumVolumeSize : undefined;
inputs["metadata"] = args ? args.metadata : undefined;
inputs["nodeTopology"] = args ? args.nodeTopology : undefined;
inputs["storageClassName"] = args ? args.storageClassName : undefined;
} else {
inputs["apiVersion"] = undefined /*out*/;
inputs["capacity"] = undefined /*out*/;
inputs["kind"] = undefined /*out*/;
inputs["maximumVolumeSize"] = undefined /*out*/;
inputs["metadata"] = undefined /*out*/;
inputs["nodeTopology"] = undefined /*out*/;
inputs["storageClassName"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
const aliasOpts = { aliases: [{ type: "kubernetes:storage.k8s.io/v1alpha1:CSIStorageCapacity" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(CSIStorageCapacity.__pulumiType, name, inputs, opts);
}
}
/**
* The set of arguments for constructing a CSIStorageCapacity resource.
*/
export interface CSIStorageCapacityArgs {
/**
* APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
*/
apiVersion?: pulumi.Input<"storage.k8s.io/v1beta1">;
/**
* Capacity is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
*
* The semantic is currently (CSI spec 1.2) defined as: The available capacity, in bytes, of the storage that can be used to provision volumes. If not set, that information is currently unavailable and treated like zero capacity.
*/
capacity?: pulumi.Input<string>;
/**
* Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
*/
kind?: pulumi.Input<"CSIStorageCapacity">;
/**
* MaximumVolumeSize is the value reported by the CSI driver in its GetCapacityResponse for a GetCapacityRequest with topology and parameters that match the previous fields.
*
* This is defined since CSI spec 1.4.0 as the largest size that may be used in a CreateVolumeRequest.capacity_range.required_bytes field to create a volume with the same parameters as those in GetCapacityRequest. The corresponding value in the Kubernetes API is ResourceRequirements.Requests in a volume claim.
*/
maximumVolumeSize?: pulumi.Input<string>;
/**
* Standard object's metadata. The name has no particular meaning. It must be be a DNS subdomain (dots allowed, 253 characters). To ensure that there are no conflicts with other CSI drivers on the cluster, the recommendation is to use csisc-<uuid>, a generated name, or a reverse-domain name which ends with the unique CSI driver name.
*
* Objects are namespaced.
*
* More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
*/
metadata?: pulumi.Input<inputs.meta.v1.ObjectMeta>;
/**
* NodeTopology defines which nodes have access to the storage for which capacity was reported. If not set, the storage is not accessible from any node in the cluster. If empty, the storage is accessible from all nodes. This field is immutable.
*/
nodeTopology?: pulumi.Input<inputs.meta.v1.LabelSelector>;
/**
* The name of the StorageClass that the reported capacity applies to. It must meet the same requirements as the name of a StorageClass object (non-empty, DNS subdomain). If that object no longer exists, the CSIStorageCapacity object is obsolete and should be removed by its creator. This field is immutable.
*/
storageClassName: pulumi.Input<string>;
} | the_stack |
import {
Accessibility,
datepickerBehavior,
DatepickerBehaviorProps,
AccessibilityAttributes,
} from '@fluentui/accessibility';
import {
DateRangeType,
DayOfWeek,
FirstWeekOfYear,
DEFAULT_CALENDAR_STRINGS,
IDayGridOptions,
ICalendarStrings,
IDatepickerOptions,
IRestrictedDatesOptions,
} from '../../utils/date-time-utilities';
import {
getElementType,
useAccessibility,
useFluentContext,
useStyles,
useTelemetry,
useUnhandledProps,
useAutoControlled,
ForwardRefWithAs,
} from '@fluentui/react-bindings';
import { CalendarIcon } from '@fluentui/react-icons-northstar';
import * as customPropTypes from '@fluentui/react-proptypes';
import { handleRef } from '@fluentui/react-component-ref';
import * as _ from 'lodash';
import * as PropTypes from 'prop-types';
import * as React from 'react';
import { ComponentEventHandler, FluentComponentStaticProps, ShorthandValue } from '../../types';
import { commonPropTypes, createShorthand, createShorthandFactory, UIComponentProps } from '../../utils';
import { Button } from '../Button/Button';
import { Input, InputProps } from '../Input/Input';
import { Popup, PopupProps } from '../Popup/Popup';
import { DatepickerCalendar, DatepickerCalendarProps } from './DatepickerCalendar';
import { DatepickerCalendarCell } from './DatepickerCalendarCell';
import { DatepickerCalendarCellButton } from './DatepickerCalendarCellButton';
import { DatepickerCalendarHeader } from './DatepickerCalendarHeader';
import { DatepickerCalendarHeaderAction } from './DatepickerCalendarHeaderAction';
import { DatepickerCalendarHeaderCell } from './DatepickerCalendarHeaderCell';
import { DatepickerCalendarGrid } from './DatepickerCalendarGrid';
import { DatepickerCalendarGridRow } from './DatepickerCalendarGridRow';
import { validateDate } from './validateDate';
import { format } from '@uifabric/utilities';
export interface DatepickerProps extends UIComponentProps, Partial<ICalendarStrings>, Partial<IDatepickerOptions> {
/** Accessibility behavior if overridden by the user. */
accessibility?: Accessibility<DatepickerBehaviorProps>;
/** Identifies the element (or elements) that labels the current element. Will be passed to `input` with usage accessibibility behavior. */
'aria-labelledby'?: AccessibilityAttributes['aria-labelledby'];
/** Indicates the entered value does not conform to the format expected by the application. Will be passed to `input` with usage accessibibility behavior. */
'aria-invalid'?: AccessibilityAttributes['aria-invalid'];
/** Shorthand for the datepicker calendar. */
calendar?: ShorthandValue<DatepickerCalendarProps>;
/** Shorthand for the datepicker popup. */
popup?: ShorthandValue<PopupProps>;
/** Shorthand for the date text input. */
input?: ShorthandValue<InputProps>;
/** Datepicker shows it is currently unable to be interacted with. */
disabled?: boolean;
/** Date needs to be entered, otherwise datepicker produces an error state. */
required?: boolean;
/**
* Called on change of the date.
*
* @param event - React's original SyntheticEvent.
* @param data - All props and proposed value.
*/
onDateChange?: ComponentEventHandler<DatepickerProps & { value: Date }>;
/**
* Called on error when changing the date.
*
* @param event - React's original SyntheticEvent.
* @param data - All props and proposed value.
*/
onDateChangeError?: ComponentEventHandler<DatepickerProps & { error: string }>;
/** Target dates can be also entered through the input field. */
allowManualInput?: boolean;
/** The component automatically overrides faulty manual input upon blur. */
fallbackToLastCorrectDateOnBlur?: boolean;
/** Initial 'calendarOpenState' value. */
defaultCalendarOpenState?: boolean;
/** Controls the calendar's open state. */
calendarOpenState?: boolean;
/** Initial 'selectedDate' value. */
defaultSelectedDate?: Date;
/** Controls the calendar's 'selectedDate'. */
selectedDate?: Date;
/** Marks that the datepicker should only render the input field and not the trigger button with an icon. */
inputOnly?: boolean;
/** Marks that the datepicker should only render the trigger button with an icon and not the input field. */
buttonOnly?: boolean;
}
export type DatepickerStylesProps = Pick<DatepickerProps, 'allowManualInput'>;
export const datepickerClassName = 'ui-datepicker';
const formatRestrictedInput = (restrictedOptions: IRestrictedDatesOptions, localizationStrings: ICalendarStrings) => {
let formattedString = '';
if (!!restrictedOptions.minDate && !!restrictedOptions.maxDate) {
formattedString = format(
localizationStrings.inputBoundedFormatString,
localizationStrings.formatMonthDayYear(restrictedOptions.minDate, localizationStrings),
localizationStrings.formatMonthDayYear(restrictedOptions.maxDate, localizationStrings),
);
} else if (!!restrictedOptions.minDate) {
formattedString = format(
localizationStrings.inputMinBoundedFormatString,
localizationStrings.formatMonthDayYear(restrictedOptions.minDate, localizationStrings),
);
} else if (!!restrictedOptions.maxDate) {
formattedString = format(
localizationStrings.inputMaxBoundedFormatString,
localizationStrings.formatMonthDayYear(restrictedOptions.maxDate, localizationStrings),
);
} else {
formattedString = localizationStrings.inputAriaLabel;
}
return formattedString;
};
/**
* A Datepicker is a control which is used to display dates grid and allow user to select them.
*
* @accessibilityIssues
* [NVDA - Aria-selected is not narrated for the gridcell](https://github.com/nvaccess/nvda/issues/11986)
*/
export const Datepicker = (React.forwardRef<HTMLDivElement, DatepickerProps>((props, ref) => {
const context = useFluentContext();
const { setStart, setEnd } = useTelemetry(Datepicker.displayName, context.telemetry);
setStart();
const inputRef = React.useRef<HTMLElement>();
// FIXME: This object is created every render, causing a cascade of useCallback/useEffect re-runs.
// Needs to be reworked by someone who understands the intent for when various updates ought to happen.
// eslint-disable-next-line react-hooks/exhaustive-deps
const dateFormatting: ICalendarStrings = {
formatDay: props.formatDay,
formatYear: props.formatYear,
formatMonthDayYear: props.formatMonthDayYear,
formatMonthYear: props.formatMonthYear,
parseDate: props.parseDate,
months: props.months,
shortMonths: props.shortMonths,
days: props.days,
shortDays: props.shortDays,
isRequiredErrorMessage: props.isRequiredErrorMessage,
invalidInputErrorMessage: props.invalidInputErrorMessage,
isOutOfBoundsErrorMessage: props.isOutOfBoundsErrorMessage,
goToToday: props.goToToday,
openCalendarTitle: props.openCalendarTitle,
inputPlaceholder: props.inputPlaceholder,
prevMonthAriaLabel: props.prevMonthAriaLabel,
nextMonthAriaLabel: props.nextMonthAriaLabel,
prevYearAriaLabel: props.prevYearAriaLabel,
nextYearAriaLabel: props.nextYearAriaLabel,
prevYearRangeAriaLabel: props.prevYearRangeAriaLabel,
nextYearRangeAriaLabel: props.nextYearRangeAriaLabel,
monthPickerHeaderAriaLabel: props.monthPickerHeaderAriaLabel,
yearPickerHeaderAriaLabel: props.yearPickerHeaderAriaLabel,
closeButtonAriaLabel: props.closeButtonAriaLabel,
weekNumberFormatString: props.weekNumberFormatString,
selectedDateFormatString: props.selectedDateFormatString,
todayDateFormatString: props.todayDateFormatString,
inputAriaLabel: props.inputAriaLabel,
inputBoundedFormatString: props.inputBoundedFormatString,
inputMinBoundedFormatString: props.inputMinBoundedFormatString,
inputMaxBoundedFormatString: props.inputMaxBoundedFormatString,
};
const {
calendar,
popup,
input,
className,
design,
styles,
variables,
formatMonthDayYear,
allowManualInput,
'aria-labelledby': ariaLabelledby,
'aria-invalid': ariaInvalid,
} = props;
const valueFormatter = React.useCallback(
date =>
date
? formatMonthDayYear(date, {
months: dateFormatting.months,
shortMonths: dateFormatting.shortMonths,
days: dateFormatting.days,
shortDays: dateFormatting.shortDays,
})
: '',
[
dateFormatting.days,
dateFormatting.months,
dateFormatting.shortDays,
dateFormatting.shortMonths,
formatMonthDayYear,
],
);
const [openState, setOpenState] = useAutoControlled<boolean>({
defaultValue: props.defaultCalendarOpenState,
value: props.calendarOpenState,
initialValue: false,
});
const [selectedDate, setSelectedDate] = useAutoControlled<Date | undefined>({
defaultValue: props.defaultSelectedDate,
value: props.selectedDate,
initialValue: undefined,
});
const [formattedDate, setFormattedDate] = React.useState<string>(valueFormatter(selectedDate));
React.useEffect(() => {
setFormattedDate(valueFormatter(selectedDate));
}, [selectedDate, valueFormatter]);
const restrictedDatesOptions: IRestrictedDatesOptions = {
minDate: props.minDate,
maxDate: props.maxDate,
restrictedDates: props.restrictedDates,
};
const [error, setError] = React.useState<string>(() =>
!!props.selectedDate || !!props.defaultSelectedDate
? validateDate(selectedDate, formattedDate, restrictedDatesOptions, dateFormatting, props.required)
: '',
);
const calendarOptions: IDayGridOptions = {
selectedDate,
navigatedDate: !!selectedDate && !error ? selectedDate : props.today ?? new Date(),
firstDayOfWeek: props.firstDayOfWeek,
firstWeekOfYear: props.firstWeekOfYear,
dateRangeType: props.dateRangeType,
daysToSelectInDayView: props.daysToSelectInDayView,
today: props.today,
showWeekNumbers: props.showWeekNumbers,
workWeekDays: props.workWeekDays,
...restrictedDatesOptions,
};
const ElementType = getElementType(props);
const unhandledProps = useUnhandledProps(Datepicker.handledProps, props);
const getA11yProps = useAccessibility(props.accessibility, {
debugName: Datepicker.displayName,
actionHandlers: {
open: e => {
if (allowManualInput) {
setOpenState(!openState);
} else {
// Keep popup open in case we can only enter the date through calendar.
setOpenState(true);
}
e.preventDefault();
},
},
mapPropsToBehavior: () => ({
'aria-invalid': ariaInvalid,
'aria-labelledby': ariaLabelledby,
}),
rtl: context.rtl,
});
const { classes } = useStyles<DatepickerStylesProps>(Datepicker.displayName, {
className: datepickerClassName,
mapPropsToStyles: () => ({
allowManualInput,
}),
mapPropsToInlineStyles: () => ({
className,
design,
styles,
variables,
}),
rtl: context.rtl,
});
const overrideDatepickerCalendarProps = (predefinedProps: DatepickerCalendarProps): DatepickerCalendarProps => ({
onDateChange: (e, itemProps) => {
const targetDay = itemProps.value;
setSelectedDate(targetDay.originalDate);
setOpenState(false);
setError('');
setFormattedDate(valueFormatter(targetDay.originalDate));
_.invoke(props, 'onDateChange', e, { itemProps, value: targetDay.originalDate });
},
});
const calendarElement = createShorthand(DatepickerCalendar, calendar, {
defaultProps: () => getA11yProps('calendar', { ...calendarOptions, ...dateFormatting }),
overrideProps: overrideDatepickerCalendarProps,
});
const overrideInputProps = (predefinedProps: InputProps): InputProps => ({
onClick: (e): void => {
if (allowManualInput) {
setOpenState(!openState);
} else {
// Keep popup open in case we can only enter the date through calendar.
setOpenState(true);
}
_.invoke(predefinedProps, 'onClick', e, predefinedProps);
},
onChange: (e, target: { value: string }) => {
const parsedDate = props.parseDate(target.value);
const validationError = validateDate(parsedDate, target.value, calendarOptions, dateFormatting, props.required);
setError(validationError);
setFormattedDate(target.value);
if (!!validationError) {
_.invoke(props, 'onDateChangeError', e, { ...props, error: validationError });
} else {
setSelectedDate(parsedDate);
_.invoke(props, 'onDateChange', e, { ...props, value: parsedDate });
}
_.invoke(predefinedProps, 'onChange', e, predefinedProps);
},
onBlur: e => {
if (props.fallbackToLastCorrectDateOnBlur && !!error) {
const futureFormattedDate = valueFormatter(selectedDate);
const validationError = validateDate(
selectedDate,
futureFormattedDate,
calendarOptions,
dateFormatting,
props.required,
);
setError(validationError);
setFormattedDate(futureFormattedDate);
if (!!validationError) {
_.invoke(props, 'onDateChangeError', e, { ...props, error: validationError });
}
}
_.invoke(predefinedProps, 'onBlur', e, predefinedProps);
},
inputRef: (node: HTMLInputElement) => {
handleRef(predefinedProps.inputRef, node);
inputRef.current = node;
},
});
const triggerButtonElement = props.inputOnly ? null : (
<Button icon={<CalendarIcon />} title={props.openCalendarTitle} iconOnly disabled={props.disabled} type="button" />
);
const element = getA11yProps.unstable_wrapWithFocusZone(
<ElementType
{...getA11yProps('root', {
className: classes.root,
ref,
...unhandledProps,
})}
>
{!props.buttonOnly &&
createShorthand(Input, input, {
defaultProps: () =>
getA11yProps('input', {
placeholder: props.inputPlaceholder,
disabled: props.disabled,
error: !!error,
value: formattedDate,
readOnly: !allowManualInput,
required: props.required,
'aria-label': formatRestrictedInput(restrictedDatesOptions, dateFormatting),
}),
overrideProps: overrideInputProps,
})}
{createShorthand(Popup, popup, {
defaultProps: () => ({
open: openState && !props.disabled,
trapFocus: {
disableFirstFocus: true,
},
position: 'below' as const,
align: 'start' as const,
}),
overrideProps: (predefinedProps: PopupProps): PopupProps => ({
trigger: predefinedProps.trigger ?? triggerButtonElement,
target: props.buttonOnly ? null : inputRef.current,
content: calendarElement,
onOpenChange: (e, { open }) => {
// In case the event is a click on input, we ignore such events as it should be directly handled by input.
if (!(e.type === 'click' && e.target === inputRef?.current)) {
setOpenState(open);
_.invoke(predefinedProps, 'onOpenChange', e, { open });
}
},
}),
})}
</ElementType>,
);
setEnd();
return element;
}) as unknown) as ForwardRefWithAs<'div', HTMLDivElement, DatepickerProps> &
FluentComponentStaticProps<DatepickerProps> & {
Calendar: typeof DatepickerCalendar;
CalendarHeader: typeof DatepickerCalendarHeader;
CalendarHeaderAction: typeof DatepickerCalendarHeaderAction;
CalendarHeaderCell: typeof DatepickerCalendarHeaderCell;
CalendarCell: typeof DatepickerCalendarCell;
CalendarCellButton: typeof DatepickerCalendarCellButton;
CalendarGrid: typeof DatepickerCalendarGrid;
CalendarGridRow: typeof DatepickerCalendarGridRow;
Input: typeof Input;
};
Datepicker.displayName = 'Datepicker';
Datepicker.propTypes = {
...commonPropTypes.createCommon(),
calendar: customPropTypes.itemShorthand,
popup: customPropTypes.itemShorthand,
input: customPropTypes.itemShorthand,
disabled: PropTypes.bool,
required: PropTypes.bool,
onDateChange: PropTypes.func,
onDateChangeError: PropTypes.func,
allowManualInput: PropTypes.bool,
fallbackToLastCorrectDateOnBlur: PropTypes.bool,
defaultCalendarOpenState: PropTypes.bool,
calendarOpenState: PropTypes.bool,
selectedDate: PropTypes.instanceOf(Date),
defaultSelectedDate: PropTypes.instanceOf(Date),
inputOnly: PropTypes.bool,
buttonOnly: PropTypes.bool,
minDate: PropTypes.instanceOf(Date),
maxDate: PropTypes.instanceOf(Date),
restrictedDates: PropTypes.arrayOf(PropTypes.instanceOf(Date)),
firstDayOfWeek: PropTypes.oneOf(Object.keys(DayOfWeek).map(name => DayOfWeek[name])),
firstWeekOfYear: PropTypes.oneOf(Object.keys(FirstWeekOfYear).map(name => FirstWeekOfYear[name])),
dateRangeType: PropTypes.oneOf(Object.keys(DateRangeType).map(name => DateRangeType[name])),
daysToSelectInDayView: PropTypes.number,
today: PropTypes.instanceOf(Date),
showWeekNumbers: PropTypes.bool,
workWeekDays: PropTypes.arrayOf(PropTypes.oneOf(Object.keys(DayOfWeek).map(name => DayOfWeek[name]))),
formatDay: PropTypes.func,
formatYear: PropTypes.func,
formatMonthDayYear: PropTypes.func,
formatMonthYear: PropTypes.func,
parseDate: PropTypes.func,
months: PropTypes.arrayOf(PropTypes.string),
shortMonths: PropTypes.arrayOf(PropTypes.string),
days: PropTypes.arrayOf(PropTypes.string),
shortDays: PropTypes.arrayOf(PropTypes.string),
isRequiredErrorMessage: PropTypes.string,
invalidInputErrorMessage: PropTypes.string,
isOutOfBoundsErrorMessage: PropTypes.string,
goToToday: PropTypes.string,
openCalendarTitle: PropTypes.string,
inputPlaceholder: PropTypes.string,
prevMonthAriaLabel: PropTypes.string,
nextMonthAriaLabel: PropTypes.string,
prevYearAriaLabel: PropTypes.string,
nextYearAriaLabel: PropTypes.string,
prevYearRangeAriaLabel: PropTypes.string,
nextYearRangeAriaLabel: PropTypes.string,
monthPickerHeaderAriaLabel: PropTypes.string,
yearPickerHeaderAriaLabel: PropTypes.string,
closeButtonAriaLabel: PropTypes.string,
weekNumberFormatString: PropTypes.string,
selectedDateFormatString: PropTypes.string,
todayDateFormatString: PropTypes.string,
inputAriaLabel: PropTypes.string,
inputBoundedFormatString: PropTypes.string,
inputMinBoundedFormatString: PropTypes.string,
inputMaxBoundedFormatString: PropTypes.string,
'aria-labelledby': PropTypes.string,
'aria-invalid': PropTypes.bool,
};
Datepicker.defaultProps = {
accessibility: datepickerBehavior,
inputOnly: false,
buttonOnly: false,
calendar: {},
popup: {},
input: {},
firstDayOfWeek: DayOfWeek.Monday,
firstWeekOfYear: FirstWeekOfYear.FirstDay,
dateRangeType: DateRangeType.Day,
fallbackToLastCorrectDateOnBlur: true,
allowManualInput: true,
required: false,
...DEFAULT_CALENDAR_STRINGS,
};
Datepicker.handledProps = Object.keys(Datepicker.propTypes) as any;
Datepicker.create = createShorthandFactory({ Component: Datepicker });
Datepicker.Calendar = DatepickerCalendar;
Datepicker.CalendarHeader = DatepickerCalendarHeader;
Datepicker.CalendarHeaderAction = DatepickerCalendarHeaderAction;
Datepicker.CalendarHeaderCell = DatepickerCalendarHeaderCell;
Datepicker.CalendarCell = DatepickerCalendarCell;
Datepicker.CalendarCellButton = DatepickerCalendarCellButton;
Datepicker.CalendarGrid = DatepickerCalendarGrid;
Datepicker.CalendarGridRow = DatepickerCalendarGridRow;
Datepicker.Input = Input; | the_stack |
import { Base } from "../class/Base.js"
import { AnyFunction } from "../class/Mixin.js"
import { concat } from "../collection/Iterator.js"
import { warn } from "../environment/Debug.js"
import { CalculationContext, CalculationFunction, CalculationIterator, Context } from "../primitives/Calculation.js"
import { copySetInto, isGeneratorFunction } from "../util/Helpers.js"
import {
BreakCurrentStackExecution,
Effect,
HasProposedValueSymbol,
OwnIdentifierSymbol,
OwnQuarkSymbol,
PreviousValueOfEffect,
PreviousValueOfSymbol,
ProgressNotificationEffect,
ProposedArgumentsOfSymbol,
ProposedOrPreviousSymbol,
ProposedOrPreviousValueOfSymbol,
ProposedValueOfEffect,
ProposedValueOfSymbol,
RejectEffect,
RejectSymbol,
TransactionSymbol,
UnsafePreviousValueOfSymbol,
UnsafeProposedOrPreviousValueOfSymbol,
WriteEffect,
WriteSeveralEffect,
WriteSeveralSymbol,
WriteSymbol
} from "./Effect.js"
import { CalculatedValueGen, CalculatedValueGenC, CalculatedValueSyncC, Identifier, Variable, VariableC } from "./Identifier.js"
import { TombStone, Quark } from "./Quark.js"
import { Revision } from "./Revision.js"
import { EdgeTypePast, Transaction, TransactionCommitResult, YieldableValue } from "./Transaction.js"
import { ComputationCycle } from "./TransactionCycleDetectionWalkContext.js"
//---------------------------------------------------------------------------------------------------------------------
/**
* The type of the argument for the [[commit]] call. Currently empty.
*/
export type CommitArguments = {
}
/**
* The type of the return value of the [[commit]] call.
*/
export type CommitResult = {
/**
* If the transaction has been rejected, this property will be filled with the [[RejectEffect]] instance
*/
rejectedWith? : RejectEffect<unknown> | null
}
/**
* A constant which will be used a commit result, when graph is not available.
*/
export const CommitZero : CommitResult = {
rejectedWith : null
}
//---------------------------------------------------------------------------------------------------------------------
export class Listener extends Base {
handlers : AnyFunction[] = []
trigger (value : any) {
for (let i = 0; i < this.handlers.length; i++)
this.handlers[ i ](value)
}
}
//---------------------------------------------------------------------------------------------------------------------
/**
* Generic reactive graph. Consists from [[Identifier]]s, depending on each other. This is a low-level representation
* of the ChronoGraph dataset, it is not "aware" of the entity/relation framework and operates as "just graph".
*
* For higher-level (and more convenient) representation, please refer to [[Replica]].
*
* An example of usage:
*
* const graph = ChronoGraph.new({ historyLimit : 10 })
*
* const var1 = graph.variable(1)
* const var2 = graph.variable(2)
* const iden1 = graph.identifier((Y) => Y(var1) + Y(var2))
*
* graph.read(iden1) // 3
*
* graph.commit()
*
* graph.write(var1, 2)
*
* graph.read(iden1) // 4
*
* graph.reject()
*
* graph.read(var1) // 1
* graph.read(iden1) // 3
*
*/
export class ChronoGraph extends Base {
baseRevisionStable : Revision = undefined
baseRevisionTentative : Revision = undefined
baseRevision : Revision = Revision.new()
// the revision to follow to, when performing `redo` operation
topRevision : Revision = undefined
/**
* Integer value, indicating how many transactions to keep in memory, to be available for [[undo]] call.
* Default value is 0 - previous transaction is cleared immediately.
*
* Increase this config to opt-in for the [[undo]]/[[redo]] functionality.
*/
historyLimit : number = 0
listeners : Map<Identifier, Listener> = new Map()
$activeTransaction : Transaction = undefined
isCommitting : boolean = false
enableProgressNotifications : boolean = false
ongoing : Promise<any> = Promise.resolve()
_isInitialCommit : boolean = true
//-------------------------------------
// a "cross-platform" trick to avoid specifying the type of the `autoCommitTimeoutId` explicitly
autoCommitTimeoutId : ReturnType<typeof setTimeout> = null
/**
* If this option is enabled with `true` value, all data modification calls ([[write]], [[addIdentifier]], [[removeIdentifier]]) will trigger
* a delayed [[commit]] call (or [[commitAsync]], depending from the [[autoCommitMode]] option).
*/
autoCommit : boolean = false
/**
* Indicates the default commit mode, which is used in [[autoCommit]].
*/
autoCommitMode : 'sync' | 'async' = 'sync'
autoCommitHandler : AnyFunction = null
onWriteDuringCommit : 'throw' | 'warn' | 'ignore' = 'throw'
onComputationCycle : 'throw' | 'warn' | 'reject' | 'ignore' | 'effect' = 'throw'
transactionClass : typeof Transaction = Transaction
initialize (...args) {
super.initialize(...args)
if (!this.topRevision) this.topRevision = this.baseRevision
if (this.autoCommit) {
this.autoCommitHandler = this.autoCommitMode === 'sync' ? arg => this.commit(arg) : async arg => this.commitAsync(arg)
}
this.markAndSweep()
}
/**
* Returns boolean, indicating whether the auto-commit is pending.
*/
hasPendingAutoCommit () : boolean {
return this.autoCommitTimeoutId !== null
}
get dirty () : boolean {
return this.activeTransaction.dirty
}
get dirtyProposed () : boolean {
return this.activeTransaction.dirtyProposed
}
clear () {
this.reject()
this.unScheduleAutoCommit()
// some stale state - `clear` called at sensitive time
this.baseRevision.scope && this.baseRevision.scope.clear()
this.baseRevision.previous = null
this.listeners.clear()
this.topRevision = this.baseRevision
this.$followingRevision = undefined
this.$activeTransaction = undefined
this.markAndSweep()
}
* eachReachableRevision () : IterableIterator<[ Revision, boolean ]> {
let isBetweenTopBottom = true
let counter = 0
for (const revision of this.topRevision.previousAxis()) {
yield [ revision, isBetweenTopBottom || counter < this.historyLimit ]
if (revision === this.baseRevision) {
isBetweenTopBottom = false
} else {
if (!isBetweenTopBottom) counter++
}
}
}
get isInitialCommit () : boolean {
return this._isInitialCommit
}
set isInitialCommit (value : boolean) {
this._isInitialCommit = value
}
markAndSweep () {
let lastReferencedRevision : Revision
const unreachableRevisions : Revision[] = []
for (const [ revision, isReachable ] of this.eachReachableRevision()) {
if (isReachable) {
revision.reachableCount++
lastReferencedRevision = revision
} else
unreachableRevisions.push(revision)
revision.referenceCount++
}
unreachableRevisions.unshift(lastReferencedRevision)
for (let i = unreachableRevisions.length - 1; i >= 1 && unreachableRevisions[ i ].reachableCount === 0; i--) {
this.compactRevisions(unreachableRevisions[ i - 1 ], unreachableRevisions[ i ])
}
}
compactRevisions (newRev : Revision, prevRev : Revision) {
if (prevRev.reachableCount > 0 || newRev.previous !== prevRev) throw new Error("Invalid compact operation")
// we can only shred revision if its being referenced maximum 1 time (from the current Checkout instance)
if (prevRev.referenceCount <= 1) {
for (const [ identifier, entry ] of newRev.scope) {
if (entry.getValue() === TombStone) {
prevRev.scope.delete(identifier)
} else {
const prevQuark = prevRev.scope.get(identifier)
if (entry.origin === entry) {
if (prevQuark) {
prevQuark.clear()
prevQuark.clearProperties()
}
}
else if (prevQuark && entry.origin === prevQuark) {
entry.mergePreviousOrigin(newRev.scope)
}
else if (identifier.lazy && !entry.origin && prevQuark && prevQuark.origin) {
// for lazy quarks, that depends on the `ProposedOrPrevious` effect, we need to save the value or proposed value
// from the previous revision
entry.startOrigin().proposedValue = prevQuark.origin.value !== undefined ? prevQuark.origin.value : prevQuark.origin.proposedValue
}
entry.previous = undefined
prevRev.scope.set(identifier, entry)
}
}
copySetInto(newRev.selfDependent, prevRev.selfDependent)
// some help for garbage collector
// this clears the "entries" in the transaction commit result in the "finalizeCommitAsync"
// newRev.scope.clear()
newRev.scope = prevRev.scope
// make sure the previous revision won't be used inconsistently
prevRev.scope = null
}
// otherwise, we have to copy from it, and keep it intact
else {
newRev.scope = new Map(concat(prevRev.scope, newRev.scope))
newRev.selfDependent = new Set(concat(prevRev.selfDependent, newRev.selfDependent))
prevRev.referenceCount--
}
// in both cases break the `previous` chain
newRev.previous = null
}
$followingRevision : Map<Revision, Revision> = undefined
get followingRevision () : Map<Revision, Revision> {
if (this.$followingRevision !== undefined) return this.$followingRevision
const revisions = Array.from(this.topRevision.previousAxis())
const entries : [ Revision, Revision ][] = []
for (let i = revisions.length - 1; i > 0; i--)
entries.push([ revisions[ i ], revisions[ i - 1 ] ])
return this.$followingRevision = new Map(entries)
}
get activeTransaction () : Transaction {
if (this.$activeTransaction) return this.$activeTransaction
return this.$activeTransaction = this.transactionClass.new({
baseRevision : this.baseRevisionTentative || this.baseRevision,
graph : this
})
}
/**
* Creates a new branch of this graph. Only committed data will be "visible" in the new branch.
*
* ```ts
* const graph2 = ChronoGraph.new()
*
* const variable13 : Variable<number> = graph2.variable(5)
*
* const branch2 = graph2.branch()
*
* branch2.write(variable13, 10)
*
* const value13_1 = graph2.read(variable13) // 5
* const value13_2 = branch2.read(variable13) // 10
* ```
*
* When using the branching feature in [[Replica]], you need to reference the field values by yielding their
* corresponding identifiers. This is because ChronoGraph need to know in context of which branch
* the calculation happens and this information is encoded in the outer context. This may improve in the future.
*
* ```ts
* class Author extends Entity.mix(Base) {
* @calculate('fullName')
* calculateFullName (Y) : string {
* return Y(this.$.firstName) + ' ' + Y(this.$.lastName)
* }
*
* @calculate('fullName')
* * calculateFullName (Y) : CalculationIterator<string> {
* return (yield this.$.firstName) + ' ' + (yield this.$.lastName)
* }
* }
* ```
*
* @param config Configuration object for the new graph instance.
*/
branch (config? : Partial<this>) : this {
const Constructor = this.constructor as (typeof ChronoGraph)
return Constructor.new(Object.assign({}, config, { baseRevision : this.baseRevision })) as this
}
propagate (args? : CommitArguments) : CommitResult {
return this.commit(args)
}
/**
* Rejects the current changes in the graph and revert it to the state of the previous [[commit]].
*
* See also [[RejectEffect]].
*
* @param reason Any value, describing why reject has happened
*/
reject<Reason> (reason? : Reason) {
this.activeTransaction.reject(RejectEffect.new({ reason }))
// reject resets the `ongoing` promise (which is possibly rejected because of cycle exception)
this.ongoing = Promise.resolve()
this.$activeTransaction = undefined
this.baseRevisionTentative = undefined
if (this.baseRevisionStable) {
this.baseRevision = this.baseRevisionStable
this.baseRevisionStable = undefined
}
}
/**
* Synchronously commit the state of the graph. All potentially changed [[Identifier.lazy|strict]] identifiers
* will be calculated during this call. If any of such identifiers will be [[Identifier.sync|async]], an exception
* will be thrown.
*
* This call marks a "stable" state of the graph and a transaction border. Using the [[undo]] call one can revert to the previous
* state.
*
* See also [[reject]].
*
* @param args
*/
commit (args? : CommitArguments) : CommitResult {
// TODO should have a "while" loop adding extra transactions, similar to `commitAsync`
this.unScheduleAutoCommit()
this.baseRevisionStable = this.baseRevision
const activeTransaction = this.activeTransaction
const transactionCommitResult = activeTransaction.commit(args)
this.$activeTransaction = undefined
const result = this.finalizeCommit(transactionCommitResult)
this.baseRevisionStable = undefined
this.isInitialCommit = false
return result
}
async propagateAsync (args? : CommitArguments) : Promise<CommitResult> {
return this.commitAsync(args)
}
/**
* Asynchronously commit the state of the replica. All potentially changed strict identifiers (see [[Identifier.lazy]])
* will be calculated during this call.
*
* This call marks a "stable" state of the graph and a transaction border. Using the [[undo]] call one can revert to the previous
* state.
*
* See also [[reject]].
*
* @param args
*/
async commitAsync (args? : CommitArguments) : Promise<CommitResult> {
if (this.isCommitting) return this.ongoing
this.isCommitting = true
this.baseRevisionStable = this.baseRevision
let result : CommitResult
return this.ongoing = this.ongoing.then(() => {
return this.doCommitAsync(args)
}).then(res => {
result = res
return res
}).finally(() => {
this.baseRevisionStable = undefined
this.baseRevisionTentative = undefined
this.isInitialCommit = false
this.isCommitting = false
})
}
async doCommitAsync (args? : CommitArguments) : Promise<CommitResult> {
this.unScheduleAutoCommit()
const activeTransaction = this.activeTransaction
const transactionResult = await activeTransaction.commitAsync(args)
this.baseRevisionTentative = activeTransaction.candidate
this.$activeTransaction = undefined
const result = this.finalizeCommit(transactionResult)
await this.finalizeCommitAsync(transactionResult)
if (activeTransaction.rejectedWith) activeTransaction.clearRejected()
if (this.dirty) {
await this.doCommitAsync(args)
}
return result
}
finalizeCommit (transactionResult : TransactionCommitResult) : CommitResult {
const { revision, entries, transaction } = transactionResult
if (!transaction.rejectedWith) {
if (revision.previous !== this.baseRevision) throw new Error('Invalid revisions chain')
// dereference all revisions
for (const [ revision, isReachable ] of this.eachReachableRevision()) {
if (isReachable) revision.reachableCount--
revision.referenceCount--
}
this.baseRevision = this.topRevision = revision
// activating listeners BEFORE the `markAndSweep`, because in that call, `baseRevision`
// might be already merged with previous
for (const [ identifier, quarkEntry ] of entries) {
quarkEntry.cleanup()
// ignore "shadowing" and lazy entries
if (quarkEntry.isShadow() || !quarkEntry.hasValue()) continue
const listener = this.listeners.get(identifier)
if (listener) listener.trigger(quarkEntry.getValue())
}
this.$followingRevision = undefined
this.markAndSweep()
} else {
// `baseRevisionStable` might be already cleared in the `reject` method of the graph
if (this.baseRevisionStable) this.baseRevision = this.baseRevisionStable
this.baseRevisionStable = undefined
this.baseRevisionTentative = undefined
}
return { rejectedWith : transaction.rejectedWith }
}
async finalizeCommitAsync (transactionResult : TransactionCommitResult) {
}
* onComputationCycleHandler (cycle : ComputationCycle) : Generator<any, IteratorResult<any>> {
const exception = new Error("Computation cycle:\n" + cycle)
//@ts-ignore
exception.cycle = cycle
switch (this.onComputationCycle) {
case 'ignore' :
console.log(exception.message)
const { requestedEntry, activeEntry } = cycle
// if we ignore the cycle we just continue the calculation with the best possible value
return activeEntry.continueCalculation(requestedEntry.proposedValue !== undefined ? requestedEntry.proposedValue : requestedEntry.value)
case 'throw' :
throw exception
case 'reject' :
this.reject(exception)
break
case 'warn' :
warn(exception)
break
}
}
onComputationCycleHandlerSync (cycle : ComputationCycle) {
const exception = new Error("Computation cycle:\n" + cycle)
//@ts-ignore
exception.cycle = cycle
switch (this.onComputationCycle) {
case 'ignore' :
console.log(exception.message)
const { requestedEntry, activeEntry } = cycle
// if we ignore the cycle we just continue the calculation with the best possible value
return activeEntry.continueCalculation(requestedEntry.proposedValue !== undefined ? requestedEntry.proposedValue : requestedEntry.value)
case 'throw' :
throw exception
case 'reject' :
this.reject(exception)
break
case 'warn' :
warn(exception)
break
}
}
scheduleAutoCommit () {
// the `&& !this.isCommitting` part was added for the conflicts branch
// however, it seems to fail several tests
// commenting for now, to be reviewed later
if (this.autoCommitTimeoutId === null /*&& !this.isCommitting*/) {
this.autoCommitTimeoutId = setTimeout(this.autoCommitHandler, 10)
}
}
unScheduleAutoCommit () {
if (this.autoCommitTimeoutId !== null) {
clearTimeout(this.autoCommitTimeoutId)
this.autoCommitTimeoutId = null
}
}
/**
* Creates a variable identifier with the given initial value and adds it to graph.
*
* @param value The initial value. The `undefined` value will be converted to `null`
*/
variable<T> (value : T) : Variable<T> {
const variable = VariableC<T>()
// always initialize variables with `null`
return this.addIdentifier(variable, value === undefined ? null : value)
}
/**
* Creates a named variable identifier with the given initial value and adds it to graph.
*
* @param name The [[Variable.name]] property of the newly created variable
* @param value The initial value. The `undefined` value will be converted to `null`
*/
variableNamed<T> (name : any, value : T) : Variable<T> {
const variable = VariableC<T>({ name })
// always initialize variables with `null`
return this.addIdentifier(variable, value === undefined ? null : value)
}
/**
* Creates an identifier based on the given calculation function and adds it to this graph. Depending form the type of the function
* (sync/generator) either [[CalculatedValueGen]] or [[CalculatedValueSync]] will be created.
*
* To have full control on the identifier creation, instantiate it yourself and add to graph using the [[ChronoGraph.addIdentifier]] call.
*
* @param calculation The calculation function of the identifier.
* @param context The [[Identifier.context|context]] property of the newly created identifier
*/
identifier<ContextT extends Context, ValueT> (calculation : CalculationFunction<ContextT, ValueT, any, [ CalculationContext<any>, ...any[] ]>, context? : any) : Identifier<ValueT, ContextT> {
const identifier : Identifier<ValueT, ContextT> = isGeneratorFunction(calculation) ?
CalculatedValueGenC<ValueT>({ calculation, context }) as Identifier<ValueT, ContextT>
:
CalculatedValueSyncC<ValueT>({ calculation, context }) as Identifier<ValueT, ContextT>
return this.addIdentifier(identifier)
}
/**
* Creates a named identifier based on the given calculation function and adds it to this graph. Depending form the type of the function
* (sync/generator) either [[CalculatedValueGen]] or [[CalculatedValueSync]] will be created.
*
* To have full control on the identifier creation, instantiate it yourself and add to graph using the [[ChronoGraph.addIdentifier]] call.
*
* @param name The [[Identifier.name]] property of the newly created identifier
* @param calculation The calculation function of the identifier.
* @param context The [[Identifier.context]] property of the newly created identifier
*/
identifierNamed<ContextT extends Context, ValueT> (name : any, calculation : CalculationFunction<ContextT, ValueT, any, [ CalculationContext<any>, ...any[] ]>, context? : any) : Identifier<ValueT, ContextT> {
const identifier : Identifier<ValueT, ContextT> = calculation.constructor.name === 'GeneratorFunction' ?
CalculatedValueGenC<ValueT>({ name, calculation, context }) as Identifier<ValueT, ContextT>
:
CalculatedValueSyncC<ValueT>({ name, calculation, context }) as Identifier<ValueT, ContextT>
return this.addIdentifier(identifier)
}
/**
* Adds an identifier to this graph. Optionally [[write|writes]] the `proposedValue` to it afterwards.
*
* @param identifier
* @param proposedValue
* @param args
*/
addIdentifier<T extends Identifier> (identifier : T, proposedValue? : any, ...args : any[]) : T {
if (this.isCommitting) {
if (this.onWriteDuringCommit === 'throw')
throw new Error('Adding identifier during commit')
else if (this.onWriteDuringCommit === 'warn')
warn(new Error('Adding identifier during commit'))
}
this.activeTransaction.addIdentifier(identifier, proposedValue, ...args)
if (this.autoCommit) this.scheduleAutoCommit()
return identifier
}
/**
* Removes an identifier from this graph.
*
* @param identifier
*/
removeIdentifier (identifier : Identifier) {
if (this.isCommitting) {
if (this.onWriteDuringCommit === 'throw')
throw new Error('Removing identifier during commit')
else if (this.onWriteDuringCommit === 'warn')
warn(new Error('Removinfg identifier during commit'))
}
this.activeTransaction.removeIdentifier(identifier)
this.listeners.delete(identifier)
if (this.autoCommit) this.scheduleAutoCommit()
}
/**
* Tests, whether this graph has given identifier.
*
* @param identifier
*/
hasIdentifier (identifier : Identifier) : boolean {
return this.activeTransaction.hasIdentifier(identifier)
}
/**
* Writes a value to the given `identifier`.
*
* @param identifier
* @param proposedValue
* @param args
*/
write<T> (identifier : Identifier<T>, proposedValue : T, ...args : any[]) {
if (this.isCommitting) {
if (this.onWriteDuringCommit === 'throw')
throw new Error('Write during commit')
else if (this.onWriteDuringCommit === 'warn')
warn(new Error('Write during commit'))
}
this.activeTransaction.write(identifier, proposedValue, ...args)
if (this.autoCommit) this.scheduleAutoCommit()
}
// keep if possible?
// pin (identifier : Identifier) : Quark {
// return this.activeTransaction.pin(identifier)
// }
// Synchronously read the "previous", "stable" value from the graph. If its a lazy entry, it will be calculated
// Synchronous read can not calculate lazy asynchronous identifiers and will throw exception
// Lazy identifiers supposed to be "total" (or accept repeating observes?)
readPrevious<T> (identifier : Identifier<T>) : T {
return this.activeTransaction.readPrevious(identifier)
}
// Asynchronously read the "previous", "stable" value from the graph. If its a lazy entry, it will be calculated
// Asynchronous read can calculate both synchornous and asynchronous lazy identifiers.
// Lazy identifiers supposed to be "total" (or accept repeating observes?)
readPreviousAsync<T> (identifier : Identifier<T>) : Promise<T> {
return this.activeTransaction.readPreviousAsync(identifier)
}
/**
* Synchronously read the value of the given identifier from the graph.
*
* Synchronous read can not calculate asynchronous identifiers and will throw exception
*
* @param identifier
*/
read<T> (identifier : Identifier<T>) : T {
return this.activeTransaction.read(identifier)
}
/**
* Asynchronously read the value of the given identifier from the graph.
*
* Asynchronous read can calculate both synchronous and asynchronous identifiers
*
* @param identifier
*/
readAsync<T> (identifier : Identifier<T>) : Promise<T> {
return this.activeTransaction.readAsync(identifier)
}
/**
* Read the value of the identifier either synchronously or asynchronously, depending on its type (see [[Identifier.sync]])
*
* @param identifier
*/
get<T> (identifier : Identifier<T>) : T | Promise<T> {
return this.activeTransaction.get(identifier)
}
// // read the identifier value, return the proposed value if no "current" value is calculated yet
// readDirty<T> (identifier : Identifier<T>) : T {
// return this.activeTransaction.readDirty(identifier)
// }
//
//
// // read the identifier value, return the proposed value if no "current" value is calculated yet
// readDirtyAsync<T> (identifier : Identifier<T>) : Promise<T> {
// return this.activeTransaction.readDirtyAsync(identifier)
// }
observe
<ContextT extends Context, Result, Yield extends YieldableValue, ArgsT extends [ CalculationContext<Yield>, ...any[] ]>
(observerFunc : CalculationFunction<ContextT, Result, Yield, ArgsT>, onUpdated : (value : Result) => any) : Identifier<Result>
{
const identifier = this.addIdentifier(CalculatedValueGen.new({
// observers are explicitly eager
lazy : false,
calculation : observerFunc as any,
// equality : () => false,
// this is to be able to extract observer identifiers only
// segment : ObserverSegment
}))
this.addListener(identifier, onUpdated)
return identifier as Identifier<Result>
}
observeContext
<ContextT extends Context, Result, Yield extends YieldableValue, ArgsT extends [ CalculationContext<Yield>, ...any[] ]>
(observerFunc : CalculationFunction<ContextT, Result, Yield, ArgsT>, context : object, onUpdated : (value : Result) => any) : Identifier<Result>
{
const identifier = this.addIdentifier(CalculatedValueGen.new({
// observers are explicitly eager
lazy : false,
calculation : observerFunc as any,
context : context,
// equality : () => false,
// this is to be able to extract observer identifiers only
// segment : ObserverSegment
}))
this.addListener(identifier, onUpdated)
return identifier as Identifier<Result>
}
addListener (identifier : Identifier, onUpdated : (value : any) => any) {
let listener = this.listeners.get(identifier)
if (!listener) {
listener = Listener.new()
this.listeners.set(identifier, listener)
}
listener.handlers.push(onUpdated)
}
/**
* Revert the replica to the state of previous transaction (marked with the [[commit]] call).
*
* To enable this feature, you need to opt-in using the [[ChronoGraph.historyLimit|historyLimit]] configuration property.
*
* Returns boolean, indicating whether the state transition actually happened.
*/
undo () : boolean {
const baseRevision = this.baseRevision
const previous = baseRevision.previous
if (!previous) return false
this.baseRevision = previous
// note: all unpropagated "writes" are lost
this.$activeTransaction = undefined
return true
}
/**
* Advance the replica to the state of next transaction (marked with the [[commit]] call). Only meaningful
* if a [[ChronoGraph.undo|undo]] call has been made earlier.
*
* To enable this feature, you need to opt-in using the [[historyLimit]] configuration property.
*
* Returns boolean, indicating whether the state transition actually happened.
*/
redo () : boolean {
const baseRevision = this.baseRevision
if (baseRevision === this.topRevision) return false
const nextRevision = this.followingRevision.get(baseRevision)
this.baseRevision = nextRevision
// note: all unpropagated "writes" are lost
this.$activeTransaction = undefined
return true
}
onPropagationProgressNotification (notification : ProgressNotificationEffect) {
}
[ProposedOrPreviousSymbol] (effect : Effect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
activeEntry.usedProposedOrPrevious = true
const proposedValue = activeEntry.getProposedValue(transaction)
if (proposedValue !== undefined) return proposedValue
// newly added identifier
if (!activeEntry.previous) return undefined
const identifier = activeEntry.identifier
if (identifier.lazy) {
if (activeEntry.previous.hasValue()) return activeEntry.previous.getValue()
if (activeEntry.previous.hasProposedValue()) return activeEntry.previous.getProposedValue(transaction)
return null
}
return transaction.readPrevious(activeEntry.identifier)
}
[RejectSymbol] (effect : RejectEffect<any>, transaction : Transaction) : any {
this.reject(effect.reason)
return BreakCurrentStackExecution
}
[TransactionSymbol] (effect : Effect, transaction : Transaction) : any {
return transaction
}
[OwnQuarkSymbol] (effect : Effect, transaction : Transaction) : any {
return transaction.getActiveEntry()
}
[OwnIdentifierSymbol] (effect : Effect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
return activeEntry.identifier
}
[WriteSymbol] (effect : WriteEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
if (activeEntry.identifier.lazy) throw new Error('Lazy identifiers can not use `Write` effect')
const writeToHigherLevel = effect.identifier.level > activeEntry.identifier.level
if (!writeToHigherLevel) transaction.walkContext.startNewEpoch()
transaction.write(effect.identifier, ...effect.proposedArgs)
// // transaction.writes.push(effect)
//
// // const writeTo = effect.identifier
// //
// // writeTo.write.call(writeTo.context || writeTo, writeTo, transaction, null, ...effect.proposedArgs)
//
// transaction.onNewWrite()
return writeToHigherLevel ? undefined : BreakCurrentStackExecution
}
[WriteSeveralSymbol] (effect : WriteSeveralEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
if (activeEntry.identifier.lazy) throw new Error('Lazy identifiers can not use `Write` effect')
let writeToHigherLevel = true
// effect.writes.forEach(writeInfo => {
effect.writes.forEach(writeInfo => {
if (writeInfo.identifier.level <= activeEntry.identifier.level && writeToHigherLevel) {
transaction.walkContext.startNewEpoch()
writeToHigherLevel = false
}
transaction.write(writeInfo.identifier, ...writeInfo.proposedArgs)
})
// const identifier = writeInfo.identifier
//
// identifier.write.call(identifier.context || identifier, identifier, transaction, null, ...writeInfo.proposedArgs)
// })
// transaction.onNewWrite()
return writeToHigherLevel ? undefined : BreakCurrentStackExecution
}
[PreviousValueOfSymbol] (effect : PreviousValueOfEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
const source = effect.identifier
transaction.addEdge(source, activeEntry, EdgeTypePast)
return transaction.readPrevious(source)
}
[ProposedValueOfSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
const source = effect.identifier
transaction.addEdge(source, activeEntry, EdgeTypePast)
const quark = transaction.entries.get(source)
const proposedValue = quark && !quark.isShadow() ? quark.getProposedValue(transaction) : undefined
return proposedValue
}
[HasProposedValueSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
const source = effect.identifier
transaction.addEdge(source, activeEntry, EdgeTypePast)
const quark = transaction.entries.get(source)
return quark ? quark.hasProposedValue() : false
}
[ProposedOrPreviousValueOfSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
const source = effect.identifier
transaction.addEdge(source, activeEntry, EdgeTypePast)
return transaction.readProposedOrPrevious(source)
}
[UnsafeProposedOrPreviousValueOfSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
return transaction.readProposedOrPrevious(effect.identifier)
}
[UnsafePreviousValueOfSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
return transaction.readPrevious(effect.identifier)
}
[ProposedArgumentsOfSymbol] (effect : ProposedValueOfEffect, transaction : Transaction) : any {
const activeEntry = transaction.getActiveEntry()
const source = effect.identifier
transaction.addEdge(source, activeEntry, EdgeTypePast)
const quark = transaction.entries.get(source)
return quark && !quark.isShadow() ? quark.proposedArguments : undefined
}
}
/**
* Type, that represent the return value of the generator-based identifier's calculation function.
* The `Result` argument corresponds to the type of the value being computed.
*
* For example:
*
* class Author extends Entity.mix(Base) {
* @field()
* firstName : string
* @field()
* lastName : string
* @field()
* fullName : string
*
* @calculate('fullName')
* * calculateFullName () : ChronoIterator<string> {
* return (yield this.$.firstName) + ' ' + (yield this.$.lastName)
* }
* }
*/
export type ChronoIterator<ResultT, YieldT = any> = CalculationIterator<ResultT, YieldT> | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.