text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import type {Side} from '@floating-ui/core';
import type {FloatingContext, FloatingTreeType, ReferenceType} from './types';
import {getChildren} from './utils/getChildren';
type Point = [number, number];
type Polygon = Point[];
function isPointInPolygon(point: Point, polygon: Polygon) {
const [x, y] = point;
let isInside = false;
const length = polygon.length;
for (let i = 0, j = length - 1; i < length; j = i++) {
const [xi, yi] = polygon[i] || [0, 0];
const [xj, yj] = polygon[j] || [0, 0];
const intersect =
yi >= y !== yj >= y && x <= ((xj - xi) * (y - yi)) / (yj - yi) + xi;
if (intersect) {
isInside = !isInside;
}
}
return isInside;
}
export function safePolygon<RT extends ReferenceType = ReferenceType>({
restMs = 0,
buffer = 0.5,
debug = null,
}: Partial<{
restMs: number;
buffer: number;
debug: null | ((points?: string | null) => void);
}> = {}) {
let timeoutId: NodeJS.Timeout;
let polygonIsDestroyed = false;
return ({
x,
y,
placement,
refs,
onClose,
nodeId,
tree,
leave = false,
}: FloatingContext<RT> & {
onClose: () => void;
tree?: FloatingTreeType<RT> | null;
leave?: boolean;
}) => {
return function onPointerMove(event: PointerEvent) {
clearTimeout(timeoutId);
function close() {
clearTimeout(timeoutId);
onClose();
}
if (event.pointerType && event.pointerType !== 'mouse') {
return;
}
const {clientX, clientY} = event;
const target =
'composedPath' in event
? event.composedPath()[0]
: (event as Event).target;
const targetNode = target as Element | null;
// If the pointer is over the reference or floating element already, there
// is no need to run the logic.
if (
event.type === 'pointermove' &&
refs.domReference.current?.contains(targetNode)
) {
return;
}
// If any nested child is open, abort.
if (
tree &&
getChildren(tree.nodesRef.current, nodeId).some(
({context}) => context?.open
)
) {
return;
}
// The cursor landed, so we destroy the polygon logic
if (refs.floating.current?.contains(targetNode) && !leave) {
polygonIsDestroyed = true;
return;
}
if (
!refs.domReference.current ||
!refs.floating.current ||
placement == null ||
x == null ||
y == null
) {
return;
}
const refRect = refs.domReference.current.getBoundingClientRect();
const rect = refs.floating.current.getBoundingClientRect();
const side = placement.split('-')[0] as Side;
const cursorLeaveFromRight = x > rect.right - rect.width / 2;
const cursorLeaveFromBottom = y > rect.bottom - rect.height / 2;
// If the pointer is leaving from the opposite side, the "buffer" logic
// creates a point where the floating element remains open, but should be
// ignored.
// A constant of 1 handles floating point rounding errors.
if (
(side === 'top' && y >= refRect.bottom - 1) ||
(side === 'bottom' && y <= refRect.top + 1) ||
(side === 'left' && x >= refRect.right - 1) ||
(side === 'right' && x <= refRect.left + 1)
) {
return close();
}
// Ignore when the cursor is within the rectangular trough between the
// two elements. Since the triangle is created from the cursor point,
// which can start beyond the ref element's edge, traversing back and
// forth from the ref to the floating element can cause it to close. This
// ensures it always remains open in that case.
switch (side) {
case 'top':
if (
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= refRect.top + 1
) {
return;
}
break;
case 'bottom':
if (
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= refRect.bottom - 1 &&
clientY <= rect.bottom
) {
return;
}
break;
case 'left':
if (
clientX >= rect.left &&
clientX <= refRect.left + 1 &&
clientY >= rect.top &&
clientY <= rect.bottom
) {
return;
}
break;
case 'right':
if (
clientX >= refRect.right - 1 &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
) {
return;
}
break;
}
if (polygonIsDestroyed) {
return close();
}
function getPolygon([x, y]: Point): Array<Point> {
const isFloatingWider = rect.width > refRect.width;
const isFloatingTaller = rect.height > refRect.height;
switch (side) {
case 'top': {
const cursorPointOne: Point = [
isFloatingWider
? x + buffer / 2
: cursorLeaveFromRight
? x + buffer * 4
: x - buffer * 4,
y + buffer + 1,
];
const cursorPointTwo: Point = [
isFloatingWider
? x - buffer / 2
: cursorLeaveFromRight
? x + buffer * 4
: x - buffer * 4,
y + buffer + 1,
];
const commonPoints: [Point, Point] = [
[
rect.left,
cursorLeaveFromRight
? rect.bottom - buffer
: isFloatingWider
? rect.bottom - buffer
: rect.top,
],
[
rect.right,
cursorLeaveFromRight
? isFloatingWider
? rect.bottom - buffer
: rect.top
: rect.bottom - buffer,
],
];
return [cursorPointOne, cursorPointTwo, ...commonPoints];
}
case 'bottom': {
const cursorPointOne: Point = [
isFloatingWider
? x + buffer / 2
: cursorLeaveFromRight
? x + buffer * 4
: x - buffer * 4,
y - buffer,
];
const cursorPointTwo: Point = [
isFloatingWider
? x - buffer / 2
: cursorLeaveFromRight
? x + buffer * 4
: x - buffer * 4,
y - buffer,
];
const commonPoints: [Point, Point] = [
[
rect.left,
cursorLeaveFromRight
? rect.top + buffer
: isFloatingWider
? rect.top + buffer
: rect.bottom,
],
[
rect.right,
cursorLeaveFromRight
? isFloatingWider
? rect.top + buffer
: rect.bottom
: rect.top + buffer,
],
];
return [cursorPointOne, cursorPointTwo, ...commonPoints];
}
case 'left': {
const cursorPointOne: Point = [
x + buffer + 1,
isFloatingTaller
? y + buffer / 2
: cursorLeaveFromBottom
? y + buffer * 4
: y - buffer * 4,
];
const cursorPointTwo: Point = [
x + buffer + 1,
isFloatingTaller
? y - buffer / 2
: cursorLeaveFromBottom
? y + buffer * 4
: y - buffer * 4,
];
const commonPoints: [Point, Point] = [
[
cursorLeaveFromBottom
? rect.right - buffer
: isFloatingTaller
? rect.right - buffer
: rect.left,
rect.top,
],
[
cursorLeaveFromBottom
? isFloatingTaller
? rect.right - buffer
: rect.left
: rect.right - buffer,
rect.bottom,
],
];
return [...commonPoints, cursorPointOne, cursorPointTwo];
}
case 'right': {
const cursorPointOne: Point = [
x - buffer,
isFloatingTaller
? y + buffer / 2
: cursorLeaveFromBottom
? y + buffer * 4
: y - buffer * 4,
];
const cursorPointTwo: Point = [
x - buffer,
isFloatingTaller
? y - buffer / 2
: cursorLeaveFromBottom
? y + buffer * 4
: y - buffer * 4,
];
const commonPoints: [Point, Point] = [
[
cursorLeaveFromBottom
? rect.left + buffer
: isFloatingTaller
? rect.left + buffer
: rect.right,
rect.top,
],
[
cursorLeaveFromBottom
? isFloatingTaller
? rect.left + buffer
: rect.right
: rect.left + buffer,
rect.bottom,
],
];
return [cursorPointOne, cursorPointTwo, ...commonPoints];
}
}
}
const poly = getPolygon([x, y]);
if (__DEV__) {
debug?.(poly.slice(0, 4).join(', '));
}
if (!isPointInPolygon([clientX, clientY], poly)) {
close();
} else if (restMs) {
timeoutId = setTimeout(onClose, restMs);
}
};
};
} | the_stack |
import * as zrUtil from 'zrender/src/core/util';
import * as textContain from 'zrender/src/contain/text';
import {makeInner} from '../util/model';
import {
makeLabelFormatter,
getOptionCategoryInterval,
shouldShowAllLabels
} from './axisHelper';
import Axis from './Axis';
import Model from '../model/Model';
import { AxisBaseOption } from './axisCommonTypes';
import OrdinalScale from '../scale/Ordinal';
import { AxisBaseModel } from './AxisBaseModel';
import type Axis2D from './cartesian/Axis2D';
type CacheKey = string | number;
type InnerTickLabelCache<T> = {
key: CacheKey
value: T
}[];
interface InnerLabelCachedVal {
labels: MakeLabelsResultObj[]
labelCategoryInterval?: number
}
interface InnerTickCachedVal {
ticks: number[]
tickCategoryInterval?: number
}
type InnerStore = {
labels: InnerTickLabelCache<InnerLabelCachedVal>
ticks: InnerTickLabelCache<InnerTickCachedVal>
autoInterval: number
lastAutoInterval: number
lastTickCount: number
axisExtent0: number
axisExtent1: number
};
const inner = makeInner<InnerStore, any>();
export function createAxisLabels(axis: Axis): {
labels: {
level?: number,
formattedLabel: string,
rawLabel: string,
tickValue: number
}[],
labelCategoryInterval?: number
} {
// Only ordinal scale support tick interval
return axis.type === 'category'
? makeCategoryLabels(axis)
: makeRealNumberLabels(axis);
}
/**
* @param {module:echats/coord/Axis} axis
* @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
* @return {Object} {
* ticks: Array.<number>
* tickCategoryInterval: number
* }
*/
export function createAxisTicks(axis: Axis, tickModel: AxisBaseModel): {
ticks: number[],
tickCategoryInterval?: number
} {
// Only ordinal scale support tick interval
return axis.type === 'category'
? makeCategoryTicks(axis, tickModel)
: {ticks: zrUtil.map(axis.scale.getTicks(), tick => tick.value) };
}
function makeCategoryLabels(axis: Axis) {
const labelModel = axis.getLabelModel();
const result = makeCategoryLabelsActually(axis, labelModel);
return (!labelModel.get('show') || axis.scale.isBlank())
? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
: result;
}
function makeCategoryLabelsActually(axis: Axis, labelModel: Model<AxisBaseOption['axisLabel']>) {
const labelsCache = getListCache(axis, 'labels');
const optionLabelInterval = getOptionCategoryInterval(labelModel);
const result = listCacheGet(labelsCache, optionLabelInterval as CacheKey);
if (result) {
return result;
}
let labels;
let numericLabelInterval;
if (zrUtil.isFunction(optionLabelInterval)) {
labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
}
else {
numericLabelInterval = optionLabelInterval === 'auto'
? makeAutoCategoryInterval(axis) : optionLabelInterval;
labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
}
// Cache to avoid calling interval function repeatly.
return listCacheSet(labelsCache, optionLabelInterval as CacheKey, {
labels: labels, labelCategoryInterval: numericLabelInterval
});
}
function makeCategoryTicks(axis: Axis, tickModel: AxisBaseModel) {
const ticksCache = getListCache(axis, 'ticks');
const optionTickInterval = getOptionCategoryInterval(tickModel);
const result = listCacheGet(ticksCache, optionTickInterval as CacheKey);
if (result) {
return result;
}
let ticks: number[];
let tickCategoryInterval;
// Optimize for the case that large category data and no label displayed,
// we should not return all ticks.
if (!tickModel.get('show') || axis.scale.isBlank()) {
ticks = [];
}
if (zrUtil.isFunction(optionTickInterval)) {
ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
}
// Always use label interval by default despite label show. Consider this
// scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
// labels. `splitLine` and `axisTick` should be consistent in this case.
else if (optionTickInterval === 'auto') {
const labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
tickCategoryInterval = labelsResult.labelCategoryInterval;
ticks = zrUtil.map(labelsResult.labels, function (labelItem) {
return labelItem.tickValue;
});
}
else {
tickCategoryInterval = optionTickInterval;
ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
}
// Cache to avoid calling interval function repeatly.
return listCacheSet(ticksCache, optionTickInterval as CacheKey, {
ticks: ticks, tickCategoryInterval: tickCategoryInterval
});
}
function makeRealNumberLabels(axis: Axis) {
const ticks = axis.scale.getTicks();
const labelFormatter = makeLabelFormatter(axis);
return {
labels: zrUtil.map(ticks, function (tick, idx) {
return {
level: tick.level,
formattedLabel: labelFormatter(tick, idx),
rawLabel: axis.scale.getLabel(tick),
tickValue: tick.value
};
})
};
}
// Large category data calculation is performence sensitive, and ticks and label
// probably be fetched by multiple times. So we cache the result.
// axis is created each time during a ec process, so we do not need to clear cache.
function getListCache(axis: Axis, prop: 'ticks'): InnerStore['ticks'];
function getListCache(axis: Axis, prop: 'labels'): InnerStore['labels'];
function getListCache(axis: Axis, prop: 'ticks' | 'labels') {
// Because key can be funciton, and cache size always be small, we use array cache.
return inner(axis)[prop] || (inner(axis)[prop] = []);
}
function listCacheGet<T>(cache: InnerTickLabelCache<T>, key: CacheKey): T {
for (let i = 0; i < cache.length; i++) {
if (cache[i].key === key) {
return cache[i].value;
}
}
}
function listCacheSet<T>(cache: InnerTickLabelCache<T>, key: CacheKey, value: T): T {
cache.push({key: key, value: value});
return value;
}
function makeAutoCategoryInterval(axis: Axis) {
const result = inner(axis).autoInterval;
return result != null
? result
: (inner(axis).autoInterval = axis.calculateCategoryInterval());
}
/**
* Calculate interval for category axis ticks and labels.
* To get precise result, at least one of `getRotate` and `isHorizontal`
* should be implemented in axis.
*/
export function calculateCategoryInterval(axis: Axis) {
const params = fetchAutoCategoryIntervalCalculationParams(axis);
const labelFormatter = makeLabelFormatter(axis);
const rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
const ordinalScale = axis.scale as OrdinalScale;
const ordinalExtent = ordinalScale.getExtent();
// Providing this method is for optimization:
// avoid generating a long array by `getTicks`
// in large category data case.
const tickCount = ordinalScale.count();
if (ordinalExtent[1] - ordinalExtent[0] < 1) {
return 0;
}
let step = 1;
// Simple optimization. Empirical value: tick count should less than 40.
if (tickCount > 40) {
step = Math.max(1, Math.floor(tickCount / 40));
}
let tickValue = ordinalExtent[0];
const unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
const unitW = Math.abs(unitSpan * Math.cos(rotation));
const unitH = Math.abs(unitSpan * Math.sin(rotation));
let maxW = 0;
let maxH = 0;
// Caution: Performance sensitive for large category data.
// Consider dataZoom, we should make appropriate step to avoid O(n) loop.
for (; tickValue <= ordinalExtent[1]; tickValue += step) {
let width = 0;
let height = 0;
// Not precise, do not consider align and vertical align
// and each distance from axis line yet.
const rect = textContain.getBoundingRect(
labelFormatter({ value: tickValue }), params.font, 'center', 'top'
);
// Magic number
width = rect.width * 1.3;
height = rect.height * 1.3;
// Min size, void long loop.
maxW = Math.max(maxW, width, 7);
maxH = Math.max(maxH, height, 7);
}
let dw = maxW / unitW;
let dh = maxH / unitH;
// 0/0 is NaN, 1/0 is Infinity.
isNaN(dw) && (dw = Infinity);
isNaN(dh) && (dh = Infinity);
let interval = Math.max(0, Math.floor(Math.min(dw, dh)));
const cache = inner(axis.model);
const axisExtent = axis.getExtent();
const lastAutoInterval = cache.lastAutoInterval;
const lastTickCount = cache.lastTickCount;
// Use cache to keep interval stable while moving zoom window,
// otherwise the calculated interval might jitter when the zoom
// window size is close to the interval-changing size.
// For example, if all of the axis labels are `a, b, c, d, e, f, g`.
// The jitter will cause that sometimes the displayed labels are
// `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
if (lastAutoInterval != null
&& lastTickCount != null
&& Math.abs(lastAutoInterval - interval) <= 1
&& Math.abs(lastTickCount - tickCount) <= 1
// Always choose the bigger one, otherwise the critical
// point is not the same when zooming in or zooming out.
&& lastAutoInterval > interval
// If the axis change is caused by chart resize, the cache should not
// be used. Otherwise some hiden labels might not be shown again.
&& cache.axisExtent0 === axisExtent[0]
&& cache.axisExtent1 === axisExtent[1]
) {
interval = lastAutoInterval;
}
// Only update cache if cache not used, otherwise the
// changing of interval is too insensitive.
else {
cache.lastTickCount = tickCount;
cache.lastAutoInterval = interval;
cache.axisExtent0 = axisExtent[0];
cache.axisExtent1 = axisExtent[1];
}
return interval;
}
function fetchAutoCategoryIntervalCalculationParams(axis: Axis) {
const labelModel = axis.getLabelModel();
return {
axisRotate: axis.getRotate
? axis.getRotate()
: ((axis as Axis2D).isHorizontal && !(axis as Axis2D).isHorizontal())
? 90
: 0,
labelRotate: labelModel.get('rotate') || 0,
font: labelModel.getFont()
};
}
interface MakeLabelsResultObj {
formattedLabel: string
rawLabel: string
tickValue: number
}
function makeLabelsByNumericCategoryInterval(axis: Axis, categoryInterval: number): MakeLabelsResultObj[];
/* eslint-disable-next-line */
function makeLabelsByNumericCategoryInterval(axis: Axis, categoryInterval: number, onlyTick: false): MakeLabelsResultObj[];
function makeLabelsByNumericCategoryInterval(axis: Axis, categoryInterval: number, onlyTick: true): number[];
function makeLabelsByNumericCategoryInterval(axis: Axis, categoryInterval: number, onlyTick?: boolean) {
const labelFormatter = makeLabelFormatter(axis);
const ordinalScale = axis.scale as OrdinalScale;
const ordinalExtent = ordinalScale.getExtent();
const labelModel = axis.getLabelModel();
const result: (MakeLabelsResultObj | number)[] = [];
// TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
const step = Math.max((categoryInterval || 0) + 1, 1);
let startTick = ordinalExtent[0];
const tickCount = ordinalScale.count();
// Calculate start tick based on zero if possible to keep label consistent
// while zooming and moving while interval > 0. Otherwise the selection
// of displayable ticks and symbols probably keep changing.
// 3 is empirical value.
if (startTick !== 0 && step > 1 && tickCount / step > 2) {
startTick = Math.round(Math.ceil(startTick / step) * step);
}
// (1) Only add min max label here but leave overlap checking
// to render stage, which also ensure the returned list
// suitable for splitLine and splitArea rendering.
// (2) Scales except category always contain min max label so
// do not need to perform this process.
const showAllLabel = shouldShowAllLabels(axis);
const includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
const includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
if (includeMinLabel && startTick !== ordinalExtent[0]) {
addItem(ordinalExtent[0]);
}
// Optimize: avoid generating large array by `ordinalScale.getTicks()`.
let tickValue = startTick;
for (; tickValue <= ordinalExtent[1]; tickValue += step) {
addItem(tickValue);
}
if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
addItem(ordinalExtent[1]);
}
function addItem(tickValue: number) {
const tickObj = { value: tickValue };
result.push(onlyTick
? tickValue
: {
formattedLabel: labelFormatter(tickObj),
rawLabel: ordinalScale.getLabel(tickObj),
tickValue: tickValue
}
);
}
return result;
}
type CategoryIntervalCb = (tickVal: number, rawLabel: string) => boolean;
// When interval is function, the result `false` means ignore the tick.
// It is time consuming for large category data.
/* eslint-disable-next-line */
function makeLabelsByCustomizedCategoryInterval(axis: Axis, categoryInterval: CategoryIntervalCb): MakeLabelsResultObj[];
/* eslint-disable-next-line */
function makeLabelsByCustomizedCategoryInterval(axis: Axis, categoryInterval: CategoryIntervalCb, onlyTick: false): MakeLabelsResultObj[];
/* eslint-disable-next-line */
function makeLabelsByCustomizedCategoryInterval(axis: Axis, categoryInterval: CategoryIntervalCb, onlyTick: true): number[];
function makeLabelsByCustomizedCategoryInterval(axis: Axis, categoryInterval: CategoryIntervalCb, onlyTick?: boolean) {
const ordinalScale = axis.scale;
const labelFormatter = makeLabelFormatter(axis);
const result: (MakeLabelsResultObj | number)[] = [];
zrUtil.each(ordinalScale.getTicks(), function (tick) {
const rawLabel = ordinalScale.getLabel(tick);
const tickValue = tick.value;
if (categoryInterval(tick.value, rawLabel)) {
result.push(
onlyTick
? tickValue
: {
formattedLabel: labelFormatter(tick),
rawLabel: rawLabel,
tickValue: tickValue
}
);
}
});
return result;
} | the_stack |
import type { RegExpVisitor } from "regexpp/visitor"
import type {
Alternative,
CapturingGroup,
Group,
LookaroundAssertion,
Node,
Pattern,
Quantifier,
} from "regexpp/ast"
import type { RegExpContext } from "../utils"
import { createRule, defineRegexpVisitor } from "../utils"
import { isCoveredNode, isEqualNodes } from "../utils/regexp-ast"
import type { Expression, FiniteAutomaton, NoParent, ReadonlyNFA } from "refa"
import {
combineTransformers,
Transformers,
DFA,
NFA,
JS,
visitAst,
transform,
} from "refa"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import {
hasSomeDescendant,
getMatchingDirection,
getEffectiveMaximumRepetition,
} from "regexp-ast-analysis"
import { RegExpParser } from "regexpp"
import { UsageOfPattern } from "../utils/get-usage-of-pattern"
import { canReorder } from "../utils/reorder-alternatives"
import { mention } from "../utils/mention"
type ParentNode = Group | CapturingGroup | Pattern | LookaroundAssertion
/**
* Returns whether the node or the elements of the node are effectively
* quantified with a star.
*/
function isStared(node: Node): boolean {
let max = getEffectiveMaximumRepetition(node)
if (node.type === "Quantifier") {
max *= node.max
}
return max > 10
}
/**
* Check has after pattern
*/
function hasNothingAfterNode(node: ParentNode): boolean {
const md = getMatchingDirection(node)
for (
let p:
| Group
| Pattern
| CapturingGroup
| LookaroundAssertion
| Quantifier
| Alternative = node;
;
p = p.parent
) {
if (p.type === "Assertion" || p.type === "Pattern") {
return true
}
if (p.type !== "Alternative") {
const parent: Quantifier | Alternative = p.parent
if (parent.type === "Quantifier") {
if (parent.max > 1) {
return false
}
} else {
const lastIndex: number =
md === "ltr" ? parent.elements.length - 1 : 0
if (parent.elements[lastIndex] !== p) {
return false
}
}
}
}
}
/**
* Returns whether the given RE AST contains assertions.
*/
function containsAssertions(expression: NoParent<Expression>): boolean {
try {
visitAst(expression, {
onAssertionEnter() {
throw new Error()
},
})
return false
} catch (error) {
return true
}
}
/**
* Returns whether the given RE AST contains assertions or unknowns.
*/
function containsAssertionsOrUnknowns(
expression: NoParent<Expression>,
): boolean {
try {
visitAst(expression, {
onAssertionEnter() {
throw new Error()
},
onUnknownEnter() {
throw new Error()
},
})
return false
} catch (error) {
return true
}
}
const creationOption: Transformers.CreationOptions = {
ignoreAmbiguity: true,
ignoreOrder: true,
}
const assertionTransformer = combineTransformers([
Transformers.applyAssertions(creationOption),
Transformers.removeUnnecessaryAssertions(creationOption),
Transformers.inline(creationOption),
Transformers.removeDeadBranches(creationOption),
])
/**
* Create an NFA from the given element.
*
* The `partial` value determines whether the NFA perfectly represents the given
* element. Some elements might contain features that cannot be represented
* using NFA in which case a partial NFA will be created (e.g. the NFA of
* `a|\bfoo\b` is equivalent to the NFA of `a`).
*/
function toNFA(
parser: JS.Parser,
element: JS.ParsableElement,
): { nfa: NFA; partial: boolean } {
try {
const { expression, maxCharacter } = parser.parseElement(element, {
backreferences: "unknown",
assertions: "parse",
})
let e
if (containsAssertions(expression)) {
e = transform(assertionTransformer, expression)
} else {
e = expression
}
return {
nfa: NFA.fromRegex(
e,
{ maxCharacter },
{ assertions: "disable", unknowns: "disable" },
),
partial: containsAssertionsOrUnknowns(e),
}
} catch (error) {
return {
nfa: NFA.empty({
maxCharacter: parser.ast.flags.unicode ? 0x10ffff : 0xffff,
}),
partial: true,
}
}
}
/**
* Unions all given NFAs
*/
function unionAll(nfas: readonly ReadonlyNFA[]): ReadonlyNFA {
if (nfas.length === 0) {
throw new Error("Cannot union 0 NFAs.")
} else if (nfas.length === 1) {
return nfas[0]
}
const total = nfas[0].copy()
for (let i = 1; i < nfas.length; i++) {
total.union(nfas[i])
}
return total
}
const DFA_OPTIONS: DFA.CreationOptions = { maxNodes: 100_000 }
/**
* Returns whether one NFA is a subset of another.
*/
function isSubsetOf(
superset: ReadonlyNFA,
subset: ReadonlyNFA,
): boolean | null {
try {
const a = DFA.fromIntersection(superset, subset, DFA_OPTIONS)
const b = DFA.fromFA(subset, DFA_OPTIONS)
a.minimize()
b.minimize()
return a.structurallyEqual(b)
} catch (error) {
return null
}
}
const enum SubsetRelation {
none,
leftEqualRight,
leftSubsetOfRight,
leftSupersetOfRight,
unknown,
}
/**
* Returns the subset relation
*/
function getSubsetRelation(
left: ReadonlyNFA,
right: ReadonlyNFA,
): SubsetRelation {
try {
const inter = DFA.fromIntersection(left, right, DFA_OPTIONS)
inter.minimize()
const l = DFA.fromFA(left, DFA_OPTIONS)
l.minimize()
const r = DFA.fromFA(right, DFA_OPTIONS)
r.minimize()
const subset = l.structurallyEqual(inter)
const superset = r.structurallyEqual(inter)
if (subset && superset) {
return SubsetRelation.leftEqualRight
} else if (subset) {
return SubsetRelation.leftSubsetOfRight
} else if (superset) {
return SubsetRelation.leftSupersetOfRight
}
return SubsetRelation.none
} catch (error) {
return SubsetRelation.unknown
}
}
/**
* The `getSubsetRelation` function assumes that both NFAs perfectly represent
* their language.
*
* This function adjusts their subset relation to account for partial NFAs.
*/
function getPartialSubsetRelation(
left: ReadonlyNFA,
leftIsPartial: boolean,
right: ReadonlyNFA,
rightIsPartial: boolean,
): SubsetRelation {
const relation = getSubsetRelation(left, right)
if (!leftIsPartial && !rightIsPartial) {
return relation
}
if (
relation === SubsetRelation.none ||
relation === SubsetRelation.unknown
) {
return relation
}
if (leftIsPartial && !rightIsPartial) {
switch (relation) {
case SubsetRelation.leftEqualRight:
return SubsetRelation.leftSupersetOfRight
case SubsetRelation.leftSubsetOfRight:
return SubsetRelation.none
case SubsetRelation.leftSupersetOfRight:
return SubsetRelation.leftSupersetOfRight
default:
throw new Error(relation)
}
}
if (rightIsPartial && !leftIsPartial) {
switch (relation) {
case SubsetRelation.leftEqualRight:
return SubsetRelation.leftSubsetOfRight
case SubsetRelation.leftSubsetOfRight:
return SubsetRelation.leftSubsetOfRight
case SubsetRelation.leftSupersetOfRight:
return SubsetRelation.none
default:
throw new Error(relation)
}
}
// both are partial
return SubsetRelation.none
}
/**
* Returns the regex source of the given FA.
*/
function faToSource(fa: FiniteAutomaton, flags: ReadonlyFlags): string {
try {
return JS.toLiteral(fa.toRegex(), { flags }).source
} catch (error) {
return "<ERROR>"
}
}
interface ResultBase {
alternative: Alternative
others: Alternative[]
}
interface DuplicateResult extends ResultBase {
type: "Duplicate"
others: [Alternative]
}
interface SubsetResult extends ResultBase {
type: "Subset"
}
interface PrefixSubsetResult extends ResultBase {
type: "PrefixSubset"
}
interface SupersetResult extends ResultBase {
type: "Superset"
}
interface OverlapResult extends ResultBase {
type: "Overlap"
overlap: NFA
}
type Result =
| DuplicateResult
| SubsetResult
| PrefixSubsetResult
| SupersetResult
| OverlapResult
interface Options {
parser: JS.Parser
hasNothingAfter: boolean
fastAst: boolean
noNfa: boolean
ignoreOverlap: boolean
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplicationAstFast(
alternatives: Alternative[],
flags: ReadonlyFlags,
): Iterable<Result> {
// eslint-disable-next-line func-style -- x
const shortCircuit: Parameters<typeof isEqualNodes>[3] = (a) => {
return a.type === "CapturingGroup" ? false : null
}
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
for (let j = 0; j < i; j++) {
const other = alternatives[j]
if (isEqualNodes(other, alternative, flags, shortCircuit)) {
yield { type: "Duplicate", alternative, others: [other] }
}
}
}
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplicationAst(
alternatives: Alternative[],
flags: ReadonlyFlags,
hasNothingAfter: boolean,
): Iterable<Result> {
const isCoveredOptions: Parameters<typeof isCoveredNode>[2] = {
flags,
canOmitRight: hasNothingAfter,
}
const isCoveredOptionsNoPrefix: Parameters<typeof isCoveredNode>[2] = {
flags,
canOmitRight: false,
}
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
for (let j = 0; j < i; j++) {
const other = alternatives[j]
if (isCoveredNode(other, alternative, isCoveredOptions)) {
if (isEqualNodes(other, alternative, flags)) {
yield {
type: "Duplicate",
alternative,
others: [other],
}
} else if (
hasNothingAfter &&
!isCoveredNode(other, alternative, isCoveredOptionsNoPrefix)
) {
yield {
type: "PrefixSubset",
alternative,
others: [other],
}
} else {
yield { type: "Subset", alternative, others: [other] }
}
}
}
}
}
/**
* Tries to find duplication in the given alternatives.
*
* It will search for prefix duplications. I.e. the alternative `ab` in `a|ab`
* is a duplicate of `a` because if `ab` accepts, `a` will have already accepted
* the input string. This makes `ab` effectively useless.
*
* This operation will modify the given NFAs.
*/
function* findPrefixDuplicationNfa(
alternatives: [NFA, boolean, Alternative][],
): Iterable<Result> {
if (alternatives.length === 0) {
return
}
// For two alternatives `A|B`, `B` is useless if `B` is a subset of `A[^]*`
const all = NFA.all({ maxCharacter: alternatives[0][0].maxCharacter })
for (let i = 0; i < alternatives.length; i++) {
const [nfa, partial, alternative] = alternatives[i]
if (!partial) {
const overlapping = alternatives
.slice(0, i)
.filter(([otherNfa]) => !nfa.isDisjointWith(otherNfa))
if (overlapping.length >= 1) {
const othersNfa = unionAll(overlapping.map(([n]) => n))
const others = overlapping.map(([, , a]) => a)
// Only checking for a subset relation is sufficient here.
// Duplicates are VERY unlikely. (Who would use alternatives
// like `a|a[^]*`?)
if (isSubsetOf(othersNfa, nfa)) {
yield { type: "PrefixSubset", alternative, others }
}
}
}
nfa.append(all)
}
}
/**
* Tries to find duplication in the given alternatives.
*/
function* findDuplicationNfa(
alternatives: Alternative[],
flags: ReadonlyFlags,
{ hasNothingAfter, parser, ignoreOverlap }: Options,
): Iterable<Result> {
const previous: [NFA, boolean, Alternative][] = []
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
const { nfa, partial } = toNFA(parser, alternative)
const overlapping = previous.filter(
([otherNfa]) => !nfa.isDisjointWith(otherNfa),
)
if (overlapping.length >= 1) {
const othersNfa = unionAll(overlapping.map(([n]) => n))
const othersPartial = overlapping.some(([, p]) => p)
const others = overlapping.map(([, , a]) => a)
const relation = getPartialSubsetRelation(
nfa,
partial,
othersNfa,
othersPartial,
)
switch (relation) {
case SubsetRelation.leftEqualRight:
if (others.length === 1) {
// only return "duplicate" if there is only one other
// alternative
yield {
type: "Duplicate",
alternative,
others: [others[0]],
}
} else {
yield { type: "Subset", alternative, others }
}
break
case SubsetRelation.leftSubsetOfRight:
yield { type: "Subset", alternative, others }
break
case SubsetRelation.leftSupersetOfRight: {
const reorder = canReorder([alternative, ...others], flags)
if (reorder) {
// We are allowed to freely reorder the alternatives.
// This means that we can reverse the order of our
// alternatives to convert the superset into a subset.
for (const other of others) {
yield {
type: "Subset",
alternative: other,
others: [alternative],
}
}
} else {
yield { type: "Superset", alternative, others }
}
break
}
case SubsetRelation.none:
case SubsetRelation.unknown:
if (!ignoreOverlap) {
yield {
type: "Overlap",
alternative,
others,
overlap: NFA.fromIntersection(nfa, othersNfa),
}
}
break
default:
throw new Error(relation)
}
}
previous.push([nfa, partial, alternative])
}
if (hasNothingAfter) {
yield* findPrefixDuplicationNfa(previous)
}
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplication(
alternatives: Alternative[],
flags: ReadonlyFlags,
options: Options,
): Iterable<Result> {
// AST-based approach
if (options.fastAst) {
yield* findDuplicationAstFast(alternatives, flags)
} else {
yield* findDuplicationAst(alternatives, flags, options.hasNothingAfter)
}
// NFA-based approach
if (!options.noNfa) {
yield* findDuplicationNfa(alternatives, flags, options)
}
}
const RESULT_TYPE_ORDER: Result["type"][] = [
"Duplicate",
"Subset",
"PrefixSubset",
"Superset",
"Overlap",
]
/**
* Returns an array of the given results that is sorted by result type from
* most important to least important.
*/
function deduplicateResults(
unsorted: Iterable<Result>,
{ reportExp }: FilterInfo,
): Result[] {
const results = [...unsorted].sort(
(a, b) =>
RESULT_TYPE_ORDER.indexOf(a.type) -
RESULT_TYPE_ORDER.indexOf(b.type),
)
const seen = new Map<Alternative, Result["type"]>()
return results.filter(({ alternative, type }) => {
const firstSeen = seen.get(alternative)
if (firstSeen === undefined) {
seen.set(alternative, type)
return true
}
if (
reportExp &&
firstSeen === "PrefixSubset" &&
type !== "PrefixSubset"
) {
// Prefix subset might overshadow some other results (Superset or
// Overlap) that report exponential backtracking. In this case, we
// want to report BOTH the Prefix subset and one Superset or
// Overlap.
seen.set(alternative, type)
return true
}
return false
})
}
/**
* Throws if called.
*/
function assertNever(value: never): never {
throw new Error(`Invalid value: ${value}`)
}
const enum ReportOption {
all = "all",
trivial = "trivial",
interesting = "interesting",
}
const enum ReportExponentialBacktracking {
none = "none",
certain = "certain",
potential = "potential",
}
const enum ReportUnreachable {
certain = "certain",
potential = "potential",
}
const enum MaybeBool {
false = 0,
true = 1,
maybe = 2,
}
interface FilterInfo {
stared: MaybeBool
nothingAfter: MaybeBool
reportExp: boolean
reportPrefix: boolean
}
export default createRule("no-dupe-disjunctions", {
meta: {
docs: {
description: "disallow duplicate disjunctions",
category: "Possible Errors",
recommended: true,
},
schema: [
{
type: "object",
properties: {
report: {
type: "string",
enum: ["all", "trivial", "interesting"],
},
reportExponentialBacktracking: {
enum: ["none", "certain", "potential"],
},
reportUnreachable: {
enum: ["certain", "potential"],
},
},
additionalProperties: false,
},
],
messages: {
duplicate:
"Unexpected duplicate alternative. This alternative can be removed.{{cap}}{{exp}}",
subset: "Unexpected useless alternative. This alternative is a strict subset of {{others}} and can be removed.{{cap}}{{exp}}",
prefixSubset:
"Unexpected useless alternative. This alternative is already covered by {{others}} and can be removed.{{cap}}",
superset:
"Unexpected superset. This alternative is a superset of {{others}}. It might be possible to remove the other alternative(s).{{cap}}{{exp}}",
overlap:
"Unexpected overlap. This alternative overlaps with {{others}}. The overlap is {{expr}}.{{cap}}{{exp}}",
},
type: "suggestion", // "problem",
},
create(context) {
const reportExponentialBacktracking: ReportExponentialBacktracking =
context.options[0]?.reportExponentialBacktracking ??
ReportExponentialBacktracking.potential
const reportUnreachable: ReportUnreachable =
context.options[0]?.reportUnreachable ?? ReportUnreachable.certain
const report: ReportOption =
context.options[0]?.report ?? ReportOption.trivial
/**
* Create visitor
*/
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const {
patternAst,
flagsString,
flags,
node,
getRegexpLocation,
getUsageOfPattern,
} = regexpContext
const parser = JS.Parser.fromAst({
pattern: patternAst,
flags: new RegExpParser().parseFlags(
[
...new Set(
(flagsString || "").replace(/[^gimsuy]/gu, ""),
),
].join(""),
),
})
/** Returns the filter information for the given node */
function getFilterInfo(parentNode: ParentNode): FilterInfo {
const usage = getUsageOfPattern()
let stared: MaybeBool
if (isStared(parentNode)) {
stared = MaybeBool.true
} else if (
usage === UsageOfPattern.partial ||
usage === UsageOfPattern.mixed
) {
stared = MaybeBool.maybe
} else {
stared = MaybeBool.false
}
// eslint-disable-next-line one-var -- false positive
let nothingAfter: MaybeBool
if (!hasNothingAfterNode(parentNode)) {
nothingAfter = MaybeBool.false
} else if (
usage === UsageOfPattern.partial ||
usage === UsageOfPattern.mixed
) {
nothingAfter = MaybeBool.maybe
} else {
nothingAfter = MaybeBool.true
}
// eslint-disable-next-line one-var -- false positive
let reportExp: boolean
switch (reportExponentialBacktracking) {
case ReportExponentialBacktracking.none:
reportExp = false
break
case ReportExponentialBacktracking.certain:
reportExp = stared === MaybeBool.true
break
case ReportExponentialBacktracking.potential:
reportExp = stared !== MaybeBool.false
break
default:
assertNever(reportExponentialBacktracking)
}
// eslint-disable-next-line one-var -- false positive
let reportPrefix: boolean
switch (reportUnreachable) {
case ReportUnreachable.certain:
reportPrefix = nothingAfter === MaybeBool.true
break
case ReportUnreachable.potential:
reportPrefix = nothingAfter !== MaybeBool.false
break
default:
assertNever(reportUnreachable)
}
return { stared, nothingAfter, reportExp, reportPrefix }
}
/** Verify group node */
function verify(parentNode: ParentNode) {
const info = getFilterInfo(parentNode)
const rawResults = findDuplication(
parentNode.alternatives,
flags,
{
fastAst: false,
noNfa: false,
ignoreOverlap:
!info.reportExp && report !== ReportOption.all,
hasNothingAfter: info.reportPrefix,
parser,
},
)
let results = filterResults([...rawResults], info)
results = deduplicateResults(results, info)
results.forEach((result) => reportResult(result, info))
}
/** Filters the results of a parent node. */
function filterResults(
results: Result[],
{ nothingAfter, reportExp, reportPrefix }: FilterInfo,
): Result[] {
switch (report) {
case ReportOption.all: {
// We really want to report _everything_.
return results
}
case ReportOption.trivial: {
// For "trivial", we want to filter out all results
// where the user cannot just remove the reported
// alternative. So "Overlap" and "Superset" types are
// removed.
return results.filter(({ type }) => {
switch (type) {
case "Duplicate":
case "Subset":
return true
case "Overlap":
case "Superset":
return reportExp
case "PrefixSubset":
return reportPrefix
default:
throw assertNever(type)
}
})
}
case ReportOption.interesting: {
// For "interesting", we want to behave like "trivial"
// but we also want to retain "Superset" results like
// `\b(?:Foo|\w+)\b`. So "Overlap" types are always
// removed and "Superset" types are removed if there is
// nothing after it.
return results.filter(({ type }) => {
switch (type) {
case "Duplicate":
case "Subset":
return true
case "Overlap":
return reportExp
case "Superset":
return (
reportExp ||
nothingAfter === MaybeBool.false
)
case "PrefixSubset":
return reportPrefix
default:
throw assertNever(type)
}
})
}
default:
throw assertNever(report)
}
}
/** Report the given result. */
function reportResult(result: Result, { stared }: FilterInfo) {
let exp
if (stared === MaybeBool.true) {
exp =
" This ambiguity is likely to cause exponential backtracking."
} else if (stared === MaybeBool.maybe) {
exp =
" This ambiguity might cause exponential backtracking."
} else {
exp = ""
}
const cap = hasSomeDescendant(
result.alternative,
(d) => d.type === "CapturingGroup",
)
? " Careful! This alternative contains capturing groups which might be difficult to remove."
: ""
const others = mention(
result.others.map((a) => a.raw).join("|"),
)
switch (result.type) {
case "Duplicate":
context.report({
node,
loc: getRegexpLocation(result.alternative),
messageId: "duplicate",
data: { exp, cap, others },
})
break
case "Subset":
context.report({
node,
loc: getRegexpLocation(result.alternative),
messageId: "subset",
data: { exp, cap, others },
})
break
case "PrefixSubset":
context.report({
node,
loc: getRegexpLocation(result.alternative),
messageId: "prefixSubset",
data: { exp, cap, others },
})
break
case "Superset":
context.report({
node,
loc: getRegexpLocation(result.alternative),
messageId: "superset",
data: { exp, cap, others },
})
break
case "Overlap":
context.report({
node,
loc: getRegexpLocation(result.alternative),
messageId: "overlap",
data: {
exp,
cap,
others,
expr: mention(
faToSource(result.overlap, flags),
),
},
})
break
default:
throw new Error(result)
}
}
return {
onPatternEnter: verify,
onGroupEnter: verify,
onCapturingGroupEnter: verify,
onAssertionEnter(aNode) {
if (
aNode.kind === "lookahead" ||
aNode.kind === "lookbehind"
) {
verify(aNode)
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
}) | the_stack |
import { isMac } from "./util"
interface ExampleScript {
guid :string
name :string
code :string
}
function s(guid :string, name :string, code :string) :ExampleScript {
return {
guid: "examples/" + guid,
name,
code: code.replace(/^\s*\n|\n\s*$/, "") + "\n",
}
}
function kb(mac :string, other :string) {
return isMac ? mac : other
}
export default (samples => {
let categories :{[k:string]:ExampleScript[]} = {}
for (let s of samples) {
let [category, title] = s.name.split("/", 2)
if (!title) {
title = category
category = ""
} else {
s.name = title
}
let ss = categories[category]
if (ss) {
ss.push(s)
} else {
categories[category] = [ s ]
}
}
return categories
})([
s("intro", "Introduction", `
/**
Hello hi and welcome to Scripter.
Scripts are written in relaxed TypeScript.
This grey text here is a comment.
Try running this script using the ► button in the toolbar, or by pressing ${kb("⌘↩︎", "Ctrl+Return")}
*/
print(\`Today is \${Date()}\`)
print("Your viewport:", viewport.bounds)
/**
There are more examples in the menu ☰.
Open the menu using the ☰ button in the bottom left corner.
Create a new script using the + button in the top toolbar.
This editor provides automatic completions of all available functionality, including the Figma API.
Type "figma." to start exploring the API.
Scripts are automatically saved locally and securely.
You can also load and save scripts to the current Figma file.
To save a script, press the "Save to Figma File" button in the toolbar.
Changes to the script are not automatically saved both to the Figma file
as well as locally to your computer.
To remove a script from a Figma file, simply delete the frame in the Figma file's page.
To share a script with someone else, save it to a Figma file and invite others to the file.
To load a script from a Figma file, select the script's frame in Figma and then start Scripter.
Editor basics
• Scripts are automatically saved locally
• Scripts can optionally by saved to the Figma file
• Manage your scripts in the menu.
• Double-click a script in the menu to rename,
pressing RETURN to commit a name change or
ESC to cancel.
• Rename a script "" (nothing) to delete it.
Keyboard shortcuts
Runs the current script ${kb("⌘↩", "Ctrl+Return")}
Stop a running script ${kb("⇧⌘↩", "Ctrl+Shift+Return")}
Closes Scripter ${kb("⌥⌘P", "Ctrl+Alt+P")}
Toggle the menu ${kb("⌃M", "Ctrl+M")}
Increases text size ${kb("⌘+", "Ctrl+Plus")}
Decreases text size ${kb("⌘−", "Ctrl+Minus")}
Resets text size ${kb("⌘0", "Ctrl+0")}
Opens quick commander ${kb("F1 ", "F1")} or ${kb(" ⇧⌘P", "Ctrl+Shift+P")}
Goes to defintion of selected symbol ${kb("⌘F12 ", "Ctrl+F12")} or ${kb(" F12", "F12")}
Peek definitions of selected symbol F11
Show references to selected symbol ${kb("⇧F12", "Shift+F12")}
Quick navigator ${kb("⇧⌘O ", "Ctrl+Shift+O")} or ${kb(" ⌘P", "Ctrl+P")}
Go back in history ${kb("⇧⌘[ ", "Ctrl+Shift+[")} or ${kb(" ⌃-", "Alt+←")}
Go forward in history ${kb("⇧⌘] ", "Ctrl+Shift+]")} or ${kb(" ⌃⇧-", "Alt+→")}
*/
`),
//------------------------------------------------------------------------------------------------
s("figma/rects", "Figma/Create rectangles", `
// Create some rectangles on the current page
let rectangles = range(0, 5).map(i =>
Rectangle({ x: i * 150, fills: [ ORANGE.paint ] }))
// select our new rectangles and center the viewport
viewport.scrollAndZoomIntoView(setSelection(rectangles))
`),
s("figma/trim-ws", "Figma/Trim whitespace", `
// Select some text and run this script to trim away linebreaks and space.
for (let n of selection()) {
if (isText(n)) {
n.characters = n.characters.trim()
}
}
`),
s("figma/trim-line-indent", "Figma/Trim line indentation", `
// Select some text and run this script to trim away whitespace from the beginning of lines
for (let n of selection()) {
if (isText(n)) {
n.characters = n.characters.replace(/\\n\\s+/g, "\\n")
}
}
`),
s("figma/select-all-images", "Figma/Select all images", `
let images = await find(n => isImage(n) && n)
setSelection(images)
// More node type filters:
// isDocument, isPage
// isFrame, isGroup, isSlice
// isRect, isRectangle
// isLine
// isEllipse, isPolygon, isStar
// isVector
// isText
// isBooleanOperation
// isComponent, isInstance
// isSceneNode, isContainerNode, isShape
//
// These can also be used as type guards:
//
let n = selection(0)
// here, n's type is the generic BaseNode
if (isRect(n)) {
// but here n's type is RectangleNode
}
`),
s("figma/set-images-fit", "Figma/Set images to fit", `
// Loop over images in the selection
for (let shape of await find(selection(), n => isImage(n) && n)) {
// Update image paints to use "FIT" scale mode
shape.fills = shape.fills.map(p =>
isImage(p) ? {...p, scaleMode: "FIT"} : p)
}
`),
s("figma/viewport-intro", "Figma/Viewport", `
// This demonstrates use of the viewport API
// Helper pause function
const pause = () => timer(1000)
// Save current viewport and then change it
viewport.save()
viewport.center = {x:1000,y:0}
// wait for a little while so we can see the effect
await pause()
// restore the last saved viewport
viewport.restore()
await pause()
// Viewports are saved on a stack. We can save multiple:
viewport.save() // viewport 1
viewport.center = {x:1000,y:0}
await pause()
viewport.save() // viewport 2
viewport.center = {x:-1000,y:0}
await pause()
viewport.restore() // restore viewport 2
await pause()
viewport.restore() // restore viewport 1
// save() returns a handle to a specific viewport
let vp1 = viewport.save() // viewport 1
viewport.center = {x:1000,y:0}
viewport.save(false) // viewport 2
viewport.center = {x:-1000,y:0}
await pause()
viewport.restore(vp1) // restore viewport 1
// We can also animate viewport changes.
// This makes use of animate.transition()
viewport.save()
await viewport.setAnimated({x:0,y:0}, 2.0, 0.5)
await pause()
await viewport.restoreAnimated(0.5, animate.easeInOutExpo)
await pause()
// Finally, the first saved viewport is automatically
// restored when a script ends:
viewport.save()
viewport.center = {x:1000,y:0}
await pause()
// viewport.restore() called automatically
`),
//------------------------------------------------------------------------------------------------
s("basics/paths", "Basics/Working with paths", `
// The Path library provides functions for working
// with pathnames.
let path = "/foo/bar/baz.png"
print(Path.ext(path))
print(Path.dir(path))
print(Path.base(path))
print(Path.clean("a/c//b/../k"))
print(Path.isAbs(path))
print(Path.join("foo", "//bar/", "baz", "internet"))
print(Path.split(path))
`),
s("basics/files", "Basics/Working with files", `
// Scripter doesn't support interfacing with your file system,
// but it does provide functions for working with file data.
// fileType can be used to investigate what type of file a
// filename represents:
print(fileType("foo/bar.zip"))
// fileType can even guess the file type based on the first
// few bytes of some file data:
print(fileType([0xFF, 0xD8, 0xFF])) // JPEG image data
`),
s("basics/images", "Basics/Showing images", `
// The Img function and class can be used to describe images
// and load image data for a few common image types.
// Passing an Img to print vizualizes the image.
// Img can take a URL which is then loaded by the web browser
print(Img("https://scripter.rsms.me/icon.png"))
// We can specify the size if we want
print(Img("https://scripter.rsms.me/icon.png", {width:128, height:16}))
// Img.load() allows us to load the image data
let icon = await Img("https://scripter.rsms.me/icon.png").load()
print(icon.data)
// A loaded image may also have information that was read from
// the image data itself, like mime type and bitmap dimensions:
print(icon, icon.type, icon.meta)
// fetchImg is a shorthand function for loading an Img
let loadedIcon = await fetchImg("https://scripter.rsms.me/icon.png")
print(loadedIcon, loadedIcon.meta)
// Img also accepts image data as its input,
// in common image formats like png, gif and jpeg.
let gifData = Bytes(\`
47 49 46 38 39 61
0A 00 0A 00 91 00 00
FF FF FF FF 00 00 00 00 FF 00 00 00
21 F9 04 00 00 00 00 00
2C 00 00 00 00 0A 00 0A 00 00
02 16 8C 2D 99 87 2A 1C DC 33 A0 02 75
EC 95 FA A8 DE 60 8C 04 91 4C 01 00
3B
\`)
print(Img(gifData, 32))
// Img also supports JPEG in addition to PNG and GIF
let im1 = Img("https://scripter.rsms.me/sample/colors.jpg")
await im1.load()
print(im1, [im1])
`),
s("basics/timers", "Basics/Timers", `
// Timers allows waiting for some time to pass
// or to execute some code after a delay.
await timer(200)
print("200ms passed")
// Timers are promises with a cancel() function
let t = timer(200)
print("timer started")
// cancel the timer before it expires.
// Comment this line out to see the effect.
t.cancel()
// wait for timer
try {
await t
print("Rrrriiiiing!")
} catch (_) {
print("timer canceled")
}
// Timers accept an optional handler function:
timer(200, canceled => {
print("timer expired.", {canceled})
})
// .cancel() // uncomment to try canceling
`),
s("basics/range", "Basics/Ranges", `
// The range() function creates a sequence of numbers in the
// range [start–end), incrementing in steps. Steps defaults to 1.
print(range(1, 10))
print(range(1, 10, 3))
print(range(100, 0, 20))
// Ranges are iterable
for (let n of range(1,4)) {
print(n) ; await timer(200)
}
// If we want a pre-allocated array, we can call the array() function
print(range(10).array())
// or use Array.from, since ranges are iterables
print(Array.from(range(1, 10)))
// range is often useful for graphics. We can represent columns or
// rows similar to the Layout Grids feature in Figma:
let columns = range(80, 512, 64)
print(\`64dp wide columns with 80dp offset: \${columns}\`)
// range() returns a LazySeq, which has several functions commonly
// found for Array, like for instance map():
print(range(-4, 4).map(v => \`0x\${(v*10).toString(16)}\`))
// Since the sequence created by range() is lazy, values are allocated
// only as needed, making range() feasible to represent very large
// imaginary ranges.
// For instance, the following only uses very little memory:
print(range(0, 90000000, 2).at(1234567))
// We can even use Inifite to descrive never-ending sequences.
print(range(0, Infinity, 3).at(1234567918383))
// Be careful when iterating over an infinite sequence since it's easy
// to lock Figma if you forget to explicitly stop iteration.
// Scripter will do its best to stop you from doing this: passing an
// infinite sequence to print() or calling toString() on the sequence
// will only show the first 50 entries followed by "... ∞" to indicate
// that it goes on forever:
print(range(0, Infinity, 3))
// Calling functions which only makes sense on finite sequences—like
// map(), array() or join()—on an infinite sequence throws an error:
try {
range(0, Infinity).array()
} catch (e) {
print(e)
}
`),
s("basics/jsx", "Basics/JSX", `
/**
* Scripter supports JSX for creating nodes.
* JSX tags map 1:1 to Scripter's node constructor functions,
* like for instance Rectangle() and Frame().
**/
<Rectangle fills={[ RED.paint ]} />
/**
* You may notice that the above line does not actually add a
* rectangle to the current page. This is an intentional
* difference between the regular constructor form:
* Rectangle(...)
* and the JSX form:
* <Rectangle ... />
* The regular constructor form adds the object to the current
* page automatically, while the JSX form does not add the node
* to the page on creation. Instead you call appendChild or
* addToScene explicitly.
**/
let frame :FrameNode =
<Frame height={130} fills={[ WHITE.paint ]}>
<Rectangle fills={[ RED.paint ]} />
<Text characters="Hello" x={8} y={110} />
</Frame>
// Try uncommenting this to see the frame added to the page
// addToPage(frame)
// Here is an example of using the regular node constructors:
let g = Group(
Rectangle(),
Text({characters:"Hello", y:110}),
)
// remove the group since the regular constructor form automatically
// adds nodes to the current page.
g.remove()
`),
s("basics/animate.transition", "Basics/Animated transitions", `
// This demonstrates use of animate.transition()
// See Misc/Animation for custom animation examples.
// First, save & set the viewport to 0,0
viewport.setSave({x:0,y:0}, 1)
// Create a temporary circle
let n = Ellipse({ width:200, height:200, fills:[RED.paint] })
scripter.onend = () => n.remove()
// Animate the circle moving from left to right by 400dp
await animate.transition(2.0, progress => {
n.x = progress * -400
})
// Pause for a little while
await timer(500)
// Animate the circle back to 0,using a different timing function
await animate.transition(1.0, animate.easeOutElastic, progress => {
n.x = -400 + (progress * 400)
})
// Pause for a little while before ending
await timer(500)
`),
//------------------------------------------------------------------------------------------------
s("ui/dialogs", "UI input/Dialogs & Messaging", `
const { notify } = libui
// alert(message) shows a message dialog.
// Blocks the UI. Useful for important messages.
alert("Something very important")
// confirm(question) asks the user a yes or no
// question via a message dialog. Blocks the UI.
// Returns true if the user answered "yes".
print(await confirm("Would you like a kitten?"))
// notify(message, options?) shows a message in
// the bottom of the user's screen.
// Does not block the UI.
notify("Notification", { timeout: 2000 })
`),
s("ui/range-slider", "UI input/Range sliders", `
// Example of using interactive range slider to move a rectangle
const { rangeInput } = libui
// Save viewport and create a red rectangle
let origViewport = { zoom: viewport.zoom, center: viewport.center }
let r = addToPage(Rectangle({ fills: [ORANGE.paint], cornerRadius: 10 }))
try {
// Set viewport to focus on the rectangle
viewport.zoom = 1
viewport.center = {y: r.y, x: r.x}
// Show a slider and move rectangle as it changes
for await (let v of rangeInput({min:-300, max:300})) {
r.x = Math.sin(v * 0.03) * 200
r.y = Math.cos(v * 0.05) * 80
}
} finally {
// Remove the rectangle and restore viewport
r.remove()
viewport.center = origViewport.center
viewport.zoom = origViewport.zoom
}
`),
s("ui/async-gen", "UI input/Async generators", `
// Async generator functions allows creation of iterators which
// may take some amount of time to produce their results.
//
// In this example we use a range input control to generate lists
// of strings upon user moving the slider
async function* meowGenerator(max :number) {
for await (let count of libui.rangeInput({max, value:1, step:1})) {
yield range(0, count).map(() => "Meow")
}
}
// We can now use our meow generator like this:
for await (const meows of meowGenerator(10)) {
print(meows)
}
`),
//------------------------------------------------------------------------------------------------
s("http/fetch", "HTTP/Fetch", `
// fetch can be used to fetch resources across the interwebs.
// It's the standard fetch API you might already be used to.
let r = await fetch("https://jsonplaceholder.typicode.com/users/1")
print(await r.json())
// Scripter provides a few shorthand functions for common tasks:
print(await fetchJson("https://jsonplaceholder.typicode.com/users/1"))
print(await fetchText("https://jsonplaceholder.typicode.com/users/1"))
print(await fetchImg("https://scripter.rsms.me/icon.png"))
print(await fetchData("https://scripter.rsms.me/icon.png"))
`),
s("http/figma", "HTTP/Figma REST API", `
// This script demonstrates accessing the Figma HTTP API
//
// First, generate an access token for yourself using the
// "+ Get personal access token" function on this page:
// https://www.figma.com/developers/api#access-tokens
const figmaHttpApiToken = "your_access_token_here"
// We can now fetch JSON representations of files via the HTTP API
let file = await fetchFigmaFile("jahkK3lhzuegZBQXz5BbL7")
print(Img(file.thumbnailUrl), file)
// Simple helper function for GETing files from Figma servers
async function fetchFigmaFile(fileKey :string) :Promise<any> {
let json = await fetchJson(
"https://api.figma.com/v1/files/" + encodeURIComponent(fileKey),
{ headers: { "X-FIGMA-TOKEN": figmaHttpApiToken } }
)
if (json.status && json.err) {
throw new Error(\`API error: \${json.err}\`)
}
return json
}
`),
//------------------------------------------------------------------------------------------------
s("worker/basics", "Workers/Worker Basics", `
/**
Workers are new in Scripter since July 2020. Workers is a way to execute code in parallel inside a full WebWorker environment, with access to features like script loading and OffscreenCanvas. There are also iframe-based workers as an option when you need a full complete web DOM with access to the full Web API.
Let's get started with a simple worker:
*/
let w = createWorker(async w => {
let r = await w.recv() // wait for input
let result = "Hello ".repeat(r).trim() // compute some stuff
w.send(result) // send the result
w.close() // close the worker
})
w.send(4) // send some input
print(await w.recv()) // wait for a reply
/**
The above worker is written in idiomatic Scripter style using send() and recv() calls.
If that's not your jam, you can alternatively use the event-based WebWorker API. The following example also shows how you can pass a worker script as a string:
*/
let w2 = createWorker(\`w => {
w.onmessage = ev => {
let result = "Bye ".repeat(ev.data).trim()
w.postMessage(result)
w.close()
}
}\`)
w2.postMessage(4)
w2.onmessage = ev => {
print(ev.data)
}
// We must await the worker or it will be closed immediately
// as the script ends.
await w2
/**
Since Scripter is fully async-await capable, it's usually easier to use the send() and recv() functions instead of postMessage & onmessage events.
send() and recv() are optionally typed, which can be useful when you are writing more complicated scripts or simply prefer to have stricter types:
*/
let w3 = createWorker(async w => {
let r = await w.recv<number>() // r is a number
let result = "Hej ".repeat(r).trim()
w.send(result) // type inferred from result
w.close()
})
w3.send<number>(4) // this call now only accepts numbers
print(await w3.recv<string>())
/**
One final example: worker requests
The request-response patterns is common with many worker uses and so there is a function-and-event pair to save you time from managing your own request IDs over send & recv:
*/
let w4 = createWorker(async w => {
w.onrequest = req => {
return "Hi ".repeat(req.data).trim() // compute some stuff
}
})
const r1 = w4.request(/* input: */ 4, /* timeout: */ 1000)
const r2 = w4.request(/* input: */ 9, /* timeout: */ 1000)
print(await r1)
print(await r2)
`),
s("worker/import", "Workers/Importing libraries", `
/**
Workers can import scripts from the Internet and NPM, using w.import().
This opens up a world of millions of JavaScript libraries to Scripter!
Browse libraries at https://www.npmjs.com/
Let's import the lru_map package:
*/
let w = createWorker(async w => {
let { LRUMap } = await w.import("lru_map")
let c = new LRUMap(3)
c.set('sam', 42)
c.set('john', 26)
c.set('angela', 24)
w.send(c.toString())
c.get('john') // touch entry to make it "recently used"
w.send(c.toString())
})
print(await w.recv())
print(await w.recv())
/**
You can import any URL; you are not limited to NPM. Additionally, using the importAll function we can import multiple packages at once:
*/
w = createWorker(async w => {
let [{ LRUMap }, d3] = await w.importAll(
"https://unpkg.com/lru_map@0.4.0/dist/lru.js",
"d3@5",
)
w.send(\`d3: \${typeof d3}, LRUMap: \${typeof LRUMap}\`)
})
print(await w.recv())
// Note that TypeScript types are not supported for imported modules.
// Scripter considers the API exposed by an imported library as "any".
`),
s("worker/iframe-d3-density-contours", "Workers/IFrame workers", `
/**
Sometimes a worker needs a full Web DOM or access to a Web API only available in full-blown documents, like WebGL. That's when iframe-based workers comes in handy.
This example shows how to load an external library which manipulates SVG in a DOM to create complex graphs. Specifically, the chart generated shows the relationship between idle and eruption times for Old Faithful. (Source: https://observablehq.com/@d3/density-contours)
*/
let w = createWorker({iframe:true}, async w => {
// load d3 library
const d3 = await w.import("d3@5")
// load dataset and add labels to the array
const data = Object.assign(
await w.recv<{x:number,y:number}[]>(),
{x: "Idle (min.)", y: "Erupting (min.)"}
)
const width = 800
const height = 800
const margin = {top: 20, right: 30, bottom: 30, left: 40}
const x = d3.scaleLinear()
.domain(d3.extent(data, d => d.x)).nice()
.rangeRound([margin.left, width - margin.right])
const y = d3.scaleLinear()
.domain(d3.extent(data, d => d.y)).nice()
.rangeRound([height - margin.bottom, margin.top])
const xAxis = g => g.append("g")
.attr("transform", \`translate(0,\${height - margin.bottom})\`)
.call(d3.axisBottom(x).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("y", -3)
.attr("dy", null)
.attr("font-weight", "bold")
.text(data.x))
const yAxis = g => g.append("g")
.attr("transform", \`translate(\${margin.left},0)\`)
.call(d3.axisLeft(y).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
const contours = d3.contourDensity()
.x(d => x(d.x))
.y(d => y(d.y))
.size([width, height])
.bandwidth(30)
.thresholds(30)
(data)
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g").call(xAxis);
svg.append("g").call(yAxis);
svg.append("g")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.selectAll("path")
.data(contours)
.enter().append("path")
.attr("stroke-width", (d, i) => i % 5 ? 0.25 : 1)
.attr("d", d3.geoPath());
svg.append("g")
.attr("stroke", "white")
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 2);
// respond with SVG code
w.send(svg.node().outerHTML)
})
// load sample data
const data = await fetchJson("https://scripter.rsms.me/sample/old-faithful.json")
// Send data to the worker for processing.
// The second argument causes data to be transferred
// instead of copied.
w.send(data, [data])
// await a response, then add SVG to Figma document
let svg = await w.recv<string>()
let n = figma.createNodeFromSvg(svg)
figma.viewport.scrollAndZoomIntoView([n])
`),
s("worker/window-basics", "Workers/Windows", `
/**
Workers backed by an iframe can be made visible and interactive via the "visible" property passed to createWorker.
*/
const w1 = createWorker({iframe:{visible:true,width:100}}, async w => {
w.document.body.innerHTML = \`<p>Hello</p>\`
})
/**
createWindow is a dedicated function for creating windows that house workers. To explore the options and the API, either place your pointer over createWindow below and press F12 or ALT-click the createWindow call to jump to the API documentation.
*/
const w2 = createWindow({width:300,height:100}, async w => {
let time :any
const ui = w.createElement("div", {
style: {
display: "flex",
"flex-direction": "column",
font: "12px sans-serif",
}},
w.createElement("button", { onclick() { w.send("ping") } }, "Ping!"),
w.createElement("button", { onclick() { w.close() } }, "Close window"),
time = w.createElement("p", {}, "")
)
w.document.body.appendChild(ui)
function updateTime() {
time.innerText = \`Time: \${(new Date).toTimeString()}\`
}
updateTime()
setInterval(updateTime, 1000)
})
w2.onmessage = ev => {
// click the "Ping!" button in the window
print(ev.data)
}
// wait until both windows have been closed
await Promise.all([w1,w2])
`),
s("worker/window-advanced1", "Workers/Windows advanced", `
/**
This is a version of the "IFrame worker" example which uses the d3 library inside a window to create a data visualization. However, instead of adding the generating graph to the Figma document, its shown in an interactive window instead. (Source: https://observablehq.com/@d3/density-contours)
A second window is opened as well, loading a Three.js WebGL via an external URL.
*/
const w1 = createWindow({title:"d3",width:800}, async w => {
// load data
const datap = fetch("https://scripter.rsms.me/sample/old-faithful.json").then(r => r.json())
// load d3 library
const d3 = await w.import("d3@5")
// wait for dataset and add labels
const data = Object.assign(
await datap,
{x: "Idle (min.)", y: "Erupting (min.)"}
)
const width = 800
const height = 800
const margin = {top: 20, right: 30, bottom: 30, left: 40}
const x = d3.scaleLinear()
.domain(d3.extent(data, d => d.x)).nice()
.rangeRound([margin.left, width - margin.right])
const y = d3.scaleLinear()
.domain(d3.extent(data, d => d.y)).nice()
.rangeRound([height - margin.bottom, margin.top])
const xAxis = g => g.append("g")
.attr("transform", \`translate(0,\${height - margin.bottom})\`)
.call(d3.axisBottom(x).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("y", -3)
.attr("dy", null)
.attr("font-weight", "bold")
.text(data.x))
const yAxis = g => g.append("g")
.attr("transform", \`translate(\${margin.left},0)\`)
.call(d3.axisLeft(y).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
const contours = d3.contourDensity()
.x(d => x(d.x))
.y(d => y(d.y))
.size([width, height])
.bandwidth(30)
.thresholds(30)
(data)
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
svg.append("g").call(xAxis);
svg.append("g").call(yAxis);
svg.append("g")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.selectAll("path")
.data(contours)
.enter().append("path")
.attr("stroke-width", (d, i) => i % 5 ? 0.25 : 1)
.attr("d", d3.geoPath());
svg.append("g")
.attr("stroke", "white")
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cx", d => x(d.x))
.attr("cy", d => y(d.y))
.attr("r", 2);
// respond with SVG code
w.document.body.appendChild(svg.node())
})
const w2 = createWindow(
{title:"Three.js"},
"https://threejs.org/examples/webgl_postprocessing_unreal_bloom.html")
// wait until both windows have been closed
await Promise.all([w1,w2])
`),
//------------------------------------------------------------------------------------------------
s("advanced/timeout", "Misc/Timeout", `
// Example of using withTimeout for limiting the time
// of a long-running process.
// Try changing the delay here from 200 to 300:
await doSlowThing(200)
async function doSlowThing(timeout :number) {
let result = await withTimeout(getFromSlowInternet(), timeout)
if (result == "TIMEOUT") {
print("network request timed out :-(")
} else {
print("network request finished on time :-)", result)
}
}
// Function that simulates a slow, cancellable network fetch.
// In parctice, this would be some some actual long-running thing
// like fetch call or timer.
function getFromSlowInternet() :CancellablePromise<Object> {
return timer(250).catch(_=>{}).then(() => ({message: "Hello"}))
}
`),
s("advanced/tick-tock", "Misc/Tick tock, tick tock, tick tock", `
// Demonstrates continously-running scripts.
// This loops forever until you restart or
// stop the script.
for (let i = 1; true; i++) {
print(i % 2 ? "Tick" : "Tock")
await timer(1000) // wait for 1 second
}
`),
s("advanced/animation", "Misc/Animation", `
// Example of using animate() to create custom animations
// Create a temporary rectangle
let r = Rectangle({ fills:[ORANGE.paint], rotation: 45 })
scripter.onend = () => r.remove()
// save viewport and focus on the rectangle
viewport.focusSave(r, 1.0)
// extent of motion in dp and shorthand functions
const size = viewport.bounds.width / 2 - r.width
const { cos, sin, abs, PI } = Math
// animation loop
await animate(time => {
// This function is called at a high frequency with
// time incrementing for every call.
time *= 3 // alter speed
let scale = size / (3 - cos(time * 2))
r.x = scale * cos(time) - (r.width / 2)
r.y = scale * sin(3 * time) / 1.5 - (r.height / 2)
r.rotation = cos(time) * 45
})
`),
// Note: There's a reference to the name of this in scripter-env.d.ts
s("misc/timing-function-viz", "Misc/Timing Functions", `
// This generates a grid of graphs visualizing the different
// timing functions available from animate.ease*
// See Misc/Animation for examples of how to use these functions.
viewport.focus(getTimingFunctions().map(createGraph))
function createGraph(f :(n:number)=>number, index :int) {
const width = 200, height = 200, step = 2
const columns = 6
const spacing = Math.round(width * 0.75)
const xoffs = (index % columns) * (width + spacing)
const yoffs = Math.ceil((index + 1) / columns) * (height + spacing)
let n = buildVector({ width, height, strokeWeight: 2 }, c => {
let prevy = 0
for (let x of range(step, width, step)) {
let y = f(x / width) * height
c.line(
{x: xoffs + x, y: yoffs + prevy},
{x: xoffs + x + step, y: yoffs + y}
)
prevy = y
}
}) as SceneNode
n = figma.flatten([n]) // merge into a line
if (f.name) {
let t = createText({
characters: f.name,
x: xoffs,
y: yoffs + height + 10,
width: width,
})
n = createGroup({expanded:false}, n, t)
n.name = f.name
}
return n
}
function getTimingFunctions() :SAnimationTimingFunction[] {
// collect timing functions, using a set to ignore aliases
let v = new Set<SAnimationTimingFunction>()
for (let k of Object.keys(animate)) {
if (k.startsWith("ease")) {
v.add(animate[k])
}
}
return Array.from(v)
}
`),
s("advanced/poisson-disc-gen", "Misc/Poisson-disc generator", `
/**
Progressively generates Poisson-disc pattern.
Poisson-disc sampling produces points that are tightly-packed, but no closer to each other than a specified minimum distance, resulting in a more natural pattern.
This implementation is based on https://bl.ocks.org/mbostock/dbb02448b0f93e4c82c3 and uses a worker which computes Poisson-disc samples using a generator. Samples are sent from the worker to the Scripter script which then creates discs on the Figma canvas.
*/
// Constants controlling the resulting graphic
const width = 900
const height = 800
const density = 8 // average distance between vertices
const circleRadius = 2 // radius of dots drawn for each vertex
// Simple 2D vector used for vertices
type Vec = [number,number]
// Request data that the Poisson-disc generator worker accepts
interface PoissonDiscGenRequest {
width :number // size of area to fill
height :number // size of area to fill
radius :number // density of vertices
}
// Poisson-disc generator worker
const w = createWorker({iframe:{visible:false}}, async w => {
const r = await w.recv<PoissonDiscGenRequest>()
let sendq :Vec[] = []
for (const v of poissonDiscSampler(r.width, r.height, r.radius)) {
sendq.push(v)
if (sendq.length >= 100) {
await w.recv()
w.send(sendq)
sendq.length = 0
}
}
// send possibly last samples and finally an empty list,
// which signals the end for the Scripter script.
w.send(sendq)
w.send([])
function* poissonDiscSampler(width :int, height :int, radius :number) :Generator<Vec> {
// Based on https://bl.ocks.org/mbostock/dbb02448b0f93e4c82c3
const k = 30, // maximum number of samples before rejection
radius2 = radius * radius,
radius2_3 = 3 * radius2,
cellSize = radius * Math.SQRT1_2,
gridWidth = Math.ceil(width / cellSize),
gridHeight = Math.ceil(height / cellSize),
grid = new Array<Vec>(gridWidth * gridHeight),
queue :Vec[] = []
// Pick the first sample.
yield sample(
width / 2 + Math.random() * radius,
height / 2 + Math.random() * radius)
// Pick a random existing sample from the queue.
pick: while (queue.length) {
const i = Math.random() * queue.length | 0
const parent = queue[i]
// Make a new candidate between [radius, 2 * radius] from the existing sample.
for (let j = 0; j < k; ++j) {
const a = 2 * Math.PI * Math.random(),
r = Math.sqrt(Math.random() * radius2_3 + radius2),
x = parent[0] + r * Math.cos(a),
y = parent[1] + r * Math.sin(a)
// Accept candidates that are inside the allowed extent
// and farther than 2 * radius to all existing samples.
if (0 <= x && x < width && 0 <= y && y < height && far(x, y)) {
//yield {add: sample(x, y), parent}
yield sample(x, y)
continue pick
}
}
// If none of k candidates were accepted, remove it from the queue.
const r = queue.pop()
if (i < queue.length) queue[i] = r as Vec
}
function far(x :number, y :number) :bool {
const i = x / cellSize | 0,
j = y / cellSize | 0,
i0 = Math.max(i - 2, 0),
j0 = Math.max(j - 2, 0),
i1 = Math.min(i + 3, gridWidth),
j1 = Math.min(j + 3, gridHeight)
for (let j = j0; j < j1; ++j) {
const o = j * gridWidth
for (let i = i0; i < i1; ++i) {
const s = grid[o + i]
if (s) {
const dx = s[0] - x
const dy = s[1] - y
if (dx * dx + dy * dy < radius2) return false
}
}
}
return true
}
function sample(x :number, y :number) :Vec {
const i = gridWidth * (y / cellSize | 0) + (x / cellSize | 0)
const s = grid[i] = [x, y]
queue.push(s)
return s
}
}
})
// Ask the worker to generate vertices with poisson-disc distribution
w.send<PoissonDiscGenRequest>({
width,
height,
radius: density,
})
// make a frame to house the results
const frame = Frame({ width, height, expanded: false })
figma.viewport.scrollAndZoomIntoView([frame])
// color spectrum
const colors :(t :number)=>RGB = rgbSpline([
"#ff0000", "#d53e4f", "#f46d43",
"#fdae61", "#fee08b", // "#ffffbf", "#e6f598",
"#abdda4", "#66c2a5", "#3288bd", "#5e4fa2"
])
// add dots as they arrive from the worker
const center :Vec = [ width * 0.5, height * 0.5 ]
const farDistance = squareDistance([0,0], center)
while (true) {
w.send(1)
const vertices = await w.recv<Vec[]>()
if (vertices.length == 0) {
break
}
for (let v of vertices) {
frame.appendChild(
// Create a shape.
// Try changing "Ellipse" to "Star" or "Rectangle"
Ellipse({
fills: [ {
type: "SOLID",
color: colors(squareDistance(center, v) / farDistance)
} ],
x: v[0] - circleRadius,
y: v[1] - circleRadius,
width: circleRadius * 2,
height: circleRadius * 2,
constrainProportions: true
})
)
}
}
function squareDistance(a :Vec, b :Vec) :number {
let x = a[0] - b[0]
let y = a[1] - b[1]
return Math.sqrt(x * x + y * y)
}
// little color gradient function for making interpolateable ramps
function rgbSpline(colors :string[]) :(t:number)=>RGB {
const n = colors.length
const r = new Float64Array(n)
const g = new Float64Array(n)
const b = new Float64Array(n)
let color = { r:0, g:0, b:0 }
for (let i = 0; i < n; ++i) {
parseColor(colors[i], color)
r[i] = color.r || 0
g[i] = color.g || 0
b[i] = color.b || 0
}
const rf = basisSpline(r),
gf = basisSpline(g),
bf = basisSpline(b)
return (t :number) :RGB => {
color.r = Math.max(0, Math.min(1, rf(t) / 255.0))
color.g = Math.max(0, Math.min(1, gf(t) / 255.0))
color.b = Math.max(0, Math.min(1, bf(t) / 255.0))
return color // borrow
// return { r: rf(t), g: gf(t), b: bf(t) } // alloc & copy
}
function basisSpline(values :ArrayLike<number>) :(t :number)=>number {
const n = values.length - 1
return (t :number) => {
let i = (
t <= 0 ? (t = 0) :
t >= 1 ? (t = 1, n - 1) :
Math.floor(t * n)
)
let v1 = values[i]
let v2 = values[i + 1]
let v0 = i > 0 ? values[i - 1] : 2 * v1 - v2
let v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1
let t1 = (t - i / n) * n
let t2 = t1 * t1, t3 = t2 * t1
return ((1 - 3 * t1 + 3 * t2 - t3) * v0
+ (4 - 6 * t2 + 3 * t3) * v1
+ (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2
+ t3 * v3) / 6;
}
}
function parseColor(s :string, out :{ r :number, g :number, b :number }) {
if (s[0] == '#') {
s = s.substr(1)
}
let n = parseInt(s, 16)
out.r = n >> 16 & 0xff
out.g = n >> 8 & 0xff
out.b = n & 0xff
}
}
`),
] as ExampleScript[]) | the_stack |
* @module Polyface
*/
import { Point2d } from "../geometry3d/Point2dVector2d";
import { PolyfaceData } from "./PolyfaceData";
import { IndexedPolyface, Polyface, PolyfaceVisitor } from "./Polyface";
import { Geometry } from "../Geometry";
/* eslint-disable @itwin/prefer-get */
/**
* An `IndexedPolyfaceVisitor` is an iterator-like object that "visits" facets of a mesh.
* * The visitor extends a `PolyfaceData ` class, so it can at any time hold all the data of a single facet.
* @public
*/
export class IndexedPolyfaceVisitor extends PolyfaceData implements PolyfaceVisitor {
private _currentFacetIndex: number;
private _nextFacetIndex: number;
private _numWrap: number;
private _numEdges: number;
private _polyface: IndexedPolyface;
// to be called from static factory method that validates the polyface ...
protected constructor(facets: IndexedPolyface, numWrap: number) {
super(facets.data.normalCount > 0, facets.data.paramCount > 0, facets.data.colorCount > 0, facets.twoSided);
this._polyface = facets;
this._numWrap = numWrap;
if (facets.data.auxData)
this.auxData = facets.data.auxData.createForVisitor();
this.reset();
this._numEdges = 0;
this._nextFacetIndex = 0;
this._currentFacetIndex = -1;
}
/** Return the client polyface object. */
public clientPolyface(): Polyface { return this._polyface; }
/** Set the number of vertices duplicated (e.g. 1 for start and end) in arrays in the visitor. */
public setNumWrap(numWrap: number) { this._numWrap = numWrap; }
/** Return the number of edges in the current facet.
* * Not that if this visitor has `numWrap` greater than zero, the number of edges is smaller than the number of points.
*/
public get numEdgesThisFacet(): number { return this._numEdges; }
/** Create a visitor for iterating the facets of `polyface`, with indicated number of points to be added to each facet to produce closed point arrays
* Typical wrap counts are:
* * 0 -- leave the point arrays with "missing final edge"
* * 1 -- add point 0 as closure point
* * 2 -- add points 0 and 1 as closure and wrap point. This is useful when vertex visit requires two adjacent vectors, e.g. for cross products.
*/
public static create(polyface: IndexedPolyface, numWrap: number): IndexedPolyfaceVisitor {
return new IndexedPolyfaceVisitor(polyface, numWrap);
}
/** Advance the iterator to a particular facet in the client polyface */
public moveToReadIndex(facetIndex: number): boolean {
if (!this._polyface.isValidFacetIndex(facetIndex))
return false;
this._currentFacetIndex = facetIndex;
this._nextFacetIndex = facetIndex + 1;
this._numEdges = this._polyface.numEdgeInFacet(facetIndex);
this.resizeAllDataArrays(this._numEdges + this._numWrap);
this.gatherIndexedData(this._polyface.data, this._polyface.facetIndex0(this._currentFacetIndex), this._polyface.facetIndex1(this._currentFacetIndex), this._numWrap);
return true;
}
/** Advance the iterator to a the 'next' facet in the client polyface */
public moveToNextFacet(): boolean {
if (this._nextFacetIndex !== this._currentFacetIndex)
return this.moveToReadIndex(this._nextFacetIndex);
this._nextFacetIndex++;
return true;
}
/** Reset the iterator to start at the first facet of the polyface. */
public reset(): void {
this.moveToReadIndex(0);
this._nextFacetIndex = 0; // so immediate moveToNextFacet stays here.
}
/**
* Attempts to extract the distance parameter for the given vertex index on the current facet
* Returns the distance parameter as a point. Returns undefined on failure.
*/
public tryGetDistanceParameter(index: number, result?: Point2d): Point2d | undefined {
if (index >= this.numEdgesThisFacet)
return undefined;
if (this.param === undefined || this._polyface.data.face.length === 0)
return undefined;
const faceData = this._polyface.tryGetFaceData(this._currentFacetIndex);
if (!faceData)
return undefined;
return faceData.convertParamXYToDistance(this.param.getXAtUncheckedPointIndex(index), this.param.getYAtUncheckedPointIndex(index), result);
}
/**
* Attempts to extract the normalized parameter (0,1) for the given vertex index on the current facet.
* Returns the normalized parameter as a point. Returns undefined on failure.
*/
public tryGetNormalizedParameter(index: number, result?: Point2d): Point2d | undefined {
if (index >= this.numEdgesThisFacet)
return undefined;
if (this.param === undefined || this._polyface.data.face.length === 0)
return undefined;
const faceData = this._polyface.tryGetFaceData(this._currentFacetIndex);
if (!faceData)
return undefined;
return faceData.convertParamXYToNormalized(this.param.getXAtUncheckedPointIndex(index), this.param.getYAtUncheckedPointIndex(index), result);
}
/** Return the index (in the client polyface) of the current facet */
public currentReadIndex(): number { return this._currentFacetIndex; }
/** Return the point index of vertex i within the currently loaded facet */
public clientPointIndex(i: number): number { return this.pointIndex[i]; }
/** Return the param index of vertex i within the currently loaded facet */
public clientParamIndex(i: number): number { return this.paramIndex ? this.paramIndex[i] : -1; }
/** Return the normal index of vertex i within the currently loaded facet */
public clientNormalIndex(i: number): number { return this.normalIndex ? this.normalIndex[i] : -1; }
/** Return the color index of vertex i within the currently loaded facet */
public clientColorIndex(i: number): number { return this.colorIndex ? this.colorIndex[i] : -1; }
/** Return the aux data index of vertex i within the currently loaded facet */
public clientAuxIndex(i: number): number { return this.auxData ? this.auxData.indices[i] : -1; }
/** clear the contents of all arrays. Use this along with transferDataFrom methods to build up new facets */
public clearArrays(): void {
if (this.point !== undefined)
this.point.length = 0;
if (this.param !== undefined)
this.param.length = 0;
if (this.normal !== undefined)
this.normal.length = 0;
if (this.color !== undefined)
this.color.length = 0;
}
/** transfer data from a specified index of the other visitor as new data in this visitor. */
public pushDataFrom(other: PolyfaceVisitor, index: number): void {
this.point.pushFromGrowableXYZArray(other.point, index);
if (this.color && other.color && index < other.color.length)
this.color.push(other.color[index]);
if (this.param && other.param && index < other.param.length)
this.param.pushFromGrowableXYArray(other.param, index);
if (this.normal && other.normal && index < other.normal.length)
this.normal.pushFromGrowableXYZArray(other.normal, index);
}
/** transfer interpolated data from the other visitor.
* * all data values are interpolated at `fraction` between `other` values at index0 and index1.
*/
public pushInterpolatedDataFrom(other: PolyfaceVisitor, index0: number, fraction: number, index1: number): void {
this.point.pushInterpolatedFromGrowableXYZArray(other.point, index0, fraction, index1);
if (this.color && other.color && index0 < other.color.length && index1 < other.color.length)
this.color.push(interpolateColor(other.color[index0], fraction, other.color[index1]));
if (this.param && other.param && index0 < other.param.length && index1 < other.param.length)
this.param.pushInterpolatedFromGrowableXYArray(other.param, index0, fraction, index1);
if (this.normal && other.normal && index0 < other.normal.length && index1 < other.normal.length)
this.normal.pushInterpolatedFromGrowableXYZArray(other.normal, index0, fraction, index1);
}
}
/**
* * shift to right by shiftBits.
* * mask off the low 8 bits
* * interpolate the number
* * truncate to floor
* * shift left
* * Hence all numbers in and out of the floating point are 0..255.
* @param color0
* @param fraction
* @param color1
* @param shiftBits
*/
function interpolateByte(color0: number, fraction: number, color1: number, shiftBits: number): number {
color0 = (color0 >>> shiftBits) & 0xFF;
color1 = (color1 >>> shiftBits) & 0xFF;
const color = Math.floor(color0 + fraction * (color1 - color0)) & 0xFF;
return color << shiftBits;
}
/**
* Interpolate each byte of color0 and color1 as integers.
* @param color0 32 bit color (e.g. rgb+transparency)
* @param fraction fractional position. This is clamped to 0..1 to prevent byte values outside their 0..255 range.
* @param color1
* @param shiftBits
* @internal
*/
export function interpolateColor(color0: number, fraction: number, color1: number) {
// don't allow fractions outside the individual byte ranges.
fraction = Geometry.clamp(fraction, 0, 1);
// interpolate each byte in place ....
/*
const byte0 = interpolateLowByte(color0 & 0xFF, fraction, color1 & 0xFF);
const byte1 = interpolateLowByte((color0 & 0xFF00) >>> 8, fraction, (color1 & 0xFF00) >>> 8) << 8;
const byte2 = interpolateLowByte((color0 & 0xFF0000) >>> 16, fraction, (color1 & 0xFF0000) >>> 16) << 16;
const byte3 = interpolateLowByte((color0 & 0xFF000000) >>> 24, fraction, (color1 & 0xFF000000) >>> 24) << 24;
*/
const byte0 = interpolateByte(color0, fraction, color1, 0);
const byte1 = interpolateByte(color0, fraction, color1, 8);
const byte2 = interpolateByte(color0, fraction, color1, 16);
const byte3 = interpolateByte(color0, fraction, color1, 24);
return (byte0 | byte1 | byte2 | byte3);
}
/**
* An `IndexedPolyfaceSubsetVisitor` is an IndexedPolyfaceVisitor which only visits a subset of facets in the polyface.
* * The subset is defined by an array of facet indices provided when this visitor is created.
* * Within the subset visitor, "facetIndex" is understood as index within the subset array:
* * moveToNextFacet moves only within the subset
* * moveToReadIndex(i) moves underlying visitor's parentFacetIndex(i)
* @public
*/
export class IndexedPolyfaceSubsetVisitor extends IndexedPolyfaceVisitor {
private _parentFacetIndices: number[];
// index WITHIN THE _activeFacetIndices array.
private _nextActiveIndex: number;
private constructor(polyface: IndexedPolyface, activeFacetIndices: number[], numWrap: number) {
super(polyface, numWrap);
this._parentFacetIndices = activeFacetIndices.slice();
this._nextActiveIndex = 0;
}
/** Create a visitor for iterating a subset of the facets of `polyface`, with indicated number of points to be added to each facet to produce closed point arrays
* * Typical wrap counts are:
* * 0 -- leave the point arrays with "missing final edge"
* * 1 -- add point 0 as closure point
* * 2 -- add points 0 and 1 as closure and wrap point. This is useful when vertex visit requires two adjacent vectors, e.g. for cross products.
* * The activeFacetIndices array indicates all facets to be visited.
*/
public static createSubsetVisitor(polyface: IndexedPolyface, activeFacetIndices: number[], numWrap: number): IndexedPolyfaceSubsetVisitor {
return new IndexedPolyfaceSubsetVisitor(polyface, activeFacetIndices.slice(), numWrap);
}
/** Advance the iterator to a particular facet in the client polyface */
public override moveToReadIndex(activeIndex: number): boolean {
if (activeIndex >= 0 && activeIndex <= this._parentFacetIndices.length) {
this._nextActiveIndex = activeIndex;
return super.moveToReadIndex(this._parentFacetIndices[activeIndex++]);
}
return false;
}
/** Advance the iterator to a the 'next' facet in the client polyface */
public override moveToNextFacet(): boolean {
if (this._nextActiveIndex < this._parentFacetIndices.length) {
const result = this.moveToReadIndex(this._nextActiveIndex);
if (result) {
this._nextActiveIndex++;
return true;
}
}
return false;
}
/** Reset the iterator to start at the first facet of the polyface. */
public override reset(): void {
this._nextActiveIndex = 0;
}
/** return the parent facet index of the indicated index within the active facets */
public parentFacetIndex(activeIndex: number): number | undefined {
if (activeIndex >= 0 && activeIndex <= this._nextActiveIndex) {
return this._parentFacetIndices[activeIndex];
}
return undefined;
}
} | the_stack |
import * as path from 'path';
import * as FS from '../../tools/fs';
import * as fs from 'fs';
import * as Tools from '../../tools/index';
import * as semver from 'semver';
import Logger from '../../tools/env.logger';
import ServicePaths from '../../services/service.paths';
import ServiceElectronService from '../../services/service.electron.state';
import ServicePackage from '../../services/service.package';
import GitHubClient, { IReleaseAsset, IReleaseData, GitHubAsset } from '../../tools/env.github.client';
import { getPlatform, EPlatforms } from '../../tools/env.os';
import { download } from '../../tools/env.net';
import { CommonInterfaces } from '../../interfaces/interface.common';
import { getValidPluginReleaseInfo } from './plugins.validator';
const CSettings: {
user: string,
repo: string,
registerListFile: string,
} = {
/*
user: 'DmitryAstafyev',
repo: 'chipmunk.plugins.store',
registerListFile: 'releases-{platform}.json',
*/
user: 'esrlabs',
repo: 'chipmunk-plugins-store',
registerListFile: 'releases-{platform}.json'
};
const CFileNamePattern = /[\w\d-_\.]*@\d*\.\d*\.\d*-\d*\.\d*.\d*-\w*\.tgz$/gi;
// chipmunk-serial-plugin@81100880.110000220.0024211238-1.0.1-linux.tgz
/**
* @class ControllerPluginStore
* @description Delivery default plugins into logviewer folder
*/
export default class ControllerPluginStore {
private _logger: Logger = new Logger(`ControllerPluginStore ("${CSettings.user}/${CSettings.repo}")`);
private _remote: Map<string, CommonInterfaces.Plugins.IPlugin> | undefined = undefined;
private _local: Map<string, CommonInterfaces.Plugins.IPlugin> = new Map();
private _downloads: Map<string, boolean> = new Map();
public destroy(): Promise<void> {
return new Promise((resolve, reject) => {
resolve();
});
}
public local(): Promise<void> {
return new Promise((resolve) => {
this._setupLocalReleaseNotes().then((plugins: Map<string, CommonInterfaces.Plugins.IPlugin>) => {
this._local = plugins;
resolve();
}).catch((error: Error) => {
this._logger.warn(`Fail to get plugin's register due error: ${error.message}`);
resolve();
});
});
}
public remote(): Promise<void> {
return new Promise((resolve, reject) => {
this._setupRemoteReleaseNotes().then((plugins: Map<string, CommonInterfaces.Plugins.IPlugin>) => {
this._remote = plugins;
resolve();
}).catch((error: Error) => {
this._logger.warn(`Fail to get plugin's register due error: ${error.message}`);
resolve();
});
});
}
public download(name: string, version: string): Promise<string> {
return new Promise((resolve, reject) => {
ServiceElectronService.logStateToRender(`Downloading plugin "${name}"...`);
// Check plugin info
const plugin: CommonInterfaces.Plugins.IPlugin | undefined = this.getInfo(name);
if (plugin === undefined) {
return reject(new Error(this._logger.warn(`Plugin "${name}" isn't found.`)));
}
this.delivery(plugin.name, version).then((filename: string) => {
resolve(filename);
}).catch((deliveryErr: Error) => {
reject(new Error(this._logger.warn(`Fail to delivery plugin "${plugin.name}" due error: ${deliveryErr.message}`)));
});
});
}
public getDefaults(exclude: string[]): string[] {
return Array.from(this.getRegister().values()).filter((plugin: CommonInterfaces.Plugins.IPlugin) => {
return exclude.indexOf(plugin.name) === -1 && plugin.default;
}).map((plugin: CommonInterfaces.Plugins.IPlugin) => {
return plugin.name;
});
}
public isDefault(name: string): boolean {
let defaults: boolean = false;
Array.from(this.getRegister().values()).filter((plugin: CommonInterfaces.Plugins.IPlugin) => {
if (defaults) {
return;
}
if (plugin.name === name) {
defaults = plugin.default;
}
});
return defaults;
}
public getAvailable(): CommonInterfaces.Plugins.IPlugin[] {
return Array.from(this.getRegister().values()).map((plugin: CommonInterfaces.Plugins.IPlugin) => {
return Object.assign({}, plugin);
});
}
public getSuitableVersions(name: string): CommonInterfaces.Plugins.IHistory[] {
const plugin: CommonInterfaces.Plugins.IPlugin | undefined = this.getPluginReleaseInfo(name);
if (plugin === undefined) {
return [];
}
const history: CommonInterfaces.Plugins.IHistory[] = plugin.history.filter((record: CommonInterfaces.Plugins.IHistory) => {
if (!semver.valid(record.version)) {
this._logger.warn(`Plugin "name" has bad record in history. Version "${record.version}" is invalid.`);
return false;
}
return record.hash === ServicePackage.getHash();
}).map((record: CommonInterfaces.Plugins.IHistory | undefined) => {
return Object.assign({}, record);
});
if (history.length === 0 && plugin.hash === ServicePackage.getHash()) {
history.push({
hash: plugin.hash,
phash: plugin.phash,
version: plugin.version,
url: plugin.url,
});
}
return history;
}
public getLatestVersion(name: string): CommonInterfaces.Plugins.IHistory | undefined {
const versions: CommonInterfaces.Plugins.IHistory[] = this.getSuitableVersions(name);
if (versions.length === 0) {
return undefined;
}
return versions[0];
}
public getRegister(): Map<string, CommonInterfaces.Plugins.IPlugin> {
return this._remote === undefined ? this._local : this._remote;
}
public delivery(name: string, version: string): Promise<string> {
return new Promise((resolve, reject) => {
const plugin: CommonInterfaces.Plugins.IPlugin | undefined = this.getRegister().get(name);
if (plugin === undefined) {
return reject(new Error(`Fail to find plugin in register`));
}
const url: string | undefined = this._getUrl(plugin.name, version);
if (url === undefined) {
return reject(new Error(`Fail to find plugin's url for "${plugin.name}@${version}"`));
}
const urlfilename: string | Error = this._getFileNameFromURL(url);
const filename: string = urlfilename instanceof Error ? plugin.file : urlfilename;
const target: string = path.resolve(ServicePaths.getDownloads(), filename);
this._findLocally(filename).then((file: string) => {
resolve(file);
}).catch((error: Error) => {
if (this._downloads.has(target)) {
return reject(new Error(`Plugin "${plugin.name}" (${target}) is already downloading.`));
}
this._downloads.set(target, true);
this._logger.debug(`Plugin "${plugin.name}" isn't found and will be downloaded: ${error.message}`);
const temp: string = path.resolve(ServicePaths.getDownloads(), Tools.guid());
FS.unlink(target).then(() => {
download(url, temp).then(() => {
fs.stat(temp, (statErr: NodeJS.ErrnoException | null, stat: fs.Stats) => {
if (statErr) {
return reject(new Error(this._logger.warn(`Fail download file "${temp}" due error: ${statErr.message}`)));
}
this._logger.debug(`Plugin "${name}" is downloaded:\n\t- file: ${temp} (${target}) \n\t- size: ${stat.size} bytes`);
fs.rename(temp, target, (renameErr: NodeJS.ErrnoException | null) => {
if (renameErr) {
return reject(new Error(this._logger.warn(`Fail rename file "${temp}" to "${target}" due error: ${renameErr.message}`)));
}
resolve(target);
});
});
}).catch((downloadErr: Error) => {
reject(new Error(this._logger.warn(`Fail to download file "${target}" due error: ${downloadErr.message}`)));
});
}).catch((unlinkErr: Error) => {
reject(new Error(this._logger.warn(`Fail to remove file "${target}" due error: ${unlinkErr.message}`)));
});
});
});
}
public getPluginReleaseInfo(name: string): CommonInterfaces.Plugins.IPlugin | undefined {
const register: Map<string, CommonInterfaces.Plugins.IPlugin> = this.getRegister();
return register.get(name);
}
public getInfo(name: string): CommonInterfaces.Plugins.IPlugin | undefined {
return this._remote === undefined ? this._local.get(name) : this._remote.get(name);
}
private _getUrl(name: string, version: string): string | undefined {
const info: CommonInterfaces.Plugins.IPlugin | undefined = this.getInfo(name);
if (info === undefined) {
return undefined;
}
if (info.version === version && info.hash === ServicePackage.getHash()) {
return info.url;
}
let url: string | undefined;
info.history.forEach((record: CommonInterfaces.Plugins.IHistory) => {
if (record.version === version && record.hash === ServicePackage.getHash()) {
url = record.url;
}
});
return url;
}
private _getFileNameFromURL(url: string): string | Error {
const match: RegExpMatchArray | null = url.match(CFileNamePattern);
if (match === null || match.length !== 1) {
return new Error(`Fail to extract filename from url: ${url}`);
}
return match[0];
}
private _findLocally(filename: string): Promise<string> {
return new Promise((resolve, reject) => {
this._findIn(filename, 'includes').then((file: string) => {
resolve(file);
}).catch((inclErr: Error) => {
this._logger.debug(`Fail to find a plugin "${filename}" in included due error: ${inclErr.message}`);
this._findIn(filename, 'downloads').then((file: string) => {
resolve(file);
}).catch((downloadsErr: Error) => {
this._logger.debug(`Fail to find a plugin "${filename}" in downloads due error: ${downloadsErr.message}`);
reject(new Error(`Plugin "${filename}" isn't found.`));
});
});
});
}
private _findIn(filename: string, source: 'includes' | 'downloads'): Promise<string> {
return new Promise((resolve, reject) => {
const folder: string = source === 'includes' ? ServicePaths.getIncludedPlugins() : ServicePaths.getDownloads();
const fullname: string = path.resolve(folder, filename);
FS.exist(fullname).then((exist: boolean) => {
if (!exist) {
return reject(new Error(`Plugin "${fullname}" isn't found.`));
}
resolve(fullname);
}).catch((error: Error) => {
reject(error);
});
});
}
private _setupRemoteReleaseNotes(): Promise<Map<string, CommonInterfaces.Plugins.IPlugin>> {
return new Promise((resolve, reject) => {
ServiceElectronService.logStateToRender(`Getting plugin's store state.`);
GitHubClient.getLatestRelease({ user: CSettings.user, repo: CSettings.repo }).then((release: IReleaseData) => {
if (release.map === undefined) {
return reject(new Error(this._logger.warn(`Plugins-store repo doesn't have any assets in latest release.`)));
}
const filename: string = this._getRegisterFileName();
const asset: GitHubAsset | undefined = release.map.get(filename);
if (asset === undefined) {
return reject(new Error(this._logger.warn(`Fail to find "${filename}" in assets of latest release.`)));
}
asset.raw().then((raw: string) => {
try {
const list: CommonInterfaces.Plugins.IPlugin[] = JSON.parse(raw);
if (!(list instanceof Array)) {
return reject(new Error(this._logger.warn(`Incorrect format of asseets`)));
}
const plugins: Map<string, CommonInterfaces.Plugins.IPlugin> = new Map();
list.forEach((plugin: CommonInterfaces.Plugins.IPlugin) => {
const valid: CommonInterfaces.Plugins.IPlugin | Error = getValidPluginReleaseInfo(plugin);
if (valid instanceof Error) {
this._logger.warn(`Fail to validate plugin: ${JSON.stringify(plugin)}`);
} else {
plugins.set(valid.name, valid);
}
});
ServiceElectronService.logStateToRender(`Information of last versions of plugins has been gotten`);
resolve(plugins);
} catch (e) {
return reject(new Error(this._logger.warn(`Fail parse asset to JSON due error: ${e.message}`)));
}
}).catch((assetErr: Error) => {
this._logger.warn(`Fail get asset due error: ${assetErr.message}`);
reject(assetErr);
});
}).catch((error: Error) => {
reject(new Error(this._logger.warn(`Fail get latest release due error: ${error.message}`)));
});
});
}
private _setupLocalReleaseNotes(): Promise<Map<string, CommonInterfaces.Plugins.IPlugin>> {
return new Promise((resolve, reject) => {
const local: string = path.resolve(ServicePaths.getIncludedPlugins(), this._getRegisterFileName());
FS.exist(local).then((exist: boolean) => {
if (!exist) {
return reject(new Error(`Fail to find local register "${local}"`));
}
FS.readTextFile(local).then((json: string) => {
try {
const list: CommonInterfaces.Plugins.IPlugin[] = JSON.parse(json);
if (!(list instanceof Array)) {
return reject(new Error(this._logger.warn(`Incorrect format of asseets`)));
}
const plugins: Map<string, CommonInterfaces.Plugins.IPlugin> = new Map();
list.forEach((plugin: CommonInterfaces.Plugins.IPlugin) => {
const valid: CommonInterfaces.Plugins.IPlugin | Error = getValidPluginReleaseInfo(plugin);
if (valid instanceof Error) {
this._logger.warn(`Fail to validate plugin: ${JSON.stringify(plugin)}`);
} else {
plugins.set(valid.name, valid);
}
});
ServiceElectronService.logStateToRender(this._logger.debug(`Information of last versions of plugins has been gotten`));
resolve(plugins);
} catch (e) {
return reject(new Error(this._logger.warn(`Fail parse asset (from local store) to JSON due error: ${e.message}`)));
}
}).catch((readErr: Error) => {
reject(readErr);
});
}).catch((exErr: Error) => {
reject(exErr);
});
});
}
private _getRegisterFileName(): string {
return CSettings.registerListFile.replace('{platform}', getPlatform(true));
}
} | the_stack |
import { AEndpointBuilder, HttpMethod, QueryParams, ApiDefinition, EndpointDefinition } from './types';
import { RemoveKey } from './private/ts-kung-fu';
/**
* Builder class to create endpoint definitions.
*
* This class provides a high-level user friendly interface to create a typed definition of an API endpoint.
*
* Endpoint definitions are usually grouped together in API definitions, which can be shared between producers
* and consumers of the API to create a type-safe communication channel.
*
* You will generally not need to create this class explicitly. Instead, use the helper methods [[GET]], [[PUT]],
* [[PATCH]], [[POST]] or [[DELETE]] to create an instance of EndpointBuilder.
*/
export class EndpointBuilder<T extends Partial<EndpointDefinition>> implements AEndpointBuilder<T> {
constructor(public readonly def: Readonly<T>) { }
/**
* Change the HTTP method of this endpoint
* @param method Any valid HTTP method. See [[HttpMethod]].
*/
public method<U extends HttpMethod>(method: U): EndpointBuilder<RemoveKey<T, 'method'> & { method: U }> {
return new EndpointBuilder<T & { method: U }>(Object.assign({}, this.def, { method }));
}
/**
* Change the type of the response.
*
* You must provide a real object whose type will be inferred and used as the response type for this endpoint.
* Rest.ts offers multiple ways to do this:
*
* 1. Use a regular object.
* For instance, if you need a string, use `'string'`, if you need a number, use `123`.
* This also works for complex objects like so:
*
* GET `/current-user`
* .response({
* id: 'string',
* kind: 'person' as 'person' | 'robot' | 'cat'
* })
*
* 2. Some people like to use classes to define their DTOs. If this is your situation, you may just put the
* class constructor here, and the instance type will be inferred.
*
* class CurrentUserDTO {
* id: string;
* kind: 'person' | 'robot' | 'cat';
* }
*
* GET `/current-user`
* .response(CurrentUserDTO)
*
* 3. **(Preferred method)** Use a Runtype. [runtypes](https://github.com/pelotom/runtypes) is a
* library that allows you to create type definitions with runtime type metadata to ensure that
* input data conforms to an expected type.
* Rest.ts has first-class support for runtypes:
*
* const CurrentUserDTO = rt.Record({
* id: rt.String,
* kind: rt.Union(
* rt.String('person'),
* rt.String('robot'),
* rt.String('cat')
* )
* });
*
* GET `/current-user`
* .response(CurrentUserDTO)
*
* @param response type of the response data.
*/
public response<U>(response: U): EndpointBuilder<RemoveKey<T, 'response'> & { response: U }> {
return new EndpointBuilder<T & { response: U }>(Object.assign({}, this.def, { response }));
}
/**
* Change the type of the request body.
*
* You must provide a real object whose type will be inferred and used as the response type for this endpoint.
* Rest.ts offers multiple ways to do this:
*
* 1. Use a regular object.
* For instance, if you need a string, use `'string'`, if you need a number, use `123`.
* This also works for complex objects like so:
*
* POST `/current-user`
* .body({
* id: 'string',
* kind: 'person' as 'person' | 'robot' | 'cat'
* })
*
* 2. Some people like to use classes to define their DTOs. If this is your situation, you may just put the
* class constructor here, and the instance type will be inferred.
*
* class CurrentUserDTO {
* id: string;
* kind: 'person' | 'robot' | 'cat';
* }
*
* POST `/current-user`
* .body(CurrentUserDTO)
*
* 3. **(Preferred method)** Use a Runtype. [runtypes](https://github.com/pelotom/runtypes) is a
* library that allows you to create type definitions with runtime type metadata to ensure that
* input data conforms to an expected type.
* Rest.ts has first-class support for runtypes:
*
* const CurrentUserDTO = rt.Record({
* id: rt.String,
* kind: rt.Union(
* rt.String('person'),
* rt.String('robot'),
* rt.String('cat')
* )
* });
*
* POST `/current-user`
* .body(CurrentUserDTO)
*
* rest-ts-express automatically type-checks incoming data when the body of the endpoint definition is a runtype.
*
* @param response type of the response data.
*/
public body<U>(body: U): EndpointBuilder<RemoveKey<T, 'body'> & { body: U }> {
return new EndpointBuilder<T & { body: U }>(Object.assign({}, this.def, { body }));
}
/**
* Add query parameters.
*
* Note that query parameters are always optional.
*
* Example:
*
* GET `/users/search`
* .query({
* 'order': 'string',
* 'filter': 'string'
* })
*
* @param query type of the query parameters.
*/
public query<U extends QueryParams>(query: U): EndpointBuilder<RemoveKey<T, 'query'> & { query: U }> {
return new EndpointBuilder<T & { query: U }>(Object.assign({}, this.def, { query }));
}
}
function endpoint(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]) {
if (typeof pathOrStaticParts === 'string') {
return new EndpointBuilder({
path: [ pathOrStaticParts ],
params: [],
response: undefined
});
}
return new EndpointBuilder({
path: pathOrStaticParts.slice(),
params: params || [],
response: undefined
});
}
export interface InitialEndpointDefinition<Params, METHOD extends HttpMethod | undefined> {
path: string[];
params: Params;
method: METHOD;
response: undefined;
}
export interface EmptyInitialEndpointDefinition<METHOD extends HttpMethod | undefined> {
path: string[];
method: METHOD;
response: undefined;
}
/**
* Create a GET endpoint definition.
*
* Use of the template literal allows to easily add dynamic path parameters to the endpoint definition, as shown in the example below.
*
* Use as a tagged template literal to add path parameters to the endpoint, and use methods of
* the [[EndpointBuilder]] class to customize the endpoint definition.
*
* This endpoint definition can be consumed by API servers and clients such as rest-ts-express and rest-ts-axios.
*
* Example:
*
* export const carsAPI = defineAPI({
* // Get emissions test results for a given car.
* // For example: GET /cars/VW_Golf_TDI/results => "OK"
* getCarTestResults: GET `/cars/${'model'}/results`
* .response(CarTestResults)
* });
*/
export function GET(path: string | TemplateStringsArray): EndpointBuilder<EmptyInitialEndpointDefinition<'GET'>>;
export function GET<A extends string>(strings: TemplateStringsArray, a: A): EndpointBuilder<InitialEndpointDefinition<[A], 'GET'>>;
export function GET<A extends string, B extends string>(strings: TemplateStringsArray, a: A, b: B): EndpointBuilder<InitialEndpointDefinition<[A, B], 'GET'>>;
export function GET<A extends string, B extends string, C extends string>(strings: TemplateStringsArray, a: A, b: B, c: C): EndpointBuilder<InitialEndpointDefinition<[A, B, C], 'GET'>>;
export function GET<A extends string, B extends string, C extends string, D extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D], 'GET'>>;
export function GET<A extends string, B extends string, C extends string, D extends string, E extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E], 'GET'>>;
export function GET<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F], 'GET'>>;
export function GET<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G], 'GET'>>;
export function GET<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string, H extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G, H], 'GET'>>;
export function GET(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]): EndpointBuilder<InitialEndpointDefinition<string[], 'GET'>> {
return endpoint(pathOrStaticParts, ...params).method('GET');
}
/**
* Create a PUT endpoint definition.
*
* Use of the template literal allows to easily add dynamic path parameters to the endpoint definition, as shown in the example below.
*
* Use as a tagged template literal to add path parameters to the endpoint, and use methods of
* the [[EndpointBuilder]] class to customize the endpoint definition.
*
* This endpoint definition can be consumed by API servers and clients such as rest-ts-express and rest-ts-axios.
*
* Example:
*
* export const carsAPI = defineAPI({
* // Edit a car in the list
* // For example: PUT /cars/123/edit
* editCar: PUT `/cars/${'id'}/edit`
* .body(CarAttributes)
* .response(CarSaveResponse)
* });
*/
export function PUT(path: string | TemplateStringsArray): EndpointBuilder<EmptyInitialEndpointDefinition<'PUT'>>;
export function PUT<A extends string>(strings: TemplateStringsArray, a: A): EndpointBuilder<InitialEndpointDefinition<[A], 'PUT'>>;
export function PUT<A extends string, B extends string>(strings: TemplateStringsArray, a: A, b: B): EndpointBuilder<InitialEndpointDefinition<[A, B], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string>(strings: TemplateStringsArray, a: A, b: B, c: C): EndpointBuilder<InitialEndpointDefinition<[A, B, C], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string, D extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string, D extends string, E extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G], 'PUT'>>;
export function PUT<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string, H extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G, H], 'PUT'>>;
export function PUT(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]): EndpointBuilder<InitialEndpointDefinition<string[], 'PUT'>> {
return endpoint(pathOrStaticParts, ...params).method('PUT');
}
/**
* Create a POST endpoint definition.
*
* Use of the template literal allows to easily add dynamic path parameters to the endpoint definition, as shown in the example below.
*
* Use as a tagged template literal to add path parameters to the endpoint, and use methods of
* the [[EndpointBuilder]] class to customize the endpoint definition.
*
* This endpoint definition can be consumed by API servers and clients such as rest-ts-express and rest-ts-axios.
*
* Example:
*
* export const commentsAPI = defineAPI({
* // Add a comment to an article
* // For example: POST /article/123/comment
* addComment: POST `/article/${'id'}/comment`
* .body(CommentAttributes)
* .response(CommentSaveResponse)
* });
*/
export function POST(path: string | TemplateStringsArray): EndpointBuilder<EmptyInitialEndpointDefinition<'POST'>>;
export function POST<A extends string>(strings: TemplateStringsArray, a: A): EndpointBuilder<InitialEndpointDefinition<[A], 'POST'>>;
export function POST<A extends string, B extends string>(strings: TemplateStringsArray, a: A, b: B): EndpointBuilder<InitialEndpointDefinition<[A, B], 'POST'>>;
export function POST<A extends string, B extends string, C extends string>(strings: TemplateStringsArray, a: A, b: B, c: C): EndpointBuilder<InitialEndpointDefinition<[A, B, C], 'POST'>>;
export function POST<A extends string, B extends string, C extends string, D extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D], 'POST'>>;
export function POST<A extends string, B extends string, C extends string, D extends string, E extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E], 'POST'>>;
export function POST<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F], 'POST'>>;
export function POST<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G], 'POST'>>;
export function POST<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string, H extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G, H], 'POST'>>;
export function POST(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]): EndpointBuilder<InitialEndpointDefinition<string[], 'POST'>> {
return endpoint(pathOrStaticParts, ...params).method('POST');
}
/**
* Create a DELETE endpoint definition.
*
* Use of the template literal allows to easily add dynamic path parameters to the endpoint definition, as shown in the example below.
*
* Use as a tagged template literal to add path parameters to the endpoint, and use methods of
* the [[EndpointBuilder]] class to customize the endpoint definition.
*
* This endpoint definition can be consumed by API servers and clients such as rest-ts-express and rest-ts-axios.
*
* Example:
*
* export const commentsAPI = defineAPI({
* // Remove a comment
* // For example: DELETE /comments/123
* removeComment: DELETE `/comments/${'id'}`
* .response(CommentDeleteResponse)
* });
*/
export function DELETE(path: string | TemplateStringsArray): EndpointBuilder<EmptyInitialEndpointDefinition<'DELETE'>>;
export function DELETE<A extends string>(strings: TemplateStringsArray, a: A): EndpointBuilder<InitialEndpointDefinition<[A], 'DELETE'>>;
export function DELETE<A extends string, B extends string>(strings: TemplateStringsArray, a: A, b: B): EndpointBuilder<InitialEndpointDefinition<[A, B], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string>(strings: TemplateStringsArray, a: A, b: B, c: C): EndpointBuilder<InitialEndpointDefinition<[A, B, C], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string, D extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string, D extends string, E extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G], 'DELETE'>>;
export function DELETE<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string, H extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G, H], 'DELETE'>>;
export function DELETE(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]): EndpointBuilder<InitialEndpointDefinition<string[], 'DELETE'>> {
return endpoint(pathOrStaticParts, ...params).method('DELETE');
}
/**
* Create a PATCH endpoint definition.
*
* Use of the template literal allows to easily add dynamic path parameters to the endpoint definition, as shown in the example below.
*
* Use as a tagged template literal to add path parameters to the endpoint, and use methods of
* the [[EndpointBuilder]] class to customize the endpoint definition.
*
* This endpoint definition can be consumed by API servers and clients such as rest-ts-express and rest-ts-axios.
*
* Example:
*
* export const commentsAPI = defineAPI({
* // Edit a comment
* // For example: PATCH /article/123/comment/2
* editComment: PATCH `/article/${'id'}/comment/${'commentId'}`
* .body(CommentAttributes)
* .response(CommentSaveResponse)
* });
*/
export function PATCH(path: string | TemplateStringsArray): EndpointBuilder<EmptyInitialEndpointDefinition<'PATCH'>>;
export function PATCH<A extends string>(strings: TemplateStringsArray, a: A): EndpointBuilder<InitialEndpointDefinition<[A], 'PATCH'>>;
export function PATCH<A extends string, B extends string>(strings: TemplateStringsArray, a: A, b: B): EndpointBuilder<InitialEndpointDefinition<[A, B], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string>(strings: TemplateStringsArray, a: A, b: B, c: C): EndpointBuilder<InitialEndpointDefinition<[A, B, C], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string, D extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string, D extends string, E extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G], 'PATCH'>>;
export function PATCH<A extends string, B extends string, C extends string, D extends string, E extends string, F extends string, G extends string, H extends string>(strings: TemplateStringsArray, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H): EndpointBuilder<InitialEndpointDefinition<[A, B, C, D, E, F, G, H], 'PATCH'>>;
export function PATCH(pathOrStaticParts: TemplateStringsArray | string, ...params: string[]): EndpointBuilder<InitialEndpointDefinition<string[], 'PATCH'>> {
return endpoint(pathOrStaticParts, ...params).method('PATCH');
}
/**
* Create an API definition to share across producers and consumers of the API.
*
* The usual workflow of rest-ts-core goes like this:
*
* 1. Create an API definition:
*
* const myAwesomeAPI = defineAPI({
* someEndpoint: GET `/some/path`
* .response(SomeResponseDTO)
* });
*
* 2. Create a server for this API.
* rest-ts-express allows you to import the API definition you just created and
* turn it into an express router. See the documentation for that package for more details.
*
* 3. Create a consumer for this API.
* rest-ts-axios lets you create a typed instance of [axios](https://github.com/axios/axios) to
* perform requests to your API.
*
* 4. ... Profit!
*
*
* Notice: Unless you are authoring an adapter for Rest.ts, you should always treat the return type of this function
* as an opaque type. Use the utilities provided by this library to create the API definition within the brackets
* of `defineAPI({ ... })`, and export the resulting symbol to be consumed by your server and client(s).
* The type you get from `defineAPI` is very complex, and for a good reason: it encodes all of the type information
* of your API! It is pointless to inspect the raw type you get. Instead, we recommend that you feed it directly
* to a compatible binding library such as rest-ts-express and rest-ts-axios. These libraries are able to decode
* the complex type and make sense out of it.
*
* @param api
*/
export const defineAPI = <T extends ApiDefinition>(api: T) => api; | the_stack |
import CellPath from '../view/cell/CellPath';
import CodecRegistry from './CodecRegistry';
import { NODETYPE } from '../util/Constants';
import Cell from '../view/cell/Cell';
import MaxLog from '../gui/MaxLog';
import { getFunctionName } from '../util/StringUtils';
import { importNode, isNode } from '../util/domUtils';
import ObjectCodec from './ObjectCodec';
const createXmlDocument = () => {
return document.implementation.createDocument('', '', null);
};
/**
* XML codec for JavaScript object graphs. See {@link ObjectCodec} for a
* description of the general encoding/decoding scheme. This class uses the
* codecs registered in {@link CodecRegistry} for encoding/decoding each object.
*
* ### References
*
* In order to resolve references, especially forward references, the Codec
* constructor must be given the document that contains the referenced
* elements.
*
* ### Examples
*
* The following code is used to encode a graph model.
*
* ```javascript
* var encoder = new Codec();
* var result = encoder.encode(graph.getDataModel());
* var xml = mxUtils.getXml(result);
* ```
*
* #### Example
*
* Using the code below, an XML document is decoded into an existing model. The
* document may be obtained using one of the functions in mxUtils for loading
* an XML file, eg. {@link mxUtils.get}, or using {@link mxUtils.parseXml} for parsing an
* XML string.
*
* ```javascript
* var doc = mxUtils.parseXml(xmlString);
* var codec = new Codec(doc);
* codec.decode(doc.documentElement, graph.getDataModel());
* ```
*
* #### Example
*
* This example demonstrates parsing a list of isolated cells into an existing
* graph model. Note that the cells do not have a parent reference so they can
* be added anywhere in the cell hierarchy after parsing.
*
* ```javascript
* var xml = '<root><mxCell id="2" value="Hello," vertex="1"><mxGeometry x="20" y="20" width="80" height="30" as="geometry"/></mxCell><mxCell id="3" value="World!" vertex="1"><mxGeometry x="200" y="150" width="80" height="30" as="geometry"/></mxCell><mxCell id="4" value="" edge="1" source="2" target="3"><mxGeometry relative="1" as="geometry"/></mxCell></root>';
* var doc = mxUtils.parseXml(xml);
* var codec = new Codec(doc);
* var elt = doc.documentElement.firstChild;
* var cells = [];
*
* while (elt != null)
* {
* cells.push(codec.decode(elt));
* elt = elt.nextSibling;
* }
*
* graph.addCells(cells);
* ```
*
* #### Example
*
* Using the following code, the selection cells of a graph are encoded and the
* output is displayed in a dialog box.
*
* ```javascript
* var enc = new Codec();
* var cells = graph.getSelectionCells();
* mxUtils.alert(mxUtils.getPrettyXml(enc.encode(cells)));
* ```
*
* Newlines in the XML can be converted to <br>, in which case a '<br>' argument
* must be passed to {@link mxUtils.getXml} as the second argument.
*
* ### Debugging
*
* For debugging I/O you can use the following code to get the sequence of
* encoded objects:
*
* ```javascript
* var oldEncode = encode;
* encode(obj)
* {
* MaxLog.show();
* MaxLog.debug('Codec.encode: obj='+mxUtils.getFunctionName(obj.constructor));
*
* return oldEncode.apply(this, arguments);
* };
* ```
*
* Note that the I/O system adds object codecs for new object automatically. For
* decoding those objects, the constructor should be written as follows:
*
* ```javascript
* var MyObj(name)
* {
* // ...
* };
* ```
*
* @class Codec
*/
class Codec {
constructor(document: XMLDocument=createXmlDocument()) {
this.document = document;
this.objects = {};
}
/**
* The owner document of the codec.
*/
document: XMLDocument;
/**
* Maps from IDs to objects.
*/
objects: { [key: string]: Element };
/**
* Lookup table for resolving IDs to elements.
*/
elements: any = null; // { [key: string]: Element } | null
/**
* Specifies if default values should be encoded. Default is false.
*/
encodeDefaults: boolean = false;
/**
* Assoiates the given object with the given ID and returns the given object.
*
* @param id ID for the object to be associated with.
* @param obj Object to be associated with the ID.
*/
putObject(id: string, obj: any): any {
this.objects[id] = obj;
return obj;
}
/**
* Returns the decoded object for the element with the specified ID in
* {@link document}. If the object is not known then {@link lookup} is used to find an
* object. If no object is found, then the element with the respective ID
* from the document is parsed using {@link decode}.
*/
getObject(id: string): any {
let obj = null;
if (id != null) {
obj = this.objects[id];
if (obj == null) {
obj = this.lookup(id);
if (obj == null) {
const node = this.getElementById(id);
if (node != null) {
obj = this.decode(node);
}
}
}
}
return obj;
}
/**
* Hook for subclassers to implement a custom lookup mechanism for cell IDs.
* This implementation always returns null.
*
* Example:
*
* ```javascript
* var codec = new Codec();
* codec.lookup(id)
* {
* return model.getCell(id);
* };
* ```
*
* @param id ID of the object to be returned.
*/
lookup(id: string): any {
return null;
}
/**
* Returns the element with the given ID from {@link document}.
*
* @param id String that contains the ID.
*/
getElementById(id: string): Element {
this.updateElements();
return this.elements[id];
}
/**
* Returns the element with the given ID from {@link document}.
*
* @param id String that contains the ID.
*/
updateElements(): void {
if (this.elements == null) {
this.elements = {};
if (this.document.documentElement != null) {
this.addElement(this.document.documentElement);
}
}
}
/**
* Adds the given element to {@link elements} if it has an ID.
*/
addElement(node: Element): void {
if (node.nodeType === NODETYPE.ELEMENT) {
const id = node.getAttribute('id');
if (id != null) {
if (this.elements[id] == null) {
this.elements[id] = node;
} else if (this.elements[id] !== node) {
throw new Error(`${id}: Duplicate ID`);
}
}
}
let nodeChild = node.firstChild;
while (nodeChild != null) {
this.addElement(<Element>nodeChild);
nodeChild = nodeChild.nextSibling;
}
}
/**
* Returns the ID of the specified object. This implementation
* calls {@link reference} first and if that returns null handles
* the object as an {@link Cell} by returning their IDs using
* {@link Cell.getId}. If no ID exists for the given cell, then
* an on-the-fly ID is generated using {@link CellPath.create}.
*
* @param obj Object to return the ID for.
*/
getId(obj: any): string {
let id = null;
if (obj != null) {
id = this.reference(obj);
if (id == null && obj instanceof Cell) {
id = obj.getId();
if (id == null) {
// Uses an on-the-fly Id
id = CellPath.create(obj);
if (id.length === 0) {
id = 'root';
}
}
}
}
return id;
}
/**
* Hook for subclassers to implement a custom method
* for retrieving IDs from objects. This implementation
* always returns null.
*
* Example:
*
* ```javascript
* var codec = new Codec();
* codec.reference(obj)
* {
* return obj.getCustomId();
* };
* ```
*
* @param obj Object whose ID should be returned.
*/
reference(obj: any): any {
return null;
}
/**
* Encodes the specified object and returns the resulting
* XML node.
*
* @param obj Object to be encoded.
*/
encode(obj: any): Element | null {
let node = null;
if (obj != null && obj.constructor != null) {
const enc = CodecRegistry.getCodec(obj.constructor);
if (enc != null) {
node = enc.encode(this, obj);
} else if (isNode(obj)) {
node = importNode(this.document, obj, true);
} else {
MaxLog.warn(
`Codec.encode: No codec for ${getFunctionName(obj.constructor)}`
);
}
}
return node;
}
/**
* Decodes the given XML node. The optional "into"
* argument specifies an existing object to be
* used. If no object is given, then a new instance
* is created using the constructor from the codec.
*
* The function returns the passed in object or
* the new instance if no object was given.
*
* @param node XML node to be decoded.
* @param into Optional object to be decodec into.
*/
decode(node: Element, into?: any): any {
this.updateElements();
let obj = null;
if (node != null && node.nodeType === NODETYPE.ELEMENT) {
let ctor: any = null;
try {
// @ts-ignore
ctor = window[node.nodeName];
} catch (err) {
// ignore
}
const dec = CodecRegistry.getCodec(ctor);
if (dec != null) {
obj = dec.decode(this, node, into);
} else {
obj = <Element>node.cloneNode(true);
obj.removeAttribute('as');
}
}
return obj;
}
/**
* Encoding of cell hierarchies is built-into the core, but
* is a higher-level function that needs to be explicitely
* used by the respective object encoders (eg. {@link ModelCodec},
* {@link ChildChangeCodec} and {@link RootChangeCodec}). This
* implementation writes the given cell and its children as a
* (flat) sequence into the given node. The children are not
* encoded if the optional includeChildren is false. The
* function is in charge of adding the result into the
* given node and has no return value.
*
* @param cell {@link mxCell} to be encoded.
* @param node Parent XML node to add the encoded cell into.
* @param includeChildren Optional boolean indicating if the
* function should include all descendents. Default is true.
*/
encodeCell(cell: Cell, node: Node, includeChildren?: boolean): void {
const appendMe = this.encode(cell);
if (appendMe) {
node.appendChild(appendMe);
}
if (includeChildren == null || includeChildren) {
const childCount = cell.getChildCount();
for (let i = 0; i < childCount; i += 1) {
this.encodeCell(cell.getChildAt(i), node);
}
}
}
/**
* Returns true if the given codec is a cell codec. This uses
* {@link CellCodec.isCellCodec} to check if the codec is of the
* given type.
*/
isCellCodec(codec: any): boolean {
if (codec != null && 'isCellCodec' in codec) {
return codec.isCellCodec();
}
return false;
}
/**
* Decodes cells that have been encoded using inversion, ie.
* where the user object is the enclosing node in the XML,
* and restores the group and graph structure in the cells.
* Returns a new {@link Cell} instance that represents the
* given node.
*
* @param node XML node that contains the cell data.
* @param restoreStructures Optional boolean indicating whether
* the graph structure should be restored by calling insert
* and insertEdge on the parent and terminals, respectively.
* Default is true.
*/
decodeCell(node: Element, restoreStructures?: boolean): Cell {
restoreStructures = restoreStructures != null ? restoreStructures : true;
let cell = null;
if (node != null && node.nodeType === NODETYPE.ELEMENT) {
// Tries to find a codec for the given node name. If that does
// not return a codec then the node is the user object (an XML node
// that contains the mxCell, aka inversion).
let decoder = CodecRegistry.getCodec(node.nodeName);
// Tries to find the codec for the cell inside the user object.
// This assumes all node names inside the user object are either
// not registered or they correspond to a class for cells.
if (!this.isCellCodec(decoder)) {
let child = node.firstChild;
while (child != null && !this.isCellCodec(decoder)) {
decoder = CodecRegistry.getCodec(child.nodeName);
child = child.nextSibling;
}
}
if (!this.isCellCodec(decoder)) {
decoder = CodecRegistry.getCodec(Cell);
}
cell = (<ObjectCodec>decoder).decode(this, node);
if (restoreStructures) {
this.insertIntoGraph(cell);
}
}
return cell;
}
/**
* Inserts the given cell into its parent and terminal cells.
*/
insertIntoGraph(cell: Cell): void {
const { parent } = cell;
const source = cell.getTerminal(true);
const target = cell.getTerminal(false);
// Fixes possible inconsistencies during insert into graph
cell.setTerminal(null, false);
cell.setTerminal(null, true);
cell.parent = null;
if (parent != null) {
if (parent === cell) {
throw new Error(`${parent.id}: Self Reference`);
} else {
parent.insert(cell);
}
}
if (source != null) {
source.insertEdge(cell, true);
}
if (target != null) {
target.insertEdge(cell, false);
}
}
/**
* Sets the attribute on the specified node to value. This is a
* helper method that makes sure the attribute and value arguments
* are not null.
*
* @param node XML node to set the attribute for.
* @param attributes Attributename to be set.
* @param value New value of the attribute.
*/
setAttribute(node: Element, attribute: string, value: any): void {
if (attribute != null && value != null) {
node.setAttribute(attribute, value);
}
}
}
export default Codec; | the_stack |
declare module 'medooze-media-server' {
import SemanticSDP = require('semantic-sdp');
/**
* "min","max" and "avg" packet waiting times in rtp buffer before delivering
* them
*/
export interface WaitTimeStats {
min: number;
max: number;
avg: number;
}
export type MediaCapabilities = {
audio?: SemanticSDP.SupportedMedia;
video?: SemanticSDP.SupportedMedia;
};
export interface CreateStreamerSessionOptions {
/** Local parameters */
local?: {
/** receiving port */
port: number;
};
/** Remote parameters */
remote?: {
/** sending ip address */
ip: string;
/** sending port */
port: number;
};
}
export interface CreateOutgoingStreamOptions {
id?: string;
audio?: boolean|CreateStreamTrackOptions|CreateStreamTrackOptions[];
video?: boolean|CreateStreamTrackOptions|CreateStreamTrackOptions[];
}
export interface PlayerPlayOptions {
/** Repeat playback when file is ended */
repeat: boolean;
}
export interface EmulatedTransportPlayOptions {
/** Set start time */
start: number;
}
export interface Encoding {
id: string;
source: any;
depacketizer: any;
}
export interface LayerStats {
/** Spatial layer id */
spatialLayerId: number;
/** Temporatl layer id */
temporalLayerId: number;
/** total rtp received bytes for this layer */
totalBytes: number;
/** number of rtp packets received for this layer */
numPackets: number;
/** average bitrate received during last second for this layer */
bitrate: number;
}
export interface IncomingSourceStats {
/** total lost packkets */
lostPackets: number;
/** droppted packets by media server */
dropPackets: number;
/** number of rtp packets received */
numPackets: number;
/** number of rtcp packsets received */
numRTCPPackets: number;
/** total rtp received bytes */
totalBytes: number;
/** total rtp received bytes */
totalRTCPBytes: number;
/** total PLIs sent */
totalPLIs: number;
/** total NACk packets setn */
totalNACKs: number;
/** average bitrate received during last second in bps */
bitrate: number;
/** Information about each spatial/temporal layer (if present) */
layers: LayerStats[];
}
export interface OutgoingSourceStats {
/** number of rtp packets sent */
numPackets: number;
/** number of rtcp packsets sent */
numRTCPPackets: number;
/** total rtp sent bytes */
totalBytes: number;
/** total rtp sent bytes */
totalRTCPBytes: number;
/** average bitrate sent during last second in bps */
bitrate: number;
}
export interface OutgoingStreamTrackStats {
media: OutgoingSourceStats;
rtx: OutgoingSourceStats;
fec: OutgoingSourceStats;
timestamp: number;
}
export interface OutgoingStreamStatsReport {
[trackID: string]: OutgoingStreamTrackStats;
}
export interface IncomingStreamTrackStats {
/** Stats for the media stream */
media: IncomingSourceStats;
/** Stats for the rtx retransmission stream */
rtx: IncomingSourceStats;
/** Stats for the fec stream */
fec: IncomingSourceStats;
/** Round Trip Time in ms */
rtt: number;
/**
* "min","max" and "avg" packet waiting times in rtp buffer before
* delivering them
*/
waitTime: WaitTimeStats;
/** Bitrate for media stream only in bps */
bitrate: number;
/** Accumulated bitrate for rtx, media and fec streams in bps */
total: number;
/**
* Estimated avialable bitrate for receving (only avaailable if not using
* tranport wide cc)
*/
remb: number;
/**
* When this stats was generated, in order to save workload, stats are
* cached for 200ms
*/
timestamp: number;
/**
* Simulcast layer index based on bitrate received (-1 if it is inactive).
*/
simulcastIdx: number;
}
export interface IncomingStreamTrackStatsReport {
[layerID: string]: IncomingStreamTrackStats;
}
export interface IncomingStreamStatsReport {
[trackID: string]: IncomingStreamTrackStatsReport;
}
export interface CreateRecorderOptions {
/** Periodically refresh an intra on all video tracks (in ms) */
refresh?: number;
/** Wait until first video iframe is received to start recording media */
waitForIntra?: boolean;
}
export interface SetTargetBitrateOptions {
/**
* Traversal algorithm "default", "spatial-temporal",
* "zig-zag-spatial-temporal", "temporal-spatial",
* "zig-zag-temporal-spatial" [Default: "default"]
*/
traversal?: 'default'|'spatial-temporal'|'zig-zag-temporal-spatial';
/**
* If there is not a layer with a bitrate lower thatn target, stop sending
* media [Default: false]
*/
strict?: boolean;
}
export interface SetTransportPropertiesOptions {
/** Audio media info */
audio?: SemanticSDP.MediaInfo;
/** Video media info */
video?: SemanticSDP.MediaInfo;
}
export interface CreateTransportOptions {
/**
* Disable ICE/STUN keep alives, required for server to server transports
*/
disableSTUNKeepAlive: boolean;
/** Colon delimited list of SRTP protection profile names */
srtpProtectionProfiles: boolean;
}
export interface TransportDumpOptions {
/** Dump incoming RTP data */
incoming: boolean;
/** Dump outgoing RTP data */
outbound: boolean;
/** Dump rtcp RTP data */
rtcp: boolean;
}
export interface SSRCs {
/** ssrc for the media track */
media?: number;
/** ssrc for the rtx track */
rtx?: number;
/** ssrc for the fec track */
fec?: number;
}
export interface CreateStreamTrackOptions {
/** Stream track id */
id?: string;
/** Override the generated ssrcs for this track */
ssrcs?: SSRCs;
}
export interface Layer {
encodingId?: number;
simulcastIdx?: number;
spatialLayerId?: number;
temporalLayerId?: number;
bitrate?: number;
}
export interface Encoding {
id: string;
simulcastIdx: number;
bitrate: number;
layers: Layer[];
}
export interface ActiveLayers {
active: Encoding[];
inactive: Layer[];
layers: Layer[];
}
export interface OutgoingStream {
/**
* Get statistics for all tracks in the stream
*
* See OutgoingStreamTrack.getStats for information about the stats returned
* by each track.
*
* @returns {Map<String>,Object} Map with stats by trackId
*/
getStats(): OutgoingStreamStatsReport;
/**
* Check if the stream is muted or not
* @returns {boolean} muted
*/
isMuted(): boolean;
/*
* Mute/Unmute this stream and all the tracks in it
* @param {boolean} muting - if we want to mute or unmute
*/
mute(muting: boolean): void;
/**
* Listen media from the incoming stream and send it to the remote peer of
* the associated transport.
* @param {IncomingStream} incomingStream - The incoming stream to listen
* media for
* @returns {Array<Transponder>} Track transponders array
*/
attachTo(incomingStream: IncomingStream): Transponder[];
/**
* Stop listening for media
*/
detach(): void;
/**
* Get the stream info object for signaling the ssrcs and stream info on the
* SDP to the remote peer
* @returns {StreamInfo} The stream info object
*/
getStreamInfo(): SemanticSDP.StreamInfo;
/**
* The media stream id as announced on the SDP
* @returns {String}
*/
getId(): string;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
on(event: 'track',
listener: (track: OutgoingStreamTrack) => any): OutgoingStream;
on(event: 'stopped',
listener:
(stream: OutgoingStream, stats: OutgoingStreamStatsReport) => any):
OutgoingStream;
on(event: 'muted', listener: (muted: boolean) => any): OutgoingStream;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'track', listener: (track: OutgoingStreamTrack) => any):
OutgoingStream;
once(
event: 'stopped',
listener:
(stream: OutgoingStream, stats: OutgoingStreamStatsReport) => any):
OutgoingStream;
once(event: 'muted', listener: (muted: boolean) => any): OutgoingStream;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {OutgoingStream}
*/
off(event: 'track',
listener: (track: OutgoingStreamTrack) => any): OutgoingStream;
off(event: 'stopped',
listener:
(stream: OutgoingStream, stats: OutgoingStreamStatsReport) => any):
OutgoingStream;
off(event: 'muted', listener: (muted: boolean) => any): OutgoingStream;
/**
* Get all the tracks
* @param {String} type - The media type (Optional)
* @returns {Array<OutgoingStreamTrack>} - Array of tracks
*/
getTracks(type?: string): OutgoingStreamTrack[];
/**
* Get track by id
* @param {String} trackId - The track id
* @returns {IncomingStreamTrack} - requested track or null
*/
getTrack(trackId: string): IncomingStreamTrack;
/**
* Get an array of the media stream audio tracks
* @returns {Array|OutgoingStreamTracks} - Array of tracks
*/
getAudioTracks(): OutgoingStreamTrack[];
/**
* Get an array of the media stream video tracks
* @returns {Array|OutgoingStreamTrack} - Array of tracks
*/
getVideoTracks(): OutgoingStreamTrack[];
/*
* Adds an incoming stream track created using the
* Transpocnder.createOutgoingStreamTrack to this stream
*
* @param {OuggoingStreamTrack} track
*/
addTrack(track: OutgoingStreamTrack): void;
/**
* Create new track from a TrackInfo object and add it to this stream
* @param {Object|TrackInfo|String} params Params plain object, StreamInfo
* object or media type
* @param {String?} params.id - Stream track id
* @param {String?} params.media - Media type ("audio" or "video")
* @param {Object?} params.ssrcs - Override the generated ssrcs for this
* track
* @param {Number?} params.ssrcs.media - ssrc for the track
* @param {Number?} params.ssrcs.rtx - ssrc for the rtx video track
* @param {Number?} params.ssrcs.fec - ssrc for the fec video track
* @returns {OutgoingStream} The new outgoing stream
* @param {TrackInfo} trackInfo Track info object
* @returns {OuggoingStreamTrack}
*/
createTrack(params: SemanticSDP.TrackInfo|SemanticSDP.TrackInfoPlain|
string): OutgoingStreamTrack;
stop(): void;
}
export interface Transport {
/**
* Dump incoming and outgoint rtp and rtcp packets into a pcap file
* @param {String} filename - Filename of the pcap file
* @param {Object} options - Dump parameters (optional)
* @param {Boolean} options.incomoning - Dump incomoning RTP data
* @param {Boolean} options.outbound - Dump outgoing RTP data
* @param {Boolean} options.rtcp - Dump rtcp RTP data
*/
dump(filename: string, options?: TransportDumpOptions): void;
/**
* Enable bitrate probing.
* This will send padding only RTX packets to allow bandwidth estimation
* algortithm to probe bitrate beyonf current sent values. The ammoung of
* probing bitrate would be limited by the sender bitrate estimation and the
* limit set on the setMaxProbing Bitrate. Note that this will only work on
* browsers that supports RTX and transport wide cc.
* @param {Boolen} probe
*/
setBandwidthProbing(probe: boolean): void;
/**
* Set the maximum bitrate to be used if probing is enabled.
* @param {Number} bitrate
*/
setMaxProbingBitrate(bitrate: number): void;
/**
* Set local RTP properties
* @param {Object|SDPInfo} rtp - Object param containing media information
* for audio and video
* @param {MediaInfo} rtp.audio - Audio media info
* @param {MediaInfo} rtp.video - Video media info
*/
setLocalProperties(rtp: SemanticSDP.SDPInfo|
SetTransportPropertiesOptions): void;
/**
* Set remote RTP properties
* @param {Object|SDPInfo} rtp - Object param containing media information
* for audio and video
* @param {MediaInfo} rtp.audio - Audio media info
* @param {MediaInfo} rtp.video - Video media info
*/
setRemoteProperties(rtp: SemanticSDP.SDPInfo|
SetTransportPropertiesOptions): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listeener - Event listener
* @returns {Transport}
*/
on(event: 'targetbitrate',
listener: (bitrate: number, transport: Transport) => any): Transport;
on(event: 'outgoingtrack',
listener:
(track: OutgoingStreamTrack, stream: OutgoingStream|null) => any):
Transport;
on(event: 'incomingtrack',
listener:
(track: IncomingStreamTrack, stream: IncomingStream|null) => any):
Transport;
on(event: 'stopped', listener: (transport: Transport) => any): Transport;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(
event: 'targetbitrate',
listener: (bitrate: number, transport: Transport) => any): Transport;
once(
event: 'outgoingtrack',
listener:
(track: OutgoingStreamTrack, stream: OutgoingStream|null) => any):
Transport;
once(
event: 'incomingtrack',
listener:
(track: IncomingStreamTrack, stream: IncomingStream|null) => any):
Transport;
once(event: 'stopped', listener: (transport: Transport) => any): Transport;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transport}
*/
off(event: 'targetbitrate',
listener: (bitrate: number, transport: Transport) => any): Transport;
off(event: 'outgoingtrack',
listener:
(track: OutgoingStreamTrack, stream: OutgoingStream|null) => any):
Transport;
off(event: 'incomingtrack',
listener:
(track: IncomingStreamTrack, stream: IncomingStream|null) => any):
Transport;
off(event: 'stopped', listener: (transport: Transport) => any): Transport;
/**
* Get transport local DTLS info
* @returns {DTLSInfo} DTLS info object
*/
getLocalDTLSInfo(): SemanticSDP.DTLSInfo;
/**
* Get transport local ICE info
* @returns {ICEInfo} ICE info object
*/
getLocalICEInfo(): SemanticSDP.ICEInfo;
/**
* Get local ICE candidates for this transport
* @returns {Array.CandidateInfo}
*/
getLocalCandidates(): SemanticSDP.CandidateInfo[];
/**
* Get remote ICE candidates for this transport
* @returns {Array.CandidateInfo}
*/
getRemoteCandidates(): SemanticSDP.CandidateInfo[];
/**
* Register a remote candidate info. Only needed for ice-lite to ice-lite
* endpoints
* @param {CandidateInfo} candidate
* @returns {boolean} Wheter the remote ice candidate was alrady presnet or
* not
*/
addRemoteCandidate(candidate: SemanticSDP.CandidateInfo): boolean;
/**
* Register an array remote candidate info. Only needed for ice-lite to
* ice-lite endpoints
* @param {Array.CandidateInfo} candidates
*/
addRemoteCandidates(candidates: SemanticSDP.CandidateInfo[]): void;
/**
* Create new outgoing stream in this transport
* @param {Object|StreamInfo|String} params Params plain object, StreamInfo
* object or stream id
* @param {Array<Object>|Object|boolean} params.audio - Add audio track to
* the new stream
* @param {Object?} params.id - Stream id, an UUID will be generated if not
* provided
* @param {Object?} params.audio.id - Stream track id (default: "audio")
* @param {Number?} params.audio.ssrcs - Override the generated ssrcs for
* this track
* @param {Number?} params.audio.ssrcs.media - ssrc for the audio track
* @param {Array<Object>|Object|boolean} params.video - Add video track to
* the new stream
* @param {Object?} params.video.id - Stream track id (default: "video")
* @param {Object?} params.video.ssrcs - Override the generated ssrcs for
* this track
* @param {Number?} params.video.ssrcs.media - ssrc for the video
* track
* @param {Number?} params.video.ssrcs.rtx - ssrc for the rtx video track
* @param {Number?} params.video.ssrcs.fec - ssrc for the fec video track
* @returns {OutgoingStream} The new outgoing stream
*/
createOutgoingStream(params: SemanticSDP.StreamInfo|
CreateOutgoingStreamOptions|string): OutgoingStream;
/**
* Create new outgoing stream in this transport
* @param {String} media - Track media type "audio" or "video"
* @param {Object?} params - Track parameters
* @param {Object?} params.id - Stream track id
* @param {Number?} params.ssrcs - Override the generated ssrcs for this
* track
* @param {Number?} params.ssrcs.media - ssrc for the media track
* @param {Number?} params.ssrcs.rtx - ssrc for the rtx track
* @param {Number?} params.ssrcs.fec - ssrc for the fec track
* @returns {OutgoingStreamTrack} The new outgoing stream track
*/
createOutgoingStreamTrack(
media: SemanticSDP.MediaType,
params?: CreateStreamTrackOptions): OutgoingStreamTrack;
/**
* Create an incoming stream object from the media stream info objet
* @param {StreamInfo|Object} info Contains the ids and ssrcs of the stream
* to be created
* @returns {IncomingStream} The newly created incoming stream object
*/
createIncomingStream(info: SemanticSDP.StreamInfo|string): IncomingStream;
/**
* Get all the incoming streams in the transport
* @returns {Array<IncomingStreams>}
*/
getIncomingStreams(): IncomingStream[];
/**
* Get incoming stream
* @param {String} streamId the stream ID
* @returns {IncomingStream}
*/
getIncomingStream(streamId: string): IncomingStream;
/**
* Get all the outgoing streams in the transport
* @returns {Array<OutgoingStreams>}
*/
getOutgoingStreams(): OutgoingStream[];
/**
* Get incoming stream
* @param {String} streamId the stream ID
* @returns {IncomingStream}
*/
getOutgoingStream(streamId: string): OutgoingStream;
/**
* Create new incoming stream in this transport. TODO: Simulcast is still
* not supported
* @param {String} media - Track media type "audio" or "video"
* @param {Object?} params - Track parameters
* @param {Object?} params.id - Stream track id
* @param {Number?} params.ssrcs - Override the generated ssrcs for this
* track
* @param {Number?} params.ssrcs.media - ssrc for the media track
* @param {Number?} params.ssrcs.rtx - ssrc for the rtx track
* @param {Number?} params.ssrcs.fec - ssrc for the fec track
* @returns {IncomingStreamTrack} The new incoming stream track
*/
createIncomingStreamTrack(
media: SemanticSDP.MediaType,
params?: CreateStreamTrackOptions): IncomingStreamTrack;
/**
* Create new outgoing stream and attach to the incoming stream
* @param {IncomingStream} incomingStream the incoming stream to be
* published in this transport
* @returns {OutgoingStream} The new outgoing stream
*/
publish(incomingStream: IncomingStream): OutgoingStream;
/**
* Stop transport and all the associated incoming and outgoing streams
*/
stop(): void;
}
export interface Endpoint {
/**
* Set cpu affinity for udp send/recv thread.
* @param {Number} cpu - CPU core or -1 to reset affinity.
* @returns {boolean}
*/
setAffinity(cpu: number): void;
/**
* Create a new transport object and register it with the remote ICE
* username and password
* @param {Object|SDPInfo} remoteInfo - Remote ICE and DTLS properties
* @param {Object|ICEInfo} remote.ice - Remote ICE info, containing the
* username and password.
* @param {Object|DTLSInfo} remote.dtls - Remote DTLS info
* @param {Array.CandidateInfo|Array.Object} remote.candidates - Remote ICE
* candidate info
* @param {Object} localInfo - Local ICE and DTLS properties
* (optional)
* @param {ICEInfo} local.ice - Local ICE info, containing the username
* and password. Local ICE candidates list is not really used at all.
* @param {DTLSInfo} local.dtls - Local DTLS info
* @param {Array.CandidateInfo} local.candidates - Local candidate info
* @param {Object} options - Dictionary with transport properties
* @param {boolean} options.disableSTUNKeepAlive - Disable ICE/STUN keep
* alives, required for server to server transports
* @param {String} options.srtpProtectionProfiles - Colon delimited list of
* SRTP protection profile names
* @returns {Transport} New transport object
*/
createTransport(
remoteInfo: SemanticSDP.SDPInfo|SemanticSDP.SDPInfoPlain,
localInfo?: SemanticSDP.SDPInfo|SemanticSDP.SDPInfoPlain,
options?: CreateTransportOptions): Transport;
/**
* Get local ICE candidates for this endpoint. It will be shared by all the
* transport associated to this endpoint.
* @returns {Array.CandidateInfo}
*/
getLocalCandidates(): SemanticSDP.CandidateInfo[];
/**
* Get local DTLS fingerprint for this endpoint. It will be shared by all
* the transport associated to this endpoint.
* @returns {String}
*/
getDTLSFingerprint(): string;
/**
* Helper that creates an offer from capabilities
* It generates a random ICE username and password and gets endpoint
* fingerprint
* @param {Object} capabilities - Media capabilities as required by
* SDPInfo.create
* @returns {SDPInfo} - SDP offer
*/
createOffer(capabilities: MediaCapabilities): SemanticSDP.SDPInfo;
/**
* Create new peer connection server to manage remote peer connection
* clients
* @param {TransactionManager} tm
* @param {Object} capabilities - Same as SDPInfo.answer capabilites
* @returns {PeerConnectionServer}
*/
createPeerConnectionServer(tm: any, capabilities: MediaCapabilities):
PeerConnectionServer;
/**
* Mirror incoming stream from another endpoint. Used to avoid inter-thread
* synchronization when attaching multiple output streams. The endpoint will
* cache the cucrrent mirrored streams and return an already existing object
* if calling this method twice with same stream.
* @param {IncomingStream} incomingStream - stream to mirror
* @returns {IncomingStream} mirrored stream.
*/
mirrorIncomingStream(incomingStream: IncomingStream): IncomingStream;
/**
* Mirror incoming stream track from another endpoint. Used to avoid
* inter-thread synchronization when attaching multiple output tracks. The
* endpoint will cache the cucrrent mirrored tracks and return an already
* existing object if calling this method twice with same track.
* @param {IncomingStreamTrack} incomingStreamTrack - track to mirror
* @returns {IncomingStreamTrackMirrored} mirrored track.
*/
mirrorIncomingStreamTrack(incomingStreamTrack: IncomingStreamTrack):
IncomingStreamTrack;
/**
* Create new SDP manager, this object will manage the SDP O/A for you and
* produce a suitable trasnport.
* @param {String} sdpSemantics - Type of sdp plan "unified-plan" or
* "plan-b"
* @param {Object} capabilities - Capabilities objects
* @returns {SDPManager}
*/
createSDPManager(
sdpSemantics: 'unified-plan'|'plan-b',
capabilities: MediaCapabilities): SDPManager;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listeener - Event listener
* @returns {Endpoint}
*/
on(event: 'stopped', listener: (endpoint: Endpoint) => any): Endpoint;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Endpoint}
*/
once(event: 'stopped', listener: (endpoint: Endpoint) => any): Endpoint;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Endpoint}
*/
off(event: 'stopped', listener: (endpoint: Endpoint) => any): Endpoint;
/**
* Stop the endpoint UDP server and terminate any associated transport
*/
stop(): void;
}
export interface Transponder {
/**
* Set incoming track
* @param {IncomingStreamTrack} track
*/
setIncomingTrack(track: IncomingStreamTrack): void;
/**
* Get attached track
* @returns {IncomingStreamTrack} track
*/
getIncomingTrack(): IncomingStreamTrack;
/**
* Get available encodings and layers
* @returns {Object}
*/
getAvailableLayers(): ActiveLayers|null;
/**
* Check if the track is muted or not
* @returns {boolean} muted
*/
isMuted(): boolean;
/*
* Mute/Unmute track
* This operation will not change the muted state of the stream this track
* belongs too.
* @param {boolean} muting - if we want to mute or unmute
*/
mute(muting: boolean): void;
/*
* Select encoding and temporal and spatial layers based on the desired
* bitrate. This operation will unmute the transponder if it was mutted and
* it is possible to select an encoding and layer based on the target
* bitrate and options.
*
* @param {Number} bitrate
* @param {Object} options - Options for configuring algorithm to select
* best encoding/layers [Optional]
* @param {Object} options.traversal - Traversal algorithm "default",
* "spatial-temporal", "zig-zag-spatial-temporal", "temporal-spatial",
* "zig-zag-temporal-spatial" [Default: "default"]
* @param {Object} options.strict - If there is not a layer with a
* bitrate lower thatn target, stop sending media [Default: false]
* @returns {Number} Current bitrate of the selected encoding and layers
*/
setTargetBitrate(target: number, options?: SetTargetBitrateOptions): number;
/*
* Select the simulcast encoding layer
* @param {String} encoding Id - rid value of the simulcast encoding of the
* track
*/
selectEncoding(encodingId: string): void;
/**
* Return the encoding that is being forwarded
* @returns {String} encodingId
*/
getSelectedEncoding(): string;
/**
* Return the spatial layer id that is being forwarded
* @returns {Number} spatial layer id
*/
getSelectedSpatialLayerId(): number;
/**
* Return the temporal layer id that is being forwarded
* @returns {Number} temporal layer id
*/
getSelectedTemporalLayerId(): number;
/**
* Select SVC temporatl and spatial layers. Only available for VP9 media.
* @param {Number} spatialLayerId The spatial layer id to send to the
* outgoing stream
* @param {Number} temporalLayerId The temporaral layer id to send to the
* outgoing stream
*/
selectLayer(spatialLayerId: number, temporalLayerId: number): void;
/**
* Set maximum statial and temporal layers to be forwrarded. Base layer is
* always enabled.
* @param {Number} maxSpatialLayerId - Max spatial layer id
* @param {Number} maxTemporalLayerId - Max temporal layer id
*/
setMaximumLayers(maxSpatialLayerId: number, maxTemporalLayerId: number):
void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transponder}
*/
on(event: 'stopped',
listener: (transponder: Transponder) => any): Transponder;
on(event: 'muted', listener: (muted: boolean) => any): Transponder;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transponder}
*/
once(event: 'stopped', listener: (transponder: Transponder) => any):
Transponder;
once(event: 'muted', listener: (muted: boolean) => any): Transponder;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transponder}
*/
off(event: 'stopped',
listener: (transponder: Transponder) => any): Transponder;
off(event: 'muted', listener: (muted: boolean) => any): Transponder;
/**
* Stop this transponder, will dettach the OutgoingStreamTrack
*/
stop(): void;
}
export interface MediaServer {
/**
* Close async handlers so nodejs can exit nicely
* Only call it once!
* @memberof MediaServer
*/
terminate(): void;
/**
* Enable or disable log level traces
* @memberof MediaServer
* @param {Boolean} flag
*/
enableLog(flag: boolean): void;
/**
* Enable or disable debug level traces
* @memberof MediaServer
* @param {Boolean} flag
*/
enableDebug(flag: boolean): void;
/**
* Set UDP port range for encpoints
* @memberof MediaServer
* @param {Integer} minPort - Min UDP port
* @param {Integer} maxPort - Max UDP port
* @returns {Endpoint} The new created endpoing
*/
setPortRange(minPort: number, maxPort: number): boolean;
/**
* Enable or disable ultra debug level traces
* @memberof MediaServer
* @param {Boolean} flag
*/
enableUltraDebug(flag: boolean): void;
/**
* Create a new endpoint object
* @memberof MediaServer
* @param {String | String[]} ip - External IP address(es) of server, to be
* used when announcing the local ICE candidate
* @returns {Endpoint} The new created endpoing
*/
createEndpoint(ip: string | string[]): Endpoint;
/**
* Create a new MP4 recorder
* @memberof MediaServer
* @param {String} filename - Path and filename of the recorded mp4 file
* @param {Object} params - Recording parameters (Optional)
* @param {Object} params.refresh - Periodically refresh an intra on all
* video tracks (in ms)
* @param {Object} params.waitForIntra - Wait until first video iframe is
* received to start recording media
* @returns {Recorder}
*/
createRecorder(filename: string, params?: CreateRecorderOptions): Recorder;
/**
* Create a new MP4 player
* @memberof MediaServer
* @param {String} filename - Path and filename of the mp4 file
* @returns {Player}
*/
createPlayer(filename: string): Player;
/**
* Create a new RTP streamer
* @memberof MediaServer
* @returns {Streamer}
*/
createStreamer(): Streamer;
/**
* Create a new Active Speaker Detecrtor
*/
createActiveSpeakerDetector(): ActiveSpeakerDetector;
/**
* Create a new stream refresher
* @param {type} period - Intra refresh period
*/
createRefresher(period: number): Refresher;
/**
* Create a new emulated transport from pcap file
* @param {String} filename - PCAP filename and path
*/
createEmulatedTransport(filename: string): EmulatedTransport;
/**
* Get the default media server capabilities for each supported media type
* @returns {Object} Object containing the capabilities by media ("audio","video")
*/
getDefaultCapabilities(): MediaCapabilities;
}
export interface IncomingStream {
/**
* The media stream id as announced on the SDP
* @returns {String}
*/
getId(): string;
/**
* Get the stream info object for signaling the ssrcs and stream info on the
* SDP from the remote peer
* @returns {StreamInfo} The stream info object
*/
getStreamInfo(): SemanticSDP.StreamInfo;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
on(event: 'track',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
on(event: 'stopped',
listener:
(stream: IncomingStream, stats: IncomingStreamStatsReport) => any):
IncomingStream;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'track', listener: (track: IncomingStreamTrack) => any):
IncomingStream;
once(
event: 'stopped',
listener:
(stream: IncomingStream, stats: IncomingStreamStatsReport) => any):
IncomingStream;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
off(event: 'track',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
off(event: 'stopped',
listener:
(stream: IncomingStream, stats: IncomingStreamStatsReport) => any):
IncomingStream;
/**
* Get statistics for all tracks in the stream
*
* See OutgoingStreamTrack.getStats for information about the stats returned
* by each track.
*
* @returns {Map<String>,Object} Map with stats by trackId
*/
getStats(): IncomingStreamStatsReport;
/**
* Get track by id
* @param {String} trackId - The track id
* @returns {IncomingStreamTrack} - requested track or null
*/
getTrack(trackId: string): IncomingStreamTrack;
/**
* Get all the tracks
* @param {String} type - The media type (Optional)
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getTracks(type?: string): IncomingStreamTrack[];
/**
* Get an array of the media stream audio tracks
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getAudioTracks(): IncomingStreamTrack[];
/**
* Get an array of the media stream video tracks
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getVideoTracks(): IncomingStreamTrack[];
/*
* Adds an incoming stream track created using the
* Transpocnder.createIncomingStreamTrack to this stream
*
* @param {IncomingStreamTrack} track
*/
addTrack(track: IncomingStreamTrack): void;
/**
* Create new track from a TrackInfo object and add it to this stream
*
* @param {TrackInfo} trackInfo Track info object
* @returns {IncomingStreamTrack}
*/
createTrack(trackInfo: SemanticSDP.TrackInfo): IncomingStreamTrack;
/**
* Removes the media strem from the transport and also detaches from any
* attached incoming stream
*/
stop(): void;
}
export interface IncomingStreamTrack {
/**
* Get stats for all encodings
* @returns {Map<String,Object>} Map with stats by encodingId
*/
getStats(): IncomingStreamTrackStatsReport;
/**
* Get active encodings and layers ordered by bitrate
* @returns {Object} Active layers object containing an array of active and
* inactive encodings and an array of all available layer info
*/
getActiveLayers(): ActiveLayers;
/**
* Get track id as signaled on the SDP
*/
getId(): string;
/**
* Get track info object
* @returns {TrackInfo} Track info
*/
getTrackInfo(): SemanticSDP.TrackInfo;
/**
* Return ssrcs associated to this track
* @returns {Object}
*/
getSSRCs(): {[encodingID: string]: SSRCs};
/**
* Get track media type
* @returns {String} "audio"|"video"
*/
getMedia(): SemanticSDP.MediaType;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
on(event: 'attached',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
on(event: 'detached',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
on(event: 'stopped',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'attached', listener: (track: IncomingStreamTrack) => any):
IncomingStream;
once(event: 'detached', listener: (track: IncomingStreamTrack) => any):
IncomingStream;
once(event: 'stopped', listener: (track: IncomingStreamTrack) => any):
IncomingStream;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
off(event: 'attached',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
off(event: 'detached',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
off(event: 'stopped',
listener: (track: IncomingStreamTrack) => any): IncomingStream;
/**
* Signal that this track has been attached.
* Internal use, you'd beter know what you are doing before calling this
* method
*/
attached(): void;
/**
* Request an intra refres on all sources
*/
refresh(): void;
/**
* Signal that this track has been detached.
* Internal use, you'd beter know what you are doing before calling this
* method
*/
detached(): void;
/**
* Removes the track from the incoming stream and also detaches any attached
* outgoing track or recorder
*/
stop(): void;
}
export interface PeerConnectionServer {
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listeener - Event listener
* @returns {PeerConnectionServer}
*/
on(event: 'stopped',
listener: (server: PeerConnectionServer) => any): PeerConnectionServer;
on(event: 'transport',
listener: (transport: Transport) => any): PeerConnectionServer;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {PeerConnectionServer}
*/
once(event: 'stopped', listener: (server: PeerConnectionServer) => any):
PeerConnectionServer;
once(event: 'transport', listener: (transport: Transport) => any):
PeerConnectionServer;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {PeerConnectionServer}
*/
off(event: 'stopped',
listener: (server: PeerConnectionServer) => any): PeerConnectionServer;
off(event: 'transport',
listener: (transport: Transport) => any): PeerConnectionServer;
/**
* Stop the peerconnection server, will not stop the transport created by it
*/
stop(): void;
}
export interface OutgoingStreamTrack {
/**
* Get track id as signaled on the SDP
*/
getId(): string;
/**
* Get track media type
* @returns {String} "audio"|"video"
*/
getMedia(): SemanticSDP.MediaType;
/**
* Get track info object
* @returns {TrackInfo} Track info
*/
getTrackInfo(): SemanticSDP.TrackInfo;
/**
* Get stats for all encodings
* @returns {Map<String,Object>} Map with stats by encodingId
*/
getStats(): OutgoingStreamStatsReport;
/**
* Return ssrcs associated to this track
* @returns {Object}
*/
getSSRCs(): SSRCs;
/**
* Check if the track is muted or not
* @returns {boolean} muted
*/
isMuted(): boolean;
/*
* Mute/Unmute track
* This operation will not change the muted state of the stream this track
* belongs too.
* @param {boolean} muting - if we want to mute or unmute
*/
mute(muting: boolean): void;
/**
* Listen media from the incoming stream track and send it to the remote
* peer of the associated transport. This will stop any previous transpoder
* created by a previous attach.
* @param {IncomingStreamTrack} incomingStreamTrack - The incoming stream to
* listen media for
* @returns {Transponder} Track transponder object
*/
attachTo(incomingStreamTrack: IncomingStreamTrack): Transponder;
/**
* Get attached transpoder for this track
* @returns {Transponder} Attached transpoder or null if not attached
*/
getTransponder(): Transponder;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
on(event: 'stopped',
listener: (track: OutgoingStreamTrack) => any): OutgoingStreamTrack;
on(event: 'remb',
listener: (bitrate: number, track: OutgoingStreamTrack) => any):
OutgoingStreamTrack;
on(event: 'muted', listener: (muted: boolean) => any): OutgoingStreamTrack;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (track: OutgoingStreamTrack) => any):
OutgoingStreamTrack;
once(
event: 'remb',
listener: (bitrate: number, track: OutgoingStreamTrack) => any):
OutgoingStreamTrack;
once(event: 'muted', listener: (muted: boolean) => any):
OutgoingStreamTrack;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
off(event: 'stopped',
listener: (track: OutgoingStreamTrack) => any): OutgoingStreamTrack;
off(event: 'remb',
listener: (bitrate: number, track: OutgoingStreamTrack) => any):
OutgoingStreamTrack;
off(event: 'muted', listener: (muted: boolean) => any): OutgoingStreamTrack;
/**
* Removes the track from the outgoing stream and also detaches from any
* attached incoming track
*/
stop(): void;
}
export interface Recorder {
/**
* Start recording and incoming
* @param {IncomingStream|IncomingStreamTrack} incomingStreamOrTrack -
* Incomining stream or track to be recordeds
* @returns {Array<RecorderTrack>}
*/
record(incomingStreamOrTrack: IncomingStream|
IncomingStreamTrack): RecorderTrack[];
/**
* Stop recording and close file. NOTE: File will be flsuh async,
* @returns {undefined} - TODO: return promise when flush is ended
*/
stop(): void;
}
export interface RecorderTrack {
/**
* Get recorder track id
*/
getId(): string;
/**
* Get incoming stream track
* @returns {IncomingStreamTrack}
*/
getTrack(): IncomingStreamTrack;
/**
* Get incoming encoding
* @returns {Object}
*/
getEncoding(): Encoding;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {RecorderTrack}
*/
on(event: 'stopped',
listener: (track: RecorderTrack) => any): RecorderTrack;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (track: RecorderTrack) => any):
RecorderTrack;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {RecorderTrack}
*/
off(event: 'stopped',
listener: (track: RecorderTrack) => any): RecorderTrack;
/**
* Stop recording this track
*/
stop(): void;
}
export interface Player {
/**
* Get all the tracks
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getTracks(): IncomingStreamTrack[];
/**
* Get an array of the media stream audio tracks
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getAudioTracks(): IncomingStreamTrack[];
/**
* Get an array of the media stream video tracks
* @returns {Array<IncomingStreamTrack>} - Array of tracks
*/
getVideoTracks(): IncomingStreamTrack[];
/**
* Starts playback
* @param {Object} params
* @param {Object} params.repeat - Repeat playback when file is ended
*/
play(params?: PlayerPlayOptions): void;
/**
* Resume playback
*/
resume(): void;
/**
* Pause playback
*/
pause(): void;
/**
* Start playback from given time
* @param {Number} time - in miliseconds
*/
seek(time: number): void;
/**
* Stop playing and close file
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
on(event: 'stopped', listener: (track: Player) => any): Player;
on(event: 'ended', listener: (track: Player) => any): Player;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (track: Player) => any): Player;
once(event: 'ended', listener: (track: Player) => any): Player;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
off(event: 'stopped', listener: (track: Player) => any): Player;
off(event: 'ended', listener: (track: Player) => any): Player;
}
export interface EmulatedTransport {
/**
* Set remote RTP properties
* @param {Object|SDPInfo} rtp - Object param containing media information
* for audio and video
* @param {MediaInfo} rtp.audio - Audio media info
* @param {MediaInfo} rtp.video - Video media info
*/
setRemoteProperties(rtp: SemanticSDP.SDPInfo|
SetTransportPropertiesOptions): void;
/**
* Create an incoming stream object from the media stream info objet
* @param {StreamInfo} info Contains the ids and ssrcs of the stream to be
* created
* @returns {IncomingStream} The newly created incoming stream object
*/
createIncomingStream(info: SemanticSDP.StreamInfo|
SemanticSDP.StreamInfoPlain): IncomingStream;
/**
* Starts playback
* @param {Object} params
* @param {Object} params.start - Set start time
*/
play(params?: EmulatedTransportPlayOptions): void;
/**
* Resume playback
*/
resume(): void;
/**
* Resume playback
*/
resume(): void;
/**
* Start playback from given time
* @param {Number} time - in miliseconds
*/
seek(time: number): void;
/**
* Stop transport and all the associated incoming and outgoing streams
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listeener - Event listener
* @returns {Transport}
*/
on(event: 'stopped',
listener: (track: EmulatedTransport) => any): EmulatedTransport;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (track: EmulatedTransport) => any):
EmulatedTransport;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transport}
*/
off(event: 'stopped',
listener: (track: EmulatedTransport) => any): EmulatedTransport;
}
/**
* An streamer allows to send and receive plain RTP over udp sockets.
* This allows both to bridge legacy enpoints or integrate
* streaming/broadcasting services.
*/
export interface Streamer {
/**
* Creates a new streaming session from a media description
* @param {MediaInfo} media - Media codec description info
* @param {Object} params - Network parameters
* @param {Object} params.local - Local parameters
* @param {Number} params.local.port - receiving port
* @param {Object} params.remote - Remote parameters
* @param {String} params.remote.ip - Sending ip address
* @param {Number} params.remote.port - Sending port
* @returns {StreamerSession} The new streaming session
*/
createSession(
media: SemanticSDP.MediaInfo,
params: CreateStreamerSessionOptions): StreamerSession;
/**
* Stop all streaming sessions and frees resources
*/
stop(): void;
}
/**
* Represent the connection between a local udp port and a remote one. It
* sends and/or receive plain RTP data.
*/
export interface StreamerSession {
/**
* Returns the incoming stream track associated with this streaming session
* @returns {IncomingStreamTrack}
*/
getIncomingStreamTrack(): IncomingStreamTrack;
/**
* Returns the outgoing stream track associated with this streaming session
* @returns {OutgoingStreamTrack}
*/
getOutgoingStreamTrack(): OutgoingStreamTrack;
/**
* Closes udp socket and frees resources
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {StreamerSession}
*/
on(event: 'stopped',
listener: (s: StreamerSession) => any): StreamerSession;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (s: StreamerSession) => any):
StreamerSession;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {StreamerSession}
*/
off(event: 'stopped',
listener: (s: StreamerSession) => any): StreamerSession;
}
/**
* Periodically request an I frame on all incoming stream or tracks
*/
export interface Refresher {
/**
* Add stream or track to request
* @param {IncomintgStream|IncomingStreamTrack} streamOrTrack
*/
add(streamOrTrack: IncomingStream|IncomingStreamTrack): void;
/**
* Stop refresher
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
on(event: 'stopped', listener: (r: Refresher) => any): Refresher;
on(event: 'refreshing', listener: (r: Refresher) => any): Refresher;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'stopped', listener: (r: Refresher) => any): Refresher;
once(event: 'refreshing', listener: (r: Refresher) => any): Refresher;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {OutgoingStream}
*/
off(event: 'stopped', listener: (r: Refresher) => any): Refresher;
off(event: 'refreshing', listener: (r: Refresher) => any): Refresher;
}
export interface SDPManager {
/**
* Get current SDP offer/answer state
* @returns {String} one of
* "initial","local-offer","remote-offer","stabable".
*/
getState(): 'initial'|'local-offer'|'remote-offer'|'stable';
/**
* Returns the Transport object created by the SDP O/A
* @returns {Transport}
*/
getTransport(): Transport;
/**
* Create local description
* @returns {String}
*/
createLocalDescription(): string;
/**
* Process remote offer
* @param {String} sdp - Remote session description
*/
processRemoteDescription(sdp: string): void;
/**
* Stop manager and associated tranports
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listeener - Event listener
* @returns {Transport}
*/
on(event: 'renegotiationneeded',
listener: (transport: Transport) => any): SDPManager;
on(event: 'transport', listener: (transport: Transport) => any): SDPManager;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(event: 'renegotiationneeded', listener: (transport: Transport) => any):
SDPManager;
once(event: 'transport', listener: (transport: Transport) => any):
SDPManager;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {Transport}
*/
off(event: 'renegotiationneeded',
listener: (transport: Transport) => any): SDPManager;
off(event: 'transport',
listener: (transport: Transport) => any): SDPManager;
}
export interface ActiveSpeakerDetector {
/**
* Set minimum period between active speaker changes
* @param {Number} minChangePeriod
*/
setMinChangePeriod(minChangePeriod: number): void;
/**
* Maximux activity score accumulated by an speaker
* @param {Number} maxAcummulatedScore
*/
setMaxAccumulatedScore(maxAcummulatedScore: number): void;
/**
* Minimum db level to not be considered as muted
* @param {Number} noiseGatingThreshold
*/
setNoiseGatingThreshold(noiseGatingThreshold: number): void;
/**
* Set minimum activation score to be electible as active speaker
* @param {Number} minActivationScore
*/
setMinActivationScore(minActivationScore: number): void;
/**
* Add incoming track for speaker detection
* @param {IncomingStreamTrack} track
*/
addSpeaker(track: IncomingStreamTrack): void;
/**
* Remove track from speaker detection
* @param {IncomingStreamTrakc} track
*/
removeSpeaker(track: IncomingStreamTrack): void;
/**
* Stop this transponder, will dettach the OutgoingStreamTrack
*/
stop(): void;
/**
* Add event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
on(event: 'activespeakerchanged',
listener: (track: IncomingStreamTrack) => any): ActiveSpeakerDetector;
on(event: 'stopped', listener: () => any): ActiveSpeakerDetector;
/**
* Add event listener once
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStream}
*/
once(
event: 'activespeakerchanged',
listener: (track: IncomingStreamTrack) => any): ActiveSpeakerDetector;
once(event: 'stopped', listener: () => any): ActiveSpeakerDetector;
/**
* Remove event listener
* @param {String} event - Event name
* @param {function} listener - Event listener
* @returns {IncomingStreamTrack}
*/
off(event: 'activespeakerchanged',
listener: (track: IncomingStreamTrack) => any): ActiveSpeakerDetector;
off(event: 'stopped', listener: () => any): ActiveSpeakerDetector;
}
let MediaServer: MediaServer;
export default MediaServer;
} | the_stack |
declare namespace ExcelScript {
/*
* Special Run Function
*/
function run(
callback: (workbook: Workbook) => Promise<void>
): Promise<void>;
//
// Class
//
/**
* Represents the Excel application that manages the workbook.
*/
interface Application {
/**
* Returns the Excel calculation engine version used for the last full recalculation.
*/
getCalculationEngineVersion(): number;
/**
* Returns the calculation mode used in the workbook, as defined by the constants in ExcelScript.CalculationMode. Possible values are: `Automatic`, where Excel controls recalculation; `AutomaticExceptTables`, where Excel controls recalculation but ignores changes in tables; `Manual`, where calculation is done when the user requests it.
*/
getCalculationMode(): CalculationMode;
/**
* Returns the calculation mode used in the workbook, as defined by the constants in ExcelScript.CalculationMode. Possible values are: `Automatic`, where Excel controls recalculation; `AutomaticExceptTables`, where Excel controls recalculation but ignores changes in tables; `Manual`, where calculation is done when the user requests it.
*/
setCalculationMode(calculationMode: CalculationMode): void;
/**
* Returns the calculation state of the application. See ExcelScript.CalculationState for details.
*/
getCalculationState(): CalculationState;
/**
* Provides information based on current system culture settings. This includes the culture names, number formatting, and other culturally dependent settings.
*/
getCultureInfo(): CultureInfo;
/**
* Gets the string used as the decimal separator for numeric values. This is based on Excel's local settings.
*/
getDecimalSeparator(): string;
/**
* Returns the Iterative Calculation settings.
* In Excel on Windows and Mac, the settings will apply to the Excel Application.
* In Excel on the web and other platforms, the settings will apply to the active workbook.
*/
getIterativeCalculation(): IterativeCalculation;
/**
* Gets the string used to separate groups of digits to the left of the decimal for numeric values. This is based on Excel's local settings.
*/
getThousandsSeparator(): string;
/**
* Specifies if the system separators of Excel are enabled.
* System separators include the decimal separator and thousands separator.
*/
getUseSystemSeparators(): boolean;
/**
* Recalculate all currently opened workbooks in Excel.
* @param calculationType Specifies the calculation type to use. See ExcelScript.CalculationType for details.
*/
calculate(calculationType: CalculationType): void;
}
/**
* Represents the Iterative Calculation settings.
*/
interface IterativeCalculation {
/**
* True if Excel will use iteration to resolve circular references.
*/
getEnabled(): boolean;
/**
* True if Excel will use iteration to resolve circular references.
*/
setEnabled(enabled: boolean): void;
/**
* Specifies the maximum amount of change between each iteration as Excel resolves circular references.
*/
getMaxChange(): number;
/**
* Specifies the maximum amount of change between each iteration as Excel resolves circular references.
*/
setMaxChange(maxChange: number): void;
/**
* Specifies the maximum number of iterations that Excel can use to resolve a circular reference.
*/
getMaxIteration(): number;
/**
* Specifies the maximum number of iterations that Excel can use to resolve a circular reference.
*/
setMaxIteration(maxIteration: number): void;
}
/**
* Workbook is the top level object which contains related workbook objects such as worksheets, tables, ranges, etc.
*/
interface Workbook {
/**
* Represents the Excel application instance that contains this workbook.
*/
getApplication(): Application;
/**
* Specifies if the workbook is in autosave mode.
*/
getAutoSave(): boolean;
/**
* Returns a number about the version of Excel Calculation Engine.
*/
getCalculationEngineVersion(): number;
/**
* True if all charts in the workbook are tracking the actual data points to which they are attached.
* False if the charts track the index of the data points.
*/
getChartDataPointTrack(): boolean;
/**
* True if all charts in the workbook are tracking the actual data points to which they are attached.
* False if the charts track the index of the data points.
*/
setChartDataPointTrack(chartDataPointTrack: boolean): void;
/**
* Specifies if changes have been made since the workbook was last saved.
* You can set this property to true if you want to close a modified workbook without either saving it or being prompted to save it.
*/
getIsDirty(): boolean;
/**
* Specifies if changes have been made since the workbook was last saved.
* You can set this property to true if you want to close a modified workbook without either saving it or being prompted to save it.
*/
setIsDirty(isDirty: boolean): void;
/**
* Gets the workbook name.
*/
getName(): string;
/**
* Specifies if the workbook has ever been saved locally or online.
*/
getPreviouslySaved(): boolean;
/**
* Gets the workbook properties.
*/
getProperties(): DocumentProperties;
/**
* Returns the protection object for a workbook.
*/
getProtection(): WorkbookProtection;
/**
* True if the workbook is open in Read-only mode.
*/
getReadOnly(): boolean;
/**
* True if calculations in this workbook will be done using only the precision of the numbers as they're displayed.
* Data will permanently lose accuracy when switching this property from false to true.
*/
getUsePrecisionAsDisplayed(): boolean;
/**
* True if calculations in this workbook will be done using only the precision of the numbers as they're displayed.
* Data will permanently lose accuracy when switching this property from false to true.
*/
setUsePrecisionAsDisplayed(usePrecisionAsDisplayed: boolean): void;
/**
* Gets the currently active cell from the workbook.
*/
getActiveCell(): Range;
/**
* Gets the currently active chart in the workbook. If there is no active chart, then this function will return an object with its `isNullObject` property set to `true`.
*/
getActiveChart(): Chart;
/**
* Gets the currently active slicer in the workbook. If there is no active slicer, then this function will return an object with its `isNullObject` property set to `true`.
*/
getActiveSlicer(): Slicer;
/**
* Gets the currently selected single range from the workbook. If there are multiple ranges selected, this method will throw an error.
*/
getSelectedRange(): Range;
/**
* Gets the currently selected one or more ranges from the workbook. Unlike getSelectedRange(), this method returns a RangeAreas object that represents all the selected ranges.
*/
getSelectedRanges(): RangeAreas;
/**
* Represents a collection of bindings that are part of the workbook.
*/
getBindings(): Binding[];
/**
* Add a new binding to a particular Range.
* @param range Range to bind the binding to. May be an Excel Range object, or a string. If string, must contain the full address, including the sheet name
* @param bindingType Type of binding. See ExcelScript.BindingType.
* @param id Name of binding.
*/
addBinding(
range: Range | string,
bindingType: BindingType,
id: string
): Binding;
/**
* Add a new binding based on a named item in the workbook.
* If the named item references to multiple areas, the "InvalidReference" error will be returned.
* @param name Name from which to create binding.
* @param bindingType Type of binding. See ExcelScript.BindingType.
* @param id Name of binding.
*/
addBindingFromNamedItem(
name: string,
bindingType: BindingType,
id: string
): Binding;
/**
* Add a new binding based on the current selection.
* If the selection has multiple areas, the "InvalidReference" error will be returned.
* @param bindingType Type of binding. See ExcelScript.BindingType.
* @param id Name of binding.
*/
addBindingFromSelection(bindingType: BindingType, id: string): Binding;
/**
* Gets a binding object by ID. If the binding object does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param id Id of the binding object to be retrieved.
*/
getBinding(id: string): Binding | undefined;
/**
* Represents a collection of Comments associated with the workbook.
*/
getComments(): Comment[];
/**
* Creates a new comment with the given content on the given cell. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
* @param cellAddress The cell to which the comment is added. This can be a Range object or a string. If it's a string, it must contain the full address, including the sheet name. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
* @param content The comment's content. This can be either a string or CommentRichContent object. Strings are used for plain text. CommentRichContent objects allow for other comment features, such as mentions.
* @param contentType Optional. The type of content contained within the comment. The default value is enum `ContentType.Plain`.
*/
addComment(
cellAddress: Range | string,
content: CommentRichContent | string,
contentType?: ContentType
): Comment;
/**
* Gets a comment from the collection based on its ID.
* @param commentId The identifier for the comment.
*/
getComment(commentId: string): Comment;
/**
* Gets the comment from the specified cell.
* @param cellAddress The cell which the comment is on. This can be a Range object or a string. If it's a string, it must contain the full address, including the sheet name. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
*/
getCommentByCell(cellAddress: Range | string): Comment;
/**
* Gets the comment to which the given reply is connected.
* @param replyId The identifier of comment reply.
*/
getCommentByReplyId(replyId: string): Comment;
/**
* Represents the collection of custom XML parts contained by this workbook.
*/
getCustomXmlParts(): CustomXmlPart[];
/**
* Adds a new custom XML part to the workbook.
* @param xml XML content. Must be a valid XML fragment.
*/
addCustomXmlPart(xml: string): CustomXmlPart;
/**
* Gets a new collection of custom XML parts whose namespaces match the given namespace.
* @param namespaceUri This must be a fully qualified schema URI; for example, "http://schemas.contoso.com/review/1.0".
*/
getCustomXmlPartByNamespace(namespaceUri: string): CustomXmlPart[];
/**
* Gets a custom XML part based on its ID.
* If the CustomXmlPart does not exist, the return object's isNull property will be true.
* @param id ID of the object to be retrieved.
*/
getCustomXmlPart(id: string): CustomXmlPart | undefined;
/**
* Represents a collection of workbook scoped named items (named ranges and constants).
*/
getNames(): NamedItem[];
/**
* Adds a new name to the collection of the given scope.
* @param name The name of the named item.
* @param reference The formula or the range that the name will refer to.
* @param comment Optional. The comment associated with the named item.
*/
addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;
/**
* Adds a new name to the collection of the given scope using the user's locale for the formula.
* @param name The "name" of the named item.
* @param formula The formula in the user's locale that the name will refer to.
* @param comment Optional. The comment associated with the named item.
*/
addNamedItemFormulaLocal(
name: string,
formula: string,
comment?: string
): NamedItem;
/**
* Gets a `NamedItem` object using its name. If the object does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Nameditem name.
*/
getNamedItem(name: string): NamedItem | undefined;
/**
* Represents a collection of PivotTableStyles associated with the workbook.
*/
getPivotTableStyles(): PivotTableStyle[];
/**
* Creates a blank PivotTableStyle with the specified name.
* @param name The unique name for the new PivotTableStyle. Will throw an invalid argument exception if the name is already in use.
* @param makeUniqueName Optional, defaults to false. If true, will append numbers to the name in order to make it unique, if needed.
*/
addPivotTableStyle(
name: string,
makeUniqueName?: boolean
): PivotTableStyle;
/**
* Gets the default PivotTableStyle for the parent object's scope.
*/
getDefaultPivotTableStyle(): PivotTableStyle;
/**
* Gets a PivotTableStyle by name. If the PivotTableStyle does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotTableStyle to be retrieved.
*/
getPivotTableStyle(name: string): PivotTableStyle | undefined;
/**
* Sets the default PivotTableStyle for use in the parent object's scope.
* @param newDefaultStyle The PivotTableStyle object or name of the PivotTableStyle object that should be the new default.
*/
setDefaultPivotTableStyle(
newDefaultStyle: PivotTableStyle | string
): void;
/**
* Represents a collection of PivotTables associated with the workbook.
*/
getPivotTables(): PivotTable[];
/**
* Add a PivotTable based on the specified source data and insert it at the top-left cell of the destination range.
* @param name The name of the new PivotTable.
* @param source The source data for the new PivotTable, this can either be a range (or string address including the worksheet name) or a table.
* @param destination The cell in the upper-left corner of the PivotTable report's destination range (the range on the worksheet where the resulting report will be placed).
*/
addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;
/**
* Gets a PivotTable by name. If the PivotTable does not exist, will return a null object.
* @param name Name of the PivotTable to be retrieved.
*/
getPivotTable(name: string): PivotTable | undefined;
/**
* Refreshes all the pivot tables in the collection.
*/
refreshAllPivotTables(): void;
/**
* Represents a collection of SlicerStyles associated with the workbook.
*/
getSlicerStyles(): SlicerStyle[];
/**
* Creates a blank SlicerStyle with the specified name.
* @param name The unique name for the new SlicerStyle. Will throw an invalid argument exception if the name is already in use.
* @param makeUniqueName Optional, defaults to false. If true, will append numbers to the name in order to make it unique, if needed.
*/
addSlicerStyle(name: string, makeUniqueName?: boolean): SlicerStyle;
/**
* Gets the default SlicerStyle for the parent object's scope.
*/
getDefaultSlicerStyle(): SlicerStyle;
/**
* Gets a SlicerStyle by name. If the SlicerStyle doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the SlicerStyle to be retrieved.
*/
getSlicerStyle(name: string): SlicerStyle | undefined;
/**
* Sets the default SlicerStyle for use in the parent object's scope.
* @param newDefaultStyle The SlicerStyle object or name of the SlicerStyle object that should be the new default.
*/
setDefaultSlicerStyle(newDefaultStyle: SlicerStyle | string): void;
/**
* Represents a collection of Slicers associated with the workbook.
*/
getSlicers(): Slicer[];
/**
* Adds a new slicer to the workbook.
* @param slicerSource The data source that the new slicer will be based on. It can be a PivotTable object, a Table object or a string. When a PivotTable object is passed, the data source is the source of the PivotTable object. When a Table object is passed, the data source is the Table object. When a string is passed, it is interpreted as the name/id of a PivotTable/Table.
* @param sourceField The field in the data source to filter by. It can be a PivotField object, a TableColumn object, the id of a PivotField or the id/name of TableColumn.
* @param slicerDestination Optional. The worksheet where the new slicer will be created in. It can be a Worksheet object or the name/id of a worksheet. This parameter can be omitted if the slicer collection is retrieved from worksheet.
*/
addSlicer(
slicerSource: string | PivotTable | Table,
sourceField: string | PivotField | number | TableColumn,
slicerDestination?: string | Worksheet
): Slicer;
/**
* Gets a slicer using its name or id. If the slicer doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Name or Id of the slicer to be retrieved.
*/
getSlicer(key: string): Slicer | undefined;
/**
* Represents a collection of styles associated with the workbook.
*/
getPredefinedCellStyles(): PredefinedCellStyle[];
/**
* Adds a new style to the collection.
* @param name Name of the style to be added.
*/
addPredefinedCellStyle(name: string): void;
/**
* Gets a style by name.
* @param name Name of the style to be retrieved.
*/
getPredefinedCellStyle(name: string): PredefinedCellStyle;
/**
* Represents a collection of TableStyles associated with the workbook.
*/
getTableStyles(): TableStyle[];
/**
* Creates a blank TableStyle with the specified name.
* @param name The unique name for the new TableStyle. Will throw an invalid argument exception if the name is already in use.
* @param makeUniqueName Optional, defaults to false. If true, will append numbers to the name in order to make it unique, if needed.
*/
addTableStyle(name: string, makeUniqueName?: boolean): TableStyle;
/**
* Gets the default TableStyle for the parent object's scope.
*/
getDefaultTableStyle(): TableStyle;
/**
* Gets a TableStyle by name. If the TableStyle does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the TableStyle to be retrieved.
*/
getTableStyle(name: string): TableStyle | undefined;
/**
* Sets the default TableStyle for use in the parent object's scope.
* @param newDefaultStyle The TableStyle object or name of the TableStyle object that should be the new default.
*/
setDefaultTableStyle(newDefaultStyle: TableStyle | string): void;
/**
* Represents a collection of tables associated with the workbook.
*/
getTables(): Table[];
/**
* Create a new table. The range object or source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown.
* @param address A Range object, or a string address or name of the range representing the data source. If the address does not contain a sheet name, the currently-active sheet is used.
* @param hasHeaders Boolean value that indicates whether the data being imported has column labels. If the source does not contain headers (i.e,. when this property set to false), Excel will automatically generate header shifting the data down by one row.
*/
addTable(address: Range | string, hasHeaders: boolean): Table;
/**
* Gets a table by Name or ID. If the table doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Name or ID of the table to be retrieved.
*/
getTable(key: string): Table | undefined;
/**
* Represents a collection of TimelineStyles associated with the workbook.
*/
getTimelineStyles(): TimelineStyle[];
/**
* Creates a blank TimelineStyle with the specified name.
* @param name The unique name for the new TimelineStyle. Will throw an invalid argument exception if the name is already in use.
* @param makeUniqueName Optional, defaults to false. If true, will append numbers to the name in order to make it unique, if needed.
*/
addTimelineStyle(name: string, makeUniqueName?: boolean): TimelineStyle;
/**
* Gets the default TimelineStyle for the parent object's scope.
*/
getDefaultTimelineStyle(): TimelineStyle;
/**
* Gets a TimelineStyle by name. If the TimelineStyle doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the TimelineStyle to be retrieved.
*/
getTimelineStyle(name: string): TimelineStyle | undefined;
/**
* Sets the default TimelineStyle for use in the parent object's scope.
* @param newDefaultStyle The TimelineStyle object or name of the TimelineStyle object that should be the new default.
*/
setDefaultTimelineStyle(newDefaultStyle: TimelineStyle | string): void;
/**
* Represents a collection of worksheets associated with the workbook.
*/
getWorksheets(): Worksheet[];
/**
* Adds a new worksheet to the workbook. The worksheet will be added at the end of existing worksheets. If you wish to activate the newly added worksheet, call ".activate() on it.
* @param name Optional. The name of the worksheet to be added. If specified, name should be unqiue. If not specified, Excel determines the name of the new worksheet.
*/
addWorksheet(name?: string): Worksheet;
/**
* Gets the currently active worksheet in the workbook.
*/
getActiveWorksheet(): Worksheet;
/**
* Gets the first worksheet in the collection.
* @param visibleOnly Optional. If true, considers only visible worksheets, skipping over any hidden ones.
*/
getFirstWorksheet(visibleOnly?: boolean): Worksheet;
/**
* Gets a worksheet object using its Name or ID. If the worksheet does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key The Name or ID of the worksheet.
*/
getWorksheet(key: string): Worksheet | undefined;
/**
* Gets the last worksheet in the collection.
* @param visibleOnly Optional. If true, considers only visible worksheets, skipping over any hidden ones.
*/
getLastWorksheet(visibleOnly?: boolean): Worksheet;
/**
* Refreshes all the Data Connections.
*/
refreshAllDataConnections(): void;
}
/**
* Represents the protection of a workbook object.
*/
interface WorkbookProtection {
/**
* Specifies if the workbook is protected.
*/
getProtected(): boolean;
/**
* Protects a workbook. Fails if the workbook has been protected.
* @param password workbook protection password.
*/
protect(password?: string): void;
/**
* Unprotects a workbook.
* @param password workbook protection password.
*/
unprotect(password?: string): void;
}
/**
* An Excel worksheet is a grid of cells. It can contain data, tables, charts, etc.
*/
interface Worksheet {
/**
* Represents the AutoFilter object of the worksheet.
*/
getAutoFilter(): AutoFilter;
/**
* Determines if Excel should recalculate the worksheet when necessary.
* True if Excel recalculates the worksheet when necessary. False if Excel doesn't recalculate the sheet.
*/
getEnableCalculation(): boolean;
/**
* Determines if Excel should recalculate the worksheet when necessary.
* True if Excel recalculates the worksheet when necessary. False if Excel doesn't recalculate the sheet.
*/
setEnableCalculation(enableCalculation: boolean): void;
/**
* Gets an object that can be used to manipulate frozen panes on the worksheet.
*/
getFreezePanes(): WorksheetFreezePanes;
/**
* Returns a value that uniquely identifies the worksheet in a given workbook. The value of the identifier remains the same even when the worksheet is renamed or moved.
*/
getId(): string;
/**
* The display name of the worksheet.
*/
getName(): string;
/**
* The display name of the worksheet.
*/
setName(name: string): void;
/**
* Gets the PageLayout object of the worksheet.
*/
getPageLayout(): PageLayout;
/**
* The zero-based position of the worksheet within the workbook.
*/
getPosition(): number;
/**
* The zero-based position of the worksheet within the workbook.
*/
setPosition(position: number): void;
/**
* Returns sheet protection object for a worksheet.
*/
getProtection(): WorksheetProtection;
/**
* Specifies if gridlines are visible to the user.
*/
getShowGridlines(): boolean;
/**
* Specifies if gridlines are visible to the user.
*/
setShowGridlines(showGridlines: boolean): void;
/**
* Specifies if headings are visible to the user.
*/
getShowHeadings(): boolean;
/**
* Specifies if headings are visible to the user.
*/
setShowHeadings(showHeadings: boolean): void;
/**
* Returns the standard (default) height of all the rows in the worksheet, in points.
*/
getStandardHeight(): number;
/**
* Specifies the standard (default) width of all the columns in the worksheet.
* One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used.
*/
getStandardWidth(): number;
/**
* Specifies the standard (default) width of all the columns in the worksheet.
* One unit of column width is equal to the width of one character in the Normal style. For proportional fonts, the width of the character 0 (zero) is used.
*/
setStandardWidth(standardWidth: number): void;
/**
* The tab color of the worksheet.
* When retrieving the tab color, if the worksheet is invisible, the value will be null. If the worksheet is visible but the tab color is set to auto, an empty string will be returned. Otherwise, the property will be set to a color, in the form "#123456"
* When setting the color, use an empty-string to set an "auto" color, or a real color otherwise.
*/
getTabColor(): string;
/**
* The tab color of the worksheet.
* When retrieving the tab color, if the worksheet is invisible, the value will be null. If the worksheet is visible but the tab color is set to auto, an empty string will be returned. Otherwise, the property will be set to a color, in the form "#123456"
* When setting the color, use an empty-string to set an "auto" color, or a real color otherwise.
*/
setTabColor(tabColor: string): void;
/**
* The Visibility of the worksheet.
*/
getVisibility(): SheetVisibility;
/**
* The Visibility of the worksheet.
*/
setVisibility(visibility: SheetVisibility): void;
/**
* Activate the worksheet in the Excel UI.
*/
activate(): void;
/**
* Calculates all cells on a worksheet.
* @param markAllDirty True, to mark all as dirty.
*/
calculate(markAllDirty: boolean): void;
/**
* Copies a worksheet and places it at the specified position.
* @param positionType The location in the workbook to place the newly created worksheet. The default value is "None", which inserts the worksheet at the beginning of the worksheet.
* @param relativeTo The existing worksheet which determines the newly created worksheet's position. This is only needed if `positionType` is "Before" or "After".
*/
copy(
positionType?: WorksheetPositionType,
relativeTo?: Worksheet
): Worksheet;
/**
* Deletes the worksheet from the workbook. Note that if the worksheet's visibility is set to "VeryHidden", the delete operation will fail with an `InvalidOperation` exception. You should first change its visibility to hidden or visible before deleting it.
*/
delete(): void;
/**
* Finds all occurrences of the given string based on the criteria specified and returns them as a RangeAreas object, comprising one or more rectangular ranges.
* @param text The string to find.
* @param criteria Additional search criteria, including whether the search needs to match the entire cell or be case sensitive.
*/
findAll(text: string, criteria: WorksheetSearchCriteria): RangeAreas;
/**
* Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it stays within the worksheet grid.
* @param row The row number of the cell to be retrieved. Zero-indexed.
* @param column the column number of the cell to be retrieved. Zero-indexed.
*/
getCell(row: number, column: number): Range;
/**
* Gets the worksheet that follows this one. If there are no worksheets following this one, then this method will return an object with its `isNullObject` property set to `true`.
* @param visibleOnly Optional. If true, considers only visible worksheets, skipping over any hidden ones.
*/
getNext(visibleOnly?: boolean): Worksheet;
/**
* Gets the worksheet that precedes this one. If there are no previous worksheets, this method will return a null objet.
* @param visibleOnly Optional. If true, considers only visible worksheets, skipping over any hidden ones.
*/
getPrevious(visibleOnly?: boolean): Worksheet;
/**
* Gets the range object, representing a single rectangular block of cells, specified by the address or name.
* @param address Optional. The string representing the address or name of the range. For example, "A1:B2". If not specified, the entire worksheet range is returned.
*/
getRange(address?: string): Range;
/**
* Gets the range object beginning at a particular row index and column index, and spanning a certain number of rows and columns.
* @param startRow Start row (zero-indexed).
* @param startColumn Start column (zero-indexed).
* @param rowCount Number of rows to include in the range.
* @param columnCount Number of columns to include in the range.
*/
getRangeByIndexes(
startRow: number,
startColumn: number,
rowCount: number,
columnCount: number
): Range;
/**
* Gets the RangeAreas object, representing one or more blocks of rectangular ranges, specified by the address or name.
* @param address Optional. A string containing the comma-separated addresses or names of the individual ranges. For example, "A1:B2, A5:B5". If not specified, an RangeArea object for the entire worksheet is returned.
*/
getRanges(address?: string): RangeAreas;
/**
* @param valuesOnly Optional. Considers only cells with values as used cells.
*/
getUsedRange(valuesOnly?: boolean): Range;
/**
* Finds and replaces the given string based on the criteria specified within the current worksheet.
* @param text String to find.
* @param replacement String to replace the original with.
* @param criteria Additional Replace Criteria.
*/
replaceAll(
text: string,
replacement: string,
criteria: ReplaceCriteria
): number;
/**
* Shows row or column groups by their outline levels.
* Outlines group and summarize a list of data in the worksheet.
* The `rowLevels` and `columnLevels` parameters specify how many levels of the outline will be displayed.
* The acceptable argument range is between 0 and 8.
* A value of 0 does not change the current display. A value greater than the current number of levels displays all the levels.
* @param rowLevels The number of row levels of an outline to display.
* @param columnLevels The number of column levels of an outline to display.
*/
showOutlineLevels(rowLevels: number, columnLevels: number): void;
/**
* Returns a collection of charts that are part of the worksheet.
*/
getCharts(): Chart[];
/**
* Creates a new chart.
* @param type Represents the type of a chart. See ExcelScript.ChartType for details.
* @param sourceData The Range object corresponding to the source data.
* @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See ExcelScript.ChartSeriesBy for details.
*/
addChart(
type: ChartType,
sourceData: Range,
seriesBy?: ChartSeriesBy
): Chart;
/**
* Gets a chart using its name. If there are multiple charts with the same name, the first one will be returned. If the chart doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the chart to be retrieved.
*/
getChart(name: string): Chart | undefined;
/**
* Returns a collection of all the Comments objects on the worksheet.
*/
getComments(): Comment[];
/**
* Creates a new comment with the given content on the given cell. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
* @param cellAddress The cell to which the comment is added. This can be a Range object or a string. If it's a string, it must contain the full address, including the sheet name. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
* @param content The comment's content. This can be either a string or CommentRichContent object. Strings are used for plain text. CommentRichContent objects allow for other comment features, such as mentions.
* @param contentType Optional. The type of content contained within the comment. The default value is enum `ContentType.Plain`.
*/
addComment(
cellAddress: Range | string,
content: CommentRichContent | string,
contentType?: ContentType
): Comment;
/**
* Gets a comment from the collection based on its ID.
* @param commentId The identifier for the comment.
*/
getComment(commentId: string): Comment;
/**
* Gets the comment from the specified cell.
* @param cellAddress The cell which the comment is on. This can be a Range object or a string. If it's a string, it must contain the full address, including the sheet name. An `InvalidArgument` error is thrown if the provided range is larger than one cell.
*/
getCommentByCell(cellAddress: Range | string): Comment;
/**
* Gets the comment to which the given reply is connected.
* @param replyId The identifier of comment reply.
*/
getCommentByReplyId(replyId: string): Comment;
/**
* Gets a collection of worksheet-level custom properties.
*/
getCustomProperties(): WorksheetCustomProperty[];
/**
* Adds a new custom property that maps to the provided key. This overwrites existing custom properties with that key.
* @param key The key that identifies the custom property object. It is case-insensitive.The key is limited to 255 characters (larger values will cause an "InvalidArgument" error to be thrown.)
* @param value The value of this custom property.
*/
addWorksheetCustomProperty(
key: string,
value: string
): WorksheetCustomProperty;
/**
* Gets a custom property object by its key, which is case-insensitive. If the custom property doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key The key that identifies the custom property object. It is case-insensitive.
*/
getWorksheetCustomProperty(
key: string
): WorksheetCustomProperty | undefined;
/**
* Gets the horizontal page break collection for the worksheet. This collection only contains manual page breaks.
*/
getHorizontalPageBreaks(): PageBreak[];
/**
* Adds a page break before the top-left cell of the range specified.
* @param pageBreakRange The range immediately after the page break to be added.
*/
addHorizontalPageBreak(pageBreakRange: Range | string): PageBreak;
/**
* Resets all manual page breaks in the collection.
*/
removeAllHorizontalPageBreaks(): void;
/**
* Collection of names scoped to the current worksheet.
*/
getNames(): NamedItem[];
/**
* Adds a new name to the collection of the given scope.
* @param name The name of the named item.
* @param reference The formula or the range that the name will refer to.
* @param comment Optional. The comment associated with the named item.
*/
addNamedItem(
name: string,
reference: Range | string,
comment?: string
): NamedItem;
/**
* Adds a new name to the collection of the given scope using the user's locale for the formula.
* @param name The "name" of the named item.
* @param formula The formula in the user's locale that the name will refer to.
* @param comment Optional. The comment associated with the named item.
*/
addNamedItemFormulaLocal(
name: string,
formula: string,
comment?: string
): NamedItem;
/**
* Gets a `NamedItem` object using its name. If the object does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Nameditem name.
*/
getNamedItem(name: string): NamedItem | undefined;
/**
* Collection of PivotTables that are part of the worksheet.
*/
getPivotTables(): PivotTable[];
/**
* Add a PivotTable based on the specified source data and insert it at the top-left cell of the destination range.
* @param name The name of the new PivotTable.
* @param source The source data for the new PivotTable, this can either be a range (or string address including the worksheet name) or a table.
* @param destination The cell in the upper-left corner of the PivotTable report's destination range (the range on the worksheet where the resulting report will be placed).
*/
addPivotTable(
name: string,
source: Range | string | Table,
destination: Range | string
): PivotTable;
/**
* Gets a PivotTable by name. If the PivotTable does not exist, will return a null object.
* @param name Name of the PivotTable to be retrieved.
*/
getPivotTable(name: string): PivotTable | undefined;
/**
* Refreshes all the pivot tables in the collection.
*/
refreshAllPivotTables(): void;
/**
* Returns the collection of all the Shape objects on the worksheet.
*/
getShapes(): Shape[];
/**
* Adds a geometric shape to the worksheet. Returns a Shape object that represents the new shape.
* @param geometricShapeType Represents the type of the geometric shape. See ExcelScript.GeometricShapeType for details.
*/
addGeometricShape(geometricShapeType: GeometricShapeType): Shape;
/**
* Groups a subset of shapes in this collection's worksheet. Returns a Shape object that represents the new group of shapes.
* @param values An array of shape ID or shape objects.
*/
addGroup(values: Array<string | Shape>): Shape;
/**
* Creates an image from a base64-encoded string and adds it to the worksheet. Returns the Shape object that represents the new image.
* @param base64ImageString A base64-encoded string representing an image in either JPEG or PNG format.
*/
addImage(base64ImageString: string): Shape;
/**
* Adds a line to worksheet. Returns a Shape object that represents the new line.
* @param startLeft The distance, in points, from the start of the line to the left side of the worksheet.
* @param startTop The distance, in points, from the start of the line to the top of the worksheet.
* @param endLeft The distance, in points, from the end of the line to the left of the worksheet.
* @param endTop The distance, in points, from the end of the line to the top of the worksheet.
* @param connectorType Represents the connector type. See ExcelScript.ConnectorType for details.
*/
addLine(
startLeft: number,
startTop: number,
endLeft: number,
endTop: number,
connectorType?: ConnectorType
): Shape;
/**
* Adds a text box to the worksheet with the provided text as the content. Returns a Shape object that represents the new text box.
* @param text Represents the text that will be shown in the created text box.
*/
addTextBox(text?: string): Shape;
/**
* Gets a shape using its Name or ID.
* @param key Name or ID of the shape to be retrieved.
*/
getShape(key: string): Shape;
/**
* Returns a collection of slicers that are part of the worksheet.
*/
getSlicers(): Slicer[];
/**
* Adds a new slicer to the workbook.
* @param slicerSource The data source that the new slicer will be based on. It can be a PivotTable object, a Table object or a string. When a PivotTable object is passed, the data source is the source of the PivotTable object. When a Table object is passed, the data source is the Table object. When a string is passed, it is interpreted as the name/id of a PivotTable/Table.
* @param sourceField The field in the data source to filter by. It can be a PivotField object, a TableColumn object, the id of a PivotField or the id/name of TableColumn.
* @param slicerDestination Optional. The worksheet where the new slicer will be created in. It can be a Worksheet object or the name/id of a worksheet. This parameter can be omitted if the slicer collection is retrieved from worksheet.
*/
addSlicer(
slicerSource: string | PivotTable | Table,
sourceField: string | PivotField | number | TableColumn,
slicerDestination?: string | Worksheet
): Slicer;
/**
* Gets a slicer using its name or id. If the slicer doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Name or Id of the slicer to be retrieved.
*/
getSlicer(key: string): Slicer | undefined;
/**
* Collection of tables that are part of the worksheet.
*/
getTables(): Table[];
/**
* Create a new table. The range object or source address determines the worksheet under which the table will be added. If the table cannot be added (e.g., because the address is invalid, or the table would overlap with another table), an error will be thrown.
* @param address A Range object, or a string address or name of the range representing the data source. If the address does not contain a sheet name, the currently-active sheet is used.
* @param hasHeaders Boolean value that indicates whether the data being imported has column labels. If the source does not contain headers (i.e,. when this property set to false), Excel will automatically generate header shifting the data down by one row.
*/
addTable(address: Range | string, hasHeaders: boolean): Table;
/**
* Gets a table by Name or ID. If the table doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Name or ID of the table to be retrieved.
*/
getTable(key: string): Table | undefined;
/**
* Gets the vertical page break collection for the worksheet. This collection only contains manual page breaks.
*/
getVerticalPageBreaks(): PageBreak[];
/**
* Adds a page break before the top-left cell of the range specified.
* @param pageBreakRange The range immediately after the page break to be added.
*/
addVerticalPageBreak(pageBreakRange: Range | string): PageBreak;
/**
* Resets all manual page breaks in the collection.
*/
removeAllVerticalPageBreaks(): void;
}
/**
* Represents the protection of a sheet object.
*/
interface WorksheetProtection {
/**
* Specifies the protection options for the worksheet.
*/
getOptions(): WorksheetProtectionOptions;
/**
* Specifies if the worksheet is protected.
*/
getProtected(): boolean;
/**
* Protects a worksheet. Fails if the worksheet has already been protected.
* @param options Optional. Sheet protection options.
* @param password Optional. Sheet protection password.
*/
protect(options?: WorksheetProtectionOptions, password?: string): void;
/**
* Unprotects a worksheet.
* @param password sheet protection password.
*/
unprotect(password?: string): void;
}
interface WorksheetFreezePanes {
/**
* Sets the frozen cells in the active worksheet view.
* The range provided corresponds to cells that will be frozen in the top- and left-most pane.
* @param frozenRange A range that represents the cells to be frozen, or null to remove all frozen panes.
*/
freezeAt(frozenRange: Range | string): void;
/**
* Freeze the first column or columns of the worksheet in place.
* @param count Optional number of columns to freeze, or zero to unfreeze all columns
*/
freezeColumns(count?: number): void;
/**
* Freeze the top row or rows of the worksheet in place.
* @param count Optional number of rows to freeze, or zero to unfreeze all rows
*/
freezeRows(count?: number): void;
/**
* Gets a range that describes the frozen cells in the active worksheet view.
* The frozen range is corresponds to cells that are frozen in the top- and left-most pane.
* If there is no frozen pane, then this function will return an object with its `isNullObject` property set to `true`.
*/
getLocation(): Range;
/**
* Removes all frozen panes in the worksheet.
*/
unfreeze(): void;
}
/**
* Range represents a set of one or more contiguous cells such as a cell, a row, a column, block of cells, etc.
*/
interface Range {
/**
* Specifies the range reference in A1-style. Address value will contain the Sheet reference (e.g., "Sheet1!A1:B4").
*/
getAddress(): string;
/**
* Specifies the range reference for the specified range in the language of the user.
*/
getAddressLocal(): string;
/**
* Specifies the number of cells in the range. This API will return -1 if the cell count exceeds 2^31-1 (2,147,483,647).
*/
getCellCount(): number;
/**
* Specifies the total number of columns in the range.
*/
getColumnCount(): number;
/**
* Represents if all columns of the current range are hidden.
*/
getColumnHidden(): boolean;
/**
* Represents if all columns of the current range are hidden.
*/
setColumnHidden(columnHidden: boolean): void;
/**
* Specifies the column number of the first cell in the range. Zero-indexed.
*/
getColumnIndex(): number;
/**
* Returns a data validation object.
*/
getDataValidation(): DataValidation;
/**
* Returns a format object, encapsulating the range's font, fill, borders, alignment, and other properties.
*/
getFormat(): RangeFormat;
/**
* Represents the formula in A1-style notation. If a cell has no formula, its value is returned instead.
*/
getFormulas(): string[][];
/**
* Represents the formula in A1-style notation. If a cell has no formula, its value is returned instead.
*/
setFormulas(formulas: string[][]): void;
/**
* Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.
*/
getFormulasLocal(): string[][];
/**
* Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German. If a cell has no formula, its value is returned instead.
*/
setFormulasLocal(formulasLocal: string[][]): void;
/**
* Represents the formula in R1C1-style notation. If a cell has no formula, its value is returned instead.
*/
getFormulasR1C1(): string[][];
/**
* Represents the formula in R1C1-style notation. If a cell has no formula, its value is returned instead.
*/
setFormulasR1C1(formulasR1C1: string[][]): void;
/**
* Represents if all cells have a spill border.
* Returns true if all cells have a spill border, or false if all cells do not have a spill border.
* Returns null if there are cells both with and without spill borders within the range.
*/
getHasSpill(): boolean;
/**
* Returns the distance in points, for 100% zoom, from top edge of the range to bottom edge of the range.
*/
getHeight(): number;
/**
* Represents if all cells of the current range are hidden.
*/
getHidden(): boolean;
/**
* Represents the hyperlink for the current range.
*/
getHyperlink(): RangeHyperlink;
/**
* Represents the hyperlink for the current range.
*/
setHyperlink(hyperlink: RangeHyperlink): void;
/**
* Represents if the current range is an entire column.
*/
getIsEntireColumn(): boolean;
/**
* Represents if the current range is an entire row.
*/
getIsEntireRow(): boolean;
/**
* Returns the distance in points, for 100% zoom, from left edge of the worksheet to left edge of the range.
*/
getLeft(): number;
/**
* Represents the data type state of each cell.
*/
getLinkedDataTypeStates(): LinkedDataTypeState[][];
/**
* Represents Excel's number format code for the given range.
*/
getNumberFormats(): string[][];
/**
* Represents Excel's number format code for the given range.
*/
setNumberFormats(numberFormats: string[][]): void;
/**
* Represents the category of number format of each cell.
*/
getNumberFormatCategories(): NumberFormatCategory[][];
/**
* Represents Excel's number format code for the given range, based on the language settings of the user.
* Excel does not perform any language or format coercion when getting or setting the `numberFormatLocal` property.
* Any returned text uses the locally-formatted strings based on the language specified in the system settings.
*/
getNumberFormatsLocal(): string[][];
/**
* Represents Excel's number format code for the given range, based on the language settings of the user.
* Excel does not perform any language or format coercion when getting or setting the `numberFormatLocal` property.
* Any returned text uses the locally-formatted strings based on the language specified in the system settings.
*/
setNumberFormatsLocal(numberFormatsLocal: string[][]): void;
/**
* Returns the total number of rows in the range.
*/
getRowCount(): number;
/**
* Represents if all rows of the current range are hidden.
*/
getRowHidden(): boolean;
/**
* Represents if all rows of the current range are hidden.
*/
setRowHidden(rowHidden: boolean): void;
/**
* Returns the row number of the first cell in the range. Zero-indexed.
*/
getRowIndex(): number;
/**
* Represents if ALL the cells would be saved as an array formula.
* Returns true if ALL cells would be saved as an array formula, or false if ALL cells would NOT be saved as an array formula.
* Returns null if some cells would be saved as an array formula and some would not be.
*/
getSavedAsArray(): boolean;
/**
* Represents the range sort of the current range.
*/
getSort(): RangeSort;
/**
* Represents the style of the current range.
* If the styles of the cells are inconsistent, null will be returned.
* For custom styles, the style name will be returned. For built-in styles, a string representing a value in the BuiltInStyle enum will be returned.
*/
getPredefinedCellStyle(): string;
/**
* Represents the style of the current range.
* If the styles of the cells are inconsistent, null will be returned.
* For custom styles, the style name will be returned. For built-in styles, a string representing a value in the BuiltInStyle enum will be returned.
*/
setPredefinedCellStyle(predefinedCellStyle: string): void;
/**
* Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API.
*/
getTexts(): string[][];
/**
* Returns the distance in points, for 100% zoom, from top edge of the worksheet to top edge of the range.
*/
getTop(): number;
/**
* Specifies the type of data in each cell.
*/
getValueTypes(): RangeValueType[][];
/**
* Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string.
*/
getValues(): (string | number | boolean)[][];
/**
* Represents the raw values of the specified range. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string.
*/
setValues(values: (string | number | boolean)[][]): void;
/**
* Returns the distance in points, for 100% zoom, from left edge of the range to right edge of the range.
*/
getWidth(): number;
/**
* The worksheet containing the current range.
*/
getWorksheet(): Worksheet;
/**
* Fills range from the current range to the destination range using the specified AutoFill logic.
* The destination range can be null, or can extend the source either horizontally or vertically.
* Discontiguous ranges are not supported.
*
* @param destinationRange The destination range to autofill. If the destination range is null, data is filled out based on the surrounding cells (which is the behavior when double-clicking the UI’s range fill handle).
* @param autoFillType The type of autofill. Specifies how the destination range is to be filled, based on the contents of the current range. Default is "FillDefault".
*/
autoFill(
destinationRange?: Range | string,
autoFillType?: AutoFillType
): void;
/**
* Calculates a range of cells on a worksheet.
*/
calculate(): void;
/**
* Clear range values, format, fill, border, etc.
* @param applyTo Optional. Determines the type of clear action. See ExcelScript.ClearApplyTo for details.
*/
clear(applyTo?: ClearApplyTo): void;
/**
* Converts the range cells with datatypes into text.
*/
convertDataTypeToText(): void;
/**
* Copies cell data or formatting from the source range or RangeAreas to the current range.
* The destination range can be a different size than the source range or RangeAreas. The destination will be expanded automatically if it is smaller than the source.
* @param sourceRange The source range or RangeAreas to copy from. When the source RangeAreas has multiple ranges, their form must be able to be created by removing full rows or columns from a rectangular range.
* @param copyType The type of cell data or formatting to copy over. Default is "All".
* @param skipBlanks True if to skip blank cells in the source range. Default is false.
* @param transpose True if to transpose the cells in the destination range. Default is false.
*/
copyFrom(
sourceRange: Range | RangeAreas | string,
copyType?: RangeCopyType,
skipBlanks?: boolean,
transpose?: boolean
): void;
/**
* Deletes the cells associated with the range.
* @param shift Specifies which way to shift the cells. See ExcelScript.DeleteShiftDirection for details.
*/
delete(shift: DeleteShiftDirection): void;
/**
* Finds the given string based on the criteria specified.
* If the current range is larger than a single cell, then the search will be limited to that range, else the search will cover the entire sheet starting after that cell.
* If there are no matches, then this function will return an object with its `isNullObject` property set to `true`.
* @param text The string to find.
* @param criteria Additional search criteria, including the search direction and whether the search needs to match the entire cell or be case sensitive.
*/
find(text: string, criteria: SearchCriteria): Range;
/**
* Does FlashFill to current range.Flash Fill will automatically fills data when it senses a pattern, so the range must be single column range and have data around in order to find pattern.
*/
flashFill(): void;
/**
* Gets a Range object with the same top-left cell as the current Range object, but with the specified numbers of rows and columns.
* @param numRows The number of rows of the new range size.
* @param numColumns The number of columns of the new range size.
*/
getAbsoluteResizedRange(numRows: number, numColumns: number): Range;
/**
* Gets the smallest range object that encompasses the given ranges. For example, the GetBoundingRect of "B2:C5" and "D10:E15" is "B2:E15".
* @param anotherRange The range object or address or range name.
*/
getBoundingRect(anotherRange: Range | string): Range;
/**
* Gets the range object containing the single cell based on row and column numbers. The cell can be outside the bounds of its parent range, so long as it stays within the worksheet grid. The returned cell is located relative to the top left cell of the range.
* @param row Row number of the cell to be retrieved. Zero-indexed.
* @param column Column number of the cell to be retrieved. Zero-indexed.
*/
getCell(row: number, column: number): Range;
/**
* Gets a column contained in the range.
* @param column Column number of the range to be retrieved. Zero-indexed.
*/
getColumn(column: number): Range;
/**
* Gets a certain number of columns to the right of the current Range object.
* @param count Optional. The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1.
*/
getColumnsAfter(count?: number): Range;
/**
* Gets a certain number of columns to the left of the current Range object.
* @param count Optional. The number of columns to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1.
*/
getColumnsBefore(count?: number): Range;
/**
* Returns a WorkbookRangeAreas object that represents the range containing all the direct precedents of a cell in same worksheet or in multiple worksheets.
*/
getDirectPrecedents(): WorkbookRangeAreas;
/**
* Gets an object that represents the entire column of the range (for example, if the current range represents cells "B4:E11", its `getEntireColumn` is a range that represents columns "B:E").
*/
getEntireColumn(): Range;
/**
* Gets an object that represents the entire row of the range (for example, if the current range represents cells "B4:E11", its `GetEntireRow` is a range that represents rows "4:11").
*/
getEntireRow(): Range;
/**
* Renders the range as a base64-encoded png image.
* **Important**: This API is currently unsupported in Excel for Mac. Visit [OfficeDev/office-js Issue #235](https://github.com/OfficeDev/office-js/issues/235) for the current status.
*/
getImage(): string;
/**
* Gets the range object that represents the rectangular intersection of the given ranges. If no intersection is found, then this function will return an object with its `isNullObject` property set to `true`.
* @param anotherRange The range object or range address that will be used to determine the intersection of ranges.
*/
getIntersection(anotherRange: Range | string): Range;
/**
* Gets the last cell within the range. For example, the last cell of "B2:D5" is "D5".
*/
getLastCell(): Range;
/**
* Gets the last column within the range. For example, the last column of "B2:D5" is "D2:D5".
*/
getLastColumn(): Range;
/**
* Gets the last row within the range. For example, the last row of "B2:D5" is "B5:D5".
*/
getLastRow(): Range;
/**
* Returns a RangeAreas object that represents the merged areas in this range. Note that if the merged areas count in this range is more than 512, the API will fail to return the result.
*/
getMergedAreas(): RangeAreas;
/**
* Gets an object which represents a range that's offset from the specified range. The dimension of the returned range will match this range. If the resulting range is forced outside the bounds of the worksheet grid, an error will be thrown.
* @param rowOffset The number of rows (positive, negative, or 0) by which the range is to be offset. Positive values are offset downward, and negative values are offset upward.
* @param columnOffset The number of columns (positive, negative, or 0) by which the range is to be offset. Positive values are offset to the right, and negative values are offset to the left.
*/
getOffsetRange(rowOffset: number, columnOffset: number): Range;
/**
* Gets a scoped collection of PivotTables that overlap with the range.
* @param fullyContained If true, returns only PivotTables that are fully contained within the range bounds. The default value is false.
*/
getPivotTables(fullyContained?: boolean): PivotTable[];
/**
* Gets a Range object similar to the current Range object, but with its bottom-right corner expanded (or contracted) by some number of rows and columns.
* @param deltaRows The number of rows by which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it.
* @param deltaColumns The number of columns by which to expand the bottom-right corner, relative to the current range. Use a positive number to expand the range, or a negative number to decrease it.
*/
getResizedRange(deltaRows: number, deltaColumns: number): Range;
/**
* Gets a row contained in the range.
* @param row Row number of the range to be retrieved. Zero-indexed.
*/
getRow(row: number): Range;
/**
* Gets a certain number of rows above the current Range object.
* @param count Optional. The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1.
*/
getRowsAbove(count?: number): Range;
/**
* Gets a certain number of rows below the current Range object.
* @param count Optional. The number of rows to include in the resulting range. In general, use a positive number to create a range outside the current range. You can also use a negative number to create a range within the current range. The default value is 1.
*/
getRowsBelow(count?: number): Range;
/**
* Gets the RangeAreas object, comprising one or more ranges, that represents all the cells that match the specified type and value.
* If no special cells are found, then this function will return an object with its `isNullObject` property set to `true`.
* @param cellType The type of cells to include.
* @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type.
*/
getSpecialCells(
cellType: SpecialCellType,
cellValueType?: SpecialCellValueType
): RangeAreas;
/**
* Gets the range object containing the anchor cell for the cell getting spilled into.
* If it's not a spilled cell, or more than one cell is given, then this function will return an object with its `isNullObject` property set to `true`.
*/
getSpillParent(): Range;
/**
* Gets the range object containing the spill range when called on an anchor cell.
* If the range isn't an anchor cell or the spill range can't be found, then this function will return an object with its `isNullObject` property set to `true`.
*/
getSpillingToRange(): Range;
/**
* Returns a Range object that represents the surrounding region for the top-left cell in this range. A surrounding region is a range bounded by any combination of blank rows and blank columns relative to this range.
*/
getSurroundingRegion(): Range;
/**
* Gets a scoped collection of tables that overlap with the range.
* @param fullyContained If true, returns only tables that are fully contained within the range bounds. The default value is false.
*/
getTables(fullyContained?: boolean): Table[];
/**
* Returns the used range of the given range object. If there are no used cells within the range, then this function will return an object with its `isNullObject` property set to `true`.
* @param valuesOnly Considers only cells with values as used cells.
*/
getUsedRange(valuesOnly?: boolean): Range;
/**
* Represents the visible rows of the current range.
*/
getVisibleView(): RangeView;
/**
* Groups columns and rows for an outline.
* @param groupOption Specifies how the range can be grouped by rows or columns.
* An `InvalidArgument` error is thrown when the group option differs from the range's
* `isEntireRow` or `isEntireColumn` property (i.e., `range.isEntireRow` is true and `groupOption` is "ByColumns"
* or `range.isEntireColumn` is true and `groupOption` is "ByRows").
*/
group(groupOption: GroupOption): void;
/**
* Hide details of the row or column group.
* @param groupOption Specifies whether to hide details of grouped rows or grouped columns.
*/
hideGroupDetails(groupOption: GroupOption): void;
/**
* Inserts a cell or a range of cells into the worksheet in place of this range, and shifts the other cells to make space. Returns a new Range object at the now blank space.
* @param shift Specifies which way to shift the cells. See ExcelScript.InsertShiftDirection for details.
*/
insert(shift: InsertShiftDirection): Range;
/**
* Merge the range cells into one region in the worksheet.
* @param across Optional. Set true to merge cells in each row of the specified range as separate merged cells. The default value is false.
*/
merge(across?: boolean): void;
/**
* Moves cell values, formatting, and formulas from current range to the destination range, replacing the old information in those cells.
* The destination range will be expanded automatically if it is smaller than the current range. Any cells in the destination range that are outside of the original range's area are not changed.
* @param destinationRange destinationRange Specifies the range to where the information in this range will be moved.
*/
moveTo(destinationRange: Range | string): void;
/**
* Removes duplicate values from the range specified by the columns.
* @param columns The columns inside the range that may contain duplicates. At least one column needs to be specified. Zero-indexed.
* @param includesHeader True if the input data contains header. Default is false.
*/
removeDuplicates(
columns: number[],
includesHeader: boolean
): RemoveDuplicatesResult;
/**
* Finds and replaces the given string based on the criteria specified within the current range.
* @param text String to find.
* @param replacement String to replace the original with.
* @param criteria Additional Replace Criteria.
*/
replaceAll(
text: string,
replacement: string,
criteria: ReplaceCriteria
): number;
/**
* Selects the specified range in the Excel UI.
*/
select(): void;
/**
* Set a range to be recalculated when the next recalculation occurs.
*/
setDirty(): void;
/**
* Displays the card for an active cell if it has rich value content.
*/
showCard(): void;
/**
* Show details of the row or column group.
* @param groupOption Specifies whether to show details of grouped rows or grouped columns.
*/
showGroupDetails(groupOption: GroupOption): void;
/**
* Ungroups columns and rows for an outline.
* @param groupOption Specifies how the range can be ungrouped by rows or columns.
*/
ungroup(groupOption: GroupOption): void;
/**
* Unmerge the range cells into separate cells.
*/
unmerge(): void;
/**
* The collection of ConditionalFormats that intersect the range.
*/
getConditionalFormats(): ConditionalFormat[];
/**
* Adds a new conditional format to the collection at the first/top priority.
* @param type The type of conditional format being added. See ExcelScript.ConditionalFormatType for details.
*/
addConditionalFormat(type: ConditionalFormatType): ConditionalFormat;
/**
* Clears all conditional formats active on the current specified range.
*/
clearAllConditionalFormats(): void;
/**
* Returns a conditional format for the given ID.
* @param id The id of the conditional format.
*/
getConditionalFormat(id: string): ConditionalFormat;
/**
* Represents the cell formula in A1-style notation.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getFormula(): string;
/**
* Sets the cell formula in A1-style notation.
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setFormula(formula: string): void;
/**
* Represents the cell formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getFormulaLocal(): string;
/**
* Set the cell formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German.
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setFormulaLocal(formulaLocal: string): void;
/**
* Represents the cell formula in R1C1-style notation.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getFormulaR1C1(): string;
/**
* Sets the cell formula in R1C1-style notation.
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setFormulaR1C1(formulaR1C1: string): void;
/**
* Represents the data type state of the cell.
*/
getLinkedDataTypeState(): LinkedDataTypeState;
/**
* Represents cell Excel number format code for the given range.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getNumberFormat(): string;
/**
* Sets cell Excel number format code for the given range.
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setNumberFormat(numberFormat: string): void;
/**
* Represents cell Excel number format code for the given range, based on the language settings of the user.
* Excel does not perform any language or format coercion when getting or setting the `numberFormatLocal` property.
* Any returned text uses the locally-formatted strings based on the language specified in the system settings.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getNumberFormatLocal(): string;
/**
* Sets cell Excel number format code for the given range, based on the language settings of the user.
* Excel does not perform any language or format coercion when getting or setting the `numberFormatLocal` property.
* Any returned text uses the locally-formatted strings based on the language specified in the system settings.
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setNumberFormatLocal(numberFormatLocal: string): void;
/**
* Represents Text value of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getText(): string;
/**
* Represents the type of data in the cell.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getValueType(): RangeValueType;
/**
* Represents the raw value of the specified range. The data returned could be of type string, number, or a boolean. Cell that contain an error will return the error string.
* If the range contains multiple cells, the data from first cell (represented by row index of 0 and column index of 0) will be returned.
*/
getValue(): string | number | boolean;
/**
* Sets the raw value of the specified range. The data being set could be of type string, number, or a boolean. `null` value will be ignored (not set or overwritten in Excel).
* If the range contains multiple cells, each cell in the given range will be updated with the input data.
*/
setValue(value: any): void;
}
/**
* RangeAreas represents a collection of one or more rectangular ranges in the same worksheet.
*/
interface RangeAreas {
/**
* Returns the RangeAreas reference in A1-style. Address value will contain the worksheet name for each rectangular block of cells (e.g., "Sheet1!A1:B4, Sheet1!D1:D4").
*/
getAddress(): string;
/**
* Returns the RangeAreas reference in the user locale.
*/
getAddressLocal(): string;
/**
* Returns the number of rectangular ranges that comprise this RangeAreas object.
*/
getAreaCount(): number;
/**
* Returns the number of cells in the RangeAreas object, summing up the cell counts of all of the individual rectangular ranges. Returns -1 if the cell count exceeds 2^31-1 (2,147,483,647).
*/
getCellCount(): number;
/**
* Returns a dataValidation object for all ranges in the RangeAreas.
*/
getDataValidation(): DataValidation;
/**
* Returns a RangeFormat object, encapsulating the the font, fill, borders, alignment, and other properties for all ranges in the RangeAreas object.
*/
getFormat(): RangeFormat;
/**
* Specifies if all the ranges on this RangeAreas object represent entire columns (e.g., "A:C, Q:Z").
*/
getIsEntireColumn(): boolean;
/**
* Specifies if all the ranges on this RangeAreas object represent entire rows (e.g., "1:3, 5:7").
*/
getIsEntireRow(): boolean;
/**
* Represents the style for all ranges in this RangeAreas object.
* If the styles of the cells are inconsistent, null will be returned.
* For custom styles, the style name will be returned. For built-in styles, a string representing a value in the BuiltInStyle enum will be returned.
*/
getPredefinedCellStyle(): string;
/**
* Represents the style for all ranges in this RangeAreas object.
* If the styles of the cells are inconsistent, null will be returned.
* For custom styles, the style name will be returned. For built-in styles, a string representing a value in the BuiltInStyle enum will be returned.
*/
setPredefinedCellStyle(predefinedCellStyle: string): void;
/**
* Returns the worksheet for the current RangeAreas.
*/
getWorksheet(): Worksheet;
/**
* Calculates all cells in the RangeAreas.
*/
calculate(): void;
/**
* Clears values, format, fill, border, etc on each of the areas that comprise this RangeAreas object.
* @param applyTo Optional. Determines the type of clear action. See ExcelScript.ClearApplyTo for details. Default is "All".
*/
clear(applyTo?: ClearApplyTo): void;
/**
* Converts all cells in the RangeAreas with datatypes into text.
*/
convertDataTypeToText(): void;
/**
* Copies cell data or formatting from the source range or RangeAreas to the current RangeAreas.
* The destination rangeAreas can be a different size than the source range or RangeAreas. The destination will be expanded automatically if it is smaller than the source.
* @param sourceRange The source range or RangeAreas to copy from. When the source RangeAreas has multiple ranges, their form must able to be created by removing full rows or columns from a rectangular range.
* @param copyType The type of cell data or formatting to copy over. Default is "All".
* @param skipBlanks True if to skip blank cells in the source range or RangeAreas. Default is false.
* @param transpose True if to transpose the cells in the destination RangeAreas. Default is false.
*/
copyFrom(
sourceRange: Range | RangeAreas | string,
copyType?: RangeCopyType,
skipBlanks?: boolean,
transpose?: boolean
): void;
/**
* Returns a RangeAreas object that represents the entire columns of the RangeAreas (for example, if the current RangeAreas represents cells "B4:E11, H2", it returns a RangeAreas that represents columns "B:E, H:H").
*/
getEntireColumn(): RangeAreas;
/**
* Returns a RangeAreas object that represents the entire rows of the RangeAreas (for example, if the current RangeAreas represents cells "B4:E11", it returns a RangeAreas that represents rows "4:11").
*/
getEntireRow(): RangeAreas;
/**
* Returns the RangeAreas object that represents the intersection of the given ranges or RangeAreas. If no intersection is found, then this function will return an object with its `isNullObject` property set to `true`.
* @param anotherRange The range, RangeAreas, or address that will be used to determine the intersection.
*/
getIntersection(anotherRange: Range | RangeAreas | string): RangeAreas;
/**
* Returns an RangeAreas object that is shifted by the specific row and column offset. The dimension of the returned RangeAreas will match the original object. If the resulting RangeAreas is forced outside the bounds of the worksheet grid, an error will be thrown.
* @param rowOffset The number of rows (positive, negative, or 0) by which the RangeAreas is to be offset. Positive values are offset downward, and negative values are offset upward.
* @param columnOffset The number of columns (positive, negative, or 0) by which the RangeAreas is to be offset. Positive values are offset to the right, and negative values are offset to the left.
*/
getOffsetRangeAreas(
rowOffset: number,
columnOffset: number
): RangeAreas;
/**
* Returns a RangeAreas object that represents all the cells that match the specified type and value. Returns a null object if no special cells are found that match the criteria.
* @param cellType The type of cells to include.
* @param cellValueType If cellType is either Constants or Formulas, this argument is used to determine which types of cells to include in the result. These values can be combined together to return more than one type. The default is to select all constants or formulas, no matter what the type.
*/
getSpecialCells(
cellType: SpecialCellType,
cellValueType?: SpecialCellValueType
): RangeAreas;
/**
* Returns a scoped collection of tables that overlap with any range in this RangeAreas object.
* @param fullyContained If true, returns only tables that are fully contained within the range bounds. Default is false.
*/
getTables(fullyContained?: boolean): Table[];
/**
* Returns the used RangeAreas that comprises all the used areas of individual rectangular ranges in the RangeAreas object.
* If there are no used cells within the RangeAreas, then this function will return an object with its `isNullObject` property set to `true`.
* @param valuesOnly Whether to only consider cells with values as used cells.
*/
getUsedRangeAreas(valuesOnly?: boolean): RangeAreas;
/**
* Sets the RangeAreas to be recalculated when the next recalculation occurs.
*/
setDirty(): void;
/**
* Returns a collection of rectangular ranges that comprise this RangeAreas object.
*/
getAreas(): Range[];
/**
* Returns a collection of ConditionalFormats that intersect with any cells in this RangeAreas object.
*/
getConditionalFormats(): ConditionalFormat[];
/**
* Adds a new conditional format to the collection at the first/top priority.
* @param type The type of conditional format being added. See ExcelScript.ConditionalFormatType for details.
*/
addConditionalFormat(type: ConditionalFormatType): ConditionalFormat;
/**
* Clears all conditional formats active on the current specified range.
*/
clearAllConditionalFormats(): void;
/**
* Returns a conditional format for the given ID.
* @param id The id of the conditional format.
*/
getConditionalFormat(id: string): ConditionalFormat;
}
/**
* Represents a collection of one or more rectangular ranges in multiple worksheets.
*/
interface WorkbookRangeAreas {
/**
* Returns an array of address in A1-style. Address value will contain the worksheet name for each rectangular block of cells (e.g., "Sheet1!A1:B4, Sheet1!D1:D4"). Read-only.
*/
getAddresses(): string[];
/**
* Returns the RangeAreas object based on worksheet name or id in the collection. If the worksheet does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key The name or id of the worksheet.
*/
getRangeAreasBySheet(key: string): RangeAreas;
/**
* Returns the RangeAreasCollection object, each RangeAreas in the collection represent one or more rectangle ranges in one worksheet.
*/
getAreas(): RangeAreas[];
/**
* Returns ranges that comprise this object in a RangeCollection object.
*/
getRanges(): Range[];
}
/**
* RangeView represents a set of visible cells of the parent range.
*/
interface RangeView {
/**
* Represents the cell addresses of the RangeView.
*/
getCellAddresses(): string[][];
/**
* The number of visible columns.
*/
getColumnCount(): number;
/**
* Represents the formula in A1-style notation.
*/
getFormulas(): string[][];
/**
* Represents the formula in A1-style notation.
*/
setFormulas(formulas: string[][]): void;
/**
* Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German.
*/
getFormulasLocal(): string[][];
/**
* Represents the formula in A1-style notation, in the user's language and number-formatting locale. For example, the English "=SUM(A1, 1.5)" formula would become "=SUMME(A1; 1,5)" in German.
*/
setFormulasLocal(formulasLocal: string[][]): void;
/**
* Represents the formula in R1C1-style notation.
*/
getFormulasR1C1(): string[][];
/**
* Represents the formula in R1C1-style notation.
*/
setFormulasR1C1(formulasR1C1: string[][]): void;
/**
* Returns a value that represents the index of the RangeView.
*/
getIndex(): number;
/**
* Represents Excel's number format code for the given cell.
*/
getNumberFormat(): string[][];
/**
* Represents Excel's number format code for the given cell.
*/
setNumberFormat(numberFormat: string[][]): void;
/**
* The number of visible rows.
*/
getRowCount(): number;
/**
* Text values of the specified range. The Text value will not depend on the cell width. The # sign substitution that happens in Excel UI will not affect the text value returned by the API.
*/
getText(): string[][];
/**
* Represents the type of data of each cell.
*/
getValueTypes(): RangeValueType[][];
/**
* Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string.
*/
getValues(): (string | number | boolean)[][];
/**
* Represents the raw values of the specified range view. The data returned could be of type string, number, or a boolean. Cells that contain an error will return the error string.
*/
setValues(values: (string | number | boolean)[][]): void;
/**
* Gets the parent range associated with the current RangeView.
*/
getRange(): Range;
/**
* Represents a collection of range views associated with the range.
*/
getRows(): RangeView[];
}
/**
* Represents a defined name for a range of cells or value. Names can be primitive named objects (as seen in the type below), range object, or a reference to a range. This object can be used to obtain range object associated with names.
*/
interface NamedItem {
/**
* Returns an object containing values and types of the named item.
*/
getArrayValues(): NamedItemArrayValues;
/**
* Specifies the comment associated with this name.
*/
getComment(): string;
/**
* Specifies the comment associated with this name.
*/
setComment(comment: string): void;
/**
* The formula of the named item. Formula always starts with a '=' sign.
*/
getFormula(): string;
/**
* The formula of the named item. Formula always starts with a '=' sign.
*/
setFormula(formula: string): void;
/**
* The name of the object.
*/
getName(): string;
/**
* Specifies if the name is scoped to the workbook or to a specific worksheet. Possible values are: Worksheet, Workbook.
*/
getScope(): NamedItemScope;
/**
* Specifies the type of the value returned by the name's formula. See ExcelScript.NamedItemType for details.
*/
getType(): NamedItemType;
/**
* Represents the value computed by the name's formula. For a named range, will return the range address.
*/
getValue(): string | number;
/**
* Specifies if the object is visible.
*/
getVisible(): boolean;
/**
* Specifies if the object is visible.
*/
setVisible(visible: boolean): void;
/**
* Returns the worksheet to which the named item is scoped. If the item is scoped to the workbook instead, then this function will return an object with its `isNullObject` property set to `true`.
*/
getWorksheet(): Worksheet | undefined;
/**
* Deletes the given name.
*/
delete(): void;
/**
* Returns the range object that is associated with the name. If the named item's type is not a range, then this function will return an object with its `isNullObject` property set to `true`.
*/
getRange(): Range;
}
/**
* Represents an object containing values and types of a named item.
*/
interface NamedItemArrayValues {
/**
* Represents the types for each item in the named item array
*/
getTypes(): RangeValueType[][];
/**
* Represents the values of each item in the named item array.
*/
getValues(): (string | number | boolean)[][];
}
/**
* Represents an Office.js binding that is defined in the workbook.
*/
interface Binding {
/**
* Represents binding identifier.
*/
getId(): string;
/**
* Returns the type of the binding. See ExcelScript.BindingType for details.
*/
getType(): BindingType;
/**
* Deletes the binding.
*/
delete(): void;
/**
* Returns the range represented by the binding. Will throw an error if binding is not of the correct type.
*/
getRange(): Range;
/**
* Returns the table represented by the binding. Will throw an error if binding is not of the correct type.
*/
getTable(): Table;
/**
* Returns the text represented by the binding. Will throw an error if binding is not of the correct type.
*/
getText(): string;
}
/**
* Represents an Excel table.
*/
interface Table {
/**
* Represents the AutoFilter object of the table.
*/
getAutoFilter(): AutoFilter;
/**
* Specifies if the first column contains special formatting.
*/
getHighlightFirstColumn(): boolean;
/**
* Specifies if the first column contains special formatting.
*/
setHighlightFirstColumn(highlightFirstColumn: boolean): void;
/**
* Specifies if the last column contains special formatting.
*/
getHighlightLastColumn(): boolean;
/**
* Specifies if the last column contains special formatting.
*/
setHighlightLastColumn(highlightLastColumn: boolean): void;
/**
* Returns a value that uniquely identifies the table in a given workbook. The value of the identifier remains the same even when the table is renamed.
*/
getId(): string;
/**
* Returns a numeric id.
*/
getLegacyId(): string;
/**
* Name of the table.
*
*/
getName(): string;
/**
* Name of the table.
*
*/
setName(name: string): void;
/**
* Specifies if the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier.
*/
getShowBandedColumns(): boolean;
/**
* Specifies if the columns show banded formatting in which odd columns are highlighted differently from even ones to make reading the table easier.
*/
setShowBandedColumns(showBandedColumns: boolean): void;
/**
* Specifies if the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier.
*/
getShowBandedRows(): boolean;
/**
* Specifies if the rows show banded formatting in which odd rows are highlighted differently from even ones to make reading the table easier.
*/
setShowBandedRows(showBandedRows: boolean): void;
/**
* Specifies if the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row.
*/
getShowFilterButton(): boolean;
/**
* Specifies if the filter buttons are visible at the top of each column header. Setting this is only allowed if the table contains a header row.
*/
setShowFilterButton(showFilterButton: boolean): void;
/**
* Specifies if the header row is visible. This value can be set to show or remove the header row.
*/
getShowHeaders(): boolean;
/**
* Specifies if the header row is visible. This value can be set to show or remove the header row.
*/
setShowHeaders(showHeaders: boolean): void;
/**
* Specifies if the total row is visible. This value can be set to show or remove the total row.
*/
getShowTotals(): boolean;
/**
* Specifies if the total row is visible. This value can be set to show or remove the total row.
*/
setShowTotals(showTotals: boolean): void;
/**
* Represents the sorting for the table.
*/
getSort(): TableSort;
/**
* Constant value that represents the Table style. Possible values are: "TableStyleLight1" through "TableStyleLight21", "TableStyleMedium1" through "TableStyleMedium28", "TableStyleDark1" through "TableStyleDark11". A custom user-defined style present in the workbook can also be specified.
*/
getPredefinedTableStyle(): string;
/**
* Constant value that represents the Table style. Possible values are: "TableStyleLight1" through "TableStyleLight21", "TableStyleMedium1" through "TableStyleMedium28", "TableStyleDark1" through "TableStyleDark11". A custom user-defined style present in the workbook can also be specified.
*/
setPredefinedTableStyle(predefinedTableStyle: string): void;
/**
* The worksheet containing the current table.
*/
getWorksheet(): Worksheet;
/**
* Clears all the filters currently applied on the table.
*/
clearFilters(): void;
/**
* Converts the table into a normal range of cells. All data is preserved.
*/
convertToRange(): Range;
/**
* Deletes the table.
*/
delete(): void;
/**
* Gets the range object associated with the data body of the table.
*/
getRangeBetweenHeaderAndTotal(): Range;
/**
* Gets the range object associated with header row of the table.
*/
getHeaderRowRange(): Range;
/**
* Gets the range object associated with the entire table.
*/
getRange(): Range;
/**
* Gets the range object associated with totals row of the table.
*/
getTotalRowRange(): Range;
/**
* Reapplies all the filters currently on the table.
*/
reapplyFilters(): void;
/**
* Represents a collection of all the columns in the table.
*/
getColumns(): TableColumn[];
/**
* Gets a column object by Name or ID. If the column doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Column Name or ID.
*/
getColumn(key: number | string): TableColumn | undefined;
/**
* Adds one row to the table.
* @param index Optional. Specifies the relative position of the new row. If null or -1, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed.
* @param values Optional. A 1-dimensional array of unformatted values of the table row.
*/
addRow(index?: number, values?: (boolean | string | number)[]): void;
/**
* Adds one or more rows to the table.
* @param index Optional. Specifies the relative position of the new row. If null or -1, the addition happens at the end. Any rows below the inserted row are shifted downwards. Zero-indexed.
* @param values Optional. A 2-dimensional array of unformatted values of the table row.
*/
addRows(index?: number, values?: (boolean | string | number)[][]): void;
/**
* Adds a new column to the table.
* @param index Optional. Specifies the relative position of the new column. If null or -1, the addition happens at the end. Columns with a higher index will be shifted to the side. Zero-indexed.
* @param values Optional. A 1-dimensional array of unformatted values of the table column.
* @param name Optional. Specifies the name of the new column. If null, the default name will be used.
*/
addColumn(
index?: number,
values?: (boolean | string | number)[],
name?: string
): TableColumn;
/**
* Delete a specified number of rows at a given index.
* @param index The index value of the row to be deleted. Caution: the index of the row may have moved from the time you determined the value to use for removal.
* @param count Number of rows to delete. By default, a single row will be deleted.
*/
deleteRowsAt(index: number, count?: number): void;
/**
* Gets a column object by ID. If the column does not exist, will return undefined.
* @param key Column ID.
*/
getColumnById(key: number): TableColumn | undefined;
/**
* Gets a column object by Name. If the column does not exist, will return undefined.
* @param key Column Name.
*/
getColumnByName(key: string): TableColumn | undefined;
/**
* Gets the number of rows in the table.
*/
getRowCount(): number;
}
/**
* Represents a column in a table.
*/
interface TableColumn {
/**
* Retrieve the filter applied to the column.
*/
getFilter(): Filter;
/**
* Returns a unique key that identifies the column within the table.
*/
getId(): number;
/**
* Returns the index number of the column within the columns collection of the table. Zero-indexed.
*/
getIndex(): number;
/**
* Specifies the name of the table column.
*/
getName(): string;
/**
* Specifies the name of the table column.
*/
setName(name: string): void;
/**
* Deletes the column from the table.
*/
delete(): void;
/**
* Gets the range object associated with the data body of the column.
*/
getRangeBetweenHeaderAndTotal(): Range;
/**
* Gets the range object associated with the header row of the column.
*/
getHeaderRowRange(): Range;
/**
* Gets the range object associated with the entire column.
*/
getRange(): Range;
/**
* Gets the range object associated with the totals row of the column.
*/
getTotalRowRange(): Range;
}
/**
* Represents the data validation applied to the current range.
*/
interface DataValidation {
/**
* Error alert when user enters invalid data.
*/
getErrorAlert(): DataValidationErrorAlert;
/**
* Error alert when user enters invalid data.
*/
setErrorAlert(errorAlert: DataValidationErrorAlert): void;
/**
* Specifies if data validation will be performed on blank cells, it defaults to true.
*/
getIgnoreBlanks(): boolean;
/**
* Specifies if data validation will be performed on blank cells, it defaults to true.
*/
setIgnoreBlanks(ignoreBlanks: boolean): void;
/**
* Prompt when users select a cell.
*/
getPrompt(): DataValidationPrompt;
/**
* Prompt when users select a cell.
*/
setPrompt(prompt: DataValidationPrompt): void;
/**
* Data validation rule that contains different type of data validation criteria.
*/
getRule(): DataValidationRule;
/**
* Data validation rule that contains different type of data validation criteria.
*/
setRule(rule: DataValidationRule): void;
/**
* Type of the data validation, see ExcelScript.DataValidationType for details.
*/
getType(): DataValidationType;
/**
* Represents if all cell values are valid according to the data validation rules.
* Returns true if all cell values are valid, or false if all cell values are invalid.
* Returns null if there are both valid and invalid cell values within the range.
*/
getValid(): boolean;
/**
* Clears the data validation from the current range.
*/
clear(): void;
/**
* Returns a RangeAreas, comprising one or more rectangular ranges, with invalid cell values. If all cell values are valid, this function will return null.
*/
getInvalidCells(): RangeAreas;
}
/**
* Represents the results from the removeDuplicates method on range
*/
interface RemoveDuplicatesResult {
/**
* Number of duplicated rows removed by the operation.
*/
getRemoved(): number;
/**
* Number of remaining unique rows present in the resulting range.
*/
getUniqueRemaining(): number;
}
/**
* A format object encapsulating the range's font, fill, borders, alignment, and other properties.
*/
interface RangeFormat {
/**
* Specifies if text is automatically indented when text alignment is set to equal distribution.
*/
getAutoIndent(): boolean;
/**
* Specifies if text is automatically indented when text alignment is set to equal distribution.
*/
setAutoIndent(autoIndent: boolean): void;
/**
* Specifies the width of all colums within the range. If the column widths are not uniform, null will be returned.
*/
getColumnWidth(): number;
/**
* Specifies the width of all colums within the range. If the column widths are not uniform, null will be returned.
*/
setColumnWidth(columnWidth: number): void;
/**
* Returns the fill object defined on the overall range.
*/
getFill(): RangeFill;
/**
* Returns the font object defined on the overall range.
*/
getFont(): RangeFont;
/**
* Represents the horizontal alignment for the specified object. See ExcelScript.HorizontalAlignment for details.
*/
getHorizontalAlignment(): HorizontalAlignment;
/**
* Represents the horizontal alignment for the specified object. See ExcelScript.HorizontalAlignment for details.
*/
setHorizontalAlignment(horizontalAlignment: HorizontalAlignment): void;
/**
* An integer from 0 to 250 that indicates the indent level.
*/
getIndentLevel(): number;
/**
* An integer from 0 to 250 that indicates the indent level.
*/
setIndentLevel(indentLevel: number): void;
/**
* Returns the format protection object for a range.
*/
getProtection(): FormatProtection;
/**
* The reading order for the range.
*/
getReadingOrder(): ReadingOrder;
/**
* The reading order for the range.
*/
setReadingOrder(readingOrder: ReadingOrder): void;
/**
* The height of all rows in the range. If the row heights are not uniform, null will be returned.
*/
getRowHeight(): number;
/**
* The height of all rows in the range. If the row heights are not uniform, null will be returned.
*/
setRowHeight(rowHeight: number): void;
/**
* Specifies if text automatically shrinks to fit in the available column width.
*/
getShrinkToFit(): boolean;
/**
* Specifies if text automatically shrinks to fit in the available column width.
*/
setShrinkToFit(shrinkToFit: boolean): void;
/**
* The text orientation of all the cells within the range.
* The text orientation should be an integer either from -90 to 90, or 180 for vertically-oriented text.
* If the orientation within a range are not uniform, then null will be returned.
*/
getTextOrientation(): number;
/**
* The text orientation of all the cells within the range.
* The text orientation should be an integer either from -90 to 90, or 180 for vertically-oriented text.
* If the orientation within a range are not uniform, then null will be returned.
*/
setTextOrientation(textOrientation: number): void;
/**
* Determines if the row height of the Range object equals the standard height of the sheet.
* Returns True if the row height of the Range object equals the standard height of the sheet.
* Returns Null if the range contains more than one row and the rows aren't all the same height.
* Returns False otherwise.
*/
getUseStandardHeight(): boolean;
/**
* Determines if the row height of the Range object equals the standard height of the sheet.
* Returns True if the row height of the Range object equals the standard height of the sheet.
* Returns Null if the range contains more than one row and the rows aren't all the same height.
* Returns False otherwise.
*/
setUseStandardHeight(useStandardHeight: boolean): void;
/**
* Specifies if the column width of the Range object equals the standard width of the sheet.
* Returns True if the column width of the Range object equals the standard width of the sheet.
* Returns Null if the range contains more than one column and the columns aren't all the same height.
* Returns False otherwise.
*/
getUseStandardWidth(): boolean;
/**
* Specifies if the column width of the Range object equals the standard width of the sheet.
* Returns True if the column width of the Range object equals the standard width of the sheet.
* Returns Null if the range contains more than one column and the columns aren't all the same height.
* Returns False otherwise.
*/
setUseStandardWidth(useStandardWidth: boolean): void;
/**
* Represents the vertical alignment for the specified object. See ExcelScript.VerticalAlignment for details.
*/
getVerticalAlignment(): VerticalAlignment;
/**
* Represents the vertical alignment for the specified object. See ExcelScript.VerticalAlignment for details.
*/
setVerticalAlignment(verticalAlignment: VerticalAlignment): void;
/**
* Specifies if Excel wraps the text in the object. A null value indicates that the entire range doesn't have uniform wrap setting
*/
getWrapText(): boolean;
/**
* Specifies if Excel wraps the text in the object. A null value indicates that the entire range doesn't have uniform wrap setting
*/
setWrapText(wrapText: boolean): void;
/**
* Adjusts the indentation of the range formatting. The indent value ranges from 0 to 250 and is measured in characters.
* @param amount The number of character spaces by which the current indent is adjusted. This value should be between -250 and 250.
* **Note**: If the amount would raise the indent level above 250, the indent level stays with 250.
* Similarly, if the amount would lower the indent level below 0, the indent level stays 0.
*/
adjustIndent(amount: number): void;
/**
* Changes the width of the columns of the current range to achieve the best fit, based on the current data in the columns.
*/
autofitColumns(): void;
/**
* Changes the height of the rows of the current range to achieve the best fit, based on the current data in the columns.
*/
autofitRows(): void;
/**
* Collection of border objects that apply to the overall range.
*/
getBorders(): RangeBorder[];
/**
* Specifies a double that lightens or darkens a color for Range Borders, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire border collections don't have uniform tintAndShade setting.
*/
getRangeBorderTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a color for Range Borders, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire border collections don't have uniform tintAndShade setting.
*/
setRangeBorderTintAndShade(rangeBorderTintAndShade: number): void;
/**
* Gets a border object using its name.
* @param index Index value of the border object to be retrieved. See ExcelScript.BorderIndex for details.
*/
getRangeBorder(index: BorderIndex): RangeBorder;
}
/**
* Represents the format protection of a range object.
*/
interface FormatProtection {
/**
* Specifies if Excel hides the formula for the cells in the range. A null value indicates that the entire range doesn't have uniform formula hidden setting.
*/
getFormulaHidden(): boolean;
/**
* Specifies if Excel hides the formula for the cells in the range. A null value indicates that the entire range doesn't have uniform formula hidden setting.
*/
setFormulaHidden(formulaHidden: boolean): void;
/**
* Specifies if Excel locks the cells in the object. A null value indicates that the entire range doesn't have uniform lock setting.
*/
getLocked(): boolean;
/**
* Specifies if Excel locks the cells in the object. A null value indicates that the entire range doesn't have uniform lock setting.
*/
setLocked(locked: boolean): void;
}
/**
* Represents the background of a range object.
*/
interface RangeFill {
/**
* HTML color code representing the color of the background, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")
*/
getColor(): string;
/**
* HTML color code representing the color of the background, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")
*/
setColor(color: string): void;
/**
* The pattern of a range. See ExcelScript.FillPattern for details. LinearGradient and RectangularGradient are not supported.
* A null value indicates that the entire range doesn't have uniform pattern setting.
*/
getPattern(): FillPattern;
/**
* The pattern of a range. See ExcelScript.FillPattern for details. LinearGradient and RectangularGradient are not supported.
* A null value indicates that the entire range doesn't have uniform pattern setting.
*/
setPattern(pattern: FillPattern): void;
/**
* The HTML color code representing the color of the range pattern, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getPatternColor(): string;
/**
* The HTML color code representing the color of the range pattern, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setPatternColor(patternColor: string): void;
/**
* Specifies a double that lightens or darkens a pattern color for Range Fill, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* If the pattern tintAndShades are not uniform, null will be returned.
*/
getPatternTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a pattern color for Range Fill, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* If the pattern tintAndShades are not uniform, null will be returned.
*/
setPatternTintAndShade(patternTintAndShade: number): void;
/**
* Specifies a double that lightens or darkens a color for Range Fill. The value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* If the tintAndShades are not uniform, null will be returned.
*/
getTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a color for Range Fill. The value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* If the tintAndShades are not uniform, null will be returned.
*/
setTintAndShade(tintAndShade: number): void;
/**
* Resets the range background.
*/
clear(): void;
}
/**
* Represents the border of an object.
*/
interface RangeBorder {
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getColor(): string;
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setColor(color: string): void;
/**
* Constant value that indicates the specific side of the border. See ExcelScript.BorderIndex for details.
*/
getSideIndex(): BorderIndex;
/**
* One of the constants of line style specifying the line style for the border. See ExcelScript.BorderLineStyle for details.
*/
getStyle(): BorderLineStyle;
/**
* One of the constants of line style specifying the line style for the border. See ExcelScript.BorderLineStyle for details.
*/
setStyle(style: BorderLineStyle): void;
/**
* Specifies a double that lightens or darkens a color for Range Border, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the border doesn't have uniform tintAndShade setting.
*/
getTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a color for Range Border, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the border doesn't have uniform tintAndShade setting.
*/
setTintAndShade(tintAndShade: number): void;
/**
* Specifies the weight of the border around a range. See ExcelScript.BorderWeight for details.
*/
getWeight(): BorderWeight;
/**
* Specifies the weight of the border around a range. See ExcelScript.BorderWeight for details.
*/
setWeight(weight: BorderWeight): void;
}
/**
* This object represents the font attributes (font name, font size, color, etc.) for an object.
*/
interface RangeFont {
/**
* Represents the bold status of font.
*/
getBold(): boolean;
/**
* Represents the bold status of font.
*/
setBold(bold: boolean): void;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
getColor(): string;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
setColor(color: string): void;
/**
* Specifies the italic status of the font.
*/
getItalic(): boolean;
/**
* Specifies the italic status of the font.
*/
setItalic(italic: boolean): void;
/**
* Font name (e.g., "Calibri"). The name's length should not be greater than 31 characters.
*/
getName(): string;
/**
* Font name (e.g., "Calibri"). The name's length should not be greater than 31 characters.
*/
setName(name: string): void;
/**
* Font size.
*/
getSize(): number;
/**
* Font size.
*/
setSize(size: number): void;
/**
* Specifies the strikethrough status of font. A null value indicates that the entire range doesn't have uniform Strikethrough setting.
*/
getStrikethrough(): boolean;
/**
* Specifies the strikethrough status of font. A null value indicates that the entire range doesn't have uniform Strikethrough setting.
*/
setStrikethrough(strikethrough: boolean): void;
/**
* Specifies the Subscript status of font.
* Returns True if all the fonts of the range are Subscript.
* Returns False if all the fonts of the range are Superscript or normal (neither Superscript, nor Subscript).
* Returns Null otherwise.
*/
getSubscript(): boolean;
/**
* Specifies the Subscript status of font.
* Returns True if all the fonts of the range are Subscript.
* Returns False if all the fonts of the range are Superscript or normal (neither Superscript, nor Subscript).
* Returns Null otherwise.
*/
setSubscript(subscript: boolean): void;
/**
* Specifies the Superscript status of font.
* Returns True if all the fonts of the range are Superscript.
* Returns False if all the fonts of the range are Subscript or normal (neither Superscript, nor Subscript).
* Returns Null otherwise.
*/
getSuperscript(): boolean;
/**
* Specifies the Superscript status of font.
* Returns True if all the fonts of the range are Superscript.
* Returns False if all the fonts of the range are Subscript or normal (neither Superscript, nor Subscript).
* Returns Null otherwise.
*/
setSuperscript(superscript: boolean): void;
/**
* Specifies a double that lightens or darkens a color for Range Font, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire range doesn't have uniform font tintAndShade setting.
*/
getTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a color for Range Font, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire range doesn't have uniform font tintAndShade setting.
*/
setTintAndShade(tintAndShade: number): void;
/**
* Type of underline applied to the font. See ExcelScript.RangeUnderlineStyle for details.
*/
getUnderline(): RangeUnderlineStyle;
/**
* Type of underline applied to the font. See ExcelScript.RangeUnderlineStyle for details.
*/
setUnderline(underline: RangeUnderlineStyle): void;
}
/**
* Represents a chart object in a workbook.
*/
interface Chart {
/**
* Represents chart axes.
*/
getAxes(): ChartAxes;
/**
* Specifies a ChartCategoryLabelLevel enumeration constant referring to
* the level of where the category labels are being sourced from.
*/
getCategoryLabelLevel(): number;
/**
* Specifies a ChartCategoryLabelLevel enumeration constant referring to
* the level of where the category labels are being sourced from.
*/
setCategoryLabelLevel(categoryLabelLevel: number): void;
/**
* Specifies the type of the chart. See ExcelScript.ChartType for details.
*/
getChartType(): ChartType;
/**
* Specifies the type of the chart. See ExcelScript.ChartType for details.
*/
setChartType(chartType: ChartType): void;
/**
* Represents the datalabels on the chart.
*/
getDataLabels(): ChartDataLabels;
/**
* Specifies the way that blank cells are plotted on a chart.
*/
getDisplayBlanksAs(): ChartDisplayBlanksAs;
/**
* Specifies the way that blank cells are plotted on a chart.
*/
setDisplayBlanksAs(displayBlanksAs: ChartDisplayBlanksAs): void;
/**
* Encapsulates the format properties for the chart area.
*/
getFormat(): ChartAreaFormat;
/**
* Specifies the height, in points, of the chart object.
*/
getHeight(): number;
/**
* Specifies the height, in points, of the chart object.
*/
setHeight(height: number): void;
/**
* The unique id of chart.
*/
getId(): string;
/**
* The distance, in points, from the left side of the chart to the worksheet origin.
*/
getLeft(): number;
/**
* The distance, in points, from the left side of the chart to the worksheet origin.
*/
setLeft(left: number): void;
/**
* Represents the legend for the chart.
*/
getLegend(): ChartLegend;
/**
* Specifies the name of a chart object.
*/
getName(): string;
/**
* Specifies the name of a chart object.
*/
setName(name: string): void;
/**
* Encapsulates the options for a pivot chart.
*/
getPivotOptions(): ChartPivotOptions;
/**
* Represents the plotArea for the chart.
*/
getPlotArea(): ChartPlotArea;
/**
* Specifies the way columns or rows are used as data series on the chart.
*/
getPlotBy(): ChartPlotBy;
/**
* Specifies the way columns or rows are used as data series on the chart.
*/
setPlotBy(plotBy: ChartPlotBy): void;
/**
* True if only visible cells are plotted. False if both visible and hidden cells are plotted.
*/
getPlotVisibleOnly(): boolean;
/**
* True if only visible cells are plotted. False if both visible and hidden cells are plotted.
*/
setPlotVisibleOnly(plotVisibleOnly: boolean): void;
/**
* Specifies a ChartSeriesNameLevel enumeration constant referring to
* the level of where the series names are being sourced from.
*/
getSeriesNameLevel(): number;
/**
* Specifies a ChartSeriesNameLevel enumeration constant referring to
* the level of where the series names are being sourced from.
*/
setSeriesNameLevel(seriesNameLevel: number): void;
/**
* Specifies whether to display all field buttons on a PivotChart.
*/
getShowAllFieldButtons(): boolean;
/**
* Specifies whether to display all field buttons on a PivotChart.
*/
setShowAllFieldButtons(showAllFieldButtons: boolean): void;
/**
* Specifies whether to show the data labels when the value is greater than the maximum value on the value axis.
* If value axis became smaller than the size of data points, you can use this property to set whether to show the data labels.
* This property applies to 2-D charts only.
*/
getShowDataLabelsOverMaximum(): boolean;
/**
* Specifies whether to show the data labels when the value is greater than the maximum value on the value axis.
* If value axis became smaller than the size of data points, you can use this property to set whether to show the data labels.
* This property applies to 2-D charts only.
*/
setShowDataLabelsOverMaximum(showDataLabelsOverMaximum: boolean): void;
/**
* Specifies the chart style for the chart.
*/
getStyle(): number;
/**
* Specifies the chart style for the chart.
*/
setStyle(style: number): void;
/**
* Specifies the title of the specified chart, including the text, visibility, position, and formatting of the title.
*/
getTitle(): ChartTitle;
/**
* Specifies the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart).
*/
getTop(): number;
/**
* Specifies the distance, in points, from the top edge of the object to the top of row 1 (on a worksheet) or the top of the chart area (on a chart).
*/
setTop(top: number): void;
/**
* Specifies the width, in points, of the chart object.
*/
getWidth(): number;
/**
* Specifies the width, in points, of the chart object.
*/
setWidth(width: number): void;
/**
* The worksheet containing the current chart.
*/
getWorksheet(): Worksheet;
/**
* Activates the chart in the Excel UI.
*/
activate(): void;
/**
* Deletes the chart object.
*/
delete(): void;
/**
* Renders the chart as a base64-encoded image by scaling the chart to fit the specified dimensions.
* The aspect ratio is preserved as part of the resizing.
* @param height (Optional) The desired height of the resulting image.
* @param width (Optional) The desired width of the resulting image.
* @param fittingMode (Optional) The method used to scale the chart to the specified to the specified dimensions (if both height and width are set).
*/
getImage(
width?: number,
height?: number,
fittingMode?: ImageFittingMode
): string;
/**
* Resets the source data for the chart.
* @param sourceData The range object corresponding to the source data.
* @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See ExcelScript.ChartSeriesBy for details.
*/
setData(sourceData: Range, seriesBy?: ChartSeriesBy): void;
/**
* Positions the chart relative to cells on the worksheet.
* @param startCell The start cell. This is where the chart will be moved to. The start cell is the top-left or top-right cell, depending on the user's right-to-left display settings.
* @param endCell (Optional) The end cell. If specified, the chart's width and height will be set to fully cover up this cell/range.
*/
setPosition(startCell: Range | string, endCell?: Range | string): void;
/**
* Represents either a single series or collection of series in the chart.
*/
getSeries(): ChartSeries[];
/**
* Add a new series to the collection. The new added series is not visible until set values/x axis values/bubble sizes for it (depending on chart type).
* @param name Optional. Name of the series.
* @param index Optional. Index value of the series to be added. Zero-indexed.
*/
addChartSeries(name?: string, index?: number): ChartSeries;
}
/**
* Encapsulates the options for the pivot chart.
*/
interface ChartPivotOptions {
/**
* Specifies whether to display the axis field buttons on a PivotChart. The ShowAxisFieldButtons property corresponds to the "Show Axis Field Buttons" command on the "Field Buttons" drop-down list of the "Analyze" tab, which is available when a PivotChart is selected.
*/
getShowAxisFieldButtons(): boolean;
/**
* Specifies whether to display the axis field buttons on a PivotChart. The ShowAxisFieldButtons property corresponds to the "Show Axis Field Buttons" command on the "Field Buttons" drop-down list of the "Analyze" tab, which is available when a PivotChart is selected.
*/
setShowAxisFieldButtons(showAxisFieldButtons: boolean): void;
/**
* Specifies whether to display the legend field buttons on a PivotChart.
*/
getShowLegendFieldButtons(): boolean;
/**
* Specifies whether to display the legend field buttons on a PivotChart.
*/
setShowLegendFieldButtons(showLegendFieldButtons: boolean): void;
/**
* Specifies whether to display the report filter field buttons on a PivotChart.
*/
getShowReportFilterFieldButtons(): boolean;
/**
* Specifies whether to display the report filter field buttons on a PivotChart.
*/
setShowReportFilterFieldButtons(
showReportFilterFieldButtons: boolean
): void;
/**
* Specifies whether to display the show value field buttons on a PivotChart.
*/
getShowValueFieldButtons(): boolean;
/**
* Specifies whether to display the show value field buttons on a PivotChart.
*/
setShowValueFieldButtons(showValueFieldButtons: boolean): void;
}
/**
* Encapsulates the format properties for the overall chart area.
*/
interface ChartAreaFormat {
/**
* Represents the border format of chart area, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Specifies the color scheme of the chart.
*/
getColorScheme(): ChartColorScheme;
/**
* Specifies the color scheme of the chart.
*/
setColorScheme(colorScheme: ChartColorScheme): void;
/**
* Represents the fill format of an object, which includes background formatting information.
*/
getFill(): ChartFill;
/**
* Represents the font attributes (font name, font size, color, etc.) for the current object.
*/
getFont(): ChartFont;
/**
* Specifies if the chart area of the chart has rounded corners.
*/
getRoundedCorners(): boolean;
/**
* Specifies if the chart area of the chart has rounded corners.
*/
setRoundedCorners(roundedCorners: boolean): void;
}
/**
* Represents a series in a chart.
*/
interface ChartSeries {
/**
* Specifies the group for the specified series.
*/
getAxisGroup(): ChartAxisGroup;
/**
* Specifies the group for the specified series.
*/
setAxisGroup(axisGroup: ChartAxisGroup): void;
/**
* Encapsulates the bin options for histogram charts and pareto charts.
*/
getBinOptions(): ChartBinOptions;
/**
* Encapsulates the options for the box and whisker charts.
*/
getBoxwhiskerOptions(): ChartBoxwhiskerOptions;
/**
* This can be an integer value from 0 (zero) to 300, representing the percentage of the default size. This property only applies to bubble charts.
*/
getBubbleScale(): number;
/**
* This can be an integer value from 0 (zero) to 300, representing the percentage of the default size. This property only applies to bubble charts.
*/
setBubbleScale(bubbleScale: number): void;
/**
* Represents the chart type of a series. See ExcelScript.ChartType for details.
*/
getChartType(): ChartType;
/**
* Represents the chart type of a series. See ExcelScript.ChartType for details.
*/
setChartType(chartType: ChartType): void;
/**
* Represents a collection of all dataLabels in the series.
*/
getDataLabels(): ChartDataLabels;
/**
* Represents the doughnut hole size of a chart series. Only valid on doughnut and doughnutExploded charts.
* Throws an invalid argument exception on invalid charts.
*/
getDoughnutHoleSize(): number;
/**
* Represents the doughnut hole size of a chart series. Only valid on doughnut and doughnutExploded charts.
* Throws an invalid argument exception on invalid charts.
*/
setDoughnutHoleSize(doughnutHoleSize: number): void;
/**
* Specifies the explosion value for a pie-chart or doughnut-chart slice. Returns 0 (zero) if there's no explosion (the tip of the slice is in the center of the pie).
*/
getExplosion(): number;
/**
* Specifies the explosion value for a pie-chart or doughnut-chart slice. Returns 0 (zero) if there's no explosion (the tip of the slice is in the center of the pie).
*/
setExplosion(explosion: number): void;
/**
* Specifies if the series is filtered. Not applicable for surface charts.
*/
getFiltered(): boolean;
/**
* Specifies if the series is filtered. Not applicable for surface charts.
*/
setFiltered(filtered: boolean): void;
/**
* Specifies the angle of the first pie-chart or doughnut-chart slice, in degrees (clockwise from vertical). Applies only to pie, 3-D pie, and doughnut charts. Can be a value from 0 through 360.
*/
getFirstSliceAngle(): number;
/**
* Specifies the angle of the first pie-chart or doughnut-chart slice, in degrees (clockwise from vertical). Applies only to pie, 3-D pie, and doughnut charts. Can be a value from 0 through 360.
*/
setFirstSliceAngle(firstSliceAngle: number): void;
/**
* Represents the formatting of a chart series, which includes fill and line formatting.
*/
getFormat(): ChartSeriesFormat;
/**
* Represents the gap width of a chart series. Only valid on bar and column charts, as well as
* specific classes of line and pie charts. Throws an invalid argument exception on invalid charts.
*/
getGapWidth(): number;
/**
* Represents the gap width of a chart series. Only valid on bar and column charts, as well as
* specific classes of line and pie charts. Throws an invalid argument exception on invalid charts.
*/
setGapWidth(gapWidth: number): void;
/**
* Specifies the color for maximum value of a region map chart series.
*/
getGradientMaximumColor(): string;
/**
* Specifies the color for maximum value of a region map chart series.
*/
setGradientMaximumColor(gradientMaximumColor: string): void;
/**
* Specifies the type for maximum value of a region map chart series.
*/
getGradientMaximumType(): ChartGradientStyleType;
/**
* Specifies the type for maximum value of a region map chart series.
*/
setGradientMaximumType(
gradientMaximumType: ChartGradientStyleType
): void;
/**
* Specifies the maximum value of a region map chart series.
*/
getGradientMaximumValue(): number;
/**
* Specifies the maximum value of a region map chart series.
*/
setGradientMaximumValue(gradientMaximumValue: number): void;
/**
* Specifies the color for midpoint value of a region map chart series.
*/
getGradientMidpointColor(): string;
/**
* Specifies the color for midpoint value of a region map chart series.
*/
setGradientMidpointColor(gradientMidpointColor: string): void;
/**
* Specifies the type for midpoint value of a region map chart series.
*/
getGradientMidpointType(): ChartGradientStyleType;
/**
* Specifies the type for midpoint value of a region map chart series.
*/
setGradientMidpointType(
gradientMidpointType: ChartGradientStyleType
): void;
/**
* Specifies the midpoint value of a region map chart series.
*/
getGradientMidpointValue(): number;
/**
* Specifies the midpoint value of a region map chart series.
*/
setGradientMidpointValue(gradientMidpointValue: number): void;
/**
* Specifies the color for minimum value of a region map chart series.
*/
getGradientMinimumColor(): string;
/**
* Specifies the color for minimum value of a region map chart series.
*/
setGradientMinimumColor(gradientMinimumColor: string): void;
/**
* Specifies the type for minimum value of a region map chart series.
*/
getGradientMinimumType(): ChartGradientStyleType;
/**
* Specifies the type for minimum value of a region map chart series.
*/
setGradientMinimumType(
gradientMinimumType: ChartGradientStyleType
): void;
/**
* Specifies the minimum value of a region map chart series.
*/
getGradientMinimumValue(): number;
/**
* Specifies the minimum value of a region map chart series.
*/
setGradientMinimumValue(gradientMinimumValue: number): void;
/**
* Specifies the series gradient style of a region map chart.
*/
getGradientStyle(): ChartGradientStyle;
/**
* Specifies the series gradient style of a region map chart.
*/
setGradientStyle(gradientStyle: ChartGradientStyle): void;
/**
* Specifies if the series has data labels.
*/
getHasDataLabels(): boolean;
/**
* Specifies if the series has data labels.
*/
setHasDataLabels(hasDataLabels: boolean): void;
/**
* Specifies the fill color for negative data points in a series.
*/
getInvertColor(): string;
/**
* Specifies the fill color for negative data points in a series.
*/
setInvertColor(invertColor: string): void;
/**
* True if Excel inverts the pattern in the item when it corresponds to a negative number.
*/
getInvertIfNegative(): boolean;
/**
* True if Excel inverts the pattern in the item when it corresponds to a negative number.
*/
setInvertIfNegative(invertIfNegative: boolean): void;
/**
* Encapsulates the options for a region map chart.
*/
getMapOptions(): ChartMapOptions;
/**
* Specifies the markers background color of a chart series.
*/
getMarkerBackgroundColor(): string;
/**
* Specifies the markers background color of a chart series.
*/
setMarkerBackgroundColor(markerBackgroundColor: string): void;
/**
* Specifies the markers foreground color of a chart series.
*/
getMarkerForegroundColor(): string;
/**
* Specifies the markers foreground color of a chart series.
*/
setMarkerForegroundColor(markerForegroundColor: string): void;
/**
* Specifies the marker size of a chart series.
*/
getMarkerSize(): number;
/**
* Specifies the marker size of a chart series.
*/
setMarkerSize(markerSize: number): void;
/**
* Specifies the marker style of a chart series. See ExcelScript.ChartMarkerStyle for details.
*/
getMarkerStyle(): ChartMarkerStyle;
/**
* Specifies the marker style of a chart series. See ExcelScript.ChartMarkerStyle for details.
*/
setMarkerStyle(markerStyle: ChartMarkerStyle): void;
/**
* Specifies the name of a series in a chart. The name's length should not be greater than 255 characters.
*/
getName(): string;
/**
* Specifies the name of a series in a chart. The name's length should not be greater than 255 characters.
*/
setName(name: string): void;
/**
* Specifies how bars and columns are positioned. Can be a value between –100 and 100. Applies only to 2-D bar and 2-D column charts.
*/
getOverlap(): number;
/**
* Specifies how bars and columns are positioned. Can be a value between –100 and 100. Applies only to 2-D bar and 2-D column charts.
*/
setOverlap(overlap: number): void;
/**
* Specifies the series parent label strategy area for a treemap chart.
*/
getParentLabelStrategy(): ChartParentLabelStrategy;
/**
* Specifies the series parent label strategy area for a treemap chart.
*/
setParentLabelStrategy(
parentLabelStrategy: ChartParentLabelStrategy
): void;
/**
* Specifies the plot order of a chart series within the chart group.
*/
getPlotOrder(): number;
/**
* Specifies the plot order of a chart series within the chart group.
*/
setPlotOrder(plotOrder: number): void;
/**
* Specifies the size of the secondary section of either a pie-of-pie chart or a bar-of-pie chart, as a percentage of the size of the primary pie. Can be a value from 5 to 200.
*/
getSecondPlotSize(): number;
/**
* Specifies the size of the secondary section of either a pie-of-pie chart or a bar-of-pie chart, as a percentage of the size of the primary pie. Can be a value from 5 to 200.
*/
setSecondPlotSize(secondPlotSize: number): void;
/**
* Specifies whether connector lines are shown in waterfall charts.
*/
getShowConnectorLines(): boolean;
/**
* Specifies whether connector lines are shown in waterfall charts.
*/
setShowConnectorLines(showConnectorLines: boolean): void;
/**
* Specifies whether leader lines are displayed for each data label in the series.
*/
getShowLeaderLines(): boolean;
/**
* Specifies whether leader lines are displayed for each data label in the series.
*/
setShowLeaderLines(showLeaderLines: boolean): void;
/**
* Specifies if the series has a shadow.
*/
getShowShadow(): boolean;
/**
* Specifies if the series has a shadow.
*/
setShowShadow(showShadow: boolean): void;
/**
* Specifies if the series is smooth. Only applicable to line and scatter charts.
*/
getSmooth(): boolean;
/**
* Specifies if the series is smooth. Only applicable to line and scatter charts.
*/
setSmooth(smooth: boolean): void;
/**
* Specifies the way the two sections of either a pie-of-pie chart or a bar-of-pie chart are split.
*/
getSplitType(): ChartSplitType;
/**
* Specifies the way the two sections of either a pie-of-pie chart or a bar-of-pie chart are split.
*/
setSplitType(splitType: ChartSplitType): void;
/**
* Specifies the threshold value that separates two sections of either a pie-of-pie chart or a bar-of-pie chart.
*/
getSplitValue(): number;
/**
* Specifies the threshold value that separates two sections of either a pie-of-pie chart or a bar-of-pie chart.
*/
setSplitValue(splitValue: number): void;
/**
* True if Excel assigns a different color or pattern to each data marker. The chart must contain only one series.
*/
getVaryByCategories(): boolean;
/**
* True if Excel assigns a different color or pattern to each data marker. The chart must contain only one series.
*/
setVaryByCategories(varyByCategories: boolean): void;
/**
* Represents the error bar object of a chart series.
*/
getXErrorBars(): ChartErrorBars;
/**
* Represents the error bar object of a chart series.
*/
getYErrorBars(): ChartErrorBars;
/**
* Deletes the chart series.
*/
delete(): void;
/**
* Gets the values from a single dimension of the chart series. These could be either category values or data values, depending on the dimension specified and how the data is mapped for the chart series.
* @param dimension the dimension of axis where the data from
*/
getDimensionValues(dimension: ChartSeriesDimension): string[];
/**
* Sets the bubble sizes for a chart series. Only works for bubble charts.
* @param sourceData The Range object corresponding to the source data.
*/
setBubbleSizes(sourceData: Range): void;
/**
* Sets the values for a chart series. For scatter chart, it means Y axis values.
* @param sourceData The Range object corresponding to the source data.
*/
setValues(sourceData: Range): void;
/**
* Sets the values of the X axis for a chart series. Only works for scatter charts.
* @param sourceData The Range object corresponding to the source data.
*/
setXAxisValues(sourceData: Range): void;
/**
* Returns a collection of all points in the series.
*/
getPoints(): ChartPoint[];
/**
* The collection of trendlines in the series.
*/
getTrendlines(): ChartTrendline[];
/**
* Adds a new trendline to trendline collection.
* @param type Specifies the trendline type. The default value is "Linear". See ExcelScript.ChartTrendline for details.
*/
addChartTrendline(type?: ChartTrendlineType): ChartTrendline;
/**
* Get trendline object by index, which is the insertion order in items array.
* @param index Represents the insertion order in items array.
*/
getChartTrendline(index: number): ChartTrendline;
}
/**
* Encapsulates the format properties for the chart series
*/
interface ChartSeriesFormat {
/**
* Represents the fill format of a chart series, which includes background formatting information.
*/
getFill(): ChartFill;
/**
* Represents line formatting.
*/
getLine(): ChartLineFormat;
}
/**
* Represents a point of a series in a chart.
*/
interface ChartPoint {
/**
* Returns the data label of a chart point.
*/
getDataLabel(): ChartDataLabel;
/**
* Encapsulates the format properties chart point.
*/
getFormat(): ChartPointFormat;
/**
* Represents whether a data point has a data label. Not applicable for surface charts.
*/
getHasDataLabel(): boolean;
/**
* Represents whether a data point has a data label. Not applicable for surface charts.
*/
setHasDataLabel(hasDataLabel: boolean): void;
/**
* HTML color code representation of the marker background color of data point (e.g., #FF0000 represents Red).
*/
getMarkerBackgroundColor(): string;
/**
* HTML color code representation of the marker background color of data point (e.g., #FF0000 represents Red).
*/
setMarkerBackgroundColor(markerBackgroundColor: string): void;
/**
* HTML color code representation of the marker foreground color of data point (e.g., #FF0000 represents Red).
*/
getMarkerForegroundColor(): string;
/**
* HTML color code representation of the marker foreground color of data point (e.g., #FF0000 represents Red).
*/
setMarkerForegroundColor(markerForegroundColor: string): void;
/**
* Represents marker size of data point.
*/
getMarkerSize(): number;
/**
* Represents marker size of data point.
*/
setMarkerSize(markerSize: number): void;
/**
* Represents marker style of a chart data point. See ExcelScript.ChartMarkerStyle for details.
*/
getMarkerStyle(): ChartMarkerStyle;
/**
* Represents marker style of a chart data point. See ExcelScript.ChartMarkerStyle for details.
*/
setMarkerStyle(markerStyle: ChartMarkerStyle): void;
/**
* Returns the value of a chart point.
*/
getValue(): number;
}
/**
* Represents formatting object for chart points.
*/
interface ChartPointFormat {
/**
* Represents the border format of a chart data point, which includes color, style, and weight information.
*/
getBorder(): ChartBorder;
/**
* Represents the fill format of a chart, which includes background formatting information.
*/
getFill(): ChartFill;
}
/**
* Represents the chart axes.
*/
interface ChartAxes {
/**
* Represents the category axis in a chart.
*/
getCategoryAxis(): ChartAxis;
/**
* Represents the series axis of a 3-dimensional chart.
*/
getSeriesAxis(): ChartAxis;
/**
* Represents the value axis in an axis.
*/
getValueAxis(): ChartAxis;
/**
* Returns the specific axis identified by type and group.
* @param type Specifies the axis type. See ExcelScript.ChartAxisType for details.
* @param group Optional. Specifies the axis group. See ExcelScript.ChartAxisGroup for details.
*/
getChartAxis(type: ChartAxisType, group?: ChartAxisGroup): ChartAxis;
}
/**
* Represents a single axis in a chart.
*/
interface ChartAxis {
/**
* Specifies the alignment for the specified axis tick label. See ExcelScript.ChartTextHorizontalAlignment for detail.
*/
getAlignment(): ChartTickLabelAlignment;
/**
* Specifies the alignment for the specified axis tick label. See ExcelScript.ChartTextHorizontalAlignment for detail.
*/
setAlignment(alignment: ChartTickLabelAlignment): void;
/**
* Specifies the group for the specified axis. See ExcelScript.ChartAxisGroup for details.
*/
getAxisGroup(): ChartAxisGroup;
/**
* Specifies the base unit for the specified category axis.
*/
getBaseTimeUnit(): ChartAxisTimeUnit;
/**
* Specifies the base unit for the specified category axis.
*/
setBaseTimeUnit(baseTimeUnit: ChartAxisTimeUnit): void;
/**
* Specifies the category axis type.
*/
getCategoryType(): ChartAxisCategoryType;
/**
* Specifies the category axis type.
*/
setCategoryType(categoryType: ChartAxisCategoryType): void;
/**
* Specifies the custom axis display unit value. To set this property, please use the SetCustomDisplayUnit(double) method.
*/
getCustomDisplayUnit(): number;
/**
* Represents the axis display unit. See ExcelScript.ChartAxisDisplayUnit for details.
*/
getDisplayUnit(): ChartAxisDisplayUnit;
/**
* Represents the axis display unit. See ExcelScript.ChartAxisDisplayUnit for details.
*/
setDisplayUnit(displayUnit: ChartAxisDisplayUnit): void;
/**
* Represents the formatting of a chart object, which includes line and font formatting.
*/
getFormat(): ChartAxisFormat;
/**
* Specifies the height, in points, of the chart axis. Null if the axis is not visible.
*/
getHeight(): number;
/**
* Specifies if the value axis crosses the category axis between categories.
*/
getIsBetweenCategories(): boolean;
/**
* Specifies if the value axis crosses the category axis between categories.
*/
setIsBetweenCategories(isBetweenCategories: boolean): void;
/**
* Specifies the distance, in points, from the left edge of the axis to the left of chart area. Null if the axis is not visible.
*/
getLeft(): number;
/**
* Specifies if the number format is linked to the cells. If true, the number format will change in the labels when it changes in the cells.
*/
getLinkNumberFormat(): boolean;
/**
* Specifies if the number format is linked to the cells. If true, the number format will change in the labels when it changes in the cells.
*/
setLinkNumberFormat(linkNumberFormat: boolean): void;
/**
* Specifies the base of the logarithm when using logarithmic scales.
*/
getLogBase(): number;
/**
* Specifies the base of the logarithm when using logarithmic scales.
*/
setLogBase(logBase: number): void;
/**
* Returns a Gridlines object that represents the major gridlines for the specified axis.
*/
getMajorGridlines(): ChartGridlines;
/**
* Specifies the type of major tick mark for the specified axis. See ExcelScript.ChartAxisTickMark for details.
*/
getMajorTickMark(): ChartAxisTickMark;
/**
* Specifies the type of major tick mark for the specified axis. See ExcelScript.ChartAxisTickMark for details.
*/
setMajorTickMark(majorTickMark: ChartAxisTickMark): void;
/**
* Specifies the major unit scale value for the category axis when the CategoryType property is set to TimeScale.
*/
getMajorTimeUnitScale(): ChartAxisTimeUnit;
/**
* Specifies the major unit scale value for the category axis when the CategoryType property is set to TimeScale.
*/
setMajorTimeUnitScale(majorTimeUnitScale: ChartAxisTimeUnit): void;
/**
* Specifies the interval between two major tick marks.
*/
getMajorUnit(): number;
/**
* Specifies the interval between two major tick marks.
*/
setMajorUnit(majorUnit: number): void;
/**
* Specifies the maximum value on the value axis.
*/
getMaximum(): number;
/**
* Specifies the maximum value on the value axis.
*/
setMaximum(maximum: number): void;
/**
* Specifies the minimum value on the value axis.
*/
getMinimum(): number;
/**
* Specifies the minimum value on the value axis.
*/
setMinimum(minimum: number): void;
/**
* Returns a Gridlines object that represents the minor gridlines for the specified axis.
*/
getMinorGridlines(): ChartGridlines;
/**
* Specifies the type of minor tick mark for the specified axis. See ExcelScript.ChartAxisTickMark for details.
*/
getMinorTickMark(): ChartAxisTickMark;
/**
* Specifies the type of minor tick mark for the specified axis. See ExcelScript.ChartAxisTickMark for details.
*/
setMinorTickMark(minorTickMark: ChartAxisTickMark): void;
/**
* Specifies the minor unit scale value for the category axis when the CategoryType property is set to TimeScale.
*/
getMinorTimeUnitScale(): ChartAxisTimeUnit;
/**
* Specifies the minor unit scale value for the category axis when the CategoryType property is set to TimeScale.
*/
setMinorTimeUnitScale(minorTimeUnitScale: ChartAxisTimeUnit): void;
/**
* Specifies the interval between two minor tick marks.
*/
getMinorUnit(): number;
/**
* Specifies the interval between two minor tick marks.
*/
setMinorUnit(minorUnit: number): void;
/**
* Specifies if an axis is multilevel.
*/
getMultiLevel(): boolean;
/**
* Specifies if an axis is multilevel.
*/
setMultiLevel(multiLevel: boolean): void;
/**
* Specifies the format code for the axis tick label.
*/
getNumberFormat(): string;
/**
* Specifies the format code for the axis tick label.
*/
setNumberFormat(numberFormat: string): void;
/**
* Specifies the distance between the levels of labels, and the distance between the first level and the axis line. The value should be an integer from 0 to 1000.
*/
getOffset(): number;
/**
* Specifies the distance between the levels of labels, and the distance between the first level and the axis line. The value should be an integer from 0 to 1000.
*/
setOffset(offset: number): void;
/**
* Specifies the specified axis position where the other axis crosses. See ExcelScript.ChartAxisPosition for details.
*/
getPosition(): ChartAxisPosition;
/**
* Specifies the specified axis position where the other axis crosses. See ExcelScript.ChartAxisPosition for details.
*/
setPosition(position: ChartAxisPosition): void;
/**
* Specifies the specified axis position where the other axis crosses at. You should use the SetPositionAt(double) method to set this property.
*/
getPositionAt(): number;
/**
* Specifies if Excel plots data points from last to first.
*/
getReversePlotOrder(): boolean;
/**
* Specifies if Excel plots data points from last to first.
*/
setReversePlotOrder(reversePlotOrder: boolean): void;
/**
* Specifies the value axis scale type. See ExcelScript.ChartAxisScaleType for details.
*/
getScaleType(): ChartAxisScaleType;
/**
* Specifies the value axis scale type. See ExcelScript.ChartAxisScaleType for details.
*/
setScaleType(scaleType: ChartAxisScaleType): void;
/**
* Specifies if the axis display unit label is visible.
*/
getShowDisplayUnitLabel(): boolean;
/**
* Specifies if the axis display unit label is visible.
*/
setShowDisplayUnitLabel(showDisplayUnitLabel: boolean): void;
/**
* Specifies the angle to which the text is oriented for the chart axis tick label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Specifies the angle to which the text is oriented for the chart axis tick label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Specifies the position of tick-mark labels on the specified axis. See ExcelScript.ChartAxisTickLabelPosition for details.
*/
getTickLabelPosition(): ChartAxisTickLabelPosition;
/**
* Specifies the position of tick-mark labels on the specified axis. See ExcelScript.ChartAxisTickLabelPosition for details.
*/
setTickLabelPosition(
tickLabelPosition: ChartAxisTickLabelPosition
): void;
/**
* Specifies the number of categories or series between tick-mark labels. Can be a value from 1 through 31999.
*/
getTickLabelSpacing(): number;
/**
* Specifies the number of categories or series between tick-mark labels. Can be a value from 1 through 31999.
*/
setTickLabelSpacing(tickLabelSpacing: number): void;
/**
* Specifies the number of categories or series between tick marks.
*/
getTickMarkSpacing(): number;
/**
* Specifies the number of categories or series between tick marks.
*/
setTickMarkSpacing(tickMarkSpacing: number): void;
/**
* Represents the axis title.
*/
getTitle(): ChartAxisTitle;
/**
* Specifies the distance, in points, from the top edge of the axis to the top of chart area. Null if the axis is not visible.
*/
getTop(): number;
/**
* Specifies the axis type. See ExcelScript.ChartAxisType for details.
*/
getType(): ChartAxisType;
/**
* Specifies if the axis is visible.
*/
getVisible(): boolean;
/**
* Specifies if the axis is visible.
*/
setVisible(visible: boolean): void;
/**
* Specifies the width, in points, of the chart axis. Null if the axis is not visible.
*/
getWidth(): number;
/**
* Sets all the category names for the specified axis.
* @param sourceData The Range object corresponding to the source data.
*/
setCategoryNames(sourceData: Range): void;
/**
* Sets the axis display unit to a custom value.
* @param value Custom value of the display unit.
*/
setCustomDisplayUnit(value: number): void;
/**
* Sets the specified axis position where the other axis crosses at.
* @param value Custom value of the crosses at
*/
setPositionAt(value: number): void;
}
/**
* Encapsulates the format properties for the chart axis.
*/
interface ChartAxisFormat {
/**
* Specifies chart fill formatting.
*/
getFill(): ChartFill;
/**
* Specifies the font attributes (font name, font size, color, etc.) for a chart axis element.
*/
getFont(): ChartFont;
/**
* Specifies chart line formatting.
*/
getLine(): ChartLineFormat;
}
/**
* Represents the title of a chart axis.
*/
interface ChartAxisTitle {
/**
* Specifies the formatting of chart axis title.
*/
getFormat(): ChartAxisTitleFormat;
/**
* Specifies the axis title.
*/
getText(): string;
/**
* Specifies the axis title.
*/
setText(text: string): void;
/**
* Specifies the angle to which the text is oriented for the chart axis title. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Specifies the angle to which the text is oriented for the chart axis title. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Specifies if the axis title is visibile.
*/
getVisible(): boolean;
/**
* Specifies if the axis title is visibile.
*/
setVisible(visible: boolean): void;
/**
* A string value that represents the formula of chart axis title using A1-style notation.
* @param formula a string that present the formula to set
*/
setFormula(formula: string): void;
}
/**
* Represents the chart axis title formatting.
*/
interface ChartAxisTitleFormat {
/**
* Specifies the chart axis title's border format, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Specifies the chart axis title's fill formatting.
*/
getFill(): ChartFill;
/**
* Specifies the chart axis title's font attributes, such as font name, font size, color, etc. of chart axis title object.
*/
getFont(): ChartFont;
}
/**
* Represents a collection of all the data labels on a chart point.
*/
interface ChartDataLabels {
/**
* Specifies if data labels automatically generate appropriate text based on context.
*/
getAutoText(): boolean;
/**
* Specifies if data labels automatically generate appropriate text based on context.
*/
setAutoText(autoText: boolean): void;
/**
* Specifies the format of chart data labels, which includes fill and font formatting.
*/
getFormat(): ChartDataLabelFormat;
/**
* Specifies the horizontal alignment for chart data label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of data label is 0.
*/
getHorizontalAlignment(): ChartTextHorizontalAlignment;
/**
* Specifies the horizontal alignment for chart data label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of data label is 0.
*/
setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;
/**
* Specifies if the number format is linked to the cells. If true, the number format will change in the labels when it changes in the cells.
*/
getLinkNumberFormat(): boolean;
/**
* Specifies if the number format is linked to the cells. If true, the number format will change in the labels when it changes in the cells.
*/
setLinkNumberFormat(linkNumberFormat: boolean): void;
/**
* Specifies the format code for data labels.
*/
getNumberFormat(): string;
/**
* Specifies the format code for data labels.
*/
setNumberFormat(numberFormat: string): void;
/**
* DataLabelPosition value that represents the position of the data label. See ExcelScript.ChartDataLabelPosition for details.
*/
getPosition(): ChartDataLabelPosition;
/**
* DataLabelPosition value that represents the position of the data label. See ExcelScript.ChartDataLabelPosition for details.
*/
setPosition(position: ChartDataLabelPosition): void;
/**
* String representing the separator used for the data labels on a chart.
*/
getSeparator(): string;
/**
* String representing the separator used for the data labels on a chart.
*/
setSeparator(separator: string): void;
/**
* Specifies if the data label bubble size is visible.
*/
getShowBubbleSize(): boolean;
/**
* Specifies if the data label bubble size is visible.
*/
setShowBubbleSize(showBubbleSize: boolean): void;
/**
* Specifies if the data label category name is visible.
*/
getShowCategoryName(): boolean;
/**
* Specifies if the data label category name is visible.
*/
setShowCategoryName(showCategoryName: boolean): void;
/**
* Specifies if the data label legend key is visible.
*/
getShowLegendKey(): boolean;
/**
* Specifies if the data label legend key is visible.
*/
setShowLegendKey(showLegendKey: boolean): void;
/**
* Specifies if the data label percentage is visible.
*/
getShowPercentage(): boolean;
/**
* Specifies if the data label percentage is visible.
*/
setShowPercentage(showPercentage: boolean): void;
/**
* Specifies if the data label series name is visible.
*/
getShowSeriesName(): boolean;
/**
* Specifies if the data label series name is visible.
*/
setShowSeriesName(showSeriesName: boolean): void;
/**
* Specifies if the data label value is visible.
*/
getShowValue(): boolean;
/**
* Specifies if the data label value is visible.
*/
setShowValue(showValue: boolean): void;
/**
* Represents the angle to which the text is oriented for data labels. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Represents the angle to which the text is oriented for data labels. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Represents the vertical alignment of chart data label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of data label is -90, 90, or 180.
*/
getVerticalAlignment(): ChartTextVerticalAlignment;
/**
* Represents the vertical alignment of chart data label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of data label is -90, 90, or 180.
*/
setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;
}
/**
* Represents the data label of a chart point.
*/
interface ChartDataLabel {
/**
* Specifies if the data label automatically generates appropriate text based on context.
*/
getAutoText(): boolean;
/**
* Specifies if the data label automatically generates appropriate text based on context.
*/
setAutoText(autoText: boolean): void;
/**
* Represents the format of chart data label.
*/
getFormat(): ChartDataLabelFormat;
/**
* String value that represents the formula of chart data label using A1-style notation.
*/
getFormula(): string;
/**
* String value that represents the formula of chart data label using A1-style notation.
*/
setFormula(formula: string): void;
/**
* Returns the height, in points, of the chart data label. Null if chart data label is not visible.
*/
getHeight(): number;
/**
* Represents the horizontal alignment for chart data label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of data label is -90, 90, or 180.
*/
getHorizontalAlignment(): ChartTextHorizontalAlignment;
/**
* Represents the horizontal alignment for chart data label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of data label is -90, 90, or 180.
*/
setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;
/**
* Represents the distance, in points, from the left edge of chart data label to the left edge of chart area. Null if chart data label is not visible.
*/
getLeft(): number;
/**
* Represents the distance, in points, from the left edge of chart data label to the left edge of chart area. Null if chart data label is not visible.
*/
setLeft(left: number): void;
/**
* Specifies if the number format is linked to the cells (so that the number format changes in the labels when it changes in the cells).
*/
getLinkNumberFormat(): boolean;
/**
* Specifies if the number format is linked to the cells (so that the number format changes in the labels when it changes in the cells).
*/
setLinkNumberFormat(linkNumberFormat: boolean): void;
/**
* String value that represents the format code for data label.
*/
getNumberFormat(): string;
/**
* String value that represents the format code for data label.
*/
setNumberFormat(numberFormat: string): void;
/**
* DataLabelPosition value that represents the position of the data label. See ExcelScript.ChartDataLabelPosition for details.
*/
getPosition(): ChartDataLabelPosition;
/**
* DataLabelPosition value that represents the position of the data label. See ExcelScript.ChartDataLabelPosition for details.
*/
setPosition(position: ChartDataLabelPosition): void;
/**
* String representing the separator used for the data label on a chart.
*/
getSeparator(): string;
/**
* String representing the separator used for the data label on a chart.
*/
setSeparator(separator: string): void;
/**
* Specifies if the data label bubble size is visible.
*/
getShowBubbleSize(): boolean;
/**
* Specifies if the data label bubble size is visible.
*/
setShowBubbleSize(showBubbleSize: boolean): void;
/**
* Specifies if the data label category name is visible.
*/
getShowCategoryName(): boolean;
/**
* Specifies if the data label category name is visible.
*/
setShowCategoryName(showCategoryName: boolean): void;
/**
* Specifies if the data label legend key is visible.
*/
getShowLegendKey(): boolean;
/**
* Specifies if the data label legend key is visible.
*/
setShowLegendKey(showLegendKey: boolean): void;
/**
* Specifies if the data label percentage is visible.
*/
getShowPercentage(): boolean;
/**
* Specifies if the data label percentage is visible.
*/
setShowPercentage(showPercentage: boolean): void;
/**
* Specifies if the data label series name is visible.
*/
getShowSeriesName(): boolean;
/**
* Specifies if the data label series name is visible.
*/
setShowSeriesName(showSeriesName: boolean): void;
/**
* Specifies if the data label value is visible.
*/
getShowValue(): boolean;
/**
* Specifies if the data label value is visible.
*/
setShowValue(showValue: boolean): void;
/**
* String representing the text of the data label on a chart.
*/
getText(): string;
/**
* String representing the text of the data label on a chart.
*/
setText(text: string): void;
/**
* Represents the angle to which the text is oriented for the chart data label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Represents the angle to which the text is oriented for the chart data label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Represents the distance, in points, from the top edge of chart data label to the top of chart area. Null if chart data label is not visible.
*/
getTop(): number;
/**
* Represents the distance, in points, from the top edge of chart data label to the top of chart area. Null if chart data label is not visible.
*/
setTop(top: number): void;
/**
* Represents the vertical alignment of chart data label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of data label is 0.
*/
getVerticalAlignment(): ChartTextVerticalAlignment;
/**
* Represents the vertical alignment of chart data label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of data label is 0.
*/
setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;
/**
* Returns the width, in points, of the chart data label. Null if chart data label is not visible.
*/
getWidth(): number;
}
/**
* Encapsulates the format properties for the chart data labels.
*/
interface ChartDataLabelFormat {
/**
* Represents the border format, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Represents the fill format of the current chart data label.
*/
getFill(): ChartFill;
/**
* Represents the font attributes (font name, font size, color, etc.) for a chart data label.
*/
getFont(): ChartFont;
}
/**
* This object represents the attributes for a chart's error bars.
*/
interface ChartErrorBars {
/**
* Specifies if error bars have an end style cap.
*/
getEndStyleCap(): boolean;
/**
* Specifies if error bars have an end style cap.
*/
setEndStyleCap(endStyleCap: boolean): void;
/**
* Specifies the formatting type of the error bars.
*/
getFormat(): ChartErrorBarsFormat;
/**
* Specifies which parts of the error bars to include.
*/
getInclude(): ChartErrorBarsInclude;
/**
* Specifies which parts of the error bars to include.
*/
setInclude(include: ChartErrorBarsInclude): void;
/**
* The type of range marked by the error bars.
*/
getType(): ChartErrorBarsType;
/**
* The type of range marked by the error bars.
*/
setType(type: ChartErrorBarsType): void;
/**
* Specifies whether the error bars are displayed.
*/
getVisible(): boolean;
/**
* Specifies whether the error bars are displayed.
*/
setVisible(visible: boolean): void;
}
/**
* Encapsulates the format properties for chart error bars.
*/
interface ChartErrorBarsFormat {
/**
* Represents the chart line formatting.
*/
getLine(): ChartLineFormat;
}
/**
* Represents major or minor gridlines on a chart axis.
*/
interface ChartGridlines {
/**
* Represents the formatting of chart gridlines.
*/
getFormat(): ChartGridlinesFormat;
/**
* Specifies if the axis gridlines are visible.
*/
getVisible(): boolean;
/**
* Specifies if the axis gridlines are visible.
*/
setVisible(visible: boolean): void;
}
/**
* Encapsulates the format properties for chart gridlines.
*/
interface ChartGridlinesFormat {
/**
* Represents chart line formatting.
*/
getLine(): ChartLineFormat;
}
/**
* Represents the legend in a chart.
*/
interface ChartLegend {
/**
* Represents the formatting of a chart legend, which includes fill and font formatting.
*/
getFormat(): ChartLegendFormat;
/**
* Specifies the height, in points, of the legend on the chart. Null if legend is not visible.
*/
getHeight(): number;
/**
* Specifies the height, in points, of the legend on the chart. Null if legend is not visible.
*/
setHeight(height: number): void;
/**
* Specifies the left, in points, of the legend on the chart. Null if legend is not visible.
*/
getLeft(): number;
/**
* Specifies the left, in points, of the legend on the chart. Null if legend is not visible.
*/
setLeft(left: number): void;
/**
* Specifies if the chart legend should overlap with the main body of the chart.
*/
getOverlay(): boolean;
/**
* Specifies if the chart legend should overlap with the main body of the chart.
*/
setOverlay(overlay: boolean): void;
/**
* Specifies the position of the legend on the chart. See ExcelScript.ChartLegendPosition for details.
*/
getPosition(): ChartLegendPosition;
/**
* Specifies the position of the legend on the chart. See ExcelScript.ChartLegendPosition for details.
*/
setPosition(position: ChartLegendPosition): void;
/**
* Specifies if the legend has a shadow on the chart.
*/
getShowShadow(): boolean;
/**
* Specifies if the legend has a shadow on the chart.
*/
setShowShadow(showShadow: boolean): void;
/**
* Specifies the top of a chart legend.
*/
getTop(): number;
/**
* Specifies the top of a chart legend.
*/
setTop(top: number): void;
/**
* Specifies if the ChartLegend is visible.
*/
getVisible(): boolean;
/**
* Specifies if the ChartLegend is visible.
*/
setVisible(visible: boolean): void;
/**
* Specifies the width, in points, of the legend on the chart. Null if legend is not visible.
*/
getWidth(): number;
/**
* Specifies the width, in points, of the legend on the chart. Null if legend is not visible.
*/
setWidth(width: number): void;
/**
* Represents a collection of legendEntries in the legend.
*/
getLegendEntries(): ChartLegendEntry[];
}
/**
* Represents the legendEntry in legendEntryCollection.
*/
interface ChartLegendEntry {
/**
* Specifies the height of the legendEntry on the chart legend.
*/
getHeight(): number;
/**
* Specifies the index of the legendEntry in the chart legend.
*/
getIndex(): number;
/**
* Specifies the left of a chart legendEntry.
*/
getLeft(): number;
/**
* Specifies the top of a chart legendEntry.
*/
getTop(): number;
/**
* Represents the visible of a chart legend entry.
*/
getVisible(): boolean;
/**
* Represents the visible of a chart legend entry.
*/
setVisible(visible: boolean): void;
/**
* Represents the width of the legendEntry on the chart Legend.
*/
getWidth(): number;
}
/**
* Encapsulates the format properties of a chart legend.
*/
interface ChartLegendFormat {
/**
* Represents the border format, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Represents the fill format of an object, which includes background formatting information.
*/
getFill(): ChartFill;
/**
* Represents the font attributes such as font name, font size, color, etc. of a chart legend.
*/
getFont(): ChartFont;
}
/**
* Encapsulates the properties for a region map chart.
*/
interface ChartMapOptions {
/**
* Specifies the series map labels strategy of a region map chart.
*/
getLabelStrategy(): ChartMapLabelStrategy;
/**
* Specifies the series map labels strategy of a region map chart.
*/
setLabelStrategy(labelStrategy: ChartMapLabelStrategy): void;
/**
* Specifies the series mapping level of a region map chart.
*/
getLevel(): ChartMapAreaLevel;
/**
* Specifies the series mapping level of a region map chart.
*/
setLevel(level: ChartMapAreaLevel): void;
/**
* Specifies the series projection type of a region map chart.
*/
getProjectionType(): ChartMapProjectionType;
/**
* Specifies the series projection type of a region map chart.
*/
setProjectionType(projectionType: ChartMapProjectionType): void;
}
/**
* Represents a chart title object of a chart.
*/
interface ChartTitle {
/**
* Represents the formatting of a chart title, which includes fill and font formatting.
*/
getFormat(): ChartTitleFormat;
/**
* Returns the height, in points, of the chart title. Null if chart title is not visible.
*/
getHeight(): number;
/**
* Specifies the horizontal alignment for chart title.
*/
getHorizontalAlignment(): ChartTextHorizontalAlignment;
/**
* Specifies the horizontal alignment for chart title.
*/
setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;
/**
* Specifies the distance, in points, from the left edge of chart title to the left edge of chart area. Null if chart title is not visible.
*/
getLeft(): number;
/**
* Specifies the distance, in points, from the left edge of chart title to the left edge of chart area. Null if chart title is not visible.
*/
setLeft(left: number): void;
/**
* Specifies if the chart title will overlay the chart.
*/
getOverlay(): boolean;
/**
* Specifies if the chart title will overlay the chart.
*/
setOverlay(overlay: boolean): void;
/**
* Represents the position of chart title. See ExcelScript.ChartTitlePosition for details.
*/
getPosition(): ChartTitlePosition;
/**
* Represents the position of chart title. See ExcelScript.ChartTitlePosition for details.
*/
setPosition(position: ChartTitlePosition): void;
/**
* Represents a boolean value that determines if the chart title has a shadow.
*/
getShowShadow(): boolean;
/**
* Represents a boolean value that determines if the chart title has a shadow.
*/
setShowShadow(showShadow: boolean): void;
/**
* Specifies the chart's title text.
*/
getText(): string;
/**
* Specifies the chart's title text.
*/
setText(text: string): void;
/**
* Specifies the angle to which the text is oriented for the chart title. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Specifies the angle to which the text is oriented for the chart title. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Specifies the distance, in points, from the top edge of chart title to the top of chart area. Null if chart title is not visible.
*/
getTop(): number;
/**
* Specifies the distance, in points, from the top edge of chart title to the top of chart area. Null if chart title is not visible.
*/
setTop(top: number): void;
/**
* Specifies the vertical alignment of chart title. See ExcelScript.ChartTextVerticalAlignment for details.
*/
getVerticalAlignment(): ChartTextVerticalAlignment;
/**
* Specifies the vertical alignment of chart title. See ExcelScript.ChartTextVerticalAlignment for details.
*/
setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;
/**
* Specifies if the chart title is visibile.
*/
getVisible(): boolean;
/**
* Specifies if the chart title is visibile.
*/
setVisible(visible: boolean): void;
/**
* Specifies the width, in points, of the chart title. Null if chart title is not visible.
*/
getWidth(): number;
/**
* Get the substring of a chart title. Line break '\n' also counts one character.
* @param start Start position of substring to be retrieved. Position start with 0.
* @param length Length of substring to be retrieved.
*/
getSubstring(start: number, length: number): ChartFormatString;
/**
* Sets a string value that represents the formula of chart title using A1-style notation.
* @param formula A string that represents the formula to set.
*/
setFormula(formula: string): void;
}
/**
* Represents the substring in chart related objects that contains text, like ChartTitle object, ChartAxisTitle object, etc.
*/
interface ChartFormatString {
/**
* Represents the font attributes, such as font name, font size, color, etc. of chart characters object.
*/
getFont(): ChartFont;
}
/**
* Provides access to the office art formatting for chart title.
*/
interface ChartTitleFormat {
/**
* Represents the border format of chart title, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Represents the fill format of an object, which includes background formatting information.
*/
getFill(): ChartFill;
/**
* Represents the font attributes (font name, font size, color, etc.) for an object.
*/
getFont(): ChartFont;
}
/**
* Represents the fill formatting for a chart element.
*/
interface ChartFill {
/**
* Clear the fill color of a chart element.
*/
clear(): void;
/**
* Sets the fill formatting of a chart element to a uniform color.
* @param color HTML color code representing the color of the background, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setSolidColor(color: string): void;
}
/**
* Represents the border formatting of a chart element.
*/
interface ChartBorder {
/**
* HTML color code representing the color of borders in the chart.
*/
getColor(): string;
/**
* HTML color code representing the color of borders in the chart.
*/
setColor(color: string): void;
/**
* Represents the line style of the border. See ExcelScript.ChartLineStyle for details.
*/
getLineStyle(): ChartLineStyle;
/**
* Represents the line style of the border. See ExcelScript.ChartLineStyle for details.
*/
setLineStyle(lineStyle: ChartLineStyle): void;
/**
* Represents weight of the border, in points.
*/
getWeight(): number;
/**
* Represents weight of the border, in points.
*/
setWeight(weight: number): void;
/**
* Clear the border format of a chart element.
*/
clear(): void;
}
/**
* Encapsulates the bin options for histogram charts and pareto charts.
*/
interface ChartBinOptions {
/**
* Specifies if bin overflow is enabled in a histogram chart or pareto chart.
*/
getAllowOverflow(): boolean;
/**
* Specifies if bin overflow is enabled in a histogram chart or pareto chart.
*/
setAllowOverflow(allowOverflow: boolean): void;
/**
* Specifies if bin underflow is enabled in a histogram chart or pareto chart.
*/
getAllowUnderflow(): boolean;
/**
* Specifies if bin underflow is enabled in a histogram chart or pareto chart.
*/
setAllowUnderflow(allowUnderflow: boolean): void;
/**
* Specifies the bin count of a histogram chart or pareto chart.
*/
getCount(): number;
/**
* Specifies the bin count of a histogram chart or pareto chart.
*/
setCount(count: number): void;
/**
* Specifies the bin overflow value of a histogram chart or pareto chart.
*/
getOverflowValue(): number;
/**
* Specifies the bin overflow value of a histogram chart or pareto chart.
*/
setOverflowValue(overflowValue: number): void;
/**
* Specifies the bin's type for a histogram chart or pareto chart.
*/
getType(): ChartBinType;
/**
* Specifies the bin's type for a histogram chart or pareto chart.
*/
setType(type: ChartBinType): void;
/**
* Specifies the bin underflow value of a histogram chart or pareto chart.
*/
getUnderflowValue(): number;
/**
* Specifies the bin underflow value of a histogram chart or pareto chart.
*/
setUnderflowValue(underflowValue: number): void;
/**
* Specifies the bin width value of a histogram chart or pareto chart.
*/
getWidth(): number;
/**
* Specifies the bin width value of a histogram chart or pareto chart.
*/
setWidth(width: number): void;
}
/**
* Represents the properties of a box and whisker chart.
*/
interface ChartBoxwhiskerOptions {
/**
* Specifies if the quartile calculation type of a box and whisker chart.
*/
getQuartileCalculation(): ChartBoxQuartileCalculation;
/**
* Specifies if the quartile calculation type of a box and whisker chart.
*/
setQuartileCalculation(
quartileCalculation: ChartBoxQuartileCalculation
): void;
/**
* Specifies if inner points are shown in a box and whisker chart.
*/
getShowInnerPoints(): boolean;
/**
* Specifies if inner points are shown in a box and whisker chart.
*/
setShowInnerPoints(showInnerPoints: boolean): void;
/**
* Specifies if the mean line is shown in a box and whisker chart.
*/
getShowMeanLine(): boolean;
/**
* Specifies if the mean line is shown in a box and whisker chart.
*/
setShowMeanLine(showMeanLine: boolean): void;
/**
* Specifies if the mean marker is shown in a box and whisker chart.
*/
getShowMeanMarker(): boolean;
/**
* Specifies if the mean marker is shown in a box and whisker chart.
*/
setShowMeanMarker(showMeanMarker: boolean): void;
/**
* Specifies if outlier points are shown in a box and whisker chart.
*/
getShowOutlierPoints(): boolean;
/**
* Specifies if outlier points are shown in a box and whisker chart.
*/
setShowOutlierPoints(showOutlierPoints: boolean): void;
}
/**
* Encapsulates the formatting options for line elements.
*/
interface ChartLineFormat {
/**
* HTML color code representing the color of lines in the chart.
*/
getColor(): string;
/**
* HTML color code representing the color of lines in the chart.
*/
setColor(color: string): void;
/**
* Represents the line style. See ExcelScript.ChartLineStyle for details.
*/
getLineStyle(): ChartLineStyle;
/**
* Represents the line style. See ExcelScript.ChartLineStyle for details.
*/
setLineStyle(lineStyle: ChartLineStyle): void;
/**
* Represents weight of the line, in points.
*/
getWeight(): number;
/**
* Represents weight of the line, in points.
*/
setWeight(weight: number): void;
/**
* Clear the line format of a chart element.
*/
clear(): void;
}
/**
* This object represents the font attributes (font name, font size, color, etc.) for a chart object.
*/
interface ChartFont {
/**
* Represents the bold status of font.
*/
getBold(): boolean;
/**
* Represents the bold status of font.
*/
setBold(bold: boolean): void;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
getColor(): string;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
setColor(color: string): void;
/**
* Represents the italic status of the font.
*/
getItalic(): boolean;
/**
* Represents the italic status of the font.
*/
setItalic(italic: boolean): void;
/**
* Font name (e.g., "Calibri")
*/
getName(): string;
/**
* Font name (e.g., "Calibri")
*/
setName(name: string): void;
/**
* Size of the font (e.g., 11)
*/
getSize(): number;
/**
* Size of the font (e.g., 11)
*/
setSize(size: number): void;
/**
* Type of underline applied to the font. See ExcelScript.ChartUnderlineStyle for details.
*/
getUnderline(): ChartUnderlineStyle;
/**
* Type of underline applied to the font. See ExcelScript.ChartUnderlineStyle for details.
*/
setUnderline(underline: ChartUnderlineStyle): void;
}
/**
* This object represents the attributes for a chart trendline object.
*/
interface ChartTrendline {
/**
* Represents the number of periods that the trendline extends backward.
*/
getBackwardPeriod(): number;
/**
* Represents the number of periods that the trendline extends backward.
*/
setBackwardPeriod(backwardPeriod: number): void;
/**
* Represents the formatting of a chart trendline.
*/
getFormat(): ChartTrendlineFormat;
/**
* Represents the number of periods that the trendline extends forward.
*/
getForwardPeriod(): number;
/**
* Represents the number of periods that the trendline extends forward.
*/
setForwardPeriod(forwardPeriod: number): void;
/**
* Specifies the intercept value of the trendline.
*/
getIntercept(): number;
/**
* Specifies the intercept value of the trendline.
*/
setIntercept(intercept: number): void;
/**
* Represents the label of a chart trendline.
*/
getLabel(): ChartTrendlineLabel;
/**
* Represents the period of a chart trendline. Only applicable for trendline with MovingAverage type.
*/
getMovingAveragePeriod(): number;
/**
* Represents the period of a chart trendline. Only applicable for trendline with MovingAverage type.
*/
setMovingAveragePeriod(movingAveragePeriod: number): void;
/**
* Represents the name of the trendline. Can be set to a string value, or can be set to null value represents automatic values. The returned value is always a string
*/
getName(): string;
/**
* Represents the name of the trendline. Can be set to a string value, or can be set to null value represents automatic values. The returned value is always a string
*/
setName(name: string): void;
/**
* Represents the order of a chart trendline. Only applicable for trendline with Polynomial type.
*/
getPolynomialOrder(): number;
/**
* Represents the order of a chart trendline. Only applicable for trendline with Polynomial type.
*/
setPolynomialOrder(polynomialOrder: number): void;
/**
* True if the equation for the trendline is displayed on the chart.
*/
getShowEquation(): boolean;
/**
* True if the equation for the trendline is displayed on the chart.
*/
setShowEquation(showEquation: boolean): void;
/**
* True if the R-squared for the trendline is displayed on the chart.
*/
getShowRSquared(): boolean;
/**
* True if the R-squared for the trendline is displayed on the chart.
*/
setShowRSquared(showRSquared: boolean): void;
/**
* Represents the type of a chart trendline.
*/
getType(): ChartTrendlineType;
/**
* Represents the type of a chart trendline.
*/
setType(type: ChartTrendlineType): void;
/**
* Delete the trendline object.
*/
delete(): void;
}
/**
* Represents the format properties for chart trendline.
*/
interface ChartTrendlineFormat {
/**
* Represents chart line formatting.
*/
getLine(): ChartLineFormat;
}
/**
* This object represents the attributes for a chart trendline lable object.
*/
interface ChartTrendlineLabel {
/**
* Specifies if trendline label automatically generate appropriate text based on context.
*/
getAutoText(): boolean;
/**
* Specifies if trendline label automatically generate appropriate text based on context.
*/
setAutoText(autoText: boolean): void;
/**
* The format of chart trendline label.
*/
getFormat(): ChartTrendlineLabelFormat;
/**
* String value that represents the formula of chart trendline label using A1-style notation.
*/
getFormula(): string;
/**
* String value that represents the formula of chart trendline label using A1-style notation.
*/
setFormula(formula: string): void;
/**
* Returns the height, in points, of the chart trendline label. Null if chart trendline label is not visible.
*/
getHeight(): number;
/**
* Represents the horizontal alignment for chart trendline label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of trendline label is -90, 90, or 180.
*/
getHorizontalAlignment(): ChartTextHorizontalAlignment;
/**
* Represents the horizontal alignment for chart trendline label. See ExcelScript.ChartTextHorizontalAlignment for details.
* This property is valid only when TextOrientation of trendline label is -90, 90, or 180.
*/
setHorizontalAlignment(
horizontalAlignment: ChartTextHorizontalAlignment
): void;
/**
* Represents the distance, in points, from the left edge of chart trendline label to the left edge of chart area. Null if chart trendline label is not visible.
*/
getLeft(): number;
/**
* Represents the distance, in points, from the left edge of chart trendline label to the left edge of chart area. Null if chart trendline label is not visible.
*/
setLeft(left: number): void;
/**
* Specifies if the number format is linked to the cells (so that the number format changes in the labels when it changes in the cells).
*/
getLinkNumberFormat(): boolean;
/**
* Specifies if the number format is linked to the cells (so that the number format changes in the labels when it changes in the cells).
*/
setLinkNumberFormat(linkNumberFormat: boolean): void;
/**
* String value that represents the format code for trendline label.
*/
getNumberFormat(): string;
/**
* String value that represents the format code for trendline label.
*/
setNumberFormat(numberFormat: string): void;
/**
* String representing the text of the trendline label on a chart.
*/
getText(): string;
/**
* String representing the text of the trendline label on a chart.
*/
setText(text: string): void;
/**
* Represents the angle to which the text is oriented for the chart trendline label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
getTextOrientation(): number;
/**
* Represents the angle to which the text is oriented for the chart trendline label. The value should either be an integer from -90 to 90 or the integer 180 for vertically-oriented text.
*/
setTextOrientation(textOrientation: number): void;
/**
* Represents the distance, in points, from the top edge of chart trendline label to the top of chart area. Null if chart trendline label is not visible.
*/
getTop(): number;
/**
* Represents the distance, in points, from the top edge of chart trendline label to the top of chart area. Null if chart trendline label is not visible.
*/
setTop(top: number): void;
/**
* Represents the vertical alignment of chart trendline label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of trendline label is 0.
*/
getVerticalAlignment(): ChartTextVerticalAlignment;
/**
* Represents the vertical alignment of chart trendline label. See ExcelScript.ChartTextVerticalAlignment for details.
* This property is valid only when TextOrientation of trendline label is 0.
*/
setVerticalAlignment(
verticalAlignment: ChartTextVerticalAlignment
): void;
/**
* Returns the width, in points, of the chart trendline label. Null if chart trendline label is not visible.
*/
getWidth(): number;
}
/**
* Encapsulates the format properties for the chart trendline label.
*/
interface ChartTrendlineLabelFormat {
/**
* Specifies the border format, which includes color, linestyle, and weight.
*/
getBorder(): ChartBorder;
/**
* Specifies the fill format of the current chart trendline label.
*/
getFill(): ChartFill;
/**
* Specifies the font attributes (font name, font size, color, etc.) for a chart trendline label.
*/
getFont(): ChartFont;
}
/**
* This object represents the attributes for a chart plotArea object.
*/
interface ChartPlotArea {
/**
* Specifies the formatting of a chart plotArea.
*/
getFormat(): ChartPlotAreaFormat;
/**
* Specifies the height value of plotArea.
*/
getHeight(): number;
/**
* Specifies the height value of plotArea.
*/
setHeight(height: number): void;
/**
* Specifies the insideHeight value of plotArea.
*/
getInsideHeight(): number;
/**
* Specifies the insideHeight value of plotArea.
*/
setInsideHeight(insideHeight: number): void;
/**
* Specifies the insideLeft value of plotArea.
*/
getInsideLeft(): number;
/**
* Specifies the insideLeft value of plotArea.
*/
setInsideLeft(insideLeft: number): void;
/**
* Specifies the insideTop value of plotArea.
*/
getInsideTop(): number;
/**
* Specifies the insideTop value of plotArea.
*/
setInsideTop(insideTop: number): void;
/**
* Specifies the insideWidth value of plotArea.
*/
getInsideWidth(): number;
/**
* Specifies the insideWidth value of plotArea.
*/
setInsideWidth(insideWidth: number): void;
/**
* Specifies the left value of plotArea.
*/
getLeft(): number;
/**
* Specifies the left value of plotArea.
*/
setLeft(left: number): void;
/**
* Specifies the position of plotArea.
*/
getPosition(): ChartPlotAreaPosition;
/**
* Specifies the position of plotArea.
*/
setPosition(position: ChartPlotAreaPosition): void;
/**
* Specifies the top value of plotArea.
*/
getTop(): number;
/**
* Specifies the top value of plotArea.
*/
setTop(top: number): void;
/**
* Specifies the width value of plotArea.
*/
getWidth(): number;
/**
* Specifies the width value of plotArea.
*/
setWidth(width: number): void;
}
/**
* Represents the format properties for chart plotArea.
*/
interface ChartPlotAreaFormat {
/**
* Specifies the border attributes of a chart plotArea.
*/
getBorder(): ChartBorder;
/**
* Specifies the fill format of an object, which includes background formatting information.
*/
getFill(): ChartFill;
}
/**
* Manages sorting operations on Range objects.
*/
interface RangeSort {
/**
* Perform a sort operation.
* @param fields The list of conditions to sort on.
* @param matchCase Optional. Whether to have the casing impact string ordering.
* @param hasHeaders Optional. Whether the range has a header.
* @param orientation Optional. Whether the operation is sorting rows or columns.
* @param method Optional. The ordering method used for Chinese characters.
*/
apply(
fields: SortField[],
matchCase?: boolean,
hasHeaders?: boolean,
orientation?: SortOrientation,
method?: SortMethod
): void;
}
/**
* Manages sorting operations on Table objects.
*/
interface TableSort {
/**
* Specifies the current conditions used to last sort the table.
*/
getFields(): SortField[];
/**
* Specifies if the casing impacts the last sort of the table.
*/
getMatchCase(): boolean;
/**
* Represents Chinese character ordering method last used to sort the table.
*/
getMethod(): SortMethod;
/**
* Perform a sort operation.
* @param fields The list of conditions to sort on.
* @param matchCase Optional. Whether to have the casing impact string ordering.
* @param method Optional. The ordering method used for Chinese characters.
*/
apply(
fields: SortField[],
matchCase?: boolean,
method?: SortMethod
): void;
/**
* Clears the sorting that is currently on the table. While this doesn't modify the table's ordering, it clears the state of the header buttons.
*/
clear(): void;
/**
* Reapplies the current sorting parameters to the table.
*/
reapply(): void;
}
/**
* Manages the filtering of a table's column.
*/
interface Filter {
/**
* The currently applied filter on the given column.
*/
getCriteria(): FilterCriteria;
/**
* Apply the given filter criteria on the given column.
* @param criteria The criteria to apply.
*/
apply(criteria: FilterCriteria): void;
/**
* Apply a "Bottom Item" filter to the column for the given number of elements.
* @param count The number of elements from the bottom to show.
*/
applyBottomItemsFilter(count: number): void;
/**
* Apply a "Bottom Percent" filter to the column for the given percentage of elements.
* @param percent The percentage of elements from the bottom to show.
*/
applyBottomPercentFilter(percent: number): void;
/**
* Apply a "Cell Color" filter to the column for the given color.
* @param color The background color of the cells to show.
*/
applyCellColorFilter(color: string): void;
/**
* Apply an "Icon" filter to the column for the given criteria strings.
* @param criteria1 The first criteria string.
* @param criteria2 Optional. The second criteria string.
* @param oper Optional. The operator that describes how the two criteria are joined.
*/
applyCustomFilter(
criteria1: string,
criteria2?: string,
oper?: FilterOperator
): void;
/**
* Apply a "Dynamic" filter to the column.
* @param criteria The dynamic criteria to apply.
*/
applyDynamicFilter(criteria: DynamicFilterCriteria): void;
/**
* Apply a "Font Color" filter to the column for the given color.
* @param color The font color of the cells to show.
*/
applyFontColorFilter(color: string): void;
/**
* Apply an "Icon" filter to the column for the given icon.
* @param icon The icons of the cells to show.
*/
applyIconFilter(icon: Icon): void;
/**
* Apply a "Top Item" filter to the column for the given number of elements.
* @param count The number of elements from the top to show.
*/
applyTopItemsFilter(count: number): void;
/**
* Apply a "Top Percent" filter to the column for the given percentage of elements.
* @param percent The percentage of elements from the top to show.
*/
applyTopPercentFilter(percent: number): void;
/**
* Apply a "Values" filter to the column for the given values.
* @param values The list of values to show. This must be an array of strings or an array of ExcelScript.FilterDateTime objects.
*/
applyValuesFilter(values: Array<string | FilterDatetime>): void;
/**
* Clear the filter on the given column.
*/
clear(): void;
}
/**
* Represents the AutoFilter object.
* AutoFilter turns the values in Excel column into specific filters based on the cell contents.
*/
interface AutoFilter {
/**
* An array that holds all the filter criteria in the autofiltered range.
*/
getCriteria(): FilterCriteria[];
/**
* Specifies if the AutoFilter is enabled.
*/
getEnabled(): boolean;
/**
* Specifies if the AutoFilter has filter criteria.
*/
getIsDataFiltered(): boolean;
/**
* Applies the AutoFilter to a range. This filters the column if column index and filter criteria are specified.
* @param range The range over which the AutoFilter will apply on.
* @param columnIndex The zero-based column index to which the AutoFilter is applied.
* @param criteria The filter criteria.
*/
apply(
range: Range | string,
columnIndex?: number,
criteria?: FilterCriteria
): void;
/**
* Clears the filter criteria of the AutoFilter.
*/
clearCriteria(): void;
/**
* Returns the `Range` object that represents the range to which the `AutoFilter` applies.
* If there is no `Range` object associated with the `AutoFilter`, then this method returns an object with its `isNullObject` property set to `true`.
*/
getRange(): Range;
/**
* Applies the specified Autofilter object currently on the range.
*/
reapply(): void;
/**
* Removes the AutoFilter for the range.
*/
remove(): void;
}
/**
* Provides information based on current system culture settings. This includes the culture names, number formatting, and other culturally dependent settings.
*/
interface CultureInfo {
/**
* Defines the culturally appropriate format of displaying date and time. This is based on current system culture settings.
*/
getDatetimeFormat(): DatetimeFormatInfo;
/**
* Gets the culture name in the format languagecode2-country/regioncode2 (e.g., "zh-cn" or "en-us"). This is based on current system settings.
*/
getName(): string;
/**
* Defines the culturally appropriate format of displaying numbers. This is based on current system culture settings.
*/
getNumberFormat(): NumberFormatInfo;
}
/**
* Defines the culturally appropriate format of displaying numbers. This is based on current system culture settings.
*/
interface NumberFormatInfo {
/**
* Gets the string used as the decimal separator for numeric values. This is based on current system settings.
*/
getNumberDecimalSeparator(): string;
/**
* Gets the string used to separate groups of digits to the left of the decimal for numeric values. This is based on current system settings.
*/
getNumberGroupSeparator(): string;
}
/**
* Defines the culturally appropriate format of displaying numbers. This is based on current system culture settings.
*/
interface DatetimeFormatInfo {
/**
* Gets the string used as the date separator. This is based on current system settings.
*/
getDateSeparator(): string;
/**
* Gets the format string for a long date value. This is based on current system settings.
*/
getLongDatePattern(): string;
/**
* Gets the format string for a long time value. This is based on current system settings.
*/
getLongTimePattern(): string;
/**
* Gets the format string for a short date value. This is based on current system settings.
*/
getShortDatePattern(): string;
/**
* Gets the string used as the time separator. This is based on current system settings.
*/
getTimeSeparator(): string;
}
/**
* Represents a custom XML part object in a workbook.
*/
interface CustomXmlPart {
/**
* The custom XML part's ID.
*/
getId(): string;
/**
* The custom XML part's namespace URI.
*/
getNamespaceUri(): string;
/**
* Deletes the custom XML part.
*/
delete(): void;
/**
* Gets the custom XML part's full XML content.
*/
getXml(): string;
/**
* Sets the custom XML part's full XML content.
* @param xml XML content for the part.
*/
setXml(xml: string): void;
}
/**
* Represents an Excel PivotTable.
*/
interface PivotTable {
/**
* Specifies if the PivotTable allows the application of multiple PivotFilters on a given PivotField in the table.
*/
getAllowMultipleFiltersPerField(): boolean;
/**
* Specifies if the PivotTable allows the application of multiple PivotFilters on a given PivotField in the table.
*/
setAllowMultipleFiltersPerField(
allowMultipleFiltersPerField: boolean
): void;
/**
* Specifies if the PivotTable allows values in the data body to be edited by the user.
*/
getEnableDataValueEditing(): boolean;
/**
* Specifies if the PivotTable allows values in the data body to be edited by the user.
*/
setEnableDataValueEditing(enableDataValueEditing: boolean): void;
/**
* Id of the PivotTable.
*/
getId(): string;
/**
* The PivotLayout describing the layout and visual structure of the PivotTable.
*/
getLayout(): PivotLayout;
/**
* Name of the PivotTable.
*/
getName(): string;
/**
* Name of the PivotTable.
*/
setName(name: string): void;
/**
* Specifies if the PivotTable uses custom lists when sorting.
*/
getUseCustomSortLists(): boolean;
/**
* Specifies if the PivotTable uses custom lists when sorting.
*/
setUseCustomSortLists(useCustomSortLists: boolean): void;
/**
* The worksheet containing the current PivotTable.
*/
getWorksheet(): Worksheet;
/**
* Deletes the PivotTable.
*/
delete(): void;
/**
* Refreshes the PivotTable.
*/
refresh(): void;
/**
* The Column Pivot Hierarchies of the PivotTable.
*/
getColumnHierarchies(): RowColumnPivotHierarchy[];
/**
* Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on the row, column,
* or filter axis, it will be removed from that location.
*/
addColumnHierarchy(
pivotHierarchy: PivotHierarchy
): RowColumnPivotHierarchy;
/**
* Gets a RowColumnPivotHierarchy by name. If the RowColumnPivotHierarchy does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the RowColumnPivotHierarchy to be retrieved.
*/
getColumnHierarchy(name: string): RowColumnPivotHierarchy | undefined;
/**
* Removes the PivotHierarchy from the current axis.
*/
removeColumnHierarchy(
rowColumnPivotHierarchy: RowColumnPivotHierarchy
): void;
/**
* The Data Pivot Hierarchies of the PivotTable.
*/
getDataHierarchies(): DataPivotHierarchy[];
/**
* Adds the PivotHierarchy to the current axis.
*/
addDataHierarchy(pivotHierarchy: PivotHierarchy): DataPivotHierarchy;
/**
* Gets a DataPivotHierarchy by name. If the DataPivotHierarchy does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the DataPivotHierarchy to be retrieved.
*/
getDataHierarchy(name: string): DataPivotHierarchy | undefined;
/**
* Removes the PivotHierarchy from the current axis.
*/
removeDataHierarchy(DataPivotHierarchy: DataPivotHierarchy): void;
/**
* The Filter Pivot Hierarchies of the PivotTable.
*/
getFilterHierarchies(): FilterPivotHierarchy[];
/**
* Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on the row, column,
* or filter axis, it will be removed from that location.
*/
addFilterHierarchy(
pivotHierarchy: PivotHierarchy
): FilterPivotHierarchy;
/**
* Gets a FilterPivotHierarchy by name. If the FilterPivotHierarchy does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the FilterPivotHierarchy to be retrieved.
*/
getFilterHierarchy(name: string): FilterPivotHierarchy | undefined;
/**
* Removes the PivotHierarchy from the current axis.
*/
removeFilterHierarchy(filterPivotHierarchy: FilterPivotHierarchy): void;
/**
* The Pivot Hierarchies of the PivotTable.
*/
getHierarchies(): PivotHierarchy[];
/**
* Gets a PivotHierarchy by name. If the PivotHierarchy does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotHierarchy to be retrieved.
*/
getHierarchy(name: string): PivotHierarchy | undefined;
/**
* The Row Pivot Hierarchies of the PivotTable.
*/
getRowHierarchies(): RowColumnPivotHierarchy[];
/**
* Adds the PivotHierarchy to the current axis. If the hierarchy is present elsewhere on the row, column,
* or filter axis, it will be removed from that location.
*/
addRowHierarchy(
pivotHierarchy: PivotHierarchy
): RowColumnPivotHierarchy;
/**
* Gets a RowColumnPivotHierarchy by name. If the RowColumnPivotHierarchy does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the RowColumnPivotHierarchy to be retrieved.
*/
getRowHierarchy(name: string): RowColumnPivotHierarchy | undefined;
/**
* Removes the PivotHierarchy from the current axis.
*/
removeRowHierarchy(
rowColumnPivotHierarchy: RowColumnPivotHierarchy
): void;
}
/**
* Represents the visual layout of the PivotTable.
*/
interface PivotLayout {
/**
* Specifies if formatting will be automatically formatted when it’s refreshed or when fields are moved.
*/
getAutoFormat(): boolean;
/**
* Specifies if formatting will be automatically formatted when it’s refreshed or when fields are moved.
*/
setAutoFormat(autoFormat: boolean): void;
/**
* Specifies if the field list can be shown in the UI.
*/
getEnableFieldList(): boolean;
/**
* Specifies if the field list can be shown in the UI.
*/
setEnableFieldList(enableFieldList: boolean): void;
/**
* This property indicates the PivotLayoutType of all fields on the PivotTable. If fields have different states, this will be null.
*/
getLayoutType(): PivotLayoutType;
/**
* This property indicates the PivotLayoutType of all fields on the PivotTable. If fields have different states, this will be null.
*/
setLayoutType(layoutType: PivotLayoutType): void;
/**
* Specifies if formatting is preserved when the report is refreshed or recalculated by operations such as pivoting, sorting, or changing page field items.
*/
getPreserveFormatting(): boolean;
/**
* Specifies if formatting is preserved when the report is refreshed or recalculated by operations such as pivoting, sorting, or changing page field items.
*/
setPreserveFormatting(preserveFormatting: boolean): void;
/**
* Specifies if the PivotTable report shows grand totals for columns.
*/
getShowColumnGrandTotals(): boolean;
/**
* Specifies if the PivotTable report shows grand totals for columns.
*/
setShowColumnGrandTotals(showColumnGrandTotals: boolean): void;
/**
* Specifies if the PivotTable report shows grand totals for rows.
*/
getShowRowGrandTotals(): boolean;
/**
* Specifies if the PivotTable report shows grand totals for rows.
*/
setShowRowGrandTotals(showRowGrandTotals: boolean): void;
/**
* This property indicates the SubtotalLocationType of all fields on the PivotTable. If fields have different states, this will be null.
*/
getSubtotalLocation(): SubtotalLocationType;
/**
* This property indicates the SubtotalLocationType of all fields on the PivotTable. If fields have different states, this will be null.
*/
setSubtotalLocation(subtotalLocation: SubtotalLocationType): void;
/**
* Returns the range where the PivotTable's column labels reside.
*/
getColumnLabelRange(): Range;
/**
* Returns the range where the PivotTable's data values reside.
*/
getBodyAndTotalRange(): Range;
/**
* Gets the DataHierarchy that is used to calculate the value in a specified range within the PivotTable.
* @param cell A single cell within the PivotTable data body.
*/
getDataHierarchy(cell: Range | string): DataPivotHierarchy;
/**
* Returns the range of the PivotTable's filter area.
*/
getFilterAxisRange(): Range;
/**
* Returns the range the PivotTable exists on, excluding the filter area.
*/
getRange(): Range;
/**
* Returns the range where the PivotTable's row labels reside.
*/
getRowLabelRange(): Range;
/**
* Sets the PivotTable to automatically sort using the specified cell to automatically select all necessary criteria and context. This behaves identically to applying an autosort from the UI.
* @param cell A single cell to use get the criteria from for applying the autosort.
* @param sortBy The direction of the sort.
*/
setAutoSortOnCell(cell: Range | string, sortBy: SortBy): void;
}
/**
* Represents the Excel PivotHierarchy.
*/
interface PivotHierarchy {
/**
* Id of the PivotHierarchy.
*/
getId(): string;
/**
* Name of the PivotHierarchy.
*/
getName(): string;
/**
* Name of the PivotHierarchy.
*/
setName(name: string): void;
/**
* Returns the PivotFields associated with the PivotHierarchy.
*/
getFields(): PivotField[];
/**
* Gets a PivotField by name. If the PivotField does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotField to be retrieved.
*/
getPivotField(name: string): PivotField | undefined;
}
/**
* Represents the Excel RowColumnPivotHierarchy.
*/
interface RowColumnPivotHierarchy {
/**
* Id of the RowColumnPivotHierarchy.
*/
getId(): string;
/**
* Name of the RowColumnPivotHierarchy.
*/
getName(): string;
/**
* Name of the RowColumnPivotHierarchy.
*/
setName(name: string): void;
/**
* Position of the RowColumnPivotHierarchy.
*/
getPosition(): number;
/**
* Position of the RowColumnPivotHierarchy.
*/
setPosition(position: number): void;
/**
* Reset the RowColumnPivotHierarchy back to its default values.
*/
setToDefault(): void;
/**
* Returns the PivotFields associated with the RowColumnPivotHierarchy.
*/
getFields(): PivotField[];
/**
* Gets a PivotField by name. If the PivotField does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotField to be retrieved.
*/
getPivotField(name: string): PivotField | undefined;
}
/**
* Represents the Excel FilterPivotHierarchy.
*/
interface FilterPivotHierarchy {
/**
* Determines whether to allow multiple filter items.
*/
getEnableMultipleFilterItems(): boolean;
/**
* Determines whether to allow multiple filter items.
*/
setEnableMultipleFilterItems(enableMultipleFilterItems: boolean): void;
/**
* Id of the FilterPivotHierarchy.
*/
getId(): string;
/**
* Name of the FilterPivotHierarchy.
*/
getName(): string;
/**
* Name of the FilterPivotHierarchy.
*/
setName(name: string): void;
/**
* Position of the FilterPivotHierarchy.
*/
getPosition(): number;
/**
* Position of the FilterPivotHierarchy.
*/
setPosition(position: number): void;
/**
* Reset the FilterPivotHierarchy back to its default values.
*/
setToDefault(): void;
/**
* Returns the PivotFields associated with the FilterPivotHierarchy.
*/
getFields(): PivotField[];
/**
* Gets a PivotField by name. If the PivotField does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotField to be retrieved.
*/
getPivotField(name: string): PivotField | undefined;
}
/**
* Represents the Excel DataPivotHierarchy.
*/
interface DataPivotHierarchy {
/**
* Returns the PivotFields associated with the DataPivotHierarchy.
*/
getField(): PivotField;
/**
* Id of the DataPivotHierarchy.
*/
getId(): string;
/**
* Name of the DataPivotHierarchy.
*/
getName(): string;
/**
* Name of the DataPivotHierarchy.
*/
setName(name: string): void;
/**
* Number format of the DataPivotHierarchy.
*/
getNumberFormat(): string;
/**
* Number format of the DataPivotHierarchy.
*/
setNumberFormat(numberFormat: string): void;
/**
* Position of the DataPivotHierarchy.
*/
getPosition(): number;
/**
* Position of the DataPivotHierarchy.
*/
setPosition(position: number): void;
/**
* Specifies if the data should be shown as a specific summary calculation.
*/
getShowAs(): ShowAsRule;
/**
* Specifies if the data should be shown as a specific summary calculation.
*/
setShowAs(showAs: ShowAsRule): void;
/**
* Specifies if all items of the DataPivotHierarchy are shown.
*/
getSummarizeBy(): AggregationFunction;
/**
* Specifies if all items of the DataPivotHierarchy are shown.
*/
setSummarizeBy(summarizeBy: AggregationFunction): void;
/**
* Reset the DataPivotHierarchy back to its default values.
*/
setToDefault(): void;
}
/**
* Represents the Excel PivotField.
*/
interface PivotField {
/**
* Id of the PivotField.
*/
getId(): string;
/**
* Name of the PivotField.
*/
getName(): string;
/**
* Name of the PivotField.
*/
setName(name: string): void;
/**
* Determines whether to show all items of the PivotField.
*/
getShowAllItems(): boolean;
/**
* Determines whether to show all items of the PivotField.
*/
setShowAllItems(showAllItems: boolean): void;
/**
* Subtotals of the PivotField.
*/
getSubtotals(): Subtotals;
/**
* Subtotals of the PivotField.
*/
setSubtotals(subtotals: Subtotals): void;
/**
* Sets one or more of the field's current PivotFilters and applies them to the field.
* If the provided filters are invalid or cannot be applied, an exception is thrown.
* @param filter A configured specific PivotFilter or a PivotFilters interface containing multiple configured filters.
*/
applyFilter(filter: PivotFilters): void;
/**
* Clears all criteria from all of the field's filters. This removes any active filtering on the field.
*/
clearAllFilters(): void;
/**
* Clears all existing criteria from the field's filter of the given type (if one is currently applied).
* @param filterType The type of filter on the field of which to clear all criteria.
*/
clearFilter(filterType: PivotFilterType): void;
/**
* Gets all filters currently applied on the field.
*/
getFilters(): PivotFilters;
/**
* Checks if there are any applied filters on the field.
* @param filterType The filter type to check. If no type is provided, this method will check if any filter is applied.
*/
isFiltered(filterType?: PivotFilterType): boolean;
/**
* Sorts the PivotField. If a DataPivotHierarchy is specified, then sort will be applied based on it, if not sort will be based on the PivotField itself.
* @param sortBy Specifies if the sorting is done in ascending or descending order.
*/
sortByLabels(sortBy: SortBy): void;
/**
* Sorts the PivotField by specified values in a given scope. The scope defines which specific values will be used to sort when
* there are multiple values from the same DataPivotHierarchy.
* @param sortBy Specifies if the sorting is done in ascending or descending order.
* @param valuesHierarchy Specifies the values hierarchy on the data axis to be used for sorting.
* @param pivotItemScope The items that should be used for the scope of the sorting. These will be the
* items that make up the row or column that you want to sort on. If a string is used instead of a PivotItem,
* the string represents the ID of the PivotItem. If there are no items other than data hierarchy on the axis
* you want to sort on, this can be empty.
*/
sortByValues(
sortBy: SortBy,
valuesHierarchy: DataPivotHierarchy,
pivotItemScope?: Array<PivotItem | string>
): void;
/**
* Returns the PivotFields associated with the PivotField.
*/
getItems(): PivotItem[];
/**
* Gets a PivotItem by name. If the PivotItem does not exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param name Name of the PivotItem to be retrieved.
*/
getPivotItem(name: string): PivotItem | undefined;
}
/**
* Represents the Excel PivotItem.
*/
interface PivotItem {
/**
* Id of the PivotItem.
*/
getId(): string;
/**
* Determines whether the item is expanded to show child items or if it's collapsed and child items are hidden.
*/
getIsExpanded(): boolean;
/**
* Determines whether the item is expanded to show child items or if it's collapsed and child items are hidden.
*/
setIsExpanded(isExpanded: boolean): void;
/**
* Name of the PivotItem.
*/
getName(): string;
/**
* Name of the PivotItem.
*/
setName(name: string): void;
/**
* Specifies if the PivotItem is visible.
*/
getVisible(): boolean;
/**
* Specifies if the PivotItem is visible.
*/
setVisible(visible: boolean): void;
}
/**
* Represents a worksheet-level custom property.
*/
interface WorksheetCustomProperty {
/**
* Gets the key of the custom property. Custom property keys are case-insensitive. The key is limited to 255 characters (larger values will cause an "InvalidArgument" error to be thrown.)
*/
getKey(): string;
/**
* Gets or sets the value of the custom property.
*/
getValue(): string;
/**
* Gets or sets the value of the custom property.
*/
setValue(value: string): void;
/**
* Deletes the custom property.
*/
delete(): void;
}
/**
* Represents workbook properties.
*/
interface DocumentProperties {
/**
* The author of the workbook.
*/
getAuthor(): string;
/**
* The author of the workbook.
*/
setAuthor(author: string): void;
/**
* The category of the workbook.
*/
getCategory(): string;
/**
* The category of the workbook.
*/
setCategory(category: string): void;
/**
* The comments of the workbook.
*/
getComments(): string;
/**
* The comments of the workbook.
*/
setComments(comments: string): void;
/**
* The company of the workbook.
*/
getCompany(): string;
/**
* The company of the workbook.
*/
setCompany(company: string): void;
/**
* Gets the creation date of the workbook. Read only.
*/
getCreationDate(): Date;
/**
* The keywords of the workbook.
*/
getKeywords(): string;
/**
* The keywords of the workbook.
*/
setKeywords(keywords: string): void;
/**
* Gets the last author of the workbook. Read only.
*/
getLastAuthor(): string;
/**
* The manager of the workbook.
*/
getManager(): string;
/**
* The manager of the workbook.
*/
setManager(manager: string): void;
/**
* Gets the revision number of the workbook. Read only.
*/
getRevisionNumber(): number;
/**
* Gets the revision number of the workbook. Read only.
*/
setRevisionNumber(revisionNumber: number): void;
/**
* The subject of the workbook.
*/
getSubject(): string;
/**
* The subject of the workbook.
*/
setSubject(subject: string): void;
/**
* The title of the workbook.
*/
getTitle(): string;
/**
* The title of the workbook.
*/
setTitle(title: string): void;
/**
* Gets the collection of custom properties of the workbook. Read only.
*/
getCustom(): CustomProperty[];
/**
* Creates a new or sets an existing custom property.
* @param key Required. The custom property's key, which is case-insensitive. The key is limited to 255 characters outside of Excel on the web (larger keys are automatically trimmed to 255 characters on other platforms).
* @param value Required. The custom property's value. The value is limited to 255 characters outside of Excel on the web (larger values are automatically trimmed to 255 characters on other platforms).
*/
addCustomProperty(key: string, value: any): CustomProperty;
/**
* Deletes all custom properties in this collection.
*/
deleteAllCustomProperties(): void;
/**
* Gets a custom property object by its key, which is case-insensitive. If the custom property doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Required. The key that identifies the custom property object.
*/
getCustomProperty(key: string): CustomProperty | undefined;
}
/**
* Represents a custom property.
*/
interface CustomProperty {
/**
* The key of the custom property. The key is limited to 255 characters outside of Excel on the web (larger keys are automatically trimmed to 255 characters on other platforms).
*/
getKey(): string;
/**
* The type of the value used for the custom property.
*/
getType(): DocumentPropertyType;
/**
* The value of the custom property. The value is limited to 255 characters outside of Excel on the web (larger values are automatically trimmed to 255 characters on other platforms).
*/
getValue(): any;
/**
* The value of the custom property. The value is limited to 255 characters outside of Excel on the web (larger values are automatically trimmed to 255 characters on other platforms).
*/
setValue(value: any): void;
/**
* Deletes the custom property.
*/
delete(): void;
}
/**
* An object encapsulating a conditional format's range, format, rule, and other properties.
*/
interface ConditionalFormat {
/**
* Returns the cell value conditional format properties if the current conditional format is a CellValue type.
* For example to format all cells between 5 and 10.
*/
getCellValue(): CellValueConditionalFormat | undefined;
/**
* Returns the ColorScale conditional format properties if the current conditional format is an ColorScale type.
*/
getColorScale(): ColorScaleConditionalFormat | undefined;
/**
* Returns the custom conditional format properties if the current conditional format is a custom type.
*/
getCustom(): CustomConditionalFormat | undefined;
/**
* Returns the data bar properties if the current conditional format is a data bar.
*/
getDataBar(): DataBarConditionalFormat | undefined;
/**
* Returns the IconSet conditional format properties if the current conditional format is an IconSet type.
*/
getIconSet(): IconSetConditionalFormat | undefined;
/**
* The Priority of the Conditional Format within the current ConditionalFormatCollection.
*/
getId(): string;
/**
* Returns the preset criteria conditional format. See ExcelScript.PresetCriteriaConditionalFormat for more details.
*/
getPreset(): PresetCriteriaConditionalFormat | undefined;
/**
* The priority (or index) within the conditional format collection that this conditional format currently exists in. Changing this also
* changes other conditional formats' priorities, to allow for a contiguous priority order.
* Use a negative priority to begin from the back.
* Priorities greater than than bounds will get and set to the maximum (or minimum if negative) priority.
* Also note that if you change the priority, you have to re-fetch a new copy of the object at that new priority location if you want to make further changes to it.
*/
getPriority(): number;
/**
* The priority (or index) within the conditional format collection that this conditional format currently exists in. Changing this also
* changes other conditional formats' priorities, to allow for a contiguous priority order.
* Use a negative priority to begin from the back.
* Priorities greater than than bounds will get and set to the maximum (or minimum if negative) priority.
* Also note that if you change the priority, you have to re-fetch a new copy of the object at that new priority location if you want to make further changes to it.
*/
setPriority(priority: number): void;
/**
* If the conditions of this conditional format are met, no lower-priority formats shall take effect on that cell.
* Null on databars, icon sets, and colorscales as there's no concept of StopIfTrue for these
*/
getStopIfTrue(): boolean;
/**
* If the conditions of this conditional format are met, no lower-priority formats shall take effect on that cell.
* Null on databars, icon sets, and colorscales as there's no concept of StopIfTrue for these
*/
setStopIfTrue(stopIfTrue: boolean): void;
/**
* Returns the specific text conditional format properties if the current conditional format is a text type.
* For example to format cells matching the word "Text".
*/
getTextComparison(): TextConditionalFormat | undefined;
/**
* Returns the Top/Bottom conditional format properties if the current conditional format is an TopBottom type.
* For example to format the top 10% or bottom 10 items.
*/
getTopBottom(): TopBottomConditionalFormat | undefined;
/**
* A type of conditional format. Only one can be set at a time.
*/
getType(): ConditionalFormatType;
/**
* Deletes this conditional format.
*/
delete(): void;
/**
* Returns the range to which the conditonal format is applied. If the conditional format is applied to multiple ranges, then this function will return an object with its `isNullObject` property set to `true`.
*/
getRange(): Range;
/**
* Returns the RangeAreas, comprising one or more rectangular ranges, the conditonal format is applied to.
*/
getRanges(): RangeAreas;
}
/**
* Represents an Excel Conditional Data Bar Type.
*/
interface DataBarConditionalFormat {
/**
* HTML color code representing the color of the Axis line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "" (empty string) if no axis is present or set.
*/
getAxisColor(): string;
/**
* HTML color code representing the color of the Axis line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "" (empty string) if no axis is present or set.
*/
setAxisColor(axisColor: string): void;
/**
* Representation of how the axis is determined for an Excel data bar.
*/
getAxisFormat(): ConditionalDataBarAxisFormat;
/**
* Representation of how the axis is determined for an Excel data bar.
*/
setAxisFormat(axisFormat: ConditionalDataBarAxisFormat): void;
/**
* Specifies the direction that the data bar graphic should be based on.
*/
getBarDirection(): ConditionalDataBarDirection;
/**
* Specifies the direction that the data bar graphic should be based on.
*/
setBarDirection(barDirection: ConditionalDataBarDirection): void;
/**
* The rule for what consistutes the lower bound (and how to calculate it, if applicable) for a data bar.
* The `ConditionalDataBarRule` object must be set as a JSON object (use `x.lowerBoundRule = {...}` instead of `x.lowerBoundRule.formula = ...`).
*/
getLowerBoundRule(): ConditionalDataBarRule;
/**
* The rule for what consistutes the lower bound (and how to calculate it, if applicable) for a data bar.
* The `ConditionalDataBarRule` object must be set as a JSON object (use `x.lowerBoundRule = {...}` instead of `x.lowerBoundRule.formula = ...`).
*/
setLowerBoundRule(lowerBoundRule: ConditionalDataBarRule): void;
/**
* Representation of all values to the left of the axis in an Excel data bar.
*/
getNegativeFormat(): ConditionalDataBarNegativeFormat;
/**
* Representation of all values to the right of the axis in an Excel data bar.
*/
getPositiveFormat(): ConditionalDataBarPositiveFormat;
/**
* If true, hides the values from the cells where the data bar is applied.
*/
getShowDataBarOnly(): boolean;
/**
* If true, hides the values from the cells where the data bar is applied.
*/
setShowDataBarOnly(showDataBarOnly: boolean): void;
/**
* The rule for what constitutes the upper bound (and how to calculate it, if applicable) for a data bar.
* The `ConditionalDataBarRule` object must be set as a JSON object (use `x.upperBoundRule = {...}` instead of `x.upperBoundRule.formula = ...`).
*/
getUpperBoundRule(): ConditionalDataBarRule;
/**
* The rule for what constitutes the upper bound (and how to calculate it, if applicable) for a data bar.
* The `ConditionalDataBarRule` object must be set as a JSON object (use `x.upperBoundRule = {...}` instead of `x.upperBoundRule.formula = ...`).
*/
setUpperBoundRule(upperBoundRule: ConditionalDataBarRule): void;
}
/**
* Represents a conditional format DataBar Format for the positive side of the data bar.
*/
interface ConditionalDataBarPositiveFormat {
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "" (empty string) if no border is present or set.
*/
getBorderColor(): string;
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "" (empty string) if no border is present or set.
*/
setBorderColor(borderColor: string): void;
/**
* HTML color code representing the fill color, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getFillColor(): string;
/**
* HTML color code representing the fill color, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setFillColor(fillColor: string): void;
/**
* Specifies if the DataBar has a gradient.
*/
getGradientFill(): boolean;
/**
* Specifies if the DataBar has a gradient.
*/
setGradientFill(gradientFill: boolean): void;
}
/**
* Represents a conditional format DataBar Format for the negative side of the data bar.
*/
interface ConditionalDataBarNegativeFormat {
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "Empty String" if no border is present or set.
*/
getBorderColor(): string;
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
* "Empty String" if no border is present or set.
*/
setBorderColor(borderColor: string): void;
/**
* HTML color code representing the fill color, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getFillColor(): string;
/**
* HTML color code representing the fill color, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setFillColor(fillColor: string): void;
/**
* Specifies if the negative DataBar has the same border color as the positive DataBar.
*/
getMatchPositiveBorderColor(): boolean;
/**
* Specifies if the negative DataBar has the same border color as the positive DataBar.
*/
setMatchPositiveBorderColor(matchPositiveBorderColor: boolean): void;
/**
* Specifies if the negative DataBar has the same fill color as the positive DataBar.
*/
getMatchPositiveFillColor(): boolean;
/**
* Specifies if the negative DataBar has the same fill color as the positive DataBar.
*/
setMatchPositiveFillColor(matchPositiveFillColor: boolean): void;
}
/**
* Represents a custom conditional format type.
*/
interface CustomConditionalFormat {
/**
* Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties.
*/
getFormat(): ConditionalRangeFormat;
/**
* Specifies the Rule object on this conditional format.
*/
getRule(): ConditionalFormatRule;
}
/**
* Represents a rule, for all traditional rule/format pairings.
*/
interface ConditionalFormatRule {
/**
* The formula, if required, to evaluate the conditional format rule on.
*/
getFormula(): string;
/**
* The formula, if required, to evaluate the conditional format rule on.
*/
setFormula(formula: string): void;
/**
* The formula, if required, to evaluate the conditional format rule on in the user's language.
*/
getFormulaLocal(): string;
/**
* The formula, if required, to evaluate the conditional format rule on in the user's language.
*/
setFormulaLocal(formulaLocal: string): void;
}
/**
* Represents an IconSet criteria for conditional formatting.
*/
interface IconSetConditionalFormat {
/**
* An array of Criteria and IconSets for the rules and potential custom icons for conditional icons. Note that for the first criterion only the custom icon can be modified, while type, formula, and operator will be ignored when set.
*/
getCriteria(): ConditionalIconCriterion[];
/**
* An array of Criteria and IconSets for the rules and potential custom icons for conditional icons. Note that for the first criterion only the custom icon can be modified, while type, formula, and operator will be ignored when set.
*/
setCriteria(criteria: ConditionalIconCriterion[]): void;
/**
* If true, reverses the icon orders for the IconSet. Note that this cannot be set if custom icons are used.
*/
getReverseIconOrder(): boolean;
/**
* If true, reverses the icon orders for the IconSet. Note that this cannot be set if custom icons are used.
*/
setReverseIconOrder(reverseIconOrder: boolean): void;
/**
* If true, hides the values and only shows icons.
*/
getShowIconOnly(): boolean;
/**
* If true, hides the values and only shows icons.
*/
setShowIconOnly(showIconOnly: boolean): void;
/**
* If set, displays the IconSet option for the conditional format.
*/
getStyle(): IconSet;
/**
* If set, displays the IconSet option for the conditional format.
*/
setStyle(style: IconSet): void;
}
/**
* Represents ColorScale criteria for conditional formatting.
*/
interface ColorScaleConditionalFormat {
/**
* The criteria of the color scale. Midpoint is optional when using a two point color scale.
*/
getCriteria(): ConditionalColorScaleCriteria;
/**
* The criteria of the color scale. Midpoint is optional when using a two point color scale.
*/
setCriteria(criteria: ConditionalColorScaleCriteria): void;
/**
* If true the color scale will have three points (minimum, midpoint, maximum), otherwise it will have two (minimum, maximum).
*/
getThreeColorScale(): boolean;
}
/**
* Represents a Top/Bottom conditional format.
*/
interface TopBottomConditionalFormat {
/**
* Returns a format object, encapsulating the conditional format's font, fill, borders, and other properties.
*/
getFormat(): ConditionalRangeFormat;
/**
* The criteria of the Top/Bottom conditional format.
*/
getRule(): ConditionalTopBottomRule;
/**
* The criteria of the Top/Bottom conditional format.
*/
setRule(rule: ConditionalTopBottomRule): void;
}
/**
* Represents the the preset criteria conditional format such as above average, below average, unique values, contains blank, nonblank, error, and noerror.
*/
interface PresetCriteriaConditionalFormat {
/**
* Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties.
*/
getFormat(): ConditionalRangeFormat;
/**
* The rule of the conditional format.
*/
getRule(): ConditionalPresetCriteriaRule;
/**
* The rule of the conditional format.
*/
setRule(rule: ConditionalPresetCriteriaRule): void;
}
/**
* Represents a specific text conditional format.
*/
interface TextConditionalFormat {
/**
* Returns a format object, encapsulating the conditional format's font, fill, borders, and other properties.
*/
getFormat(): ConditionalRangeFormat;
/**
* The rule of the conditional format.
*/
getRule(): ConditionalTextComparisonRule;
/**
* The rule of the conditional format.
*/
setRule(rule: ConditionalTextComparisonRule): void;
}
/**
* Represents a cell value conditional format.
*/
interface CellValueConditionalFormat {
/**
* Returns a format object, encapsulating the conditional formats font, fill, borders, and other properties.
*/
getFormat(): ConditionalRangeFormat;
/**
* Specifies the Rule object on this conditional format.
*/
getRule(): ConditionalCellValueRule;
/**
* Specifies the Rule object on this conditional format.
*/
setRule(rule: ConditionalCellValueRule): void;
}
/**
* A format object encapsulating the conditional formats range's font, fill, borders, and other properties.
*/
interface ConditionalRangeFormat {
/**
* Returns the fill object defined on the overall conditional format range.
*/
getFill(): ConditionalRangeFill;
/**
* Returns the font object defined on the overall conditional format range.
*/
getFont(): ConditionalRangeFont;
/**
* Represents Excel's number format code for the given range. Cleared if null is passed in.
*/
getNumberFormat(): string;
/**
* Represents Excel's number format code for the given range. Cleared if null is passed in.
*/
setNumberFormat(numberFormat: string): void;
/**
* Collection of border objects that apply to the overall conditional format range.
*/
getBorders(): ConditionalRangeBorder[];
/**
* Gets the bottom border.
*/
getConditionalRangeBorderBottom(): ConditionalRangeBorder;
/**
* Gets the left border.
*/
getConditionalRangeBorderLeft(): ConditionalRangeBorder;
/**
* Gets the right border.
*/
getConditionalRangeBorderRight(): ConditionalRangeBorder;
/**
* Gets the top border.
*/
getConditionalRangeBorderTop(): ConditionalRangeBorder;
/**
* Gets a border object using its name.
* @param index Index value of the border object to be retrieved. See ExcelScript.ConditionalRangeBorderIndex for details.
*/
getConditionalRangeBorder(
index: ConditionalRangeBorderIndex
): ConditionalRangeBorder;
}
/**
* This object represents the font attributes (font style, color, etc.) for an object.
*/
interface ConditionalRangeFont {
/**
* Specifies if the font is bold.
*/
getBold(): boolean;
/**
* Specifies if the font is bold.
*/
setBold(bold: boolean): void;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
getColor(): string;
/**
* HTML color code representation of the text color (e.g., #FF0000 represents Red).
*/
setColor(color: string): void;
/**
* Specifies if the font is italic.
*/
getItalic(): boolean;
/**
* Specifies if the font is italic.
*/
setItalic(italic: boolean): void;
/**
* Specifies the strikethrough status of the font.
*/
getStrikethrough(): boolean;
/**
* Specifies the strikethrough status of the font.
*/
setStrikethrough(strikethrough: boolean): void;
/**
* The type of underline applied to the font. See ExcelScript.ConditionalRangeFontUnderlineStyle for details.
*/
getUnderline(): ConditionalRangeFontUnderlineStyle;
/**
* The type of underline applied to the font. See ExcelScript.ConditionalRangeFontUnderlineStyle for details.
*/
setUnderline(underline: ConditionalRangeFontUnderlineStyle): void;
/**
* Resets the font formats.
*/
clear(): void;
}
/**
* Represents the background of a conditional range object.
*/
interface ConditionalRangeFill {
/**
* HTML color code representing the color of the fill, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getColor(): string;
/**
* HTML color code representing the color of the fill, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setColor(color: string): void;
/**
* Resets the fill.
*/
clear(): void;
}
/**
* Represents the border of an object.
*/
interface ConditionalRangeBorder {
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getColor(): string;
/**
* HTML color code representing the color of the border line, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setColor(color: string): void;
/**
* Constant value that indicates the specific side of the border. See ExcelScript.ConditionalRangeBorderIndex for details.
*/
getSideIndex(): ConditionalRangeBorderIndex;
/**
* One of the constants of line style specifying the line style for the border. See ExcelScript.BorderLineStyle for details.
*/
getStyle(): ConditionalRangeBorderLineStyle;
/**
* One of the constants of line style specifying the line style for the border. See ExcelScript.BorderLineStyle for details.
*/
setStyle(style: ConditionalRangeBorderLineStyle): void;
}
/**
* An object encapsulating a style's format and other properties.
*/
interface PredefinedCellStyle {
/**
* Specifies if text is automatically indented when the text alignment in a cell is set to equal distribution.
*/
getAutoIndent(): boolean;
/**
* Specifies if text is automatically indented when the text alignment in a cell is set to equal distribution.
*/
setAutoIndent(autoIndent: boolean): void;
/**
* Specifies if the style is a built-in style.
*/
getBuiltIn(): boolean;
/**
* The Fill of the style.
*/
getFill(): RangeFill;
/**
* A Font object that represents the font of the style.
*/
getFont(): RangeFont;
/**
* Specifies if the formula will be hidden when the worksheet is protected.
*/
getFormulaHidden(): boolean;
/**
* Specifies if the formula will be hidden when the worksheet is protected.
*/
setFormulaHidden(formulaHidden: boolean): void;
/**
* Represents the horizontal alignment for the style. See ExcelScript.HorizontalAlignment for details.
*/
getHorizontalAlignment(): HorizontalAlignment;
/**
* Represents the horizontal alignment for the style. See ExcelScript.HorizontalAlignment for details.
*/
setHorizontalAlignment(horizontalAlignment: HorizontalAlignment): void;
/**
* Specifies if the style includes the AutoIndent, HorizontalAlignment, VerticalAlignment, WrapText, IndentLevel, and TextOrientation properties.
*/
getIncludeAlignment(): boolean;
/**
* Specifies if the style includes the AutoIndent, HorizontalAlignment, VerticalAlignment, WrapText, IndentLevel, and TextOrientation properties.
*/
setIncludeAlignment(includeAlignment: boolean): void;
/**
* Specifies if the style includes the Color, ColorIndex, LineStyle, and Weight border properties.
*/
getIncludeBorder(): boolean;
/**
* Specifies if the style includes the Color, ColorIndex, LineStyle, and Weight border properties.
*/
setIncludeBorder(includeBorder: boolean): void;
/**
* Specifies if the style includes the Background, Bold, Color, ColorIndex, FontStyle, Italic, Name, Size, Strikethrough, Subscript, Superscript, and Underline font properties.
*/
getIncludeFont(): boolean;
/**
* Specifies if the style includes the Background, Bold, Color, ColorIndex, FontStyle, Italic, Name, Size, Strikethrough, Subscript, Superscript, and Underline font properties.
*/
setIncludeFont(includeFont: boolean): void;
/**
* Specifies if the style includes the NumberFormat property.
*/
getIncludeNumber(): boolean;
/**
* Specifies if the style includes the NumberFormat property.
*/
setIncludeNumber(includeNumber: boolean): void;
/**
* Specifies if the style includes the Color, ColorIndex, InvertIfNegative, Pattern, PatternColor, and PatternColorIndex interior properties.
*/
getIncludePatterns(): boolean;
/**
* Specifies if the style includes the Color, ColorIndex, InvertIfNegative, Pattern, PatternColor, and PatternColorIndex interior properties.
*/
setIncludePatterns(includePatterns: boolean): void;
/**
* Specifies if the style includes the FormulaHidden and Locked protection properties.
*/
getIncludeProtection(): boolean;
/**
* Specifies if the style includes the FormulaHidden and Locked protection properties.
*/
setIncludeProtection(includeProtection: boolean): void;
/**
* An integer from 0 to 250 that indicates the indent level for the style.
*/
getIndentLevel(): number;
/**
* An integer from 0 to 250 that indicates the indent level for the style.
*/
setIndentLevel(indentLevel: number): void;
/**
* Specifies if the object is locked when the worksheet is protected.
*/
getLocked(): boolean;
/**
* Specifies if the object is locked when the worksheet is protected.
*/
setLocked(locked: boolean): void;
/**
* The name of the style.
*/
getName(): string;
/**
* The format code of the number format for the style.
*/
getNumberFormat(): string;
/**
* The format code of the number format for the style.
*/
setNumberFormat(numberFormat: string): void;
/**
* The localized format code of the number format for the style.
*/
getNumberFormatLocal(): string;
/**
* The localized format code of the number format for the style.
*/
setNumberFormatLocal(numberFormatLocal: string): void;
/**
* The reading order for the style.
*/
getReadingOrder(): ReadingOrder;
/**
* The reading order for the style.
*/
setReadingOrder(readingOrder: ReadingOrder): void;
/**
* Specifies if text automatically shrinks to fit in the available column width.
*/
getShrinkToFit(): boolean;
/**
* Specifies if text automatically shrinks to fit in the available column width.
*/
setShrinkToFit(shrinkToFit: boolean): void;
/**
* The text orientation for the style.
*/
getTextOrientation(): number;
/**
* The text orientation for the style.
*/
setTextOrientation(textOrientation: number): void;
/**
* Specifies the vertical alignment for the style. See ExcelScript.VerticalAlignment for details.
*/
getVerticalAlignment(): VerticalAlignment;
/**
* Specifies the vertical alignment for the style. See ExcelScript.VerticalAlignment for details.
*/
setVerticalAlignment(verticalAlignment: VerticalAlignment): void;
/**
* Specifies if Excel wraps the text in the object.
*/
getWrapText(): boolean;
/**
* Specifies if Excel wraps the text in the object.
*/
setWrapText(wrapText: boolean): void;
/**
* Deletes this style.
*/
delete(): void;
/**
* A Border collection of four Border objects that represent the style of the four borders.
*/
getBorders(): RangeBorder[];
/**
* Specifies a double that lightens or darkens a color for Range Borders, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire border collections don't have uniform tintAndShade setting.
*/
getRangeBorderTintAndShade(): number;
/**
* Specifies a double that lightens or darkens a color for Range Borders, the value is between -1 (darkest) and 1 (brightest), with 0 for the original color.
* A null value indicates that the entire border collections don't have uniform tintAndShade setting.
*/
setRangeBorderTintAndShade(rangeBorderTintAndShade: number): void;
/**
* Gets a border object using its name.
* @param index Index value of the border object to be retrieved. See ExcelScript.BorderIndex for details.
*/
getRangeBorder(index: BorderIndex): RangeBorder;
}
/**
* Represents a TableStyle, which defines the style elements by region of the Table.
*/
interface TableStyle {
/**
* Gets the name of the TableStyle.
*/
getName(): string;
/**
* Gets the name of the TableStyle.
*/
setName(name: string): void;
/**
* Specifies if this TableStyle object is read-only.
*/
getReadOnly(): boolean;
/**
* Deletes the TableStyle.
*/
delete(): void;
/**
* Creates a duplicate of this TableStyle with copies of all the style elements.
*/
duplicate(): TableStyle;
}
/**
* Represents a PivotTable Style, which defines style elements by PivotTable region.
*/
interface PivotTableStyle {
/**
* Gets the name of the PivotTableStyle.
*/
getName(): string;
/**
* Gets the name of the PivotTableStyle.
*/
setName(name: string): void;
/**
* Specifies if this PivotTableStyle object is read-only.
*/
getReadOnly(): boolean;
/**
* Deletes the PivotTableStyle.
*/
delete(): void;
/**
* Creates a duplicate of this PivotTableStyle with copies of all the style elements.
*/
duplicate(): PivotTableStyle;
}
/**
* Represents a Slicer Style, which defines style elements by region of the slicer.
*/
interface SlicerStyle {
/**
* Gets the name of the SlicerStyle.
*/
getName(): string;
/**
* Gets the name of the SlicerStyle.
*/
setName(name: string): void;
/**
* Specifies if this SlicerStyle object is read-only.
*/
getReadOnly(): boolean;
/**
* Deletes the SlicerStyle.
*/
delete(): void;
/**
* Creates a duplicate of this SlicerStyle with copies of all the style elements.
*/
duplicate(): SlicerStyle;
}
/**
* Represents a Timeline style, which defines style elements by region in the Timeline.
*/
interface TimelineStyle {
/**
* Gets the name of the TimelineStyle.
*/
getName(): string;
/**
* Gets the name of the TimelineStyle.
*/
setName(name: string): void;
/**
* Specifies if this TimelineStyle object is read-only.
*/
getReadOnly(): boolean;
/**
* Deletes the TableStyle.
*/
delete(): void;
/**
* Creates a duplicate of this TimelineStyle with copies of all the style elements.
*/
duplicate(): TimelineStyle;
}
/**
* Represents layout and print settings that are not dependent any printer-specific implementation. These settings include margins, orientation, page numbering, title rows, and print area.
*/
interface PageLayout {
/**
* The worksheet's black and white print option.
*/
getBlackAndWhite(): boolean;
/**
* The worksheet's black and white print option.
*/
setBlackAndWhite(blackAndWhite: boolean): void;
/**
* The worksheet's bottom page margin to use for printing in points.
*/
getBottomMargin(): number;
/**
* The worksheet's bottom page margin to use for printing in points.
*/
setBottomMargin(bottomMargin: number): void;
/**
* The worksheet's center horizontally flag. This flag determines whether the worksheet will be centered horizontally when it's printed.
*/
getCenterHorizontally(): boolean;
/**
* The worksheet's center horizontally flag. This flag determines whether the worksheet will be centered horizontally when it's printed.
*/
setCenterHorizontally(centerHorizontally: boolean): void;
/**
* The worksheet's center vertically flag. This flag determines whether the worksheet will be centered vertically when it's printed.
*/
getCenterVertically(): boolean;
/**
* The worksheet's center vertically flag. This flag determines whether the worksheet will be centered vertically when it's printed.
*/
setCenterVertically(centerVertically: boolean): void;
/**
* The worksheet's draft mode option. If true the sheet will be printed without graphics.
*/
getDraftMode(): boolean;
/**
* The worksheet's draft mode option. If true the sheet will be printed without graphics.
*/
setDraftMode(draftMode: boolean): void;
/**
* The worksheet's first page number to print. Null value represents "auto" page numbering.
*/
getFirstPageNumber(): number | "";
/**
* The worksheet's first page number to print. Null value represents "auto" page numbering.
*/
setFirstPageNumber(firstPageNumber: number | ""): void;
/**
* The worksheet's footer margin, in points, for use when printing.
*/
getFooterMargin(): number;
/**
* The worksheet's footer margin, in points, for use when printing.
*/
setFooterMargin(footerMargin: number): void;
/**
* The worksheet's header margin, in points, for use when printing.
*/
getHeaderMargin(): number;
/**
* The worksheet's header margin, in points, for use when printing.
*/
setHeaderMargin(headerMargin: number): void;
/**
* Header and footer configuration for the worksheet.
*/
getHeadersFooters(): HeaderFooterGroup;
/**
* The worksheet's left margin, in points, for use when printing.
*/
getLeftMargin(): number;
/**
* The worksheet's left margin, in points, for use when printing.
*/
setLeftMargin(leftMargin: number): void;
/**
* The worksheet's orientation of the page.
*/
getOrientation(): PageOrientation;
/**
* The worksheet's orientation of the page.
*/
setOrientation(orientation: PageOrientation): void;
/**
* The worksheet's paper size of the page.
*/
getPaperSize(): PaperType;
/**
* The worksheet's paper size of the page.
*/
setPaperSize(paperSize: PaperType): void;
/**
* Specifies if the worksheet's comments should be displayed when printing.
*/
getPrintComments(): PrintComments;
/**
* Specifies if the worksheet's comments should be displayed when printing.
*/
setPrintComments(printComments: PrintComments): void;
/**
* The worksheet's print errors option.
*/
getPrintErrors(): PrintErrorType;
/**
* The worksheet's print errors option.
*/
setPrintErrors(printErrors: PrintErrorType): void;
/**
* Specifies if the worksheet's gridlines will be printed.
*/
getPrintGridlines(): boolean;
/**
* Specifies if the worksheet's gridlines will be printed.
*/
setPrintGridlines(printGridlines: boolean): void;
/**
* Specifies if the worksheet's headings will be printed.
*/
getPrintHeadings(): boolean;
/**
* Specifies if the worksheet's headings will be printed.
*/
setPrintHeadings(printHeadings: boolean): void;
/**
* The worksheet's page print order option. This specifies the order to use for processing the page number printed.
*/
getPrintOrder(): PrintOrder;
/**
* The worksheet's page print order option. This specifies the order to use for processing the page number printed.
*/
setPrintOrder(printOrder: PrintOrder): void;
/**
* The worksheet's right margin, in points, for use when printing.
*/
getRightMargin(): number;
/**
* The worksheet's right margin, in points, for use when printing.
*/
setRightMargin(rightMargin: number): void;
/**
* The worksheet's top margin, in points, for use when printing.
*/
getTopMargin(): number;
/**
* The worksheet's top margin, in points, for use when printing.
*/
setTopMargin(topMargin: number): void;
/**
* The worksheet's print zoom options.
* The `PageLayoutZoomOptions` object must be set as a JSON object (use `x.zoom = {...}` instead of `x.zoom.scale = ...`).
*/
getZoom(): PageLayoutZoomOptions;
/**
* The worksheet's print zoom options.
* The `PageLayoutZoomOptions` object must be set as a JSON object (use `x.zoom = {...}` instead of `x.zoom.scale = ...`).
*/
setZoom(zoom: PageLayoutZoomOptions): void;
/**
* Gets the RangeAreas object, comprising one or more rectangular ranges, that represents the print area for the worksheet. If there is no print area, then this function will return an object with its `isNullObject` property set to `true`.
*/
getPrintArea(): RangeAreas;
/**
* Gets the range object representing the title columns. If not set, then this function will return an object with its `isNullObject` property set to `true`.
*/
getPrintTitleColumns(): Range;
/**
* Gets the range object representing the title rows. If not set, then this function will return an object with its `isNullObject` property set to `true`.
*/
getPrintTitleRows(): Range;
/**
* Sets the worksheet's print area.
* @param printArea The range, or RangeAreas of the content to print.
*/
setPrintArea(printArea: Range | RangeAreas | string): void;
/**
* Sets the worksheet's page margins with units.
* @param unit Measurement unit for the margins provided.
* @param marginOptions Margin values to set, margins not provided will remain unchanged.
*/
setPrintMargins(
unit: PrintMarginUnit,
marginOptions: PageLayoutMarginOptions
): void;
/**
* Sets the columns that contain the cells to be repeated at the left of each page of the worksheet for printing.
* @param printTitleColumns The columns to be repeated to the left of each page, range must span the entire column to be valid.
*/
setPrintTitleColumns(printTitleColumns: Range | string): void;
/**
* Sets the rows that contain the cells to be repeated at the top of each page of the worksheet for printing.
* @param printTitleRows The rows to be repeated at the top of each page, range must span the entire row to be valid.
*/
setPrintTitleRows(printTitleRows: Range | string): void;
}
interface HeaderFooter {
/**
* The center footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getCenterFooter(): string;
/**
* The center footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setCenterFooter(centerFooter: string): void;
/**
* The center header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getCenterHeader(): string;
/**
* The center header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setCenterHeader(centerHeader: string): void;
/**
* The left footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getLeftFooter(): string;
/**
* The left footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setLeftFooter(leftFooter: string): void;
/**
* The left header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getLeftHeader(): string;
/**
* The left header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setLeftHeader(leftHeader: string): void;
/**
* The right footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getRightFooter(): string;
/**
* The right footer of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setRightFooter(rightFooter: string): void;
/**
* The right header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
getRightHeader(): string;
/**
* The right header of the worksheet.
* To apply font formatting or insert a variable value, use format codes specified here: https://msdn.microsoft.com/library/bb225426.aspx.
*/
setRightHeader(rightHeader: string): void;
}
interface HeaderFooterGroup {
/**
* The general header/footer, used for all pages unless even/odd or first page is specified.
*/
getDefaultForAllPages(): HeaderFooter;
/**
* The header/footer to use for even pages, odd header/footer needs to be specified for odd pages.
*/
getEvenPages(): HeaderFooter;
/**
* The first page header/footer, for all other pages general or even/odd is used.
*/
getFirstPage(): HeaderFooter;
/**
* The header/footer to use for odd pages, even header/footer needs to be specified for even pages.
*/
getOddPages(): HeaderFooter;
/**
* The state by which headers/footers are set. See ExcelScript.HeaderFooterState for details.
*/
getState(): HeaderFooterState;
/**
* The state by which headers/footers are set. See ExcelScript.HeaderFooterState for details.
*/
setState(state: HeaderFooterState): void;
/**
* Gets or sets a flag indicating if headers/footers are aligned with the page margins set in the page layout options for the worksheet.
*/
getUseSheetMargins(): boolean;
/**
* Gets or sets a flag indicating if headers/footers are aligned with the page margins set in the page layout options for the worksheet.
*/
setUseSheetMargins(useSheetMargins: boolean): void;
/**
* Gets or sets a flag indicating if headers/footers should be scaled by the page percentage scale set in the page layout options for the worksheet.
*/
getUseSheetScale(): boolean;
/**
* Gets or sets a flag indicating if headers/footers should be scaled by the page percentage scale set in the page layout options for the worksheet.
*/
setUseSheetScale(useSheetScale: boolean): void;
}
interface PageBreak {
/**
* Specifies the column index for the page break
*/
getColumnIndex(): number;
/**
* Deletes a page break object.
*/
delete(): void;
/**
* Gets the first cell after the page break.
*/
getCellAfterBreak(): Range;
}
/**
* Represents a comment in the workbook.
*/
interface Comment {
/**
* Gets the email of the comment's author.
*/
getAuthorEmail(): string;
/**
* Gets the name of the comment's author.
*/
getAuthorName(): string;
/**
* The comment's content. The string is plain text.
*/
getContent(): string;
/**
* The comment's content. The string is plain text.
*/
setContent(content: string): void;
/**
* Gets the content type of the comment.
*/
getContentType(): ContentType;
/**
* Gets the creation time of the comment. Returns null if the comment was converted from a note, since the comment does not have a creation date.
*/
getCreationDate(): Date;
/**
* Specifies the comment identifier.
*/
getId(): string;
/**
* Gets the entities (e.g., people) that are mentioned in comments.
*/
getMentions(): CommentMention[];
/**
* The comment thread status. A value of "true" means the comment thread is resolved.
*/
getResolved(): boolean;
/**
* The comment thread status. A value of "true" means the comment thread is resolved.
*/
setResolved(resolved: boolean): void;
/**
* Gets the rich comment content (e.g., mentions in comments). This string is not meant to be displayed to end-users. Your add-in should only use this to parse rich comment content.
*/
getRichContent(): string;
/**
* Deletes the comment and all the connected replies.
*/
delete(): void;
/**
* Gets the cell where this comment is located.
*/
getLocation(): Range;
/**
* Updates the comment content with a specially formatted string and a list of mentions.
* @param contentWithMentions The content for the comment. This contains a specially formatted string and a list of mentions that will be parsed into the string when displayed by Excel.
*/
updateMentions(contentWithMentions: CommentRichContent): void;
/**
* Represents a collection of reply objects associated with the comment.
*/
getReplies(): CommentReply[];
/**
* Creates a comment reply for comment.
* @param content The comment's content. This can be either a string or Interface CommentRichContent (e.g., for comments with mentions).
* @param contentType Optional. The type of content contained within the comment. The default value is enum `ContentType.Plain`.
*/
addCommentReply(
content: CommentRichContent | string,
contentType?: ContentType
): CommentReply;
/**
* Returns a comment reply identified by its ID.
* @param commentReplyId The identifier for the comment reply.
*/
getCommentReply(commentReplyId: string): CommentReply;
}
/**
* Represents a comment reply in the workbook.
*/
interface CommentReply {
/**
* Gets the email of the comment reply's author.
*/
getAuthorEmail(): string;
/**
* Gets the name of the comment reply's author.
*/
getAuthorName(): string;
/**
* The comment reply's content. The string is plain text.
*/
getContent(): string;
/**
* The comment reply's content. The string is plain text.
*/
setContent(content: string): void;
/**
* The content type of the reply.
*/
getContentType(): ContentType;
/**
* Gets the creation time of the comment reply.
*/
getCreationDate(): Date;
/**
* Specifies the comment reply identifier.
*/
getId(): string;
/**
* The entities (e.g., people) that are mentioned in comments.
*/
getMentions(): CommentMention[];
/**
* The comment reply status. A value of "true" means the reply is in the resolved state.
*/
getResolved(): boolean;
/**
* The rich comment content (e.g., mentions in comments). This string is not meant to be displayed to end-users. Your add-in should only use this to parse rich comment content.
*/
getRichContent(): string;
/**
* Deletes the comment reply.
*/
delete(): void;
/**
* Gets the cell where this comment reply is located.
*/
getLocation(): Range;
/**
* Gets the parent comment of this reply.
*/
getParentComment(): Comment;
/**
* Updates the comment content with a specially formatted string and a list of mentions.
* @param contentWithMentions The content for the comment. This contains a specially formatted string and a list of mentions that will be parsed into the string when displayed by Excel.
*/
updateMentions(contentWithMentions: CommentRichContent): void;
}
/**
* Represents a generic shape object in the worksheet. A shape could be a geometric shape, a line, a group of shapes, etc.
*/
interface Shape {
/**
* Specifies the alternative description text for a Shape object.
*/
getAltTextDescription(): string;
/**
* Specifies the alternative description text for a Shape object.
*/
setAltTextDescription(altTextDescription: string): void;
/**
* Specifies the alternative title text for a Shape object.
*/
getAltTextTitle(): string;
/**
* Specifies the alternative title text for a Shape object.
*/
setAltTextTitle(altTextTitle: string): void;
/**
* Returns the number of connection sites on this shape.
*/
getConnectionSiteCount(): number;
/**
* Returns the fill formatting of this shape.
*/
getFill(): ShapeFill;
/**
* Returns the geometric shape associated with the shape. An error will be thrown if the shape type is not "GeometricShape".
*/
getGeometricShape(): GeometricShape;
/**
* Specifies the geometric shape type of this geometric shape. See ExcelScript.GeometricShapeType for details. Returns null if the shape type is not "GeometricShape".
*/
getGeometricShapeType(): GeometricShapeType;
/**
* Specifies the geometric shape type of this geometric shape. See ExcelScript.GeometricShapeType for details. Returns null if the shape type is not "GeometricShape".
*/
setGeometricShapeType(geometricShapeType: GeometricShapeType): void;
/**
* Returns the shape group associated with the shape. An error will be thrown if the shape type is not "GroupShape".
*/
getGroup(): ShapeGroup;
/**
* Specifies the height, in points, of the shape.
* Throws an invalid argument exception when set with a negative value or zero as input.
*/
getHeight(): number;
/**
* Specifies the height, in points, of the shape.
* Throws an invalid argument exception when set with a negative value or zero as input.
*/
setHeight(height: number): void;
/**
* Specifies the shape identifier.
*/
getId(): string;
/**
* Returns the image associated with the shape. An error will be thrown if the shape type is not "Image".
*/
getImage(): Image;
/**
* The distance, in points, from the left side of the shape to the left side of the worksheet.
* Throws an invalid argument exception when set with a negative value as input.
*/
getLeft(): number;
/**
* The distance, in points, from the left side of the shape to the left side of the worksheet.
* Throws an invalid argument exception when set with a negative value as input.
*/
setLeft(left: number): void;
/**
* Specifies the level of the specified shape. For example, a level of 0 means that the shape is not part of any groups, a level of 1 means the shape is part of a top-level group, and a level of 2 means the shape is part of a sub-group of the top level.
*/
getLevel(): number;
/**
* Returns the line associated with the shape. An error will be thrown if the shape type is not "Line".
*/
getLine(): Line;
/**
* Returns the line formatting of this shape.
*/
getLineFormat(): ShapeLineFormat;
/**
* Specifies if the aspect ratio of this shape is locked.
*/
getLockAspectRatio(): boolean;
/**
* Specifies if the aspect ratio of this shape is locked.
*/
setLockAspectRatio(lockAspectRatio: boolean): void;
/**
* Specifies the name of the shape.
*/
getName(): string;
/**
* Specifies the name of the shape.
*/
setName(name: string): void;
/**
* Specifies the parent group of this shape.
*/
getParentGroup(): Shape;
/**
* Represents how the object is attached to the cells below it.
*/
getPlacement(): Placement;
/**
* Represents how the object is attached to the cells below it.
*/
setPlacement(placement: Placement): void;
/**
* Specifies the rotation, in degrees, of the shape.
*/
getRotation(): number;
/**
* Specifies the rotation, in degrees, of the shape.
*/
setRotation(rotation: number): void;
/**
* Returns the text frame object of this shape. Read only.
*/
getTextFrame(): TextFrame;
/**
* The distance, in points, from the top edge of the shape to the top edge of the worksheet.
* Throws an invalid argument exception when set with a negative value as input.
*/
getTop(): number;
/**
* The distance, in points, from the top edge of the shape to the top edge of the worksheet.
* Throws an invalid argument exception when set with a negative value as input.
*/
setTop(top: number): void;
/**
* Returns the type of this shape. See ExcelScript.ShapeType for details.
*/
getType(): ShapeType;
/**
* Specifies if the shape is visible.
*/
getVisible(): boolean;
/**
* Specifies if the shape is visible.
*/
setVisible(visible: boolean): void;
/**
* Specifies the width, in points, of the shape.
* Throws an invalid argument exception when set with a negative value or zero as input.
*/
getWidth(): number;
/**
* Specifies the width, in points, of the shape.
* Throws an invalid argument exception when set with a negative value or zero as input.
*/
setWidth(width: number): void;
/**
* Returns the position of the specified shape in the z-order, with 0 representing the bottom of the order stack.
*/
getZOrderPosition(): number;
/**
* Copies and pastes a Shape object.
* The pasted shape is copied to the same pixel location as this shape.
* @param destinationSheet The sheet to which the shape object will be pasted. The default value is the copied Shape's worksheet.
*/
copyTo(destinationSheet?: Worksheet | string): Shape;
/**
* Removes the shape from the worksheet.
*/
delete(): void;
/**
* Converts the shape to an image and returns the image as a base64-encoded string. The DPI is 96. The only supported formats are `ExcelScript.PictureFormat.BMP`, `ExcelScript.PictureFormat.PNG`, `ExcelScript.PictureFormat.JPEG`, and `ExcelScript.PictureFormat.GIF`.
* @param format Specifies the format of the image.
*/
getAsImage(format: PictureFormat): string;
/**
* Moves the shape horizontally by the specified number of points.
* @param increment The increment, in points, the shape will be horizontally moved. A positive value moves the shape to the right and a negative value moves it to the left. If the sheet is right-to-left oriented, this is reversed: positive values will move the shape to the left and negative values will move it to the right.
*/
incrementLeft(increment: number): void;
/**
* Rotates the shape clockwise around the z-axis by the specified number of degrees.
* Use the `rotation` property to set the absolute rotation of the shape.
* @param increment How many degrees the shape will be rotated. A positive value rotates the shape clockwise; a negative value rotates it counterclockwise.
*/
incrementRotation(increment: number): void;
/**
* Moves the shape vertically by the specified number of points.
* @param increment The increment, in points, the shape will be vertically moved. in points. A positive value moves the shape down and a negative value moves it up.
*/
incrementTop(increment: number): void;
/**
* Scales the height of the shape by a specified factor. For images, you can indicate whether you want to scale the shape relative to the original or the current size. Shapes other than pictures are always scaled relative to their current height.
* @param scaleFactor Specifies the ratio between the height of the shape after you resize it and the current or original height.
* @param scaleType Specifies whether the shape is scaled relative to its original or current size. The original size scaling option only works for images.
* @param scaleFrom Optional. Specifies which part of the shape retains its position when the shape is scaled. If omitted, it represents the shape's upper left corner retains its position.
*/
scaleHeight(
scaleFactor: number,
scaleType: ShapeScaleType,
scaleFrom?: ShapeScaleFrom
): void;
/**
* Scales the width of the shape by a specified factor. For images, you can indicate whether you want to scale the shape relative to the original or the current size. Shapes other than pictures are always scaled relative to their current width.
* @param scaleFactor Specifies the ratio between the width of the shape after you resize it and the current or original width.
* @param scaleType Specifies whether the shape is scaled relative to its original or current size. The original size scaling option only works for images.
* @param scaleFrom Optional. Specifies which part of the shape retains its position when the shape is scaled. If omitted, it represents the shape's upper left corner retains its position.
*/
scaleWidth(
scaleFactor: number,
scaleType: ShapeScaleType,
scaleFrom?: ShapeScaleFrom
): void;
/**
* Moves the specified shape up or down the collection's z-order, which shifts it in front of or behind other shapes.
* @param position Where to move the shape in the z-order stack relative to the other shapes. See ExcelScript.ShapeZOrder for details.
*/
setZOrder(position: ShapeZOrder): void;
}
/**
* Represents a geometric shape inside a worksheet. A geometric shape can be a rectangle, block arrow, equation symbol, flowchart item, star, banner, callout, or any other basic shape in Excel.
*/
interface GeometricShape {
/**
* Returns the shape identifier.
*/
getId(): string;
}
/**
* Represents an image in the worksheet. To get the corresponding Shape object, use Image.shape.
*/
interface Image {
/**
* Specifies the shape identifier for the image object.
*/
getId(): string;
/**
* Returns the Shape object associated with the image.
*/
getShape(): Shape;
/**
* Returns the format of the image.
*/
getFormat(): PictureFormat;
}
/**
* Represents a shape group inside a worksheet. To get the corresponding Shape object, use `ShapeGroup.shape`.
*/
interface ShapeGroup {
/**
* Specifies the shape identifier.
*/
getId(): string;
/**
* Returns the Shape object associated with the group.
*/
getGroupShape(): Shape;
/**
* Ungroups any grouped shapes in the specified shape group.
*/
ungroup(): void;
/**
* Returns the collection of Shape objects.
*/
getShapes(): Shape[];
/**
* Gets a shape using its Name or ID.
* @param key The Name or ID of the shape to be retrieved.
*/
getShape(key: string): Shape;
}
/**
* Represents a line inside a worksheet. To get the corresponding Shape object, use `Line.shape`.
*/
interface Line {
/**
* Represents the length of the arrowhead at the beginning of the specified line.
*/
getBeginArrowheadLength(): ArrowheadLength;
/**
* Represents the length of the arrowhead at the beginning of the specified line.
*/
setBeginArrowheadLength(beginArrowheadLength: ArrowheadLength): void;
/**
* Represents the style of the arrowhead at the beginning of the specified line.
*/
getBeginArrowheadStyle(): ArrowheadStyle;
/**
* Represents the style of the arrowhead at the beginning of the specified line.
*/
setBeginArrowheadStyle(beginArrowheadStyle: ArrowheadStyle): void;
/**
* Represents the width of the arrowhead at the beginning of the specified line.
*/
getBeginArrowheadWidth(): ArrowheadWidth;
/**
* Represents the width of the arrowhead at the beginning of the specified line.
*/
setBeginArrowheadWidth(beginArrowheadWidth: ArrowheadWidth): void;
/**
* Represents the shape to which the beginning of the specified line is attached.
*/
getBeginConnectedShape(): Shape;
/**
* Represents the connection site to which the beginning of a connector is connected. Returns null when the beginning of the line is not attached to any shape.
*/
getBeginConnectedSite(): number;
/**
* Represents the length of the arrowhead at the end of the specified line.
*/
getEndArrowheadLength(): ArrowheadLength;
/**
* Represents the length of the arrowhead at the end of the specified line.
*/
setEndArrowheadLength(endArrowheadLength: ArrowheadLength): void;
/**
* Represents the style of the arrowhead at the end of the specified line.
*/
getEndArrowheadStyle(): ArrowheadStyle;
/**
* Represents the style of the arrowhead at the end of the specified line.
*/
setEndArrowheadStyle(endArrowheadStyle: ArrowheadStyle): void;
/**
* Represents the width of the arrowhead at the end of the specified line.
*/
getEndArrowheadWidth(): ArrowheadWidth;
/**
* Represents the width of the arrowhead at the end of the specified line.
*/
setEndArrowheadWidth(endArrowheadWidth: ArrowheadWidth): void;
/**
* Represents the shape to which the end of the specified line is attached.
*/
getEndConnectedShape(): Shape;
/**
* Represents the connection site to which the end of a connector is connected. Returns null when the end of the line is not attached to any shape.
*/
getEndConnectedSite(): number;
/**
* Specifies the shape identifier.
*/
getId(): string;
/**
* Specifies if the beginning of the specified line is connected to a shape.
*/
getIsBeginConnected(): boolean;
/**
* Specifies if the end of the specified line is connected to a shape.
*/
getIsEndConnected(): boolean;
/**
* Returns the Shape object associated with the line.
*/
getShape(): Shape;
/**
* Represents the connector type for the line.
*/
getConnectorType(): ConnectorType;
/**
* Represents the connector type for the line.
*/
setConnectorType(connectorType: ConnectorType): void;
/**
* Attaches the beginning of the specified connector to a specified shape.
* @param shape The shape to connect.
* @param connectionSite The connection site on the shape to which the beginning of the connector is attached. Must be an integer between 0 (inclusive) and the connection-site count of the specified shape (exclusive).
*/
connectBeginShape(shape: Shape, connectionSite: number): void;
/**
* Attaches the end of the specified connector to a specified shape.
* @param shape The shape to connect.
* @param connectionSite The connection site on the shape to which the end of the connector is attached. Must be an integer between 0 (inclusive) and the connection-site count of the specified shape (exclusive).
*/
connectEndShape(shape: Shape, connectionSite: number): void;
/**
* Detaches the beginning of the specified connector from a shape.
*/
disconnectBeginShape(): void;
/**
* Detaches the end of the specified connector from a shape.
*/
disconnectEndShape(): void;
}
/**
* Represents the fill formatting of a shape object.
*/
interface ShapeFill {
/**
* Represents the shape fill foreground color in HTML color format, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")
*/
getForegroundColor(): string;
/**
* Represents the shape fill foreground color in HTML color format, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange")
*/
setForegroundColor(foregroundColor: string): void;
/**
* Specifies the transparency percentage of the fill as a value from 0.0 (opaque) through 1.0 (clear). Returns null if the shape type does not support transparency or the shape fill has inconsistent transparency, such as with a gradient fill type.
*/
getTransparency(): number;
/**
* Specifies the transparency percentage of the fill as a value from 0.0 (opaque) through 1.0 (clear). Returns null if the shape type does not support transparency or the shape fill has inconsistent transparency, such as with a gradient fill type.
*/
setTransparency(transparency: number): void;
/**
* Returns the fill type of the shape. See ExcelScript.ShapeFillType for details.
*/
getType(): ShapeFillType;
/**
* Clears the fill formatting of this shape.
*/
clear(): void;
/**
* Sets the fill formatting of the shape to a uniform color. This changes the fill type to "Solid".
* @param color A string that represents the fill color in HTML color format, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setSolidColor(color: string): void;
}
/**
* Represents the line formatting for the shape object. For images and geometric shapes, line formatting represents the border of the shape.
*/
interface ShapeLineFormat {
/**
* Represents the line color in HTML color format, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
getColor(): string;
/**
* Represents the line color in HTML color format, of the form #RRGGBB (e.g., "FFA500") or as a named HTML color (e.g., "orange").
*/
setColor(color: string): void;
/**
* Represents the line style of the shape. Returns null when the line is not visible or there are inconsistent dash styles. See ExcelScript.ShapeLineStyle for details.
*/
getDashStyle(): ShapeLineDashStyle;
/**
* Represents the line style of the shape. Returns null when the line is not visible or there are inconsistent dash styles. See ExcelScript.ShapeLineStyle for details.
*/
setDashStyle(dashStyle: ShapeLineDashStyle): void;
/**
* Represents the line style of the shape. Returns null when the line is not visible or there are inconsistent styles. See ExcelScript.ShapeLineStyle for details.
*/
getStyle(): ShapeLineStyle;
/**
* Represents the line style of the shape. Returns null when the line is not visible or there are inconsistent styles. See ExcelScript.ShapeLineStyle for details.
*/
setStyle(style: ShapeLineStyle): void;
/**
* Represents the degree of transparency of the specified line as a value from 0.0 (opaque) through 1.0 (clear). Returns null when the shape has inconsistent transparencies.
*/
getTransparency(): number;
/**
* Represents the degree of transparency of the specified line as a value from 0.0 (opaque) through 1.0 (clear). Returns null when the shape has inconsistent transparencies.
*/
setTransparency(transparency: number): void;
/**
* Specifies if the line formatting of a shape element is visible. Returns null when the shape has inconsistent visibilities.
*/
getVisible(): boolean;
/**
* Specifies if the line formatting of a shape element is visible. Returns null when the shape has inconsistent visibilities.
*/
setVisible(visible: boolean): void;
/**
* Represents the weight of the line, in points. Returns null when the line is not visible or there are inconsistent line weights.
*/
getWeight(): number;
/**
* Represents the weight of the line, in points. Returns null when the line is not visible or there are inconsistent line weights.
*/
setWeight(weight: number): void;
}
/**
* Represents the text frame of a shape object.
*/
interface TextFrame {
/**
* The automatic sizing settings for the text frame. A text frame can be set to automatically fit the text to the text frame, to automatically fit the text frame to the text, or not perform any automatic sizing.
*/
getAutoSizeSetting(): ShapeAutoSize;
/**
* The automatic sizing settings for the text frame. A text frame can be set to automatically fit the text to the text frame, to automatically fit the text frame to the text, or not perform any automatic sizing.
*/
setAutoSizeSetting(autoSizeSetting: ShapeAutoSize): void;
/**
* Represents the bottom margin, in points, of the text frame.
*/
getBottomMargin(): number;
/**
* Represents the bottom margin, in points, of the text frame.
*/
setBottomMargin(bottomMargin: number): void;
/**
* Specifies if the text frame contains text.
*/
getHasText(): boolean;
/**
* Represents the horizontal alignment of the text frame. See ExcelScript.ShapeTextHorizontalAlignment for details.
*/
getHorizontalAlignment(): ShapeTextHorizontalAlignment;
/**
* Represents the horizontal alignment of the text frame. See ExcelScript.ShapeTextHorizontalAlignment for details.
*/
setHorizontalAlignment(
horizontalAlignment: ShapeTextHorizontalAlignment
): void;
/**
* Represents the horizontal overflow behavior of the text frame. See ExcelScript.ShapeTextHorizontalOverflow for details.
*/
getHorizontalOverflow(): ShapeTextHorizontalOverflow;
/**
* Represents the horizontal overflow behavior of the text frame. See ExcelScript.ShapeTextHorizontalOverflow for details.
*/
setHorizontalOverflow(
horizontalOverflow: ShapeTextHorizontalOverflow
): void;
/**
* Represents the left margin, in points, of the text frame.
*/
getLeftMargin(): number;
/**
* Represents the left margin, in points, of the text frame.
*/
setLeftMargin(leftMargin: number): void;
/**
* Represents the angle to which the text is oriented for the text frame. See ExcelScript.ShapeTextOrientation for details.
*/
getOrientation(): ShapeTextOrientation;
/**
* Represents the angle to which the text is oriented for the text frame. See ExcelScript.ShapeTextOrientation for details.
*/
setOrientation(orientation: ShapeTextOrientation): void;
/**
* Represents the reading order of the text frame, either left-to-right or right-to-left. See ExcelScript.ShapeTextReadingOrder for details.
*/
getReadingOrder(): ShapeTextReadingOrder;
/**
* Represents the reading order of the text frame, either left-to-right or right-to-left. See ExcelScript.ShapeTextReadingOrder for details.
*/
setReadingOrder(readingOrder: ShapeTextReadingOrder): void;
/**
* Represents the right margin, in points, of the text frame.
*/
getRightMargin(): number;
/**
* Represents the right margin, in points, of the text frame.
*/
setRightMargin(rightMargin: number): void;
/**
* Represents the text that is attached to a shape in the text frame, and properties and methods for manipulating the text. See ExcelScript.TextRange for details.
*/
getTextRange(): TextRange;
/**
* Represents the top margin, in points, of the text frame.
*/
getTopMargin(): number;
/**
* Represents the top margin, in points, of the text frame.
*/
setTopMargin(topMargin: number): void;
/**
* Represents the vertical alignment of the text frame. See ExcelScript.ShapeTextVerticalAlignment for details.
*/
getVerticalAlignment(): ShapeTextVerticalAlignment;
/**
* Represents the vertical alignment of the text frame. See ExcelScript.ShapeTextVerticalAlignment for details.
*/
setVerticalAlignment(
verticalAlignment: ShapeTextVerticalAlignment
): void;
/**
* Represents the vertical overflow behavior of the text frame. See ExcelScript.ShapeTextVerticalOverflow for details.
*/
getVerticalOverflow(): ShapeTextVerticalOverflow;
/**
* Represents the vertical overflow behavior of the text frame. See ExcelScript.ShapeTextVerticalOverflow for details.
*/
setVerticalOverflow(verticalOverflow: ShapeTextVerticalOverflow): void;
/**
* Deletes all the text in the text frame.
*/
deleteText(): void;
}
/**
* Contains the text that is attached to a shape, in addition to properties and methods for manipulating the text.
*/
interface TextRange {
/**
* Returns a ShapeFont object that represents the font attributes for the text range.
*/
getFont(): ShapeFont;
/**
* Represents the plain text content of the text range.
*/
getText(): string;
/**
* Represents the plain text content of the text range.
*/
setText(text: string): void;
/**
* Returns a TextRange object for the substring in the given range.
* @param start The zero-based index of the first character to get from the text range.
* @param length Optional. The number of characters to be returned in the new text range. If length is omitted, all the characters from start to the end of the text range's last paragraph will be returned.
*/
getSubstring(start: number, length?: number): TextRange;
}
/**
* Represents the font attributes, such as font name, font size, and color, for a shape's TextRange object.
*/
interface ShapeFont {
/**
* Represents the bold status of font. Returns null the TextRange includes both bold and non-bold text fragments.
*/
getBold(): boolean;
/**
* Represents the bold status of font. Returns null the TextRange includes both bold and non-bold text fragments.
*/
setBold(bold: boolean): void;
/**
* HTML color code representation of the text color (e.g., "#FF0000" represents red). Returns null if the TextRange includes text fragments with different colors.
*/
getColor(): string;
/**
* HTML color code representation of the text color (e.g., "#FF0000" represents red). Returns null if the TextRange includes text fragments with different colors.
*/
setColor(color: string): void;
/**
* Represents the italic status of font. Returns null if the TextRange includes both italic and non-italic text fragments.
*/
getItalic(): boolean;
/**
* Represents the italic status of font. Returns null if the TextRange includes both italic and non-italic text fragments.
*/
setItalic(italic: boolean): void;
/**
* Represents font name (e.g., "Calibri"). If the text is Complex Script or East Asian language, this is the corresponding font name; otherwise it is the Latin font name.
*/
getName(): string;
/**
* Represents font name (e.g., "Calibri"). If the text is Complex Script or East Asian language, this is the corresponding font name; otherwise it is the Latin font name.
*/
setName(name: string): void;
/**
* Represents font size in points (e.g., 11). Returns null if the TextRange includes text fragments with different font sizes.
*/
getSize(): number;
/**
* Represents font size in points (e.g., 11). Returns null if the TextRange includes text fragments with different font sizes.
*/
setSize(size: number): void;
/**
* Type of underline applied to the font. Returns null if the TextRange includes text fragments with different underline styles. See ExcelScript.ShapeFontUnderlineStyle for details.
*/
getUnderline(): ShapeFontUnderlineStyle;
/**
* Type of underline applied to the font. Returns null if the TextRange includes text fragments with different underline styles. See ExcelScript.ShapeFontUnderlineStyle for details.
*/
setUnderline(underline: ShapeFontUnderlineStyle): void;
}
/**
* Represents a slicer object in the workbook.
*/
interface Slicer {
/**
* Represents the caption of slicer.
*/
getCaption(): string;
/**
* Represents the caption of slicer.
*/
setCaption(caption: string): void;
/**
* Represents the height, in points, of the slicer.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value or zero as input.
*/
getHeight(): number;
/**
* Represents the height, in points, of the slicer.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value or zero as input.
*/
setHeight(height: number): void;
/**
* Represents the unique id of slicer.
*/
getId(): string;
/**
* True if all filters currently applied on the slicer are cleared.
*/
getIsFilterCleared(): boolean;
/**
* Represents the distance, in points, from the left side of the slicer to the left of the worksheet.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value as input.
*/
getLeft(): number;
/**
* Represents the distance, in points, from the left side of the slicer to the left of the worksheet.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value as input.
*/
setLeft(left: number): void;
/**
* Represents the name of slicer.
*/
getName(): string;
/**
* Represents the name of slicer.
*/
setName(name: string): void;
/**
* Represents the sort order of the items in the slicer. Possible values are: "DataSourceOrder", "Ascending", "Descending".
*/
getSortBy(): SlicerSortType;
/**
* Represents the sort order of the items in the slicer. Possible values are: "DataSourceOrder", "Ascending", "Descending".
*/
setSortBy(sortBy: SlicerSortType): void;
/**
* Constant value that represents the Slicer style. Possible values are: "SlicerStyleLight1" through "SlicerStyleLight6", "TableStyleOther1" through "TableStyleOther2", "SlicerStyleDark1" through "SlicerStyleDark6". A custom user-defined style present in the workbook can also be specified.
*/
getStyle(): string;
/**
* Constant value that represents the Slicer style. Possible values are: "SlicerStyleLight1" through "SlicerStyleLight6", "TableStyleOther1" through "TableStyleOther2", "SlicerStyleDark1" through "SlicerStyleDark6". A custom user-defined style present in the workbook can also be specified.
*/
setStyle(style: string): void;
/**
* Represents the distance, in points, from the top edge of the slicer to the top of the worksheet.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value as input.
*/
getTop(): number;
/**
* Represents the distance, in points, from the top edge of the slicer to the top of the worksheet.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value as input.
*/
setTop(top: number): void;
/**
* Represents the width, in points, of the slicer.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value or zero as input.
*/
getWidth(): number;
/**
* Represents the width, in points, of the slicer.
* Throws an "The argument is invalid or missing or has an incorrect format." exception when set with negative value or zero as input.
*/
setWidth(width: number): void;
/**
* Represents the worksheet containing the slicer.
*/
getWorksheet(): Worksheet;
/**
* Clears all the filters currently applied on the slicer.
*/
clearFilters(): void;
/**
* Deletes the slicer.
*/
delete(): void;
/**
* Returns an array of selected items' keys.
*/
getSelectedItems(): string[];
/**
* Selects slicer items based on their keys. The previous selections are cleared.
* All items will be selected by default if the array is empty.
* @param items Optional. The specified slicer item names to be selected.
*/
selectItems(items?: string[]): void;
/**
* Represents the collection of SlicerItems that are part of the slicer.
*/
getSlicerItems(): SlicerItem[];
/**
* Gets a slicer item using its key or name. If the slicer item doesn't exist, then this function will return an object with its `isNullObject` property set to `true`.
* @param key Key or name of the slicer to be retrieved.
*/
getSlicerItem(key: string): SlicerItem | undefined;
}
/**
* Represents a slicer item in a slicer.
*/
interface SlicerItem {
/**
* True if the slicer item has data.
*/
getHasData(): boolean;
/**
* True if the slicer item is selected.
* Setting this value will not clear other SlicerItems' selected state.
* By default, if the slicer item is the only one selected, when it is deselected, all items will be selected.
*/
getIsSelected(): boolean;
/**
* True if the slicer item is selected.
* Setting this value will not clear other SlicerItems' selected state.
* By default, if the slicer item is the only one selected, when it is deselected, all items will be selected.
*/
setIsSelected(isSelected: boolean): void;
/**
* Represents the unique value representing the slicer item.
*/
getKey(): string;
/**
* Represents the title displayed in the UI.
*/
getName(): string;
}
//
// Interface
//
/**
* Configurable template for a date filter to apply to a PivotField.
* The `condition` defines what criteria need to be set in order for the filter to operate.
*/
interface PivotDateFilter {
/**
* The comparator is the static value to which other values are compared. The type of comparison is defined by the condition.
*/
comparator?: FilterDatetime;
/**
* Specifies the condition for the filter, which defines the necessary filtering criteria.
*/
condition: DateFilterCondition;
/**
* If true, filter *excludes* items that meet criteria. The default is false (filter to include items that meet criteria).
*/
exclusive?: boolean;
/**
* The lower-bound of the range for the `Between` filter condition.
*/
lowerBound?: FilterDatetime;
/**
* The upper-bound of the range for the `Between` filter condition.
*/
upperBound?: FilterDatetime;
/**
* For `Equals`, `Before`, `After`, and `Between` filter conditions, indicates if comparisons should be made as whole days.
*/
wholeDays?: boolean;
}
/**
* An interface representing all PivotFilters currently applied to a given PivotField.
*/
interface PivotFilters {
/**
* The PivotField's currently applied date filter. Null if none is applied.
*/
dateFilter?: PivotDateFilter;
/**
* The PivotField's currently applied label filter. Null if none is applied.
*/
labelFilter?: PivotLabelFilter;
/**
* The PivotField's currently applied manual filter. Null if none is applied.
*/
manualFilter?: PivotManualFilter;
/**
* The PivotField's currently applied value filter. Null if none is applied.
*/
valueFilter?: PivotValueFilter;
}
/**
* Configurable template for a label filter to apply to a PivotField.
* The `condition` defines what criteria need to be set in order for the filter to operate.
*/
interface PivotLabelFilter {
/**
* Specifies the condition for the filter, which defines the necessary filtering criteria.
*/
condition: LabelFilterCondition;
/**
* If true, filter *excludes* items that meet criteria. The default is false (filter to include items that meet criteria).
*/
exclusive?: boolean;
/**
* The lower-bound of the range for the Between filter condition.
* Note: A numeric string is treated as a number when being compared against other numeric strings.
*/
lowerBound?: string;
/**
* The substring used for `BeginsWith`, `EndsWith`, and `Contains` filter conditions.
*/
substring?: string;
/**
* The upper-bound of the range for the Between filter condition.
* Note: A numeric string is treated as a number when being compared against other numeric strings.
*/
upperBound?: string;
}
/**
* Configurable template for a manual filter to apply to a PivotField.
* The `condition` defines what criteria need to be set in order for the filter to operate.
*/
interface PivotManualFilter {
/**
* A list of selected items to manually filter. These must be existing and valid items from the chosen field.
*/
selectedItems?: (string | PivotItem)[];
}
/**
* Configurable template for a value filter to apply to a PivotField.
* The `condition` defines what criteria need to be set in order for the filter to operate.
*/
interface PivotValueFilter {
/**
* The comparator is the static value to which other values are compared. The type of comparison is defined by the condition.
* For example, if comparator is "50" and condition is "GreaterThan", all item values that are not greater than 50 will be removed by the filter.
*/
comparator?: number;
/**
* Specifies the condition for the filter, which defines the necessary filtering criteria.
*/
condition: ValueFilterCondition;
/**
* If true, filter *excludes* items that meet criteria. The default is false (filter to include items that meet criteria).
*/
exclusive?: boolean;
/**
* The lower-bound of the range for the `Between` filter condition.
*/
lowerBound?: number;
/**
* Specifies if the filter is for the top/bottom N items, top/bottom N percent, or top/bottom N sum.
*/
selectionType?: TopBottomSelectionType;
/**
* The "N" threshold number of items, percent, or sum to be filtered for a Top/Bottom filter condition.
*/
threshold?: number;
/**
* The upper-bound of the range for the `Between` filter condition.
*/
upperBound?: number;
/**
* Name of the chosen "value" in the field by which to filter.
*/
value: string;
}
/**
* Represents the options in sheet protection.
*/
interface WorksheetProtectionOptions {
/**
* Represents the worksheet protection option of allowing using auto filter feature.
*/
allowAutoFilter?: boolean;
/**
* Represents the worksheet protection option of allowing deleting columns.
*/
allowDeleteColumns?: boolean;
/**
* Represents the worksheet protection option of allowing deleting rows.
*/
allowDeleteRows?: boolean;
/**
* Represents the worksheet protection option of allowing editing objects.
*/
allowEditObjects?: boolean;
/**
* Represents the worksheet protection option of allowing editing scenarios.
*/
allowEditScenarios?: boolean;
/**
* Represents the worksheet protection option of allowing formatting cells.
*/
allowFormatCells?: boolean;
/**
* Represents the worksheet protection option of allowing formatting columns.
*/
allowFormatColumns?: boolean;
/**
* Represents the worksheet protection option of allowing formatting rows.
*/
allowFormatRows?: boolean;
/**
* Represents the worksheet protection option of allowing inserting columns.
*/
allowInsertColumns?: boolean;
/**
* Represents the worksheet protection option of allowing inserting hyperlinks.
*/
allowInsertHyperlinks?: boolean;
/**
* Represents the worksheet protection option of allowing inserting rows.
*/
allowInsertRows?: boolean;
/**
* Represents the worksheet protection option of allowing using PivotTable feature.
*/
allowPivotTables?: boolean;
/**
* Represents the worksheet protection option of allowing using sort feature.
*/
allowSort?: boolean;
/**
* Represents the worksheet protection option of selection mode.
*/
selectionMode?: ProtectionSelectionMode;
}
/**
* Represents a string reference of the form SheetName!A1:B5, or a global or local named range.
*/
interface RangeReference {
/**
* The address of the range; for example 'SheetName!A1:B5'.
*/
address: string;
}
/**
* Represents the necessary strings to get/set a hyperlink (XHL) object.
*/
interface RangeHyperlink {
/**
* Represents the url target for the hyperlink.
*/
address?: string;
/**
* Represents the document reference target for the hyperlink.
*/
documentReference?: string;
/**
* Represents the string displayed when hovering over the hyperlink.
*/
screenTip?: string;
/**
* Represents the string that is displayed in the top left most cell in the range.
*/
textToDisplay?: string;
}
/**
* Represents the search criteria to be used.
*/
interface SearchCriteria {
/**
* Specifies if the match needs to be complete or partial.
* A complete match matches the entire contents of the cell. A partial match matches a substring within the content of the cell (e.g., `cat` partially matches `caterpillar` and `scatter`).
* Default is false (partial).
*/
completeMatch?: boolean;
/**
* Specifies if the match is case sensitive. Default is false (insensitive).
*/
matchCase?: boolean;
/**
* Specifies the search direction. Default is forward. See ExcelScript.SearchDirection.
*/
searchDirection?: SearchDirection;
}
/**
* Represents the worksheet search criteria to be used.
*/
interface WorksheetSearchCriteria {
/**
* Specifies if the match needs to be complete or partial.
* A complete match matches the entire contents of the cell. A partial match matches a substring within the content of the cell (e.g., `cat` partially matches `caterpillar` and `scatter`).
* Default is false (partial).
*/
completeMatch?: boolean;
/**
* Specifies if the match is case sensitive. Default is false (insensitive).
*/
matchCase?: boolean;
}
/**
* Represents the replace criteria to be used.
*/
interface ReplaceCriteria {
/**
* Specifies if the match needs to be complete or partial.
* A complete match matches the entire contents of the cell. A partial match matches a substring within the content of the cell (e.g., `cat` partially matches `caterpillar` and `scatter`).
* Default is false (partial).
*/
completeMatch?: boolean;
/**
* Specifies if the match is case sensitive. Default is false (insensitive).
*/
matchCase?: boolean;
}
/**
* Specifies which properties to load on the `format.fill` object.
*/
interface CellPropertiesFillLoadOptions {
/**
* Specifies whether to load the `color` property.
*/
color?: boolean;
/**
* Specifies whether to load the `pattern` property.
*/
pattern?: boolean;
/**
* Specifies whether to load the `patternColor` property.
*/
patternColor?: boolean;
/**
* Specifies whether to load the `patternTintAndShade` property.
*/
patternTintAndShade?: boolean;
/**
* Specifies whether to load the `tintAndShade` property.
*/
tintAndShade?: boolean;
}
/**
* Specifies which properties to load on the `format.font` object.
*/
interface CellPropertiesFontLoadOptions {
/**
* Specifies whether to load on the `bold` property.
*/
bold?: boolean;
/**
* Specifies whether to load on the `color` property.
*/
color?: boolean;
/**
* Specifies whether to load on the `italic` property.
*/
italic?: boolean;
/**
* Specifies whether to load on the `name` property.
*/
name?: boolean;
/**
* Specifies whether to load on the `size` property.
*/
size?: boolean;
/**
* Specifies whether to load on the `strikethrough` property.
*/
strikethrough?: boolean;
/**
* Specifies whether to load on the `subscript` property.
*/
subscript?: boolean;
/**
* Specifies whether to load on the `superscript` property.
*/
superscript?: boolean;
/**
* Specifies whether to load on the `tintAndShade` property.
*/
tintAndShade?: boolean;
/**
* Specifies whether to load on the `underline` property.
*/
underline?: boolean;
}
/**
* Specifies which properties to load on the `format.borders` object.
*/
interface CellPropertiesBorderLoadOptions {
/**
* Specifies whether to load on the `color` property.
*/
color?: boolean;
/**
* Specifies whether to load on the `style` property.
*/
style?: boolean;
/**
* Specifies whether to load on the `tintAndShade` property.
*/
tintAndShade?: boolean;
/**
* Specifies whether to load on the `weight` property.
*/
weight?: boolean;
}
/**
* Represents the `format.protection` properties of `getCellProperties`, `getRowProperties`, and `getColumnProperties` or the `format.protection` input parameter of `setCellProperties`, `setRowProperties`, and `setColumnProperties`.
*/
interface CellPropertiesProtection {
/**
* Represents the `format.protection.formulaHidden` property.
*/
formulaHidden?: boolean;
/**
* Represents the `format.protection.locked` property.
*/
locked?: boolean;
}
/**
* Represents the `format.fill` properties of `getCellProperties`, `getRowProperties`, and `getColumnProperties` or the `format.fill` input parameter of `setCellProperties`, `setRowProperties`, and `setColumnProperties`.
*/
interface CellPropertiesFill {
/**
* Represents the `format.fill.color` property.
*/
color?: string;
/**
* Represents the `format.fill.pattern` property.
*/
pattern?: FillPattern;
/**
* Represents the `format.fill.patternColor` property.
*/
patternColor?: string;
/**
* Represents the `format.fill.patternTintAndShade` property.
*/
patternTintAndShade?: number;
/**
* Represents the `format.fill.tintAndShade` property.
*/
tintAndShade?: number;
}
/**
* Represents the `format.font` properties of `getCellProperties`, `getRowProperties`, and `getColumnProperties` or the `format.font` input parameter of `setCellProperties`, `setRowProperties`, and `setColumnProperties`.
*/
interface CellPropertiesFont {
/**
* Represents the `format.font.bold` property.
*/
bold?: boolean;
/**
* Represents the `format.font.color` property.
*/
color?: string;
/**
* Represents the `format.font.italic` property.
*/
italic?: boolean;
/**
* Represents the `format.font.name` property.
*/
name?: string;
/**
* Represents the `format.font.size` property.
*/
size?: number;
/**
* Represents the `format.font.strikethrough` property.
*/
strikethrough?: boolean;
/**
* Represents the `format.font.subscript` property.
*/
subscript?: boolean;
/**
* Represents the `format.font.superscript` property.
*/
superscript?: boolean;
/**
* Represents the `format.font.tintAndShade` property.
*/
tintAndShade?: number;
/**
* Represents the `format.font.underline` property.
*/
underline?: RangeUnderlineStyle;
}
/**
* Represents the `format.borders` properties of `getCellProperties`, `getRowProperties`, and `getColumnProperties` or the `format.borders` input parameter of `setCellProperties`, `setRowProperties`, and `setColumnProperties`.
*/
interface CellBorderCollection {
/**
* Represents the `format.borders.bottom` property.
*/
bottom?: CellBorder;
/**
* Represents the `format.borders.diagonalDown` property.
*/
diagonalDown?: CellBorder;
/**
* Represents the `format.borders.diagonalUp` property.
*/
diagonalUp?: CellBorder;
/**
* Represents the `format.borders.horizontal` property.
*/
horizontal?: CellBorder;
/**
* Represents the `format.borders.left` property.
*/
left?: CellBorder;
/**
* Represents the `format.borders.right` property.
*/
right?: CellBorder;
/**
* Represents the `format.borders.top` property.
*/
top?: CellBorder;
/**
* Represents the `format.borders.vertical` property.
*/
vertical?: CellBorder;
}
/**
* Represents the properties of a single border returned by `getCellProperties`, `getRowProperties`, and `getColumnProperties` or the border property input parameter of `setCellProperties`, `setRowProperties`, and `setColumnProperties`.
*/
interface CellBorder {
/**
* Represents the `color` property of a single border.
*/
color?: string;
/**
* Represents the `style` property of a single border.
*/
style?: BorderLineStyle;
/**
* Represents the `tintAndShade` property of a single border.
*/
tintAndShade?: number;
/**
* Represents the `weight` property of a single border.
*/
weight?: BorderWeight;
}
/**
* Data validation rule contains different types of data validation. You can only use one of them at a time according the ExcelScript.DataValidationType.
*/
interface DataValidationRule {
/**
* Custom data validation criteria.
*/
custom?: CustomDataValidation;
/**
* Date data validation criteria.
*/
date?: DateTimeDataValidation;
/**
* Decimal data validation criteria.
*/
decimal?: BasicDataValidation;
/**
* List data validation criteria.
*/
list?: ListDataValidation;
/**
* TextLength data validation criteria.
*/
textLength?: BasicDataValidation;
/**
* Time data validation criteria.
*/
time?: DateTimeDataValidation;
/**
* WholeNumber data validation criteria.
*/
wholeNumber?: BasicDataValidation;
}
/**
* Represents the Basic Type data validation criteria.
*/
interface BasicDataValidation {
/**
* Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand.
* For example, setting formula1 to 10 and operator to GreaterThan means that valid data for the range must be greater than 10.
* When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)").
* When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.
*/
formula1: string | number | Range;
/**
* With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan.
* When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)").
* When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.
*/
formula2?: string | number | Range;
/**
* The operator to use for validating the data.
*/
operator: DataValidationOperator;
}
/**
* Represents the Date data validation criteria.
*/
interface DateTimeDataValidation {
/**
* Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand.
* When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)").
* When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.
*/
formula1: string | Date | Range;
/**
* With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan.
* When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)").
* When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc.
*/
formula2?: string | Date | Range;
/**
* The operator to use for validating the data.
*/
operator: DataValidationOperator;
}
/**
* Represents the List data validation criteria.
*/
interface ListDataValidation {
/**
* Displays the list in cell drop down or not, it defaults to true.
*/
inCellDropDown: boolean;
/**
* Source of the list for data validation
* When setting the value, it can be passed in as a Excel Range object, or a string that contains comma separated number, boolean or date.
*/
source: string | Range;
}
/**
* Represents the Custom data validation criteria.
*/
interface CustomDataValidation {
/**
* A custom data validation formula. This creates special input rules, such as preventing duplicates, or limiting the total in a range of cells.
*/
formula: string;
}
/**
* Represents the error alert properties for the data validation.
*/
interface DataValidationErrorAlert {
/**
* Represents error alert message.
*/
message: string;
/**
* Specifies whether to show an error alert dialog when a user enters invalid data. The default is true.
*/
showAlert: boolean;
/**
* The data validation alert type, please see ExcelScript.DataValidationAlertStyle for details.
*/
style: DataValidationAlertStyle;
/**
* Represents error alert dialog title.
*/
title: string;
}
/**
* Represents the user prompt properties for the data validation.
*/
interface DataValidationPrompt {
/**
* Specifies the message of the prompt.
*/
message: string;
/**
* Specifies if a prompt is shown when a user selects a cell with data validation.
*/
showPrompt: boolean;
/**
* Specifies the title for the prompt.
*/
title: string;
}
/**
* Represents a condition in a sorting operation.
*/
interface SortField {
/**
* Specifies if the sorting is done in an ascending fashion.
*/
ascending?: boolean;
/**
* Specifies the color that is the target of the condition if the sorting is on font or cell color.
*/
color?: string;
/**
* Represents additional sorting options for this field.
*/
dataOption?: SortDataOption;
/**
* Specifies the icon that is the target of the condition if the sorting is on the cell's icon.
*/
icon?: Icon;
/**
* Specifies the column (or row, depending on the sort orientation) that the condition is on. Represented as an offset from the first column (or row).
*/
key: number;
/**
* Specifies the type of sorting of this condition.
*/
sortOn?: SortOn;
/**
* Specifies the subfield that is the target property name of a rich value to sort on.
*/
subField?: string;
}
/**
* Represents the filtering criteria applied to a column.
*/
interface FilterCriteria {
/**
* The HTML color string used to filter cells. Used with "cellColor" and "fontColor" filtering.
*/
color?: string;
/**
* The first criterion used to filter data. Used as an operator in the case of "custom" filtering.
* For example ">50" for number greater than 50 or "=*s" for values ending in "s".
*
* Used as a number in the case of top/bottom items/percents (e.g., "5" for the top 5 items if filterOn is set to "topItems").
*/
criterion1?: string;
/**
* The second criterion used to filter data. Only used as an operator in the case of "custom" filtering.
*/
criterion2?: string;
/**
* The dynamic criteria from the ExcelScript.DynamicFilterCriteria set to apply on this column. Used with "dynamic" filtering.
*/
dynamicCriteria?: DynamicFilterCriteria;
/**
* The property used by the filter to determine whether the values should stay visible.
*/
filterOn: FilterOn;
/**
* The icon used to filter cells. Used with "icon" filtering.
*/
icon?: Icon;
/**
* The operator used to combine criterion 1 and 2 when using "custom" filtering.
*/
operator?: FilterOperator;
/**
* The property used by the filter to do rich filter on richvalues.
*/
subField?: string;
/**
* The set of values to be used as part of "values" filtering.
*/
values?: Array<string | FilterDatetime>;
}
/**
* Represents how to filter a date when filtering on values.
*/
interface FilterDatetime {
/**
* The date in ISO8601 format used to filter data.
*/
date: string;
/**
* How specific the date should be used to keep data. For example, if the date is 2005-04-02 and the specifity is set to "month", the filter operation will keep all rows with a date in the month of april 2009.
*/
specificity: FilterDatetimeSpecificity;
}
/**
* Represents a cell icon.
*/
interface Icon {
/**
* Specifies the index of the icon in the given set.
*/
index: number;
/**
* Specifies the set that the icon is part of.
*/
set: IconSet;
}
interface ShowAsRule {
/**
* The base PivotField to base the ShowAs calculation, if applicable based on the ShowAsCalculation type, else null.
*/
baseField?: PivotField;
/**
* The base Item to base the ShowAs calculation on, if applicable based on the ShowAsCalculation type, else null.
*/
baseItem?: PivotItem;
/**
* The ShowAs Calculation to use for the Data PivotField. See ExcelScript.ShowAsCalculation for Details.
*/
calculation: ShowAsCalculation;
}
/**
* Subtotals for the Pivot Field.
*/
interface Subtotals {
/**
* If Automatic is set to true, then all other values will be ignored when setting the Subtotals.
*/
automatic?: boolean;
/**
* Average
*/
average?: boolean;
/**
* Count
*/
count?: boolean;
/**
* CountNumbers
*/
countNumbers?: boolean;
/**
* Max
*/
max?: boolean;
/**
* Min
*/
min?: boolean;
/**
* Product
*/
product?: boolean;
/**
* StandardDeviation
*/
standardDeviation?: boolean;
/**
* StandardDeviationP
*/
standardDeviationP?: boolean;
/**
* Sum
*/
sum?: boolean;
/**
* Variance
*/
variance?: boolean;
/**
* VarianceP
*/
varianceP?: boolean;
}
/**
* Represents a rule-type for a Data Bar.
*/
interface ConditionalDataBarRule {
/**
* The formula, if required, to evaluate the databar rule on.
*/
formula?: string;
/**
* The type of rule for the databar.
*/
type: ConditionalFormatRuleType;
}
/**
* Represents an Icon Criterion which contains a type, value, an Operator, and an optional custom icon, if not using an iconset.
*/
interface ConditionalIconCriterion {
/**
* The custom icon for the current criterion if different from the default IconSet, else null will be returned.
*/
customIcon?: Icon;
/**
* A number or a formula depending on the type.
*/
formula: string;
/**
* GreaterThan or GreaterThanOrEqual for each of the rule type for the Icon conditional format.
*/
operator: ConditionalIconCriterionOperator;
/**
* What the icon conditional formula should be based on.
*/
type: ConditionalFormatIconRuleType;
}
/**
* Represents the criteria of the color scale.
*/
interface ConditionalColorScaleCriteria {
/**
* The maximum point Color Scale Criterion.
*/
maximum: ConditionalColorScaleCriterion;
/**
* The midpoint Color Scale Criterion if the color scale is a 3-color scale.
*/
midpoint?: ConditionalColorScaleCriterion;
/**
* The minimum point Color Scale Criterion.
*/
minimum: ConditionalColorScaleCriterion;
}
/**
* Represents a Color Scale Criterion which contains a type, value, and a color.
*/
interface ConditionalColorScaleCriterion {
/**
* HTML color code representation of the color scale color (e.g., #FF0000 represents Red).
*/
color?: string;
/**
* A number, a formula, or null (if Type is LowestValue).
*/
formula?: string;
/**
* What the criterion conditional formula should be based on.
*/
type: ConditionalFormatColorCriterionType;
}
/**
* Represents the rule of the top/bottom conditional format.
*/
interface ConditionalTopBottomRule {
/**
* The rank between 1 and 1000 for numeric ranks or 1 and 100 for percent ranks.
*/
rank: number;
/**
* Format values based on the top or bottom rank.
*/
type: ConditionalTopBottomCriterionType;
}
/**
* Represents the Preset Criteria Conditional Format Rule
*/
interface ConditionalPresetCriteriaRule {
/**
* The criterion of the conditional format.
*/
criterion: ConditionalFormatPresetCriterion;
}
/**
* Represents a Cell Value Conditional Format Rule
*/
interface ConditionalTextComparisonRule {
/**
* The operator of the text conditional format.
*/
operator: ConditionalTextOperator;
/**
* The Text value of conditional format.
*/
text: string;
}
/**
* Represents a cell value conditional format rule.
*/
interface ConditionalCellValueRule {
/**
* The formula, if required, to evaluate the conditional format rule on.
*/
formula1: string;
/**
* The formula, if required, to evaluate the conditional format rule on.
*/
formula2?: string;
/**
* The operator of the cell value conditional format.
*/
operator: ConditionalCellValueOperator;
}
/**
* Represents page zoom properties.
*/
interface PageLayoutZoomOptions {
/**
* Number of pages to fit horizontally. This value can be null if percentage scale is used.
*/
horizontalFitToPages?: number;
/**
* Print page scale value can be between 10 and 400. This value can be null if fit to page tall or wide is specified.
*/
scale?: number;
/**
* Number of pages to fit vertically. This value can be null if percentage scale is used.
*/
verticalFitToPages?: number;
}
/**
* Represents the options in page layout margins.
*/
interface PageLayoutMarginOptions {
/**
* Specifies the page layout bottom margin in the unit specified to use for printing.
*/
bottom?: number;
/**
* Specifies the page layout footer margin in the unit specified to use for printing.
*/
footer?: number;
/**
* Specifies the page layout header margin in the unit specified to use for printing.
*/
header?: number;
/**
* Specifies the page layout left margin in the unit specified to use for printing.
*/
left?: number;
/**
* Specifies the page layout right margin in the unit specified to use for printing.
*/
right?: number;
/**
* Specifies the page layout top margin in the unit specified to use for printing.
*/
top?: number;
}
/**
* Represents the entity that is mentioned in comments.
*/
interface CommentMention {
/**
* The email address of the entity that is mentioned in comment.
*/
email: string;
/**
* The id of the entity. The id matches one of the ids in `CommentRichContent.richContent`.
*/
id: number;
/**
* The name of the entity that is mentioned in comment.
*/
name: string;
}
/**
* Represents the content contained within a comment or comment reply. Rich content incudes the text string and any other objects contained within the comment body, such as mentions.
*/
interface CommentRichContent {
/**
* An array containing all the entities (e.g., people) mentioned within the comment.
*/
mentions?: CommentMention[];
/**
* Specifies the rich content of the comment (e.g., comment content with mentions, the first mentioned entity has an id attribute of 0, and the second mentioned entity has an id attribute of 1).
*/
richContent: string;
}
//
// Enum
//
/**
* Enum representing all accepted conditions by which a date filter can be applied.
* Used to configure the type of PivotFilter that is applied to the field.
*/
enum DateFilterCondition {
/**
* DateFilterCondition is unknown or unsupported.
*/
unknown,
/**
* Equals comparator criterion.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`wholeDays`, `exclusive`}.
*/
equals,
/**
* Date is before comparator date.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`wholeDays`}.
*/
before,
/**
* Date is before or equal to comparator date.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`wholeDays`}.
*/
beforeOrEqualTo,
/**
* Date is after comparator date.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`wholeDays`}.
*/
after,
/**
* Date is after or equal to comparator date.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`wholeDays`}.
*/
afterOrEqualTo,
/**
* Between `lowerBound` and `upperBound` dates.
*
* Required Criteria: {`lowerBound`, `upperBound`}.
* Optional Criteria: {`wholeDays`, `exclusive`}.
*/
between,
/**
* Date is tomorrow.
*/
tomorrow,
/**
* Date is today.
*/
today,
/**
* Date is yesterday.
*/
yesterday,
/**
* Date is next week.
*/
nextWeek,
/**
* Date is this week.
*/
thisWeek,
/**
* Date is last week.
*/
lastWeek,
/**
* Date is next month.
*/
nextMonth,
/**
* Date is this month.
*/
thisMonth,
/**
* Date is last month.
*/
lastMonth,
/**
* Date is next quarter.
*/
nextQuarter,
/**
* Date is this quarter.
*/
thisQuarter,
/**
* Date is last quarter.
*/
lastQuarter,
/**
* Date is next year.
*/
nextYear,
/**
* Date is this year.
*/
thisYear,
/**
* Date is last year.
*/
lastYear,
/**
* Date is in the same year to date.
*/
yearToDate,
/**
* Date is in Quarter 1.
*/
allDatesInPeriodQuarter1,
/**
* Date is in Quarter 2.
*/
allDatesInPeriodQuarter2,
/**
* Date is in Quarter 3.
*/
allDatesInPeriodQuarter3,
/**
* Date is in Quarter 4.
*/
allDatesInPeriodQuarter4,
/**
* Date is in January.
*/
allDatesInPeriodJanuary,
/**
* Date is in February.
*/
allDatesInPeriodFebruary,
/**
* Date is in March.
*/
allDatesInPeriodMarch,
/**
* Date is in April.
*/
allDatesInPeriodApril,
/**
* Date is in May.
*/
allDatesInPeriodMay,
/**
* Date is in June.
*/
allDatesInPeriodJune,
/**
* Date is in July.
*/
allDatesInPeriodJuly,
/**
* Date is in August.
*/
allDatesInPeriodAugust,
/**
* Date is in September.
*/
allDatesInPeriodSeptember,
/**
* Date is in October.
*/
allDatesInPeriodOctober,
/**
* Date is in November.
*/
allDatesInPeriodNovember,
/**
* Date is in December.
*/
allDatesInPeriodDecember,
}
/**
* Enum representing all accepted conditions by which a label filter can be applied.
* Used to configure the type of PivotFilter that is applied to the field.
* `PivotFilter.criteria.exclusive` can be set to true to invert many of these conditions.
*/
enum LabelFilterCondition {
/**
* LabelFilterCondition is unknown or unsupported.
*/
unknown,
/**
* Equals comparator criterion.
*
* Required Criteria: {`comparator`}.
* Optional Criteria: {`exclusive`}.
*/
equals,
/**
* Label begins with substring criterion.
*
* Required Criteria: {`substring`}.
* Optional Criteria: {`exclusive`}.
*/
beginsWith,
/**
* Label ends with substring criterion.
*
* Required Criteria: {`substring`}.
* Optional Criteria: {`exclusive`}.
*/
endsWith,
/**
* Label contains substring criterion.
*
* Required Criteria: {`substring`}.
* Optional Criteria: {`exclusive`}.
*/
contains,
/**
* Greater than comparator criterion.
*
* Required Criteria: {`comparator`}.
*/
greaterThan,
/**
* Greater than or equal to comparator criterion.
*
* Required Criteria: {`comparator`}.
*/
greaterThanOrEqualTo,
/**
* Less than comparator criterion.
*
* Required Criteria: {`comparator`}.
*/
lessThan,
/**
* Less than or equal to comparator criterion.
*
* Required Criteria: {`comparator`}.
*/
lessThanOrEqualTo,
/**
* Between `lowerBound` and `upperBound` criteria.
*
* Required Criteria: {`lowerBound`, `upperBound`}.
* Optional Criteria: {`exclusive`}.
*/
between,
}
/**
* A simple enum that represents a type of filter for a PivotField.
*/
enum PivotFilterType {
/**
* PivotFilterType is unknown or unsupported.
*/
unknown,
/**
* Filters based on the value of a PivotItem with respect to a DataPivotHierarchy.
*/
value,
/**
* Filters specific manually selected PivotItems from the PivotTable.
*/
manual,
/**
* Filters PivotItems based on their labels.
* Note: A PivotField cannot simultaneously have a label filter and a date filter applied.
*/
label,
/**
* Filters PivotItems with a date in place of a label.
* Note: A PivotField cannot simultaneously have a label filter and a date filter applied.
*/
date,
}
/**
* A simple enum for Top/Bottom filters to select whether to filter by the top N or bottom N percent, number, or sum of values.
*/
enum TopBottomSelectionType {
/**
* Filter the top/bottom N number of items as measured by the chosen value.
*/
items,
/**
* Filter the top/bottom N percent of items as measured by the chosen value.
*/
percent,
/**
* Filter the top/bottom N sum as measured by the chosen value.
*/
sum,
}
/**
* Enum representing all accepted conditions by which a value filter can be applied.
* Used to configure the type of PivotFilter that is applied to the field.
* `PivotFilter.exclusive` can be set to true to invert many of these conditions.
*/
enum ValueFilterCondition {
/**
* ValueFilterCondition is unknown or unsupported.
*/
unknown,
/**
* Equals comparator criterion.
*
* Required Criteria: {`value`, `comparator`}.
* Optional Criteria: {`exclusive`}.
*/
equals,
/**
* Greater than comparator criterion.
*
* Required Criteria: {`value`, `comparator`}.
*/
greaterThan,
/**
* Greater than or equal to comparator criterion.
*
* Required Criteria: {`value`, `comparator`}.
*/
greaterThanOrEqualTo,
/**
* Less than comparator criterion.
*
* Required Criteria: {`value`, `comparator`}.
*/
lessThan,
/**
* Less than or equal to comparator criterion.
*
* Required Criteria: {`value`, `comparator`}.
*/
lessThanOrEqualTo,
/**
* Between `lowerBound` and `upperBound` criteria.
*
* Required Criteria: {`value`, `lowerBound`, `upperBound`}.
* Optional Criteria: {`exclusive`}.
*/
between,
/**
* In top N (`threshold`) [items, percent, sum] of value category.
*
* Required Criteria: {`value`, `threshold`, `selectionType`}.
*/
topN,
/**
* In bottom N (`threshold`) [items, percent, sum] of value category.
*
* Required Criteria: {`value`, `threshold`, `selectionType`}.
*/
bottomN,
}
/**
* Represents the dimensions when getting values from chart series.
*/
enum ChartSeriesDimension {
/**
* The chart series axis for the categories.
*/
categories,
/**
* The chart series axis for the values.
*/
values,
/**
* The chart series axis for the x-axis values in scatter and bubble charts.
*/
xvalues,
/**
* The chart series axis for the y-axis values in scatter and bubble charts.
*/
yvalues,
/**
* The chart series axis for the bubble sizes in bubble charts.
*/
bubbleSizes,
}
/**
* Represents the criteria for the top/bottom values filter.
*/
enum PivotFilterTopBottomCriterion {
invalid,
topItems,
topPercent,
topSum,
bottomItems,
bottomPercent,
bottomSum,
}
/**
* Represents the sort direction.
*/
enum SortBy {
/**
* Ascending sort. Smallest to largest or A to Z.
*/
ascending,
/**
* Descending sort. Largest to smallest or Z to A.
*/
descending,
}
/**
* Aggregation Function for the Data Pivot Field.
*/
enum AggregationFunction {
/**
* Aggregation function is unknown or unsupported.
*/
unknown,
/**
* Excel will automatically select the aggregation based on the data items.
*/
automatic,
/**
* Aggregate using the sum of the data, equivalent to the SUM function.
*/
sum,
/**
* Aggregate using the count of items in the data, equivalent to the COUNTA function.
*/
count,
/**
* Aggregate using the average of the data, equivalent to the AVERAGE function.
*/
average,
/**
* Aggregate using the maximum value of the data, equivalent to the MAX function.
*/
max,
/**
* Aggregate using the minimum value of the data, equivalent to the MIN function.
*/
min,
/**
* Aggregate using the product of the data, equivalent to the PRODUCT function.
*/
product,
/**
* Aggregate using the count of numbers in the data, equivalent to the COUNT function.
*/
countNumbers,
/**
* Aggregate using the standard deviation of the data, equivalent to the STDEV function.
*/
standardDeviation,
/**
* Aggregate using the standard deviation of the data, equivalent to the STDEVP function.
*/
standardDeviationP,
/**
* Aggregate using the variance of the data, equivalent to the VAR function.
*/
variance,
/**
* Aggregate using the variance of the data, equivalent to the VARP function.
*/
varianceP,
}
/**
* The ShowAs Calculation function for the Data Pivot Field.
*/
enum ShowAsCalculation {
/**
* Calculation is unknown or unsupported.
*/
unknown,
/**
* No calculation is applied.
*/
none,
/**
* Percent of the grand total.
*/
percentOfGrandTotal,
/**
* Percent of the row total.
*/
percentOfRowTotal,
/**
* Percent of the column total.
*/
percentOfColumnTotal,
/**
* Percent of the row total for the specified Base Field.
*/
percentOfParentRowTotal,
/**
* Percent of the column total for the specified Base Field.
*/
percentOfParentColumnTotal,
/**
* Percent of the grand total for the specified Base Field.
*/
percentOfParentTotal,
/**
* Percent of the specified Base Field and Base Item.
*/
percentOf,
/**
* Running Total of the specified Base Field.
*/
runningTotal,
/**
* Percent Running Total of the specified Base Field.
*/
percentRunningTotal,
/**
* Difference from the specified Base Field and Base Item.
*/
differenceFrom,
/**
* Difference from the specified Base Field and Base Item.
*/
percentDifferenceFrom,
/**
* Ascending Rank of the specified Base Field.
*/
rankAscending,
/**
* Descending Rank of the specified Base Field.
*/
rankDecending,
/**
* Calculates the values as follows:
* ((value in cell) x (Grand Total of Grand Totals)) / ((Grand Row Total) x (Grand Column Total))
*/
index,
}
/**
* Represents the axis from which to get the PivotItems.
*/
enum PivotAxis {
/**
* The axis or region is unknown or unsupported.
*/
unknown,
/**
* The row axis.
*/
row,
/**
* The column axis.
*/
column,
/**
* The data axis.
*/
data,
/**
* The filter axis.
*/
filter,
}
enum ChartAxisType {
invalid,
/**
* Axis displays categories.
*/
category,
/**
* Axis displays values.
*/
value,
/**
* Axis displays data series.
*/
series,
}
enum ChartAxisGroup {
primary,
secondary,
}
enum ChartAxisScaleType {
linear,
logarithmic,
}
enum ChartAxisPosition {
automatic,
maximum,
minimum,
custom,
}
enum ChartAxisTickMark {
none,
cross,
inside,
outside,
}
/**
* Represents the state of calculation across the entire Excel application.
*/
enum CalculationState {
/**
* Calculations complete.
*/
done,
/**
* Calculations in progress.
*/
calculating,
/**
* Changes that trigger calculation have been made, but a recalculation has not yet been performed.
*/
pending,
}
enum ChartAxisTickLabelPosition {
nextToAxis,
high,
low,
none,
}
enum ChartAxisDisplayUnit {
/**
* Default option. This will reset display unit to the axis, and set unit label invisible.
*/
none,
/**
* This will set the axis in units of hundreds.
*/
hundreds,
/**
* This will set the axis in units of thousands.
*/
thousands,
/**
* This will set the axis in units of tens of thousands.
*/
tenThousands,
/**
* This will set the axis in units of hundreds of thousands.
*/
hundredThousands,
/**
* This will set the axis in units of millions.
*/
millions,
/**
* This will set the axis in units of tens of millions.
*/
tenMillions,
/**
* This will set the axis in units of hundreds of millions.
*/
hundredMillions,
/**
* This will set the axis in units of billions.
*/
billions,
/**
* This will set the axis in units of trillions.
*/
trillions,
/**
* This will set the axis in units of custom value.
*/
custom,
}
/**
* Specifies the unit of time for chart axes and data series.
*/
enum ChartAxisTimeUnit {
days,
months,
years,
}
/**
* Represents the quartile calculation type of chart series layout. Only applies to a box and whisker chart.
*/
enum ChartBoxQuartileCalculation {
inclusive,
exclusive,
}
/**
* Specifies the type of the category axis.
*/
enum ChartAxisCategoryType {
/**
* Excel controls the axis type.
*/
automatic,
/**
* Axis groups data by an arbitrary set of categories.
*/
textAxis,
/**
* Axis groups data on a time scale.
*/
dateAxis,
}
/**
* Specifies the bin's type of a histogram chart or pareto chart series.
*/
enum ChartBinType {
category,
auto,
binWidth,
binCount,
}
enum ChartLineStyle {
none,
continuous,
dash,
dashDot,
dashDotDot,
dot,
grey25,
grey50,
grey75,
automatic,
roundDot,
}
enum ChartDataLabelPosition {
invalid,
none,
center,
insideEnd,
insideBase,
outsideEnd,
left,
right,
top,
bottom,
bestFit,
callout,
}
/**
* Represents which parts of the error bar to include.
*/
enum ChartErrorBarsInclude {
both,
minusValues,
plusValues,
}
/**
* Represents the range type for error bars.
*/
enum ChartErrorBarsType {
fixedValue,
percent,
stDev,
stError,
custom,
}
/**
* Represents the mapping level of a chart series. This only applies to region map charts.
*/
enum ChartMapAreaLevel {
automatic,
dataOnly,
city,
county,
state,
country,
continent,
world,
}
/**
* Represents the gradient style of a chart series. This is only applicable for region map charts.
*/
enum ChartGradientStyle {
twoPhaseColor,
threePhaseColor,
}
/**
* Represents the gradient style type of a chart series. This is only applicable for region map charts.
*/
enum ChartGradientStyleType {
extremeValue,
number,
percent,
}
/**
* Represents the position of chart title.
*/
enum ChartTitlePosition {
automatic,
top,
bottom,
left,
right,
}
enum ChartLegendPosition {
invalid,
top,
bottom,
left,
right,
corner,
custom,
}
enum ChartMarkerStyle {
invalid,
automatic,
none,
square,
diamond,
triangle,
x,
star,
dot,
dash,
circle,
plus,
picture,
}
enum ChartPlotAreaPosition {
automatic,
custom,
}
/**
* Represents the region level of a chart series layout. This only applies to region map charts.
*/
enum ChartMapLabelStrategy {
none,
bestFit,
showAll,
}
/**
* Represents the region projection type of a chart series layout. This only applies to region map charts.
*/
enum ChartMapProjectionType {
automatic,
mercator,
miller,
robinson,
albers,
}
/**
* Represents the parent label strategy of the chart series layout. This only applies to treemap charts
*/
enum ChartParentLabelStrategy {
none,
banner,
overlapping,
}
/**
* Specifies whether the series are by rows or by columns. On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; in Excel on the web, "auto" will simply default to "columns".
*/
enum ChartSeriesBy {
/**
* On Desktop, the "auto" option will inspect the source data shape to automatically guess whether the data is by rows or columns; in Excel on the web, "auto" will simply default to "columns".
*/
auto,
columns,
rows,
}
/**
* Represents the horizontal alignment for the specified object.
*/
enum ChartTextHorizontalAlignment {
center,
left,
right,
justify,
distributed,
}
/**
* Represents the vertical alignment for the specified object.
*/
enum ChartTextVerticalAlignment {
center,
bottom,
top,
justify,
distributed,
}
enum ChartTickLabelAlignment {
center,
left,
right,
}
enum ChartType {
invalid,
columnClustered,
columnStacked,
columnStacked100,
barClustered,
barStacked,
barStacked100,
lineStacked,
lineStacked100,
lineMarkers,
lineMarkersStacked,
lineMarkersStacked100,
pieOfPie,
pieExploded,
barOfPie,
xyscatterSmooth,
xyscatterSmoothNoMarkers,
xyscatterLines,
xyscatterLinesNoMarkers,
areaStacked,
areaStacked100,
doughnutExploded,
radarMarkers,
radarFilled,
surface,
surfaceWireframe,
surfaceTopView,
surfaceTopViewWireframe,
bubble,
bubble3DEffect,
stockHLC,
stockOHLC,
stockVHLC,
stockVOHLC,
cylinderColClustered,
cylinderColStacked,
cylinderColStacked100,
cylinderBarClustered,
cylinderBarStacked,
cylinderBarStacked100,
cylinderCol,
coneColClustered,
coneColStacked,
coneColStacked100,
coneBarClustered,
coneBarStacked,
coneBarStacked100,
coneCol,
pyramidColClustered,
pyramidColStacked,
pyramidColStacked100,
pyramidBarClustered,
pyramidBarStacked,
pyramidBarStacked100,
pyramidCol,
line,
pie,
xyscatter,
area,
doughnut,
radar,
histogram,
boxwhisker,
pareto,
regionMap,
treemap,
waterfall,
sunburst,
funnel,
}
enum ChartUnderlineStyle {
none,
single,
}
enum ChartDisplayBlanksAs {
notPlotted,
zero,
interplotted,
}
enum ChartPlotBy {
rows,
columns,
}
enum ChartSplitType {
splitByPosition,
splitByValue,
splitByPercentValue,
splitByCustomSplit,
}
enum ChartColorScheme {
colorfulPalette1,
colorfulPalette2,
colorfulPalette3,
colorfulPalette4,
monochromaticPalette1,
monochromaticPalette2,
monochromaticPalette3,
monochromaticPalette4,
monochromaticPalette5,
monochromaticPalette6,
monochromaticPalette7,
monochromaticPalette8,
monochromaticPalette9,
monochromaticPalette10,
monochromaticPalette11,
monochromaticPalette12,
monochromaticPalette13,
}
enum ChartTrendlineType {
linear,
exponential,
logarithmic,
movingAverage,
polynomial,
power,
}
/**
* Specifies where in the z-order a shape should be moved relative to other shapes.
*/
enum ShapeZOrder {
bringToFront,
bringForward,
sendToBack,
sendBackward,
}
/**
* Specifies the type of a shape.
*/
enum ShapeType {
unsupported,
image,
geometricShape,
group,
line,
}
/**
* Specifies whether the shape is scaled relative to its original or current size.
*/
enum ShapeScaleType {
currentSize,
originalSize,
}
/**
* Specifies which part of the shape retains its position when the shape is scaled.
*/
enum ShapeScaleFrom {
scaleFromTopLeft,
scaleFromMiddle,
scaleFromBottomRight,
}
/**
* Specifies a shape's fill type.
*/
enum ShapeFillType {
/**
* No fill.
*/
noFill,
/**
* Solid fill.
*/
solid,
/**
* Gradient fill.
*/
gradient,
/**
* Pattern fill.
*/
pattern,
/**
* Picture and texture fill.
*/
pictureAndTexture,
/**
* Mixed fill.
*/
mixed,
}
/**
* The type of underline applied to a font.
*/
enum ShapeFontUnderlineStyle {
none,
single,
double,
heavy,
dotted,
dottedHeavy,
dash,
dashHeavy,
dashLong,
dashLongHeavy,
dotDash,
dotDashHeavy,
dotDotDash,
dotDotDashHeavy,
wavy,
wavyHeavy,
wavyDouble,
}
/**
* The format of the image.
*/
enum PictureFormat {
unknown,
/**
* Bitmap image.
*/
bmp,
/**
* Joint Photographic Experts Group.
*/
jpeg,
/**
* Graphics Interchange Format.
*/
gif,
/**
* Portable Network Graphics.
*/
png,
/**
* Scalable Vector Graphic.
*/
svg,
}
/**
* The style for a line.
*/
enum ShapeLineStyle {
/**
* Single line.
*/
single,
/**
* Thick line with a thin line on each side.
*/
thickBetweenThin,
/**
* Thick line next to thin line. For horizontal lines, the thick line is above the thin line. For vertical lines, the thick line is to the left of the thin line.
*/
thickThin,
/**
* Thick line next to thin line. For horizontal lines, the thick line is below the thin line. For vertical lines, the thick line is to the right of the thin line.
*/
thinThick,
/**
* Two thin lines.
*/
thinThin,
}
/**
* The dash style for a line.
*/
enum ShapeLineDashStyle {
dash,
dashDot,
dashDotDot,
longDash,
longDashDot,
roundDot,
solid,
squareDot,
longDashDotDot,
systemDash,
systemDot,
systemDashDot,
}
enum ArrowheadLength {
short,
medium,
long,
}
enum ArrowheadStyle {
none,
triangle,
stealth,
diamond,
oval,
open,
}
enum ArrowheadWidth {
narrow,
medium,
wide,
}
enum BindingType {
range,
table,
text,
}
enum BorderIndex {
edgeTop,
edgeBottom,
edgeLeft,
edgeRight,
insideVertical,
insideHorizontal,
diagonalDown,
diagonalUp,
}
enum BorderLineStyle {
none,
continuous,
dash,
dashDot,
dashDotDot,
dot,
double,
slantDashDot,
}
enum BorderWeight {
hairline,
thin,
medium,
thick,
}
enum CalculationMode {
/**
* The default recalculation behavior where Excel calculates new formula results every time the relevant data is changed.
*/
automatic,
/**
* Calculates new formula results every time the relevant data is changed, unless the formula is in a data table.
*/
automaticExceptTables,
/**
* Calculations only occur when the user or add-in requests them.
*/
manual,
}
enum CalculationType {
/**
* Recalculates all cells that Excel has marked as dirty, that is, dependents of volatile or changed data, and cells programmatically marked as dirty.
*/
recalculate,
/**
* This will mark all cells as dirty and then recalculate them.
*/
full,
/**
* This will rebuild the full dependency chain, mark all cells as dirty and then recalculate them.
*/
fullRebuild,
}
enum ClearApplyTo {
all,
/**
* Clears all formatting for the range.
*/
formats,
/**
* Clears the contents of the range.
*/
contents,
/**
* Clears all hyperlinks, but leaves all content and formatting intact.
*/
hyperlinks,
/**
* Removes hyperlinks and formatting for the cell but leaves content, conditional formats, and data validation intact.
*/
removeHyperlinks,
}
/**
* Represents the format options for a Data Bar Axis.
*/
enum ConditionalDataBarAxisFormat {
automatic,
none,
cellMidPoint,
}
/**
* Represents the Data Bar direction within a cell.
*/
enum ConditionalDataBarDirection {
context,
leftToRight,
rightToLeft,
}
/**
* Represents the direction for a selection.
*/
enum ConditionalFormatDirection {
top,
bottom,
}
enum ConditionalFormatType {
custom,
dataBar,
colorScale,
iconSet,
topBottom,
presetCriteria,
containsText,
cellValue,
}
/**
* Represents the types of conditional format values.
*/
enum ConditionalFormatRuleType {
invalid,
automatic,
lowestValue,
highestValue,
number,
percent,
formula,
percentile,
}
/**
* Represents the types of icon conditional format.
*/
enum ConditionalFormatIconRuleType {
invalid,
number,
percent,
formula,
percentile,
}
/**
* Represents the types of color criterion for conditional formatting.
*/
enum ConditionalFormatColorCriterionType {
invalid,
lowestValue,
highestValue,
number,
percent,
formula,
percentile,
}
/**
* Represents the criteria for the above/below average conditional format type.
*/
enum ConditionalTopBottomCriterionType {
invalid,
topItems,
topPercent,
bottomItems,
bottomPercent,
}
/**
* Represents the criteria for the Preset Criteria conditional format type.
*/
enum ConditionalFormatPresetCriterion {
invalid,
blanks,
nonBlanks,
errors,
nonErrors,
yesterday,
today,
tomorrow,
lastSevenDays,
lastWeek,
thisWeek,
nextWeek,
lastMonth,
thisMonth,
nextMonth,
aboveAverage,
belowAverage,
equalOrAboveAverage,
equalOrBelowAverage,
oneStdDevAboveAverage,
oneStdDevBelowAverage,
twoStdDevAboveAverage,
twoStdDevBelowAverage,
threeStdDevAboveAverage,
threeStdDevBelowAverage,
uniqueValues,
duplicateValues,
}
/**
* Represents the operator of the text conditional format type.
*/
enum ConditionalTextOperator {
invalid,
contains,
notContains,
beginsWith,
endsWith,
}
/**
* Represents the operator of the text conditional format type.
*/
enum ConditionalCellValueOperator {
invalid,
between,
notBetween,
equalTo,
notEqualTo,
greaterThan,
lessThan,
greaterThanOrEqual,
lessThanOrEqual,
}
/**
* Represents the operator for each icon criteria.
*/
enum ConditionalIconCriterionOperator {
invalid,
greaterThan,
greaterThanOrEqual,
}
enum ConditionalRangeBorderIndex {
edgeTop,
edgeBottom,
edgeLeft,
edgeRight,
}
enum ConditionalRangeBorderLineStyle {
none,
continuous,
dash,
dashDot,
dashDotDot,
dot,
}
enum ConditionalRangeFontUnderlineStyle {
none,
single,
double,
}
/**
* Represents Data validation type enum.
*/
enum DataValidationType {
/**
* None means allow any value and so there is no data validation in the range.
*/
none,
/**
* Whole number data validation type
*/
wholeNumber,
/**
* Decimal data validation type
*/
decimal,
/**
* List data validation type
*/
list,
/**
* Date data validation type
*/
date,
/**
* Time data validation type
*/
time,
/**
* Text length data validation type
*/
textLength,
/**
* Custom data validation type
*/
custom,
/**
* Inconsistent means that the range has inconsistent data validation (there are different rules on different cells)
*/
inconsistent,
/**
* MixedCriteria means that the range has data validation present on some but not all cells
*/
mixedCriteria,
}
/**
* Represents Data validation operator enum.
*/
enum DataValidationOperator {
between,
notBetween,
equalTo,
notEqualTo,
greaterThan,
lessThan,
greaterThanOrEqualTo,
lessThanOrEqualTo,
}
/**
* Represents Data validation error alert style. The default is "Stop".
*/
enum DataValidationAlertStyle {
stop,
warning,
information,
}
enum DeleteShiftDirection {
up,
left,
}
enum DynamicFilterCriteria {
unknown,
aboveAverage,
allDatesInPeriodApril,
allDatesInPeriodAugust,
allDatesInPeriodDecember,
allDatesInPeriodFebruary,
allDatesInPeriodJanuary,
allDatesInPeriodJuly,
allDatesInPeriodJune,
allDatesInPeriodMarch,
allDatesInPeriodMay,
allDatesInPeriodNovember,
allDatesInPeriodOctober,
allDatesInPeriodQuarter1,
allDatesInPeriodQuarter2,
allDatesInPeriodQuarter3,
allDatesInPeriodQuarter4,
allDatesInPeriodSeptember,
belowAverage,
lastMonth,
lastQuarter,
lastWeek,
lastYear,
nextMonth,
nextQuarter,
nextWeek,
nextYear,
thisMonth,
thisQuarter,
thisWeek,
thisYear,
today,
tomorrow,
yearToDate,
yesterday,
}
enum FilterDatetimeSpecificity {
year,
month,
day,
hour,
minute,
second,
}
enum FilterOn {
bottomItems,
bottomPercent,
cellColor,
dynamic,
fontColor,
values,
topItems,
topPercent,
icon,
custom,
}
enum FilterOperator {
and,
or,
}
enum HorizontalAlignment {
general,
left,
center,
right,
fill,
justify,
centerAcrossSelection,
distributed,
}
enum IconSet {
invalid,
threeArrows,
threeArrowsGray,
threeFlags,
threeTrafficLights1,
threeTrafficLights2,
threeSigns,
threeSymbols,
threeSymbols2,
fourArrows,
fourArrowsGray,
fourRedToBlack,
fourRating,
fourTrafficLights,
fiveArrows,
fiveArrowsGray,
fiveRating,
fiveQuarters,
threeStars,
threeTriangles,
fiveBoxes,
}
enum ImageFittingMode {
fit,
fitAndCenter,
fill,
}
enum InsertShiftDirection {
down,
right,
}
enum NamedItemScope {
worksheet,
workbook,
}
enum NamedItemType {
string,
integer,
double,
boolean,
range,
error,
array,
}
enum RangeUnderlineStyle {
none,
single,
double,
singleAccountant,
doubleAccountant,
}
enum SheetVisibility {
visible,
hidden,
veryHidden,
}
enum RangeValueType {
unknown,
empty,
string,
integer,
double,
boolean,
error,
richValue,
}
/**
* Specifies the search direction.
*/
enum SearchDirection {
/**
* Search in forward order.
*/
forward,
/**
* Search in reverse order.
*/
backwards,
}
enum SortOrientation {
rows,
columns,
}
enum SortOn {
value,
cellColor,
fontColor,
icon,
}
enum SortDataOption {
normal,
textAsNumber,
}
enum SortMethod {
pinYin,
strokeCount,
}
enum VerticalAlignment {
top,
center,
bottom,
justify,
distributed,
}
enum DocumentPropertyType {
number,
boolean,
date,
string,
float,
}
enum SubtotalLocationType {
/**
* Subtotals are at the top.
*/
atTop,
/**
* Subtotals are at the bottom.
*/
atBottom,
/**
* Subtotals are off.
*/
off,
}
enum PivotLayoutType {
/**
* A horizontally compressed form with labels from the next field in the same column.
*/
compact,
/**
* Inner fields' items are always on a new line relative to the outer fields' items.
*/
tabular,
/**
* Inner fields' items are on same row as outer fields' items and subtotals are always on the bottom.
*/
outline,
}
enum ProtectionSelectionMode {
/**
* Selection is allowed for all cells.
*/
normal,
/**
* Selection is allowed only for cells that are not locked.
*/
unlocked,
/**
* Selection is not allowed for all cells.
*/
none,
}
enum PageOrientation {
portrait,
landscape,
}
enum PaperType {
letter,
letterSmall,
tabloid,
ledger,
legal,
statement,
executive,
a3,
a4,
a4Small,
a5,
b4,
b5,
folio,
quatro,
paper10x14,
paper11x17,
note,
envelope9,
envelope10,
envelope11,
envelope12,
envelope14,
csheet,
dsheet,
esheet,
envelopeDL,
envelopeC5,
envelopeC3,
envelopeC4,
envelopeC6,
envelopeC65,
envelopeB4,
envelopeB5,
envelopeB6,
envelopeItaly,
envelopeMonarch,
envelopePersonal,
fanfoldUS,
fanfoldStdGerman,
fanfoldLegalGerman,
}
enum ReadingOrder {
/**
* Reading order is determined by the language of the first character entered.
* If a right-to-left language character is entered first, reading order is right to left.
* If a left-to-right language character is entered first, reading order is left to right.
*/
context,
/**
* Left to right reading order
*/
leftToRight,
/**
* Right to left reading order
*/
rightToLeft,
}
enum BuiltInStyle {
normal,
comma,
currency,
percent,
wholeComma,
wholeDollar,
hlink,
hlinkTrav,
note,
warningText,
emphasis1,
emphasis2,
emphasis3,
sheetTitle,
heading1,
heading2,
heading3,
heading4,
input,
output,
calculation,
checkCell,
linkedCell,
total,
good,
bad,
neutral,
accent1,
accent1_20,
accent1_40,
accent1_60,
accent2,
accent2_20,
accent2_40,
accent2_60,
accent3,
accent3_20,
accent3_40,
accent3_60,
accent4,
accent4_20,
accent4_40,
accent4_60,
accent5,
accent5_20,
accent5_40,
accent5_60,
accent6,
accent6_20,
accent6_40,
accent6_60,
explanatoryText,
}
enum PrintErrorType {
asDisplayed,
blank,
dash,
notAvailable,
}
enum WorksheetPositionType {
none,
before,
after,
beginning,
end,
}
enum PrintComments {
/**
* Comments will not be printed.
*/
noComments,
/**
* Comments will be printed as end notes at the end of the worksheet.
*/
endSheet,
/**
* Comments will be printed where they were inserted in the worksheet.
*/
inPlace,
}
enum PrintOrder {
/**
* Process down the rows before processing across pages or page fields to the right.
*/
downThenOver,
/**
* Process across pages or page fields to the right before moving down the rows.
*/
overThenDown,
}
enum PrintMarginUnit {
/**
* Assign the page margins in points. A point is 1/72 of an inch.
*/
points,
/**
* Assign the page margins in inches.
*/
inches,
/**
* Assign the page margins in centimeters.
*/
centimeters,
}
enum HeaderFooterState {
/**
* Only one general header/footer is used for all pages printed.
*/
default,
/**
* There is a separate first page header/footer, and a general header/footer used for all other pages.
*/
firstAndDefault,
/**
* There is a different header/footer for odd and even pages.
*/
oddAndEven,
/**
* There is a separate first page header/footer, then there is a separate header/footer for odd and even pages.
*/
firstOddAndEven,
}
/**
* The behavior types when AutoFill is used on a range in the workbook.
*/
enum AutoFillType {
/**
* Populates the adjacent cells based on the surrounding data (the standard AutoFill behavior).
*/
fillDefault,
/**
* Populates the adjacent cells with data based on the selected data.
*/
fillCopy,
/**
* Populates the adjacent cells with data that follows a pattern in the copied cells.
*/
fillSeries,
/**
* Populates the adjacent cells with the selected formulas.
*/
fillFormats,
/**
* Populates the adjacent cells with the selected values.
*/
fillValues,
/**
* A version of "FillSeries" for dates that bases the pattern on either the day of the month or the day of the week, depending on the context.
*/
fillDays,
/**
* A version of "FillSeries" for dates that bases the pattern on the day of the week and only includes weekdays.
*/
fillWeekdays,
/**
* A version of "FillSeries" for dates that bases the pattern on the month.
*/
fillMonths,
/**
* A version of "FillSeries" for dates that bases the pattern on the year.
*/
fillYears,
/**
* A version of "FillSeries" for numbers that fills out the values in the adjacent cells according to a linear trend model.
*/
linearTrend,
/**
* A version of "FillSeries" for numbers that fills out the values in the adjacent cells according to a growth trend model.
*/
growthTrend,
/**
* Populates the adjacent cells by using Excel's FlashFill feature.
*/
flashFill,
}
enum GroupOption {
/**
* Group by rows.
*/
byRows,
/**
* Group by columns.
*/
byColumns,
}
enum RangeCopyType {
all,
formulas,
values,
formats,
}
enum LinkedDataTypeState {
none,
validLinkedData,
disambiguationNeeded,
brokenLinkedData,
fetchingData,
}
/**
* Specifies the shape type for a GeometricShape object.
*/
enum GeometricShapeType {
lineInverse,
triangle,
rightTriangle,
rectangle,
diamond,
parallelogram,
trapezoid,
nonIsoscelesTrapezoid,
pentagon,
hexagon,
heptagon,
octagon,
decagon,
dodecagon,
star4,
star5,
star6,
star7,
star8,
star10,
star12,
star16,
star24,
star32,
roundRectangle,
round1Rectangle,
round2SameRectangle,
round2DiagonalRectangle,
snipRoundRectangle,
snip1Rectangle,
snip2SameRectangle,
snip2DiagonalRectangle,
plaque,
ellipse,
teardrop,
homePlate,
chevron,
pieWedge,
pie,
blockArc,
donut,
noSmoking,
rightArrow,
leftArrow,
upArrow,
downArrow,
stripedRightArrow,
notchedRightArrow,
bentUpArrow,
leftRightArrow,
upDownArrow,
leftUpArrow,
leftRightUpArrow,
quadArrow,
leftArrowCallout,
rightArrowCallout,
upArrowCallout,
downArrowCallout,
leftRightArrowCallout,
upDownArrowCallout,
quadArrowCallout,
bentArrow,
uturnArrow,
circularArrow,
leftCircularArrow,
leftRightCircularArrow,
curvedRightArrow,
curvedLeftArrow,
curvedUpArrow,
curvedDownArrow,
swooshArrow,
cube,
can,
lightningBolt,
heart,
sun,
moon,
smileyFace,
irregularSeal1,
irregularSeal2,
foldedCorner,
bevel,
frame,
halfFrame,
corner,
diagonalStripe,
chord,
arc,
leftBracket,
rightBracket,
leftBrace,
rightBrace,
bracketPair,
bracePair,
callout1,
callout2,
callout3,
accentCallout1,
accentCallout2,
accentCallout3,
borderCallout1,
borderCallout2,
borderCallout3,
accentBorderCallout1,
accentBorderCallout2,
accentBorderCallout3,
wedgeRectCallout,
wedgeRRectCallout,
wedgeEllipseCallout,
cloudCallout,
cloud,
ribbon,
ribbon2,
ellipseRibbon,
ellipseRibbon2,
leftRightRibbon,
verticalScroll,
horizontalScroll,
wave,
doubleWave,
plus,
flowChartProcess,
flowChartDecision,
flowChartInputOutput,
flowChartPredefinedProcess,
flowChartInternalStorage,
flowChartDocument,
flowChartMultidocument,
flowChartTerminator,
flowChartPreparation,
flowChartManualInput,
flowChartManualOperation,
flowChartConnector,
flowChartPunchedCard,
flowChartPunchedTape,
flowChartSummingJunction,
flowChartOr,
flowChartCollate,
flowChartSort,
flowChartExtract,
flowChartMerge,
flowChartOfflineStorage,
flowChartOnlineStorage,
flowChartMagneticTape,
flowChartMagneticDisk,
flowChartMagneticDrum,
flowChartDisplay,
flowChartDelay,
flowChartAlternateProcess,
flowChartOffpageConnector,
actionButtonBlank,
actionButtonHome,
actionButtonHelp,
actionButtonInformation,
actionButtonForwardNext,
actionButtonBackPrevious,
actionButtonEnd,
actionButtonBeginning,
actionButtonReturn,
actionButtonDocument,
actionButtonSound,
actionButtonMovie,
gear6,
gear9,
funnel,
mathPlus,
mathMinus,
mathMultiply,
mathDivide,
mathEqual,
mathNotEqual,
cornerTabs,
squareTabs,
plaqueTabs,
chartX,
chartStar,
chartPlus,
}
enum ConnectorType {
straight,
elbow,
curve,
}
enum ContentType {
/**
* Indicates plain format type of the comment content.
*/
plain,
/**
* Comment content containing mentions.
*/
mention,
}
enum SpecialCellType {
/**
* All cells with conditional formats
*/
conditionalFormats,
/**
* Cells having validation criteria.
*/
dataValidations,
/**
* Cells with no content.
*/
blanks,
/**
* Cells containing constants.
*/
constants,
/**
* Cells containing formulas.
*/
formulas,
/**
* Cells having the same conditional format as the first cell in the range.
*/
sameConditionalFormat,
/**
* Cells having the same data validation criteria as the first cell in the range.
*/
sameDataValidation,
/**
* Cells that are visible.
*/
visible,
}
enum SpecialCellValueType {
/**
* Cells that have errors, true/false, numeric, or a string value.
*/
all,
/**
* Cells that have errors.
*/
errors,
/**
* Cells that have errors, or a true/false value.
*/
errorsLogical,
/**
* Cells that have errors, or a numeric value.
*/
errorsNumbers,
/**
* Cells that have errors, or a string value.
*/
errorsText,
/**
* Cells that have errors, true/false, or a numeric value.
*/
errorsLogicalNumber,
/**
* Cells that have errors, true/false, or a string value.
*/
errorsLogicalText,
/**
* Cells that have errors, numeric, or a string value.
*/
errorsNumberText,
/**
* Cells that have a true/false value.
*/
logical,
/**
* Cells that have a true/false, or a numeric value.
*/
logicalNumbers,
/**
* Cells that have a true/false, or a string value.
*/
logicalText,
/**
* Cells that have a true/false, numeric, or a string value.
*/
logicalNumbersText,
/**
* Cells that have a numeric value.
*/
numbers,
/**
* Cells that have a numeric, or a string value.
*/
numbersText,
/**
* Cells that have a string value.
*/
text,
}
/**
* Specifies the way that an object is attached to its underlying cells.
*/
enum Placement {
/**
* The object is moved with the cells.
*/
twoCell,
/**
* The object is moved and sized with the cells.
*/
oneCell,
/**
* The object is free floating.
*/
absolute,
}
enum FillPattern {
none,
solid,
gray50,
gray75,
gray25,
horizontal,
vertical,
down,
up,
checker,
semiGray75,
lightHorizontal,
lightVertical,
lightDown,
lightUp,
grid,
crissCross,
gray16,
gray8,
linearGradient,
rectangularGradient,
}
/**
* Specifies the horizontal alignment for the text frame in a shape.
*/
enum ShapeTextHorizontalAlignment {
left,
center,
right,
justify,
justifyLow,
distributed,
thaiDistributed,
}
/**
* Specifies the vertical alignment for the text frame in a shape.
*/
enum ShapeTextVerticalAlignment {
top,
middle,
bottom,
justified,
distributed,
}
/**
* Specifies the vertical overflow for the text frame in a shape.
*/
enum ShapeTextVerticalOverflow {
/**
* Allow text to overflow the text frame vertically (can be from the top, bottom, or both depending on the text alignment).
*/
overflow,
/**
* Hide text that does not fit vertically within the text frame, and add an ellipsis (...) at the end of the visible text.
*/
ellipsis,
/**
* Hide text that does not fit vertically within the text frame.
*/
clip,
}
/**
* Specifies the horizontal overflow for the text frame in a shape.
*/
enum ShapeTextHorizontalOverflow {
overflow,
clip,
}
/**
* Specifies the reading order for the text frame in a shape.
*/
enum ShapeTextReadingOrder {
leftToRight,
rightToLeft,
}
/**
* Specifies the orientation for the text frame in a shape.
*/
enum ShapeTextOrientation {
horizontal,
vertical,
vertical270,
wordArtVertical,
eastAsianVertical,
mongolianVertical,
wordArtVerticalRTL,
}
/**
* Determines the type of automatic sizing allowed.
*/
enum ShapeAutoSize {
/**
* No autosizing.
*/
autoSizeNone,
/**
* The text is adjusted to fit the shape.
*/
autoSizeTextToFitShape,
/**
* The shape is adjusted to fit the text.
*/
autoSizeShapeToFitText,
/**
* A combination of automatic sizing schemes are used.
*/
autoSizeMixed,
}
/**
* Specifies the slicer sort behavior for Slicer.sortBy API.
*/
enum SlicerSortType {
/**
* Sort slicer items in the order provided by the data source.
*/
dataSourceOrder,
/**
* Sort slicer items in ascending order by item captions.
*/
ascending,
/**
* Sort slicer items in descending order by item captions.
*/
descending,
}
/**
* Represents a category of number formats.
*/
enum NumberFormatCategory {
/**
* General format cells have no specific number format.
*/
general,
/**
* Number is used for general display of numbers. Currency and Accounting offer specialized formatting for monetary value.
*/
number,
/**
* Currency formats are used for general monetary values. Use Accounting formats to align decimal points in a column.
*/
currency,
/**
* Accounting formats line up the currency symbols and decimal points in a column.
*/
accounting,
/**
* Date formats display date and time serial numbers as date values. Date formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified for the operating system. Formats without an asterisk are not affected by operating system settings.
*/
date,
/**
* Time formats display date and time serial numbers as date values. Time formats that begin with an asterisk (*) respond to changes in regional date and time settings that are specified for the operating system. Formats without an asterisk are not affected by operating system settings.
*/
time,
/**
* Percentage formats multiply the cell value by 100 and displays the result with a percent symbol.
*/
percentage,
/**
* Fraction formats display the cell value as a whole number with the remainder rounded to the nearest fraction value.
*/
fraction,
/**
* Scientific formats display the cell value as a number between 1 and 10 multiplied by a power of 10.
*/
scientific,
/**
* Text format cells are treated as text even when a number is in the cell. The cell is displayed exactly as entered.
*/
text,
/**
* Special formats are useful for tracking list and database values.
*/
special,
/**
* A custom format that is not a part of any category.
*/
custom,
}
//
// Type
//
type RangeValue = string | number | boolean | null | undefined;
} | the_stack |
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base';
/**
*
* @export
* @interface AdditionalPropertiesClass
*/
export interface AdditionalPropertiesClass {
/**
*
* @type {{ [key: string]: string; }}
* @memberof AdditionalPropertiesClass
*/
'map_property'?: { [key: string]: string; };
/**
*
* @type {{ [key: string]: { [key: string]: string; }; }}
* @memberof AdditionalPropertiesClass
*/
'map_of_map_property'?: { [key: string]: { [key: string]: string; }; };
}
/**
*
* @export
* @interface Animal
*/
export interface Animal {
/**
*
* @type {string}
* @memberof Animal
*/
'className': string;
/**
*
* @type {string}
* @memberof Animal
*/
'color'?: string;
}
/**
*
* @export
* @interface ApiResponse
*/
export interface ApiResponse {
/**
*
* @type {number}
* @memberof ApiResponse
*/
'code'?: number;
/**
*
* @type {string}
* @memberof ApiResponse
*/
'type'?: string;
/**
*
* @type {string}
* @memberof ApiResponse
*/
'message'?: string;
}
/**
*
* @export
* @interface Apple
*/
export interface Apple {
/**
*
* @type {string}
* @memberof Apple
*/
'cultivar'?: string;
}
/**
*
* @export
* @interface AppleReq
*/
export interface AppleReq {
/**
*
* @type {string}
* @memberof AppleReq
*/
'cultivar': string;
/**
*
* @type {boolean}
* @memberof AppleReq
*/
'mealy'?: boolean;
}
/**
*
* @export
* @interface ArrayOfArrayOfNumberOnly
*/
export interface ArrayOfArrayOfNumberOnly {
/**
*
* @type {Array<Array<number>>}
* @memberof ArrayOfArrayOfNumberOnly
*/
'ArrayArrayNumber'?: Array<Array<number>>;
}
/**
*
* @export
* @interface ArrayOfNumberOnly
*/
export interface ArrayOfNumberOnly {
/**
*
* @type {Array<number>}
* @memberof ArrayOfNumberOnly
*/
'ArrayNumber'?: Array<number>;
}
/**
*
* @export
* @interface ArrayTest
*/
export interface ArrayTest {
/**
*
* @type {Array<string>}
* @memberof ArrayTest
*/
'array_of_string'?: Array<string>;
/**
*
* @type {Array<Array<number>>}
* @memberof ArrayTest
*/
'array_array_of_integer'?: Array<Array<number>>;
/**
*
* @type {Array<Array<ReadOnlyFirst>>}
* @memberof ArrayTest
*/
'array_array_of_model'?: Array<Array<ReadOnlyFirst>>;
}
/**
*
* @export
* @interface Banana
*/
export interface Banana {
[key: string]: object | any;
/**
*
* @type {number}
* @memberof Banana
*/
'lengthCm'?: number;
}
/**
*
* @export
* @interface BananaReq
*/
export interface BananaReq {
/**
*
* @type {number}
* @memberof BananaReq
*/
'lengthCm': number;
/**
*
* @type {boolean}
* @memberof BananaReq
*/
'sweet'?: boolean;
}
/**
*
* @export
* @interface Capitalization
*/
export interface Capitalization {
/**
*
* @type {string}
* @memberof Capitalization
*/
'smallCamel'?: string;
/**
*
* @type {string}
* @memberof Capitalization
*/
'CapitalCamel'?: string;
/**
*
* @type {string}
* @memberof Capitalization
*/
'small_Snake'?: string;
/**
*
* @type {string}
* @memberof Capitalization
*/
'Capital_Snake'?: string;
/**
*
* @type {string}
* @memberof Capitalization
*/
'SCA_ETH_Flow_Points'?: string;
/**
* Name of the pet
* @type {string}
* @memberof Capitalization
*/
'ATT_NAME'?: string;
}
/**
*
* @export
* @interface Cat
*/
export interface Cat extends Animal {
/**
*
* @type {boolean}
* @memberof Cat
*/
'declawed'?: boolean;
}
/**
*
* @export
* @interface CatAllOf
*/
export interface CatAllOf {
/**
*
* @type {boolean}
* @memberof CatAllOf
*/
'declawed'?: boolean;
}
/**
*
* @export
* @interface Category
*/
export interface Category {
/**
*
* @type {number}
* @memberof Category
*/
'id'?: number;
/**
*
* @type {string}
* @memberof Category
*/
'name': string;
}
/**
* Model for testing model with \"_class\" property
* @export
* @interface ClassModel
*/
export interface ClassModel {
/**
*
* @type {string}
* @memberof ClassModel
*/
'_class'?: string;
}
/**
*
* @export
* @interface Client
*/
export interface Client {
/**
*
* @type {string}
* @memberof Client
*/
'client'?: string;
}
/**
*
* @export
* @interface Dog
*/
export interface Dog extends Animal {
/**
*
* @type {string}
* @memberof Dog
*/
'breed'?: string;
}
/**
*
* @export
* @interface DogAllOf
*/
export interface DogAllOf {
/**
*
* @type {string}
* @memberof DogAllOf
*/
'breed'?: string;
}
/**
*
* @export
* @interface EnumArrays
*/
export interface EnumArrays {
/**
*
* @type {string}
* @memberof EnumArrays
*/
'just_symbol'?: EnumArraysJustSymbolEnum;
/**
*
* @type {Array<string>}
* @memberof EnumArrays
*/
'array_enum'?: Array<EnumArraysArrayEnumEnum>;
}
/**
* @export
* @enum {string}
*/
export enum EnumArraysJustSymbolEnum {
GreaterThanOrEqualTo = '>=',
Dollar = '$'
}
/**
* @export
* @enum {string}
*/
export enum EnumArraysArrayEnumEnum {
Fish = 'fish',
Crab = 'crab'
}
/**
*
* @export
* @enum {string}
*/
export enum EnumClass {
Abc = '_abc',
Efg = '-efg',
Xyz = '(xyz)'
}
/**
*
* @export
* @interface EnumTest
*/
export interface EnumTest {
/**
*
* @type {string}
* @memberof EnumTest
*/
'enum_string'?: EnumTestEnumStringEnum;
/**
*
* @type {string}
* @memberof EnumTest
*/
'enum_string_required': EnumTestEnumStringRequiredEnum;
/**
*
* @type {number}
* @memberof EnumTest
*/
'enum_integer'?: EnumTestEnumIntegerEnum;
/**
*
* @type {number}
* @memberof EnumTest
*/
'enum_number'?: EnumTestEnumNumberEnum;
/**
*
* @type {OuterEnum}
* @memberof EnumTest
*/
'outerEnum'?: OuterEnum | null;
/**
*
* @type {OuterEnumInteger}
* @memberof EnumTest
*/
'outerEnumInteger'?: OuterEnumInteger;
/**
*
* @type {OuterEnumDefaultValue}
* @memberof EnumTest
*/
'outerEnumDefaultValue'?: OuterEnumDefaultValue;
/**
*
* @type {OuterEnumIntegerDefaultValue}
* @memberof EnumTest
*/
'outerEnumIntegerDefaultValue'?: OuterEnumIntegerDefaultValue;
}
/**
* @export
* @enum {string}
*/
export enum EnumTestEnumStringEnum {
Upper = 'UPPER',
Lower = 'lower',
Empty = ''
}
/**
* @export
* @enum {string}
*/
export enum EnumTestEnumStringRequiredEnum {
Upper = 'UPPER',
Lower = 'lower',
Empty = ''
}
/**
* @export
* @enum {string}
*/
export enum EnumTestEnumIntegerEnum {
NUMBER_1 = 1,
NUMBER_MINUS_1 = -1
}
/**
* @export
* @enum {string}
*/
export enum EnumTestEnumNumberEnum {
NUMBER_1_DOT_1 = 1.1,
NUMBER_MINUS_1_DOT_2 = -1.2
}
/**
*
* @export
* @interface FileSchemaTestClass
*/
export interface FileSchemaTestClass {
/**
*
* @type {any}
* @memberof FileSchemaTestClass
*/
'file'?: any;
/**
*
* @type {Array<any>}
* @memberof FileSchemaTestClass
*/
'files'?: Array<any>;
}
/**
*
* @export
* @interface Foo
*/
export interface Foo {
/**
*
* @type {string}
* @memberof Foo
*/
'bar'?: string;
}
/**
*
* @export
* @interface FormatTest
*/
export interface FormatTest {
/**
*
* @type {number}
* @memberof FormatTest
*/
'integer'?: number;
/**
*
* @type {number}
* @memberof FormatTest
*/
'int32'?: number;
/**
*
* @type {number}
* @memberof FormatTest
*/
'int64'?: number;
/**
*
* @type {number}
* @memberof FormatTest
*/
'number': number;
/**
*
* @type {number}
* @memberof FormatTest
*/
'float'?: number;
/**
*
* @type {number}
* @memberof FormatTest
*/
'double'?: number;
/**
*
* @type {string}
* @memberof FormatTest
*/
'string'?: string;
/**
*
* @type {string}
* @memberof FormatTest
*/
'byte': string;
/**
*
* @type {any}
* @memberof FormatTest
*/
'binary'?: any;
/**
*
* @type {string}
* @memberof FormatTest
*/
'date': string;
/**
*
* @type {string}
* @memberof FormatTest
*/
'dateTime'?: string;
/**
*
* @type {string}
* @memberof FormatTest
*/
'uuid'?: string;
/**
*
* @type {string}
* @memberof FormatTest
*/
'password': string;
/**
* A string that is a 10 digit number. Can have leading zeros.
* @type {string}
* @memberof FormatTest
*/
'pattern_with_digits'?: string;
/**
* A string starting with \'image_\' (case insensitive) and one to three digits following i.e. Image_01.
* @type {string}
* @memberof FormatTest
*/
'pattern_with_digits_and_delimiter'?: string;
}
/**
* @type Fruit
* @export
*/
export type Fruit = Apple | Banana;
/**
* @type FruitReq
* @export
*/
export type FruitReq = AppleReq | BananaReq;
/**
*
* @export
* @interface GmFruit
*/
export interface GmFruit {
/**
*
* @type {string}
* @memberof GmFruit
*/
'color'?: string;
/**
*
* @type {string}
* @memberof GmFruit
*/
'cultivar'?: string;
/**
*
* @type {number}
* @memberof GmFruit
*/
'lengthCm'?: number;
}
/**
*
* @export
* @interface HasOnlyReadOnly
*/
export interface HasOnlyReadOnly {
/**
*
* @type {string}
* @memberof HasOnlyReadOnly
*/
'bar'?: string;
/**
*
* @type {string}
* @memberof HasOnlyReadOnly
*/
'foo'?: string;
}
/**
* Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.
* @export
* @interface HealthCheckResult
*/
export interface HealthCheckResult {
/**
*
* @type {string}
* @memberof HealthCheckResult
*/
'NullableMessage'?: string | null;
}
/**
*
* @export
* @interface InlineResponseDefault
*/
export interface InlineResponseDefault {
/**
*
* @type {Foo}
* @memberof InlineResponseDefault
*/
'string'?: Foo;
}
/**
*
* @export
* @interface List
*/
export interface List {
/**
*
* @type {string}
* @memberof List
*/
'123-list'?: string;
}
/**
* @type Mammal
* @export
*/
export type Mammal = Whale | Zebra;
/**
*
* @export
* @interface MapTest
*/
export interface MapTest {
/**
*
* @type {{ [key: string]: { [key: string]: string; }; }}
* @memberof MapTest
*/
'map_map_of_string'?: { [key: string]: { [key: string]: string; }; };
/**
*
* @type {{ [key: string]: string; }}
* @memberof MapTest
*/
'map_of_enum_string'?: { [key: string]: string; };
/**
*
* @type {{ [key: string]: boolean; }}
* @memberof MapTest
*/
'direct_map'?: { [key: string]: boolean; };
/**
*
* @type {{ [key: string]: boolean; }}
* @memberof MapTest
*/
'indirect_map'?: { [key: string]: boolean; };
}
/**
* @export
* @enum {string}
*/
export enum MapTestMapOfEnumStringEnum {
Upper = 'UPPER',
Lower = 'lower'
}
/**
*
* @export
* @interface MixedPropertiesAndAdditionalPropertiesClass
*/
export interface MixedPropertiesAndAdditionalPropertiesClass {
/**
*
* @type {string}
* @memberof MixedPropertiesAndAdditionalPropertiesClass
*/
'uuid'?: string;
/**
*
* @type {string}
* @memberof MixedPropertiesAndAdditionalPropertiesClass
*/
'dateTime'?: string;
/**
*
* @type {{ [key: string]: Animal; }}
* @memberof MixedPropertiesAndAdditionalPropertiesClass
*/
'map'?: { [key: string]: Animal; };
}
/**
* Model for testing model name starting with number
* @export
* @interface Model200Response
*/
export interface Model200Response {
/**
*
* @type {number}
* @memberof Model200Response
*/
'name'?: number;
/**
*
* @type {string}
* @memberof Model200Response
*/
'class'?: string;
}
/**
* Must be named `File` for test.
* @export
* @interface ModelFile
*/
export interface ModelFile {
/**
* Test capitalization
* @type {string}
* @memberof ModelFile
*/
'sourceURI'?: string;
}
/**
* Model for testing model name same as property name
* @export
* @interface Name
*/
export interface Name {
/**
*
* @type {number}
* @memberof Name
*/
'name': number;
/**
*
* @type {number}
* @memberof Name
*/
'snake_case'?: number;
/**
*
* @type {string}
* @memberof Name
*/
'property'?: string;
/**
*
* @type {number}
* @memberof Name
*/
'123Number'?: number;
}
/**
*
* @export
* @interface NullableClass
*/
export interface NullableClass {
[key: string]: object | any;
/**
*
* @type {number}
* @memberof NullableClass
*/
'integer_prop'?: number | null;
/**
*
* @type {number}
* @memberof NullableClass
*/
'number_prop'?: number | null;
/**
*
* @type {boolean}
* @memberof NullableClass
*/
'boolean_prop'?: boolean | null;
/**
*
* @type {string}
* @memberof NullableClass
*/
'string_prop'?: string | null;
/**
*
* @type {string}
* @memberof NullableClass
*/
'date_prop'?: string | null;
/**
*
* @type {string}
* @memberof NullableClass
*/
'datetime_prop'?: string | null;
/**
*
* @type {Array<object>}
* @memberof NullableClass
*/
'array_nullable_prop'?: Array<object> | null;
/**
*
* @type {Array<object>}
* @memberof NullableClass
*/
'array_and_items_nullable_prop'?: Array<object> | null;
/**
*
* @type {Array<object>}
* @memberof NullableClass
*/
'array_items_nullable'?: Array<object>;
/**
*
* @type {{ [key: string]: object; }}
* @memberof NullableClass
*/
'object_nullable_prop'?: { [key: string]: object; } | null;
/**
*
* @type {{ [key: string]: object; }}
* @memberof NullableClass
*/
'object_and_items_nullable_prop'?: { [key: string]: object; } | null;
/**
*
* @type {{ [key: string]: object; }}
* @memberof NullableClass
*/
'object_items_nullable'?: { [key: string]: object; };
}
/**
*
* @export
* @interface NumberOnly
*/
export interface NumberOnly {
/**
*
* @type {number}
* @memberof NumberOnly
*/
'JustNumber'?: number;
}
/**
*
* @export
* @interface Order
*/
export interface Order {
/**
*
* @type {number}
* @memberof Order
*/
'id'?: number;
/**
*
* @type {number}
* @memberof Order
*/
'petId'?: number;
/**
*
* @type {number}
* @memberof Order
*/
'quantity'?: number;
/**
*
* @type {string}
* @memberof Order
*/
'shipDate'?: string;
/**
* Order Status
* @type {string}
* @memberof Order
*/
'status'?: OrderStatusEnum;
/**
*
* @type {boolean}
* @memberof Order
*/
'complete'?: boolean;
}
/**
* @export
* @enum {string}
*/
export enum OrderStatusEnum {
Placed = 'placed',
Approved = 'approved',
Delivered = 'delivered'
}
/**
*
* @export
* @interface OuterComposite
*/
export interface OuterComposite {
/**
*
* @type {number}
* @memberof OuterComposite
*/
'my_number'?: number;
/**
*
* @type {string}
* @memberof OuterComposite
*/
'my_string'?: string;
/**
*
* @type {boolean}
* @memberof OuterComposite
*/
'my_boolean'?: boolean;
}
/**
*
* @export
* @enum {string}
*/
export enum OuterEnum {
Placed = 'placed',
Approved = 'approved',
Delivered = 'delivered'
}
/**
*
* @export
* @enum {string}
*/
export enum OuterEnumDefaultValue {
Placed = 'placed',
Approved = 'approved',
Delivered = 'delivered'
}
/**
*
* @export
* @enum {string}
*/
export enum OuterEnumInteger {
NUMBER_0 = 0,
NUMBER_1 = 1,
NUMBER_2 = 2
}
/**
*
* @export
* @enum {string}
*/
export enum OuterEnumIntegerDefaultValue {
NUMBER_0 = 0,
NUMBER_1 = 1,
NUMBER_2 = 2
}
/**
*
* @export
* @interface Pet
*/
export interface Pet {
/**
*
* @type {number}
* @memberof Pet
*/
'id'?: number;
/**
*
* @type {Category}
* @memberof Pet
*/
'category'?: Category;
/**
*
* @type {string}
* @memberof Pet
*/
'name': string;
/**
*
* @type {Array<string>}
* @memberof Pet
*/
'photoUrls': Array<string>;
/**
*
* @type {Array<Tag>}
* @memberof Pet
*/
'tags'?: Array<Tag>;
/**
* pet status in the store
* @type {string}
* @memberof Pet
* @deprecated
*/
'status'?: PetStatusEnum;
}
/**
* @export
* @enum {string}
*/
export enum PetStatusEnum {
Available = 'available',
Pending = 'pending',
Sold = 'sold'
}
/**
*
* @export
* @interface ReadOnlyFirst
*/
export interface ReadOnlyFirst {
/**
*
* @type {string}
* @memberof ReadOnlyFirst
*/
'bar'?: string;
/**
*
* @type {string}
* @memberof ReadOnlyFirst
*/
'baz'?: string;
}
/**
*
* @export
* @interface ReadOnlyWithDefault
*/
export interface ReadOnlyWithDefault {
/**
*
* @type {string}
* @memberof ReadOnlyWithDefault
*/
'prop1'?: string;
/**
*
* @type {string}
* @memberof ReadOnlyWithDefault
*/
'prop2'?: string;
/**
*
* @type {string}
* @memberof ReadOnlyWithDefault
*/
'prop3'?: string;
/**
*
* @type {boolean}
* @memberof ReadOnlyWithDefault
*/
'boolProp1'?: boolean;
/**
*
* @type {boolean}
* @memberof ReadOnlyWithDefault
*/
'boolProp2'?: boolean;
/**
*
* @type {number}
* @memberof ReadOnlyWithDefault
*/
'intProp1'?: number;
/**
*
* @type {number}
* @memberof ReadOnlyWithDefault
*/
'intProp2'?: number;
}
/**
* Model for testing reserved words
* @export
* @interface Return
*/
export interface Return {
/**
*
* @type {number}
* @memberof Return
*/
'return'?: number;
}
/**
*
* @export
* @interface SpecialModelName
*/
export interface SpecialModelName {
/**
*
* @type {number}
* @memberof SpecialModelName
*/
'$special[property.name]'?: number;
}
/**
*
* @export
* @interface Tag
*/
export interface Tag {
/**
*
* @type {number}
* @memberof Tag
*/
'id'?: number;
/**
*
* @type {string}
* @memberof Tag
*/
'name'?: string;
}
/**
*
* @export
* @interface User
*/
export interface User {
/**
*
* @type {number}
* @memberof User
*/
'id'?: number;
/**
*
* @type {string}
* @memberof User
*/
'username'?: string;
/**
*
* @type {string}
* @memberof User
*/
'firstName'?: string;
/**
*
* @type {string}
* @memberof User
*/
'lastName'?: string;
/**
*
* @type {string}
* @memberof User
*/
'email'?: string;
/**
*
* @type {string}
* @memberof User
*/
'password'?: string;
/**
*
* @type {string}
* @memberof User
*/
'phone'?: string;
/**
* User Status
* @type {number}
* @memberof User
*/
'userStatus'?: number;
/**
* test code generation for objects Value must be a map of strings to values. It cannot be the \'null\' value.
* @type {object}
* @memberof User
*/
'arbitraryObject'?: object;
/**
* test code generation for nullable objects. Value must be a map of strings to values or the \'null\' value.
* @type {object}
* @memberof User
*/
'arbitraryNullableObject'?: object | null;
/**
* test code generation for any type Value can be any type - string, number, boolean, array or object.
* @type {any}
* @memberof User
*/
'arbitraryTypeValue'?: any;
/**
* test code generation for any type Value can be any type - string, number, boolean, array, object or the \'null\' value.
* @type {any}
* @memberof User
*/
'arbitraryNullableTypeValue'?: any | null;
}
/**
*
* @export
* @interface Whale
*/
export interface Whale {
/**
*
* @type {boolean}
* @memberof Whale
*/
'hasBaleen'?: boolean;
/**
*
* @type {boolean}
* @memberof Whale
*/
'hasTeeth'?: boolean;
/**
*
* @type {string}
* @memberof Whale
*/
'className': string;
}
/**
*
* @export
* @interface Zebra
*/
export interface Zebra {
/**
*
* @type {string}
* @memberof Zebra
*/
'type'?: ZebraTypeEnum;
/**
*
* @type {string}
* @memberof Zebra
*/
'className': string;
}
/**
* @export
* @enum {string}
*/
export enum ZebraTypeEnum {
Plains = 'plains',
Mountain = 'mountain',
Grevys = 'grevys'
}
/**
* AnotherFakeApi - axios parameter creator
* @export
*/
export const AnotherFakeApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* To test special tags and operation ID starting with number
* @summary To test special tags
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
_123testSpecialTags: async (client: Client, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'client' is not null or undefined
assertParamExists('_123testSpecialTags', 'client', client)
const localVarPath = `/another-fake/dummy`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(client, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* AnotherFakeApi - functional programming interface
* @export
*/
export const AnotherFakeApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = AnotherFakeApiAxiosParamCreator(configuration)
return {
/**
* To test special tags and operation ID starting with number
* @summary To test special tags
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async _123testSpecialTags(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Client>> {
const localVarAxiosArgs = await localVarAxiosParamCreator._123testSpecialTags(client, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* AnotherFakeApi - factory interface
* @export
*/
export const AnotherFakeApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = AnotherFakeApiFp(configuration)
return {
/**
* To test special tags and operation ID starting with number
* @summary To test special tags
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
_123testSpecialTags(client: Client, options?: any): AxiosPromise<Client> {
return localVarFp._123testSpecialTags(client, options).then((request) => request(axios, basePath));
},
};
};
/**
* AnotherFakeApi - object-oriented interface
* @export
* @class AnotherFakeApi
* @extends {BaseAPI}
*/
export class AnotherFakeApi extends BaseAPI {
/**
* To test special tags and operation ID starting with number
* @summary To test special tags
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AnotherFakeApi
*/
public _123testSpecialTags(client: Client, options?: AxiosRequestConfig) {
return AnotherFakeApiFp(this.configuration)._123testSpecialTags(client, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* DefaultApi - axios parameter creator
* @export
*/
export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fooGet: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/foo`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* DefaultApi - functional programming interface
* @export
*/
export const DefaultApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration)
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fooGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<InlineResponseDefault>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fooGet(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* DefaultApi - factory interface
* @export
*/
export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = DefaultApiFp(configuration)
return {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fooGet(options?: any): AxiosPromise<InlineResponseDefault> {
return localVarFp.fooGet(options).then((request) => request(axios, basePath));
},
};
};
/**
* DefaultApi - object-oriented interface
* @export
* @class DefaultApi
* @extends {BaseAPI}
*/
export class DefaultApi extends BaseAPI {
/**
*
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public fooGet(options?: AxiosRequestConfig) {
return DefaultApiFp(this.configuration).fooGet(options).then((request) => request(this.axios, this.basePath));
}
}
/**
* FakeApi - axios parameter creator
* @export
*/
export const FakeApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Health check endpoint
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeHealthGet: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake/health`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Test serialization of outer boolean types
* @param {boolean} [body] Input boolean as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterBooleanSerialize: async (body?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake/outer/boolean`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Test serialization of object with outer number type
* @param {OuterComposite} [outerComposite] Input composite as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterCompositeSerialize: async (outerComposite?: OuterComposite, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake/outer/composite`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(outerComposite, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Test serialization of outer number types
* @param {number} [body] Input number as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterNumberSerialize: async (body?: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake/outer/number`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Test serialization of outer string types
* @param {string} [body] Input string as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterStringSerialize: async (body?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake/outer/string`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* For this test, the body for this request much reference a schema named `File`.
* @param {FileSchemaTestClass} fileSchemaTestClass
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testBodyWithFileSchema: async (fileSchemaTestClass: FileSchemaTestClass, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'fileSchemaTestClass' is not null or undefined
assertParamExists('testBodyWithFileSchema', 'fileSchemaTestClass', fileSchemaTestClass)
const localVarPath = `/fake/body-with-file-schema`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(fileSchemaTestClass, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @param {string} query
* @param {User} user
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testBodyWithQueryParams: async (query: string, user: User, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'query' is not null or undefined
assertParamExists('testBodyWithQueryParams', 'query', query)
// verify required parameter 'user' is not null or undefined
assertParamExists('testBodyWithQueryParams', 'user', user)
const localVarPath = `/fake/body-with-query-params`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (query !== undefined) {
localVarQueryParameter['query'] = query;
}
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(user, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* To test \"client\" model
* @summary To test \"client\" model
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testClientModel: async (client: Client, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'client' is not null or undefined
assertParamExists('testClientModel', 'client', client)
const localVarPath = `/fake`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(client, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @summary Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param {number} number None
* @param {number} _double None
* @param {string} patternWithoutDelimiter None
* @param {string} _byte None
* @param {number} [integer] None
* @param {number} [int32] None
* @param {number} [int64] None
* @param {number} [_float] None
* @param {string} [string] None
* @param {any} [binary] None
* @param {string} [date] None
* @param {string} [dateTime] None
* @param {string} [password] None
* @param {string} [callback] None
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'number' is not null or undefined
assertParamExists('testEndpointParameters', 'number', number)
// verify required parameter '_double' is not null or undefined
assertParamExists('testEndpointParameters', '_double', _double)
// verify required parameter 'patternWithoutDelimiter' is not null or undefined
assertParamExists('testEndpointParameters', 'patternWithoutDelimiter', patternWithoutDelimiter)
// verify required parameter '_byte' is not null or undefined
assertParamExists('testEndpointParameters', '_byte', _byte)
const localVarPath = `/fake`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new URLSearchParams();
// authentication http_basic_test required
// http basic authentication required
setBasicAuthToObject(localVarRequestOptions, configuration)
if (integer !== undefined) {
localVarFormParams.set('integer', integer as any);
}
if (int32 !== undefined) {
localVarFormParams.set('int32', int32 as any);
}
if (int64 !== undefined) {
localVarFormParams.set('int64', int64 as any);
}
if (number !== undefined) {
localVarFormParams.set('number', number as any);
}
if (_float !== undefined) {
localVarFormParams.set('float', _float as any);
}
if (_double !== undefined) {
localVarFormParams.set('double', _double as any);
}
if (string !== undefined) {
localVarFormParams.set('string', string as any);
}
if (patternWithoutDelimiter !== undefined) {
localVarFormParams.set('pattern_without_delimiter', patternWithoutDelimiter as any);
}
if (_byte !== undefined) {
localVarFormParams.set('byte', _byte as any);
}
if (binary !== undefined) {
localVarFormParams.set('binary', binary as any);
}
if (date !== undefined) {
localVarFormParams.set('date', date as any);
}
if (dateTime !== undefined) {
localVarFormParams.set('dateTime', dateTime as any);
}
if (password !== undefined) {
localVarFormParams.set('password', password as any);
}
if (callback !== undefined) {
localVarFormParams.set('callback', callback as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams.toString();
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* To test enum parameters
* @summary To test enum parameters
* @param {Array<'>' | '$'>} [enumHeaderStringArray] Header parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumHeaderString] Header parameter enum test (string)
* @param {Array<'>' | '$'>} [enumQueryStringArray] Query parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumQueryString] Query parameter enum test (string)
* @param {1 | -2} [enumQueryInteger] Query parameter enum test (double)
* @param {1.1 | -1.2} [enumQueryDouble] Query parameter enum test (double)
* @param {Array<string>} [enumFormStringArray] Form parameter enum test (string array)
* @param {string} [enumFormString] Form parameter enum test (string)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testEnumParameters: async (enumHeaderStringArray?: Array<'>' | '$'>, enumHeaderString?: '_abc' | '-efg' | '(xyz)', enumQueryStringArray?: Array<'>' | '$'>, enumQueryString?: '_abc' | '-efg' | '(xyz)', enumQueryInteger?: 1 | -2, enumQueryDouble?: 1.1 | -1.2, enumFormStringArray?: Array<string>, enumFormString?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/fake`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new URLSearchParams();
if (enumQueryStringArray) {
localVarQueryParameter['enum_query_string_array'] = enumQueryStringArray;
}
if (enumQueryString !== undefined) {
localVarQueryParameter['enum_query_string'] = enumQueryString;
}
if (enumQueryInteger !== undefined) {
localVarQueryParameter['enum_query_integer'] = enumQueryInteger;
}
if (enumQueryDouble !== undefined) {
localVarQueryParameter['enum_query_double'] = enumQueryDouble;
}
if (enumHeaderStringArray) {
let mapped = enumHeaderStringArray.map(value => (<any>"Array<'>' | '$'>" !== "Array<string>") ? JSON.stringify(value) : (value || ""));
localVarHeaderParameter['enum_header_string_array'] = mapped.join(COLLECTION_FORMATS["csv"]);
}
if (enumHeaderString !== undefined && enumHeaderString !== null) {
localVarHeaderParameter['enum_header_string'] = String(enumHeaderString);
}
if (enumFormStringArray) {
localVarFormParams.set('enum_form_string_array', enumFormStringArray.join(COLLECTION_FORMATS.csv));
}
if (enumFormString !== undefined) {
localVarFormParams.set('enum_form_string', enumFormString as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams.toString();
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Fake endpoint to test group parameters (optional)
* @summary Fake endpoint to test group parameters (optional)
* @param {number} requiredStringGroup Required String in group parameters
* @param {boolean} requiredBooleanGroup Required Boolean in group parameters
* @param {number} requiredInt64Group Required Integer in group parameters
* @param {number} [stringGroup] String in group parameters
* @param {boolean} [booleanGroup] Boolean in group parameters
* @param {number} [int64Group] Integer in group parameters
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testGroupParameters: async (requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'requiredStringGroup' is not null or undefined
assertParamExists('testGroupParameters', 'requiredStringGroup', requiredStringGroup)
// verify required parameter 'requiredBooleanGroup' is not null or undefined
assertParamExists('testGroupParameters', 'requiredBooleanGroup', requiredBooleanGroup)
// verify required parameter 'requiredInt64Group' is not null or undefined
assertParamExists('testGroupParameters', 'requiredInt64Group', requiredInt64Group)
const localVarPath = `/fake`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication bearer_test required
// http bearer authentication required
await setBearerAuthToObject(localVarHeaderParameter, configuration)
if (requiredStringGroup !== undefined) {
localVarQueryParameter['required_string_group'] = requiredStringGroup;
}
if (requiredInt64Group !== undefined) {
localVarQueryParameter['required_int64_group'] = requiredInt64Group;
}
if (stringGroup !== undefined) {
localVarQueryParameter['string_group'] = stringGroup;
}
if (int64Group !== undefined) {
localVarQueryParameter['int64_group'] = int64Group;
}
if (requiredBooleanGroup !== undefined && requiredBooleanGroup !== null) {
localVarHeaderParameter['required_boolean_group'] = String(JSON.stringify(requiredBooleanGroup));
}
if (booleanGroup !== undefined && booleanGroup !== null) {
localVarHeaderParameter['boolean_group'] = String(JSON.stringify(booleanGroup));
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary test inline additionalProperties
* @param {{ [key: string]: string; }} requestBody request body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testInlineAdditionalProperties: async (requestBody: { [key: string]: string; }, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'requestBody' is not null or undefined
assertParamExists('testInlineAdditionalProperties', 'requestBody', requestBody)
const localVarPath = `/fake/inline-additionalProperties`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(requestBody, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary test json serialization of form data
* @param {string} param field1
* @param {string} param2 field2
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testJsonFormData: async (param: string, param2: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'param' is not null or undefined
assertParamExists('testJsonFormData', 'param', param)
// verify required parameter 'param2' is not null or undefined
assertParamExists('testJsonFormData', 'param2', param2)
const localVarPath = `/fake/jsonFormData`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new URLSearchParams();
if (param !== undefined) {
localVarFormParams.set('param', param as any);
}
if (param2 !== undefined) {
localVarFormParams.set('param2', param2 as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams.toString();
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* To test the collection format in query parameters
* @param {Array<string>} pipe
* @param {Array<string>} ioutil
* @param {Array<string>} http
* @param {Array<string>} url
* @param {Array<string>} context
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testQueryParameterCollectionFormat: async (pipe: Array<string>, ioutil: Array<string>, http: Array<string>, url: Array<string>, context: Array<string>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'pipe' is not null or undefined
assertParamExists('testQueryParameterCollectionFormat', 'pipe', pipe)
// verify required parameter 'ioutil' is not null or undefined
assertParamExists('testQueryParameterCollectionFormat', 'ioutil', ioutil)
// verify required parameter 'http' is not null or undefined
assertParamExists('testQueryParameterCollectionFormat', 'http', http)
// verify required parameter 'url' is not null or undefined
assertParamExists('testQueryParameterCollectionFormat', 'url', url)
// verify required parameter 'context' is not null or undefined
assertParamExists('testQueryParameterCollectionFormat', 'context', context)
const localVarPath = `/fake/test-query-parameters`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (pipe) {
localVarQueryParameter['pipe'] = pipe;
}
if (ioutil) {
localVarQueryParameter['ioutil'] = ioutil.join(COLLECTION_FORMATS.csv);
}
if (http) {
localVarQueryParameter['http'] = http.join(COLLECTION_FORMATS.ssv);
}
if (url) {
localVarQueryParameter['url'] = url.join(COLLECTION_FORMATS.csv);
}
if (context) {
localVarQueryParameter['context'] = context;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* To test unique items in header and query parameters
* @param {Set<string>} queryUnique
* @param {Set<string>} headerUnique
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testUniqueItemsHeaderAndQueryParameterCollectionFormat: async (queryUnique: Set<string>, headerUnique: Set<string>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'queryUnique' is not null or undefined
assertParamExists('testUniqueItemsHeaderAndQueryParameterCollectionFormat', 'queryUnique', queryUnique)
// verify required parameter 'headerUnique' is not null or undefined
assertParamExists('testUniqueItemsHeaderAndQueryParameterCollectionFormat', 'headerUnique', headerUnique)
const localVarPath = `/fake/test-unique-parameters`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (queryUnique) {
localVarQueryParameter['queryUnique'] = Array.from(queryUnique);
}
if (headerUnique) {
let mapped = Array.from(headerUnique).map(value => (<any>"Set<string>" !== "Set<string>") ? JSON.stringify(value) : (value || ""));
localVarHeaderParameter['headerUnique'] = mapped.join(COLLECTION_FORMATS["csv"]);
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* FakeApi - functional programming interface
* @export
*/
export const FakeApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = FakeApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Health check endpoint
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fakeHealthGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<HealthCheckResult>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fakeHealthGet(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Test serialization of outer boolean types
* @param {boolean} [body] Input boolean as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<boolean>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterBooleanSerialize(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Test serialization of object with outer number type
* @param {OuterComposite} [outerComposite] Input composite as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<OuterComposite>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterCompositeSerialize(outerComposite, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Test serialization of outer number types
* @param {number} [body] Input number as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<number>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterNumberSerialize(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Test serialization of outer string types
* @param {string} [body] Input string as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterStringSerialize(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* For this test, the body for this request much reference a schema named `File`.
* @param {FileSchemaTestClass} fileSchemaTestClass
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithFileSchema(fileSchemaTestClass, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @param {string} query
* @param {User} user
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithQueryParams(query, user, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* To test \"client\" model
* @summary To test \"client\" model
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testClientModel(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Client>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testClientModel(client, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @summary Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param {number} number None
* @param {number} _double None
* @param {string} patternWithoutDelimiter None
* @param {string} _byte None
* @param {number} [integer] None
* @param {number} [int32] None
* @param {number} [int64] None
* @param {number} [_float] None
* @param {string} [string] None
* @param {any} [binary] None
* @param {string} [date] None
* @param {string} [dateTime] None
* @param {string} [password] None
* @param {string} [callback] None
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* To test enum parameters
* @summary To test enum parameters
* @param {Array<'>' | '$'>} [enumHeaderStringArray] Header parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumHeaderString] Header parameter enum test (string)
* @param {Array<'>' | '$'>} [enumQueryStringArray] Query parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumQueryString] Query parameter enum test (string)
* @param {1 | -2} [enumQueryInteger] Query parameter enum test (double)
* @param {1.1 | -1.2} [enumQueryDouble] Query parameter enum test (double)
* @param {Array<string>} [enumFormStringArray] Form parameter enum test (string array)
* @param {string} [enumFormString] Form parameter enum test (string)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testEnumParameters(enumHeaderStringArray?: Array<'>' | '$'>, enumHeaderString?: '_abc' | '-efg' | '(xyz)', enumQueryStringArray?: Array<'>' | '$'>, enumQueryString?: '_abc' | '-efg' | '(xyz)', enumQueryInteger?: 1 | -2, enumQueryDouble?: 1.1 | -1.2, enumFormStringArray?: Array<string>, enumFormString?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Fake endpoint to test group parameters (optional)
* @summary Fake endpoint to test group parameters (optional)
* @param {number} requiredStringGroup Required String in group parameters
* @param {boolean} requiredBooleanGroup Required Boolean in group parameters
* @param {number} requiredInt64Group Required Integer in group parameters
* @param {number} [stringGroup] String in group parameters
* @param {boolean} [booleanGroup] Boolean in group parameters
* @param {number} [int64Group] Integer in group parameters
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary test inline additionalProperties
* @param {{ [key: string]: string; }} requestBody request body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testInlineAdditionalProperties(requestBody, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary test json serialization of form data
* @param {string} param field1
* @param {string} param2 field2
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testJsonFormData(param, param2, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* To test the collection format in query parameters
* @param {Array<string>} pipe
* @param {Array<string>} ioutil
* @param {Array<string>} http
* @param {Array<string>} url
* @param {Array<string>} context
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testQueryParameterCollectionFormat(pipe: Array<string>, ioutil: Array<string>, http: Array<string>, url: Array<string>, context: Array<string>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* To test unique items in header and query parameters
* @param {Set<string>} queryUnique
* @param {Set<string>} headerUnique
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set<string>, headerUnique: Set<string>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Set<Pet>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique, headerUnique, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* FakeApi - factory interface
* @export
*/
export const FakeApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = FakeApiFp(configuration)
return {
/**
*
* @summary Health check endpoint
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeHealthGet(options?: any): AxiosPromise<HealthCheckResult> {
return localVarFp.fakeHealthGet(options).then((request) => request(axios, basePath));
},
/**
* Test serialization of outer boolean types
* @param {boolean} [body] Input boolean as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterBooleanSerialize(body?: boolean, options?: any): AxiosPromise<boolean> {
return localVarFp.fakeOuterBooleanSerialize(body, options).then((request) => request(axios, basePath));
},
/**
* Test serialization of object with outer number type
* @param {OuterComposite} [outerComposite] Input composite as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: any): AxiosPromise<OuterComposite> {
return localVarFp.fakeOuterCompositeSerialize(outerComposite, options).then((request) => request(axios, basePath));
},
/**
* Test serialization of outer number types
* @param {number} [body] Input number as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterNumberSerialize(body?: number, options?: any): AxiosPromise<number> {
return localVarFp.fakeOuterNumberSerialize(body, options).then((request) => request(axios, basePath));
},
/**
* Test serialization of outer string types
* @param {string} [body] Input string as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
fakeOuterStringSerialize(body?: string, options?: any): AxiosPromise<string> {
return localVarFp.fakeOuterStringSerialize(body, options).then((request) => request(axios, basePath));
},
/**
* For this test, the body for this request much reference a schema named `File`.
* @param {FileSchemaTestClass} fileSchemaTestClass
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: any): AxiosPromise<void> {
return localVarFp.testBodyWithFileSchema(fileSchemaTestClass, options).then((request) => request(axios, basePath));
},
/**
*
* @param {string} query
* @param {User} user
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testBodyWithQueryParams(query: string, user: User, options?: any): AxiosPromise<void> {
return localVarFp.testBodyWithQueryParams(query, user, options).then((request) => request(axios, basePath));
},
/**
* To test \"client\" model
* @summary To test \"client\" model
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testClientModel(client: Client, options?: any): AxiosPromise<Client> {
return localVarFp.testClientModel(client, options).then((request) => request(axios, basePath));
},
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @summary Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param {number} number None
* @param {number} _double None
* @param {string} patternWithoutDelimiter None
* @param {string} _byte None
* @param {number} [integer] None
* @param {number} [int32] None
* @param {number} [int64] None
* @param {number} [_float] None
* @param {string} [string] None
* @param {any} [binary] None
* @param {string} [date] None
* @param {string} [dateTime] None
* @param {string} [password] None
* @param {string} [callback] None
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: any): AxiosPromise<void> {
return localVarFp.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(axios, basePath));
},
/**
* To test enum parameters
* @summary To test enum parameters
* @param {Array<'>' | '$'>} [enumHeaderStringArray] Header parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumHeaderString] Header parameter enum test (string)
* @param {Array<'>' | '$'>} [enumQueryStringArray] Query parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumQueryString] Query parameter enum test (string)
* @param {1 | -2} [enumQueryInteger] Query parameter enum test (double)
* @param {1.1 | -1.2} [enumQueryDouble] Query parameter enum test (double)
* @param {Array<string>} [enumFormStringArray] Form parameter enum test (string array)
* @param {string} [enumFormString] Form parameter enum test (string)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testEnumParameters(enumHeaderStringArray?: Array<'>' | '$'>, enumHeaderString?: '_abc' | '-efg' | '(xyz)', enumQueryStringArray?: Array<'>' | '$'>, enumQueryString?: '_abc' | '-efg' | '(xyz)', enumQueryInteger?: 1 | -2, enumQueryDouble?: 1.1 | -1.2, enumFormStringArray?: Array<string>, enumFormString?: string, options?: any): AxiosPromise<void> {
return localVarFp.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options).then((request) => request(axios, basePath));
},
/**
* Fake endpoint to test group parameters (optional)
* @summary Fake endpoint to test group parameters (optional)
* @param {number} requiredStringGroup Required String in group parameters
* @param {boolean} requiredBooleanGroup Required Boolean in group parameters
* @param {number} requiredInt64Group Required Integer in group parameters
* @param {number} [stringGroup] String in group parameters
* @param {boolean} [booleanGroup] Boolean in group parameters
* @param {number} [int64Group] Integer in group parameters
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: any): AxiosPromise<void> {
return localVarFp.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options).then((request) => request(axios, basePath));
},
/**
*
* @summary test inline additionalProperties
* @param {{ [key: string]: string; }} requestBody request body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: any): AxiosPromise<void> {
return localVarFp.testInlineAdditionalProperties(requestBody, options).then((request) => request(axios, basePath));
},
/**
*
* @summary test json serialization of form data
* @param {string} param field1
* @param {string} param2 field2
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testJsonFormData(param: string, param2: string, options?: any): AxiosPromise<void> {
return localVarFp.testJsonFormData(param, param2, options).then((request) => request(axios, basePath));
},
/**
* To test the collection format in query parameters
* @param {Array<string>} pipe
* @param {Array<string>} ioutil
* @param {Array<string>} http
* @param {Array<string>} url
* @param {Array<string>} context
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testQueryParameterCollectionFormat(pipe: Array<string>, ioutil: Array<string>, http: Array<string>, url: Array<string>, context: Array<string>, options?: any): AxiosPromise<void> {
return localVarFp.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options).then((request) => request(axios, basePath));
},
/**
* To test unique items in header and query parameters
* @param {Set<string>} queryUnique
* @param {Set<string>} headerUnique
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set<string>, headerUnique: Set<string>, options?: any): AxiosPromise<Set<Pet>> {
return localVarFp.testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique, headerUnique, options).then((request) => request(axios, basePath));
},
};
};
/**
* FakeApi - object-oriented interface
* @export
* @class FakeApi
* @extends {BaseAPI}
*/
export class FakeApi extends BaseAPI {
/**
*
* @summary Health check endpoint
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public fakeHealthGet(options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).fakeHealthGet(options).then((request) => request(this.axios, this.basePath));
}
/**
* Test serialization of outer boolean types
* @param {boolean} [body] Input boolean as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).fakeOuterBooleanSerialize(body, options).then((request) => request(this.axios, this.basePath));
}
/**
* Test serialization of object with outer number type
* @param {OuterComposite} [outerComposite] Input composite as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).fakeOuterCompositeSerialize(outerComposite, options).then((request) => request(this.axios, this.basePath));
}
/**
* Test serialization of outer number types
* @param {number} [body] Input number as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).fakeOuterNumberSerialize(body, options).then((request) => request(this.axios, this.basePath));
}
/**
* Test serialization of outer string types
* @param {string} [body] Input string as post body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).fakeOuterStringSerialize(body, options).then((request) => request(this.axios, this.basePath));
}
/**
* For this test, the body for this request much reference a schema named `File`.
* @param {FileSchemaTestClass} fileSchemaTestClass
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testBodyWithFileSchema(fileSchemaTestClass, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @param {string} query
* @param {User} user
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testBodyWithQueryParams(query, user, options).then((request) => request(this.axios, this.basePath));
}
/**
* To test \"client\" model
* @summary To test \"client\" model
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testClientModel(client: Client, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testClientModel(client, options).then((request) => request(this.axios, this.basePath));
}
/**
* Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @summary Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
* @param {number} number None
* @param {number} _double None
* @param {string} patternWithoutDelimiter None
* @param {string} _byte None
* @param {number} [integer] None
* @param {number} [int32] None
* @param {number} [int64] None
* @param {number} [_float] None
* @param {string} [string] None
* @param {any} [binary] None
* @param {string} [date] None
* @param {string} [dateTime] None
* @param {string} [password] None
* @param {string} [callback] None
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: any, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(this.axios, this.basePath));
}
/**
* To test enum parameters
* @summary To test enum parameters
* @param {Array<'>' | '$'>} [enumHeaderStringArray] Header parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumHeaderString] Header parameter enum test (string)
* @param {Array<'>' | '$'>} [enumQueryStringArray] Query parameter enum test (string array)
* @param {'_abc' | '-efg' | '(xyz)'} [enumQueryString] Query parameter enum test (string)
* @param {1 | -2} [enumQueryInteger] Query parameter enum test (double)
* @param {1.1 | -1.2} [enumQueryDouble] Query parameter enum test (double)
* @param {Array<string>} [enumFormStringArray] Form parameter enum test (string array)
* @param {string} [enumFormString] Form parameter enum test (string)
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testEnumParameters(enumHeaderStringArray?: Array<'>' | '$'>, enumHeaderString?: '_abc' | '-efg' | '(xyz)', enumQueryStringArray?: Array<'>' | '$'>, enumQueryString?: '_abc' | '-efg' | '(xyz)', enumQueryInteger?: 1 | -2, enumQueryDouble?: 1.1 | -1.2, enumFormStringArray?: Array<string>, enumFormString?: string, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options).then((request) => request(this.axios, this.basePath));
}
/**
* Fake endpoint to test group parameters (optional)
* @summary Fake endpoint to test group parameters (optional)
* @param {number} requiredStringGroup Required String in group parameters
* @param {boolean} requiredBooleanGroup Required Boolean in group parameters
* @param {number} requiredInt64Group Required Integer in group parameters
* @param {number} [stringGroup] String in group parameters
* @param {boolean} [booleanGroup] Boolean in group parameters
* @param {number} [int64Group] Integer in group parameters
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary test inline additionalProperties
* @param {{ [key: string]: string; }} requestBody request body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testInlineAdditionalProperties(requestBody, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary test json serialization of form data
* @param {string} param field1
* @param {string} param2 field2
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testJsonFormData(param, param2, options).then((request) => request(this.axios, this.basePath));
}
/**
* To test the collection format in query parameters
* @param {Array<string>} pipe
* @param {Array<string>} ioutil
* @param {Array<string>} http
* @param {Array<string>} url
* @param {Array<string>} context
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testQueryParameterCollectionFormat(pipe: Array<string>, ioutil: Array<string>, http: Array<string>, url: Array<string>, context: Array<string>, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options).then((request) => request(this.axios, this.basePath));
}
/**
* To test unique items in header and query parameters
* @param {Set<string>} queryUnique
* @param {Set<string>} headerUnique
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeApi
*/
public testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set<string>, headerUnique: Set<string>, options?: AxiosRequestConfig) {
return FakeApiFp(this.configuration).testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique, headerUnique, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* FakeClassnameTags123Api - axios parameter creator
* @export
*/
export const FakeClassnameTags123ApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* To test class name in snake case
* @summary To test class name in snake case
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testClassname: async (client: Client, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'client' is not null or undefined
assertParamExists('testClassname', 'client', client)
const localVarPath = `/fake_classname_test`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PATCH', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication api_key_query required
await setApiKeyToObject(localVarQueryParameter, "api_key_query", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(client, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* FakeClassnameTags123Api - functional programming interface
* @export
*/
export const FakeClassnameTags123ApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = FakeClassnameTags123ApiAxiosParamCreator(configuration)
return {
/**
* To test class name in snake case
* @summary To test class name in snake case
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async testClassname(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Client>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.testClassname(client, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* FakeClassnameTags123Api - factory interface
* @export
*/
export const FakeClassnameTags123ApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = FakeClassnameTags123ApiFp(configuration)
return {
/**
* To test class name in snake case
* @summary To test class name in snake case
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
testClassname(client: Client, options?: any): AxiosPromise<Client> {
return localVarFp.testClassname(client, options).then((request) => request(axios, basePath));
},
};
};
/**
* FakeClassnameTags123Api - object-oriented interface
* @export
* @class FakeClassnameTags123Api
* @extends {BaseAPI}
*/
export class FakeClassnameTags123Api extends BaseAPI {
/**
* To test class name in snake case
* @summary To test class name in snake case
* @param {Client} client client model
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FakeClassnameTags123Api
*/
public testClassname(client: Client, options?: AxiosRequestConfig) {
return FakeClassnameTags123ApiFp(this.configuration).testClassname(client, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* PetApi - axios parameter creator
* @export
*/
export const PetApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
addPet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'pet' is not null or undefined
assertParamExists('addPet', 'pet', pet)
const localVarPath = `/pet`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication http_signature_test required
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(pet, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'petId' is not null or undefined
assertParamExists('deletePet', 'petId', petId)
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (apiKey !== undefined && apiKey !== null) {
localVarHeaderParameter['api_key'] = String(apiKey);
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByStatus: async (status: Array<'available' | 'pending' | 'sold'>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'status' is not null or undefined
assertParamExists('findPetsByStatus', 'status', status)
const localVarPath = `/pet/findByStatus`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication http_signature_test required
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (status) {
localVarQueryParameter['status'] = status.join(COLLECTION_FORMATS.csv);
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
findPetsByTags: async (tags: Array<string>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'tags' is not null or undefined
assertParamExists('findPetsByTags', 'tags', tags)
const localVarPath = `/pet/findByTags`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication http_signature_test required
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (tags) {
localVarQueryParameter['tags'] = tags.join(COLLECTION_FORMATS.csv);
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'petId' is not null or undefined
assertParamExists('getPetById', 'petId', petId)
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication api_key required
await setApiKeyToObject(localVarHeaderParameter, "api_key", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Update an existing pet
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'pet' is not null or undefined
assertParamExists('updatePet', 'pet', pet)
const localVarPath = `/pet`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication http_signature_test required
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(pet, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'petId' is not null or undefined
assertParamExists('updatePetWithForm', 'petId', petId)
const localVarPath = `/pet/{petId}`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new URLSearchParams();
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (name !== undefined) {
localVarFormParams.set('name', name as any);
}
if (status !== undefined) {
localVarFormParams.set('status', status as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams.toString();
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFile: async (petId: number, additionalMetadata?: string, file?: any, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'petId' is not null or undefined
assertParamExists('uploadFile', 'petId', petId)
const localVarPath = `/pet/{petId}/uploadImage`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (additionalMetadata !== undefined) {
localVarFormParams.append('additionalMetadata', additionalMetadata as any);
}
if (file !== undefined) {
localVarFormParams.append('file', file as any);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams;
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary uploads an image (required)
* @param {number} petId ID of pet to update
* @param {any} requiredFile file to upload
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFileWithRequiredFile: async (petId: number, requiredFile: any, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'petId' is not null or undefined
assertParamExists('uploadFileWithRequiredFile', 'petId', petId)
// verify required parameter 'requiredFile' is not null or undefined
assertParamExists('uploadFileWithRequiredFile', 'requiredFile', requiredFile)
const localVarPath = `/fake/{petId}/uploadImageWithRequiredFile`
.replace(`{${"petId"}}`, encodeURIComponent(String(petId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)();
// authentication petstore_auth required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "petstore_auth", ["write:pets", "read:pets"], configuration)
if (additionalMetadata !== undefined) {
localVarFormParams.append('additionalMetadata', additionalMetadata as any);
}
if (requiredFile !== undefined) {
localVarFormParams.append('requiredFile', requiredFile as any);
}
localVarHeaderParameter['Content-Type'] = 'multipart/form-data';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams;
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* PetApi - functional programming interface
* @export
*/
export const PetApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = PetApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async addPet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<Pet>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
async findPetsByTags(tags: Array<string>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Array<Pet>>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Pet>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Update an existing pet
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updatePet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(pet, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ApiResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary uploads an image (required)
* @param {number} petId ID of pet to update
* @param {any} requiredFile file to upload
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ApiResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* PetApi - factory interface
* @export
*/
export const PetApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = PetApiFp(configuration)
return {
/**
*
* @summary Add a new pet to the store
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
addPet(pet: Pet, options?: any): AxiosPromise<void> {
return localVarFp.addPet(pet, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deletePet(petId: number, apiKey?: string, options?: any): AxiosPromise<void> {
return localVarFp.deletePet(petId, apiKey, options).then((request) => request(axios, basePath));
},
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: any): AxiosPromise<Array<Pet>> {
return localVarFp.findPetsByStatus(status, options).then((request) => request(axios, basePath));
},
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
*/
findPetsByTags(tags: Array<string>, options?: any): AxiosPromise<Array<Pet>> {
return localVarFp.findPetsByTags(tags, options).then((request) => request(axios, basePath));
},
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPetById(petId: number, options?: any): AxiosPromise<Pet> {
return localVarFp.getPetById(petId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Update an existing pet
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePet(pet: Pet, options?: any): AxiosPromise<void> {
return localVarFp.updatePet(pet, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updatePetWithForm(petId: number, name?: string, status?: string, options?: any): AxiosPromise<void> {
return localVarFp.updatePetWithForm(petId, name, status, options).then((request) => request(axios, basePath));
},
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: any): AxiosPromise<ApiResponse> {
return localVarFp.uploadFile(petId, additionalMetadata, file, options).then((request) => request(axios, basePath));
},
/**
*
* @summary uploads an image (required)
* @param {number} petId ID of pet to update
* @param {any} requiredFile file to upload
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: any): AxiosPromise<ApiResponse> {
return localVarFp.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(axios, basePath));
},
};
};
/**
* PetApi - object-oriented interface
* @export
* @class PetApi
* @extends {BaseAPI}
*/
export class PetApi extends BaseAPI {
/**
*
* @summary Add a new pet to the store
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public addPet(pet: Pet, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).addPet(pet, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Deletes a pet
* @param {number} petId Pet id to delete
* @param {string} [apiKey]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath));
}
/**
* Multiple status values can be provided with comma separated strings
* @summary Finds Pets by status
* @param {Array<'available' | 'pending' | 'sold'>} status Status values that need to be considered for filter
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath));
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @summary Finds Pets by tags
* @param {Array<string>} tags Tags to filter by
* @param {*} [options] Override http request option.
* @deprecated
* @throws {RequiredError}
* @memberof PetApi
*/
public findPetsByTags(tags: Array<string>, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath));
}
/**
* Returns a single pet
* @summary Find pet by ID
* @param {number} petId ID of pet to return
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public getPetById(petId: number, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Update an existing pet
* @param {Pet} pet Pet object that needs to be added to the store
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public updatePet(pet: Pet, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).updatePet(pet, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Updates a pet in the store with form data
* @param {number} petId ID of pet that needs to be updated
* @param {string} [name] Updated name of the pet
* @param {string} [status] Updated status of the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary uploads an image
* @param {number} petId ID of pet to update
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {any} [file] file to upload
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: any, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary uploads an image (required)
* @param {number} petId ID of pet to update
* @param {any} requiredFile file to upload
* @param {string} [additionalMetadata] Additional data to pass to server
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof PetApi
*/
public uploadFileWithRequiredFile(petId: number, requiredFile: any, additionalMetadata?: string, options?: AxiosRequestConfig) {
return PetApiFp(this.configuration).uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* StoreApi - axios parameter creator
* @export
*/
export const StoreApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'orderId' is not null or undefined
assertParamExists('deleteOrder', 'orderId', orderId)
const localVarPath = `/store/order/{order_id}`
.replace(`{${"order_id"}}`, encodeURIComponent(String(orderId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getInventory: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/store/inventory`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication api_key required
await setApiKeyToObject(localVarHeaderParameter, "api_key", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'orderId' is not null or undefined
assertParamExists('getOrderById', 'orderId', orderId)
const localVarPath = `/store/order/{order_id}`
.replace(`{${"order_id"}}`, encodeURIComponent(String(orderId)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Place an order for a pet
* @param {Order} order order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
placeOrder: async (order: Order, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'order' is not null or undefined
assertParamExists('placeOrder', 'order', order)
const localVarPath = `/store/order`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(order, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* StoreApi - functional programming interface
* @export
*/
export const StoreApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = StoreApiAxiosParamCreator(configuration)
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Order>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Place an order for a pet
* @param {Order} order order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async placeOrder(order: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Order>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(order, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* StoreApi - factory interface
* @export
*/
export const StoreApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = StoreApiFp(configuration)
return {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteOrder(orderId: string, options?: any): AxiosPromise<void> {
return localVarFp.deleteOrder(orderId, options).then((request) => request(axios, basePath));
},
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getInventory(options?: any): AxiosPromise<{ [key: string]: number; }> {
return localVarFp.getInventory(options).then((request) => request(axios, basePath));
},
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getOrderById(orderId: number, options?: any): AxiosPromise<Order> {
return localVarFp.getOrderById(orderId, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Place an order for a pet
* @param {Order} order order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
placeOrder(order: Order, options?: any): AxiosPromise<Order> {
return localVarFp.placeOrder(order, options).then((request) => request(axios, basePath));
},
};
};
/**
* StoreApi - object-oriented interface
* @export
* @class StoreApi
* @extends {BaseAPI}
*/
export class StoreApi extends BaseAPI {
/**
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* @summary Delete purchase order by ID
* @param {string} orderId ID of the order that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public deleteOrder(orderId: string, options?: AxiosRequestConfig) {
return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath));
}
/**
* Returns a map of status codes to quantities
* @summary Returns pet inventories by status
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public getInventory(options?: AxiosRequestConfig) {
return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath));
}
/**
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* @summary Find purchase order by ID
* @param {number} orderId ID of pet that needs to be fetched
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public getOrderById(orderId: number, options?: AxiosRequestConfig) {
return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Place an order for a pet
* @param {Order} order order placed for purchasing the pet
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StoreApi
*/
public placeOrder(order: Order, options?: AxiosRequestConfig) {
return StoreApiFp(this.configuration).placeOrder(order, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* UserApi - axios parameter creator
* @export
*/
export const UserApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} user Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser: async (user: User, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'user' is not null or undefined
assertParamExists('createUser', 'user', user)
const localVarPath = `/user`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(user, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput: async (user: Array<User>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'user' is not null or undefined
assertParamExists('createUsersWithArrayInput', 'user', user)
const localVarPath = `/user/createWithArray`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(user, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput: async (user: Array<User>, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'user' is not null or undefined
assertParamExists('createUsersWithListInput', 'user', user)
const localVarPath = `/user/createWithList`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(user, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('deleteUser', 'username', username)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('getUserByName', 'username', username)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('loginUser', 'username', username)
// verify required parameter 'password' is not null or undefined
assertParamExists('loginUser', 'password', password)
const localVarPath = `/user/login`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
if (username !== undefined) {
localVarQueryParameter['username'] = username;
}
if (password !== undefined) {
localVarQueryParameter['password'] = password;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/user/logout`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} user Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser: async (username: string, user: User, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('updateUser', 'username', username)
// verify required parameter 'user' is not null or undefined
assertParamExists('updateUser', 'user', user)
const localVarPath = `/user/{username}`
.replace(`{${"username"}}`, encodeURIComponent(String(username)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(user, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UserApi - functional programming interface
* @export
*/
export const UserApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = UserApiAxiosParamCreator(configuration)
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} user Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUser(user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(user, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUsersWithArrayInput(user: Array<User>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(user, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUsersWithListInput(user: Array<User>, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(user, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} user Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateUser(username: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<void>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, user, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* UserApi - factory interface
* @export
*/
export const UserApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = UserApiFp(configuration)
return {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} user Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(user: User, options?: any): AxiosPromise<void> {
return localVarFp.createUser(user, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithArrayInput(user: Array<User>, options?: any): AxiosPromise<void> {
return localVarFp.createUsersWithArrayInput(user, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUsersWithListInput(user: Array<User>, options?: any): AxiosPromise<void> {
return localVarFp.createUsersWithListInput(user, options).then((request) => request(axios, basePath));
},
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(username: string, options?: any): AxiosPromise<void> {
return localVarFp.deleteUser(username, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUserByName(username: string, options?: any): AxiosPromise<User> {
return localVarFp.getUserByName(username, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
loginUser(username: string, password: string, options?: any): AxiosPromise<string> {
return localVarFp.loginUser(username, password, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
logoutUser(options?: any): AxiosPromise<void> {
return localVarFp.logoutUser(options).then((request) => request(axios, basePath));
},
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} user Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(username: string, user: User, options?: any): AxiosPromise<void> {
return localVarFp.updateUser(username, user, options).then((request) => request(axios, basePath));
},
};
};
/**
* UserApi - object-oriented interface
* @export
* @class UserApi
* @extends {BaseAPI}
*/
export class UserApi extends BaseAPI {
/**
* This can only be done by the logged in user.
* @summary Create user
* @param {User} user Created user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUser(user: User, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUser(user, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithArrayInput(user: Array<User>, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUsersWithArrayInput(user, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates list of users with given input array
* @param {Array<User>} user List of user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public createUsersWithListInput(user: Array<User>, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).createUsersWithListInput(user, options).then((request) => request(this.axios, this.basePath));
}
/**
* This can only be done by the logged in user.
* @summary Delete user
* @param {string} username The name that needs to be deleted
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public deleteUser(username: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Get user by user name
* @param {string} username The name that needs to be fetched. Use user1 for testing.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public getUserByName(username: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Logs user into the system
* @param {string} username The user name for login
* @param {string} password The password for login in clear text
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public loginUser(username: string, password: string, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Logs out current logged in user session
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public logoutUser(options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath));
}
/**
* This can only be done by the logged in user.
* @summary Updated user
* @param {string} username name that need to be deleted
* @param {User} user Updated user object
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UserApi
*/
public updateUser(username: string, user: User, options?: AxiosRequestConfig) {
return UserApiFp(this.configuration).updateUser(username, user, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import { BigNumber, Signer, Wallet } from "ethers"
import {
MAX_UINT256,
asyncForEach,
deployContractWithLibraries,
getUserTokenBalance,
getUserTokenBalances,
} from "./testUtils"
import { deployContract, solidity } from "ethereum-waffle"
import { deployments } from "hardhat"
import { GenericERC20 } from "../build/typechain/GenericERC20"
import GenericERC20Artifact from "../build/artifacts/contracts/helper/GenericERC20.sol/GenericERC20.json"
import { LPToken } from "../build/typechain/LPToken"
import LPTokenArtifact from "../build/artifacts/contracts/LPToken.sol/LPToken.json"
import { Swap } from "../build/typechain/Swap"
import { MetaSwap } from "../build/typechain/MetaSwap"
import MetaSwapArtifact from "../build/artifacts/contracts/meta/MetaSwap.sol/MetaSwap.json"
import { MetaSwapUtils } from "../build/typechain/MetaSwapUtils"
import MetaSwapUtilsArtifact from "../build/artifacts/contracts/meta/MetaSwapUtils.sol/MetaSwapUtils.json"
import { MetaSwapDeposit } from "../build/typechain/MetaSwapDeposit"
import MetaSwapDepositArtifact from "../build/artifacts/contracts/meta/MetaSwapDeposit.sol/MetaSwapDeposit.json"
import chai from "chai"
chai.use(solidity)
const { expect } = chai
describe("Meta-Swap with inflated baseVirtualPrice and 99% admin fees", async () => {
let signers: Array<Signer>
let baseSwap: Swap
let metaSwap: MetaSwap
let metaSwapUtils: MetaSwapUtils
let metaSwapDeposit: MetaSwapDeposit
let susd: GenericERC20
let dai: GenericERC20
let usdc: GenericERC20
let usdt: GenericERC20
let baseLPToken: GenericERC20
let metaLPToken: LPToken
let owner: Signer
let user1: Signer
let user2: Signer
let ownerAddress: string
let user1Address: string
let user2Address: string
// Test Values
const INITIAL_A_VALUE = 2000
const SWAP_FEE = 4e6 // 0.04%
const ADMIN_FEE = 99e8 // 99%
const LP_TOKEN_NAME = "Test LP Token Name"
const LP_TOKEN_SYMBOL = "TESTLP"
const AMOUNT = 1e17
const INFLATED_VP = "1013335719282759415"
const setupTest = deployments.createFixture(
async ({ deployments, ethers }) => {
const { get } = deployments
await deployments.fixture() // ensure you start from a fresh deployments
signers = await ethers.getSigners()
owner = signers[0]
user1 = signers[1]
user2 = signers[2]
ownerAddress = await owner.getAddress()
user1Address = await user1.getAddress()
user2Address = await user2.getAddress()
// Get deployed Swap
baseSwap = await ethers.getContract("Swap")
dai = await ethers.getContract("DAI")
usdc = await ethers.getContract("USDC")
usdt = await ethers.getContract("USDT")
await baseSwap.initialize(
[dai.address, usdc.address, usdt.address],
[18, 6, 6],
LP_TOKEN_NAME,
LP_TOKEN_SYMBOL,
INITIAL_A_VALUE,
SWAP_FEE,
0,
(
await get("LPToken")
).address,
)
baseLPToken = (await ethers.getContractAt(
GenericERC20Artifact.abi,
(
await baseSwap.swapStorage()
).lpToken,
)) as GenericERC20
// Deploy dummy tokens
susd = (await deployContract(owner as Wallet, GenericERC20Artifact, [
"Synthetix USD",
"sUSD",
"18",
])) as GenericERC20
// Mint tokens
await asyncForEach(
[ownerAddress, user1Address, user2Address],
async (address) => {
await dai.mint(address, BigNumber.from(10).pow(18).mul(100000))
await usdc.mint(address, BigNumber.from(10).pow(6).mul(100000))
await usdt.mint(address, BigNumber.from(10).pow(6).mul(100000))
await susd.mint(address, BigNumber.from(10).pow(18).mul(100000))
},
)
// Deploy MetaSwapUtils
metaSwapUtils = (await deployContract(
owner,
MetaSwapUtilsArtifact,
)) as MetaSwapUtils
await metaSwapUtils.deployed()
// Deploy Swap with SwapUtils library
metaSwap = (await deployContractWithLibraries(owner, MetaSwapArtifact, {
SwapUtils: (await get("SwapUtils")).address,
MetaSwapUtils: (await get("MetaSwapUtils")).address,
AmplificationUtils: (await get("AmplificationUtils")).address,
})) as MetaSwap
await metaSwap.deployed()
// Set approvals
await asyncForEach([owner, user1, user2], async (signer) => {
await susd.connect(signer).approve(metaSwap.address, MAX_UINT256)
await dai.connect(signer).approve(metaSwap.address, MAX_UINT256)
await usdc.connect(signer).approve(metaSwap.address, MAX_UINT256)
await usdt.connect(signer).approve(metaSwap.address, MAX_UINT256)
await dai.connect(signer).approve(baseSwap.address, MAX_UINT256)
await usdc.connect(signer).approve(baseSwap.address, MAX_UINT256)
await usdt.connect(signer).approve(baseSwap.address, MAX_UINT256)
await baseLPToken.connect(signer).approve(metaSwap.address, MAX_UINT256)
// Add some liquidity to the base pool
await baseSwap
.connect(signer)
.addLiquidity(
[String(1e20), String(1e8), String(1e8)],
0,
MAX_UINT256,
)
})
// Let's do some swaps to inflate base pool virtual price
for (let index = 0; index < 100; index++) {
await baseSwap.connect(user1).swap(0, 1, String(1e20), 0, MAX_UINT256)
await baseSwap.connect(user1).swap(1, 2, String(1e8), 0, MAX_UINT256)
await baseSwap.connect(user1).swap(2, 0, String(1e8), 0, MAX_UINT256)
}
// that should be inflated enough
expect(await baseSwap.getVirtualPrice()).to.eq(INFLATED_VP)
// Initialize meta swap pool
// Manually overload the signature
await metaSwap.initializeMetaSwap(
[susd.address, baseLPToken.address],
[18, 18],
LP_TOKEN_NAME,
LP_TOKEN_SYMBOL,
INITIAL_A_VALUE,
SWAP_FEE,
ADMIN_FEE,
(
await get("LPToken")
).address,
baseSwap.address,
)
metaLPToken = (await ethers.getContractAt(
LPTokenArtifact.abi,
(
await metaSwap.swapStorage()
).lpToken,
)) as LPToken
// Approve spending of metaLPToken
await asyncForEach([owner, user1, user2], async (signer) => {
await metaLPToken.connect(signer).approve(metaSwap.address, MAX_UINT256)
})
// Deploy MetaSwapDeposit contract
metaSwapDeposit = (await deployContract(
owner,
MetaSwapDepositArtifact,
)) as MetaSwapDeposit
// Initialize MetaSwapDeposit
await metaSwapDeposit.initialize(
baseSwap.address,
metaSwap.address,
metaLPToken.address,
)
// Approve token transfers to MetaSwapDeposit
await asyncForEach([owner, user1, user2], async (signer) => {
await asyncForEach(
[susd, dai, usdc, usdt, metaLPToken],
async (token) => {
await token
.connect(signer)
.approve(metaSwapDeposit.address, MAX_UINT256)
},
)
})
// Add liquidity to the meta swap pool
await metaSwap.addLiquidity([INFLATED_VP, String(1e18)], 0, MAX_UINT256)
expect(await susd.balanceOf(metaSwap.address)).to.eq(INFLATED_VP)
expect(await baseLPToken.balanceOf(metaSwap.address)).to.eq(String(1e18))
expect(await metaSwap.getVirtualPrice()).to.eq(String(1e18))
},
)
beforeEach(async () => {
await setupTest()
})
describe("addLiquidity", () => {
it("Virtual price doesn't decrease after depositing only susd", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.addLiquidity([String(AMOUNT), 0], 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after depositing only baseLPToken", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.addLiquidity([0, String(AMOUNT)], 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after depositing only susd via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.addLiquidity(
[String(AMOUNT), 0, 0, 0],
0,
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after depositing only dai via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.addLiquidity(
[0, String(AMOUNT), 0, 0],
0,
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
})
describe("removeLiquidity", () => {
it("Virtual price doesn't decrease after removeLiquidity", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.removeLiquidity(String(AMOUNT), [0, 0], MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidity via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.removeLiquidity(
String(AMOUNT),
[0, 0, 0, 0],
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
})
describe("removeLiquidityImbalance", () => {
it("Virtual price doesn't decrease after removeLiquidityImbalance susd", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.removeLiquidityImbalance(
[String(AMOUNT), 0],
String(2 * AMOUNT),
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityImbalance baseLPToken", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.removeLiquidityImbalance(
[0, String(AMOUNT)],
String(2 * AMOUNT),
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityImbalance susd via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.removeLiquidityImbalance(
[String(AMOUNT), 0, 0, 0],
String(2 * AMOUNT),
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityImbalance dai via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.removeLiquidityImbalance(
[0, String(AMOUNT), 0, 0],
String(2 * AMOUNT),
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
})
describe("removeLiquidityOneToken", () => {
it("Virtual price doesn't decrease after removeLiquidityOneToken susd", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.removeLiquidityOneToken(String(AMOUNT), 0, 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityOneToken baseLPToken", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.removeLiquidityOneToken(String(AMOUNT), 1, 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityOneToken susd via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.removeLiquidityOneToken(
String(AMOUNT),
0,
0,
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
it("Virtual price doesn't decrease after removeLiquidityOneToken dai via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.removeLiquidityOneToken(
String(AMOUNT),
1,
0,
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
})
})
describe("swap", () => {
const expectedAdminFeeValueBaseLPToken = BigNumber.from(3.96e13)
it("Virtual price doesn't decrease after swap susd -> baseLPToken", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.swap(0, 1, String(AMOUNT), 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
// We expect the increase in admin balance of base LP token to be valued at
// swap value * 50% * 0.04%
// Since the values aren't exact due to approximations, we test against +-0.01% delta
const adminFeeValue = (await metaSwap.getAdminBalance(1))
.mul(INFLATED_VP)
.div(String(1e18))
expect(adminFeeValue)
.gte(
expectedAdminFeeValueBaseLPToken
.mul(String(9999e14))
.div(String(1e18)),
)
.and.lte(
expectedAdminFeeValueBaseLPToken
.mul(String(10001e14))
.div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueBaseLPToken}`,
)
})
it("Virtual price doesn't decrease after swap baseLPToken -> susd", async () => {
const expectedDepositedBaseLpTokenAmount =
await baseSwap.callStatic.addLiquidity(
[String(AMOUNT), 0, 0],
0,
MAX_UINT256,
)
const expectedSwapValue = expectedDepositedBaseLpTokenAmount
.mul(INFLATED_VP)
.div(String(1e18))
const expectedAdminFeeValueSUSD = expectedSwapValue
.mul(3.96e14)
.div(String(1e18))
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.swap(
1,
0,
expectedDepositedBaseLpTokenAmount,
0,
MAX_UINT256,
)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
// We expect the increase in admin balance of susd to be valued at
// swap value * 50% * 0.04%
// Since the values aren't exact due to approximations, we test against +-0.05% delta
const adminFeeValue = await metaSwap.getAdminBalance(0)
expect(adminFeeValue)
.gte(expectedAdminFeeValueSUSD.mul(String(9999e14)).div(String(1e18)))
.and.lte(
expectedAdminFeeValueSUSD.mul(String(10001e14)).div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueSUSD}`,
)
})
it("susd -> baseLPToken -> susd: outcome not great not terrible", async () => {
const [tokenFromBalanceBefore, tokenToBalanceBefore] =
await getUserTokenBalances(user1, [susd, baseLPToken])
await metaSwap.connect(user1).swap(0, 1, String(AMOUNT), 0, MAX_UINT256)
const tokenToBalanceAfterFirst = await getUserTokenBalance(
user1,
baseLPToken,
)
await metaSwap
.connect(user1)
.swap(
1,
0,
String(tokenToBalanceAfterFirst.sub(tokenToBalanceBefore)),
0,
MAX_UINT256,
)
const [tokenFromBalanceAfterSecond, tokenToBalanceAfterSecond] =
await getUserTokenBalances(user1, [susd, baseLPToken])
// bought & sold exactly the same
expect(tokenToBalanceBefore).to.eq(tokenToBalanceAfterSecond)
// can't get more than we started with
expect(tokenFromBalanceAfterSecond).to.lt(tokenFromBalanceBefore)
const lossBP = tokenFromBalanceBefore
.sub(tokenFromBalanceAfterSecond)
.mul(10000)
.div(String(AMOUNT))
// two small swaps should not result in more than 0.1% loss
expect(lossBP).to.lt(10)
})
})
describe("swapUnderlying", () => {
const expectedAdminFeeValueBaseLPToken = BigNumber.from(3.96e13)
it("Virtual price doesn't decrease after swapUnderlying susd -> dai", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.swapUnderlying(0, 1, String(AMOUNT), 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
const adminFeeValue = (await metaSwap.getAdminBalance(1))
.mul(INFLATED_VP)
.div(String(1e18))
expect(adminFeeValue)
.gte(
expectedAdminFeeValueBaseLPToken
.mul(String(9999e14))
.div(String(1e18)),
)
.and.lte(
expectedAdminFeeValueBaseLPToken
.mul(String(10001e14))
.div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueBaseLPToken}`,
)
})
it("Virtual price doesn't decrease after swapUnderlying dai -> susd", async () => {
const expectedDepositedBaseLpTokenAmount =
await baseSwap.callStatic.addLiquidity(
[String(AMOUNT), 0, 0],
0,
MAX_UINT256,
)
const expectedSwapValue = expectedDepositedBaseLpTokenAmount
.mul(INFLATED_VP)
.div(String(1e18))
const expectedAdminFeeValueSUSD = expectedSwapValue
.mul(3.96e14)
.div(String(1e18))
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwap.swapUnderlying(1, 0, String(AMOUNT), 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
const adminFeeValue = await metaSwap.getAdminBalance(0)
expect(adminFeeValue)
.gte(expectedAdminFeeValueSUSD.mul(String(9999e14)).div(String(1e18)))
.and.lte(
expectedAdminFeeValueSUSD.mul(String(10001e14)).div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueSUSD}`,
)
})
it("Virtual price doesn't decrease after swap susd -> dai via MetaSwapDeposit", async () => {
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.swap(0, 1, String(AMOUNT), 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
const adminFeeValue = (await metaSwap.getAdminBalance(1))
.mul(INFLATED_VP)
.div(String(1e18))
expect(adminFeeValue)
.gte(
expectedAdminFeeValueBaseLPToken
.mul(String(9999e14))
.div(String(1e18)),
)
.and.lte(
expectedAdminFeeValueBaseLPToken
.mul(String(10001e14))
.div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueBaseLPToken}`,
)
})
it("Virtual price doesn't decrease after swap dai -> susd via MetaSwapDeposit", async () => {
const expectedDepositedBaseLpTokenAmount =
await baseSwap.callStatic.addLiquidity(
[String(AMOUNT), 0, 0],
0,
MAX_UINT256,
)
const expectedSwapValue = expectedDepositedBaseLpTokenAmount
.mul(INFLATED_VP)
.div(String(1e18))
const expectedAdminFeeValueSUSD = expectedSwapValue
.mul(3.96e14)
.div(String(1e18))
const virtualPriceBefore = await metaSwap.getVirtualPrice()
await metaSwapDeposit.swap(1, 0, String(AMOUNT), 0, MAX_UINT256)
expect(await metaSwap.getVirtualPrice()).to.gte(virtualPriceBefore)
const adminFeeValue = await metaSwap.getAdminBalance(0)
expect(adminFeeValue)
.gte(expectedAdminFeeValueSUSD.mul(String(9999e14)).div(String(1e18)))
.and.lte(
expectedAdminFeeValueSUSD.mul(String(10001e14)).div(String(1e18)),
)
console.log(
`Actual admin fee increase: ${adminFeeValue}, ideal value: ${expectedAdminFeeValueSUSD}`,
)
})
it("susd -> dai -> susd: outcome not great not terrible", async () => {
const [tokenFromBalanceBefore, tokenToBalanceBefore] =
await getUserTokenBalances(user1, [susd, dai])
await metaSwap
.connect(user1)
.swapUnderlying(0, 1, String(AMOUNT), 0, MAX_UINT256)
const tokenToBalanceAfterFirst = await getUserTokenBalance(user1, dai)
await metaSwap
.connect(user1)
.swapUnderlying(
1,
0,
String(tokenToBalanceAfterFirst.sub(tokenToBalanceBefore)),
0,
MAX_UINT256,
)
const [tokenFromBalanceAfterSecond, tokenToBalanceAfterSecond] =
await getUserTokenBalances(user1, [susd, dai])
// bought & sold exactly the same
expect(tokenToBalanceBefore).to.eq(tokenToBalanceAfterSecond)
// can't get more than we started with
expect(tokenFromBalanceAfterSecond).to.lt(tokenFromBalanceBefore)
const lossBP = tokenFromBalanceBefore
.sub(tokenFromBalanceAfterSecond)
.mul(10000)
.div(String(AMOUNT))
// two small swaps should not result in more than 0.15% loss
expect(lossBP).to.lt(15)
})
})
}) | the_stack |
import { MetadataInfo } from 'jsforce'
import { ObjectType } from '@salto-io/adapter-api'
import { collections } from '@salto-io/lowerdash'
import * as constants from '../src/constants'
import { CustomField, ProfileInfo } from '../src/client/types'
import { createDeployPackage } from '../src/transformers/xml_transformer'
import { MetadataValues, createInstanceElement } from '../src/transformers/transformer'
import SalesforceClient from '../src/client/client'
import { objectExists } from './utils'
import { mockTypes, mockDefaultValues } from '../test/mock_elements'
export const gvsName = 'TestGlobalValueSet'
export const accountApiName = 'Account'
export const customObjectWithFieldsName = 'TestFields__c'
export const customObjectAddFieldsName = 'TestAddFields__c'
export const summaryFieldName = 'Case.summary__c'
const { awu } = collections.asynciterable
const randomString = String(Date.now()).substring(6)
export const CUSTOM_FIELD_NAMES = {
ROLLUP_SUMMARY: 'rollupsummary__c',
PICKLIST: 'Pickle__c',
CURRENCY: 'Alpha__c',
AUTO_NUMBER: 'Bravo__c',
DATE: 'Charlie__c',
TIME: 'Delta__c',
MULTI_PICKLIST: 'Hotel__c',
DATE_TIME: 'Echo__c',
EMAIL: 'Foxtrot__c',
LOCATION: 'Golf__c',
PERCENT: 'India__c',
PHONE: 'Juliett__c',
LONG_TEXT_AREA: 'Kilo__c',
RICH_TEXT_AREA: 'Lima__c',
TEXT_AREA: 'Mike__c',
ENCRYPTED_TEXT: 'November__c',
URL: 'Oscar__c',
NUMBER: 'Papa__c',
TEXT: 'Sierra__c',
CHECKBOX: 'Tango__c',
GLOBAL_PICKLIST: 'Uniform__c',
LOOKUP: `Quebec${randomString}__c`,
MASTER_DETAIL: `Romeo${randomString}__c`,
FORMULA: 'Whiskey__c',
}
export const removeCustomObjectsWithVariousFields = async (client: SalesforceClient):
Promise<void> => {
const deleteCustomObject = async (objectName: string): Promise<void> => {
if (await objectExists(client, constants.CUSTOM_FIELD, summaryFieldName)) {
await client.delete(constants.CUSTOM_FIELD, summaryFieldName)
}
if (await objectExists(client, constants.CUSTOM_OBJECT, objectName)) {
await client.delete(constants.CUSTOM_OBJECT, objectName)
}
}
await Promise.all([customObjectWithFieldsName, customObjectAddFieldsName]
.map(o => deleteCustomObject(o)))
}
export const verifyElementsExist = async (client: SalesforceClient): Promise<void> => {
const verifyObjectsDependentFieldsExist = async (): Promise<void> => {
await client.upsert('GlobalValueSet', {
fullName: gvsName,
masterLabel: gvsName,
sorted: false,
description: 'GlobalValueSet that should be fetched in e2e test',
customValue: [
{
fullName: 'Val1',
default: true,
label: 'Val1',
},
{
fullName: 'Val2',
default: false,
label: 'Val2',
},
],
} as MetadataInfo)
}
const addCustomObjectWithVariousFields = async (): Promise<void> => {
await removeCustomObjectsWithVariousFields(client)
const objectToAdd = {
deploymentStatus: 'Deployed',
fields: [
{
fullName: CUSTOM_FIELD_NAMES.PICKLIST,
label: 'Picklist label',
description: 'Picklist description',
required: false,
type: constants.FIELD_TYPE_NAMES.PICKLIST,
valueSet: {
restricted: true,
valueSetDefinition: {
value: [
{
default: true,
fullName: 'NEW',
label: 'NEW',
color: '#FF0000',
},
{
default: false,
fullName: 'OLD',
label: 'OLD',
isActive: true,
},
{
default: false,
fullName: 'OLDEST',
label: 'OLDEST',
isActive: false,
},
],
},
},
},
{
defaultValue: 25,
fullName: CUSTOM_FIELD_NAMES.CURRENCY,
label: 'Currency label',
description: 'Currency description',
inlineHelpText: 'Currency help',
precision: 18,
required: true,
scale: 3,
type: constants.FIELD_TYPE_NAMES.CURRENCY,
},
{
displayFormat: 'ZZZ-{0000}',
fullName: CUSTOM_FIELD_NAMES.AUTO_NUMBER,
label: 'Autonumber label',
description: 'Autonumber description',
inlineHelpText: 'Autonumber help',
externalId: true,
type: constants.FIELD_TYPE_NAMES.AUTONUMBER,
},
{
defaultValue: 'Today() + 7',
fullName: CUSTOM_FIELD_NAMES.DATE,
label: 'Date label',
description: 'Date description',
inlineHelpText: 'Date help',
required: false,
type: constants.FIELD_TYPE_NAMES.DATE,
},
{
defaultValue: 'TIMENOW() + 5',
fullName: CUSTOM_FIELD_NAMES.TIME,
label: 'Time label',
description: 'Time description',
inlineHelpText: 'Time help',
required: true,
type: constants.FIELD_TYPE_NAMES.TIME,
},
{
defaultValue: 'NOW() + 7',
fullName: CUSTOM_FIELD_NAMES.DATE_TIME,
label: 'DateTime label',
description: 'DateTime description',
inlineHelpText: 'DateTime help',
required: false,
type: constants.FIELD_TYPE_NAMES.DATETIME,
},
{
fullName: CUSTOM_FIELD_NAMES.EMAIL,
label: 'Email label',
required: false,
unique: true,
externalId: true,
type: constants.FIELD_TYPE_NAMES.EMAIL,
},
{
displayLocationInDecimal: true,
fullName: CUSTOM_FIELD_NAMES.LOCATION,
label: 'Location label',
required: false,
scale: 2,
type: constants.COMPOUND_FIELD_TYPE_NAMES.LOCATION,
},
{
fullName: CUSTOM_FIELD_NAMES.PERCENT,
label: 'Percent label',
description: 'Percent description',
precision: 12,
required: false,
scale: 3,
type: constants.FIELD_TYPE_NAMES.PERCENT,
},
{
fullName: CUSTOM_FIELD_NAMES.PHONE,
label: 'Phone label',
inlineHelpText: 'Phone help',
required: true,
type: constants.FIELD_TYPE_NAMES.PHONE,
},
{
fullName: CUSTOM_FIELD_NAMES.LONG_TEXT_AREA,
label: 'LongTextArea label',
length: 32700,
required: false,
type: constants.FIELD_TYPE_NAMES.LONGTEXTAREA,
visibleLines: 5,
},
{
fullName: CUSTOM_FIELD_NAMES.RICH_TEXT_AREA,
label: 'RichTextArea label',
description: 'RichTextArea description',
inlineHelpText: 'RichTextArea help',
length: 32600,
required: false,
type: constants.FIELD_TYPE_NAMES.RICHTEXTAREA,
visibleLines: 32,
},
{
fullName: CUSTOM_FIELD_NAMES.TEXT_AREA,
label: 'TextArea label',
description: 'TextArea description',
inlineHelpText: 'TextArea help',
required: false,
type: constants.FIELD_TYPE_NAMES.TEXTAREA,
},
{
fullName: CUSTOM_FIELD_NAMES.ENCRYPTED_TEXT,
label: 'EncryptedText label',
length: 35,
maskChar: 'asterisk',
maskType: 'creditCard',
required: false,
type: constants.FIELD_TYPE_NAMES.ENCRYPTEDTEXT,
},
{
fullName: CUSTOM_FIELD_NAMES.URL,
label: 'Url label',
required: false,
type: constants.FIELD_TYPE_NAMES.URL,
},
{
defaultValue: 42,
fullName: CUSTOM_FIELD_NAMES.NUMBER,
label: 'Number label',
precision: 15,
required: false,
scale: 3,
type: constants.FIELD_TYPE_NAMES.NUMBER,
unique: true,
},
{
fullName: CUSTOM_FIELD_NAMES.TEXT,
label: 'Text label',
required: false,
length: 100,
caseSensitive: true,
externalId: true,
type: constants.FIELD_TYPE_NAMES.TEXT,
unique: true,
},
{
defaultValue: true,
fullName: CUSTOM_FIELD_NAMES.CHECKBOX,
label: 'Checkbox label',
type: constants.FIELD_TYPE_NAMES.CHECKBOX,
},
{
fullName: CUSTOM_FIELD_NAMES.GLOBAL_PICKLIST,
label: 'Global Picklist label',
required: false,
valueSet: {
restricted: true,
valueSetName: gvsName,
},
type: constants.FIELD_TYPE_NAMES.PICKLIST,
},
{
fullName: CUSTOM_FIELD_NAMES.MASTER_DETAIL,
label: 'MasterDetail label',
referenceTo: [
'Case',
],
relationshipName:
CUSTOM_FIELD_NAMES.MASTER_DETAIL.split(constants.SALESFORCE_CUSTOM_SUFFIX)[0],
reparentableMasterDetail: true,
required: false,
type: constants.FIELD_TYPE_NAMES.MASTER_DETAIL,
writeRequiresMasterRead: true,
relationshipOrder: 0,
},
{
formula: '5 > 4',
fullName: CUSTOM_FIELD_NAMES.FORMULA,
label: 'Formula Checkbox label',
businessStatus: 'Hidden',
securityClassification: 'Restricted',
formulaTreatBlanksAs: 'BlankAsZero',
type: constants.FIELD_TYPE_NAMES.CHECKBOX,
},
] as CustomField[],
fullName: customObjectWithFieldsName,
label: 'test object with various field types',
nameField: {
label: 'Name',
type: 'Text',
},
pluralLabel: 'test object with various field typess',
sharingModel: 'ControlledByParent',
}
const additionalFieldsToAdd = [{
fullName: `${customObjectWithFieldsName}.${CUSTOM_FIELD_NAMES.MULTI_PICKLIST}`,
label: 'Multipicklist label',
required: false,
type: constants.FIELD_TYPE_NAMES.MULTIPICKLIST,
valueSet: {
controllingField: CUSTOM_FIELD_NAMES.PICKLIST,
restricted: false,
valueSetDefinition: {
value: [
{
default: false,
fullName: 'RE',
label: 'RE',
},
{
default: true,
fullName: 'DO',
label: 'DO',
},
],
},
valueSettings: [
{
controllingFieldValue: [
'NEW',
'OLD',
],
valueName: 'DO',
},
{
controllingFieldValue: [
'OLD',
],
valueName: 'RE',
},
],
},
visibleLines: 4,
},
{
fullName: `${accountApiName}.${CUSTOM_FIELD_NAMES.ROLLUP_SUMMARY}`,
label: 'Summary label',
summarizedField: 'Opportunity.Amount',
summaryFilterItems: {
field: 'Opportunity.Amount',
operation: 'greaterThan',
value: '1',
},
summaryForeignKey: 'Opportunity.AccountId',
summaryOperation: 'sum',
type: 'Summary',
}]
const lookupField = {
deleteConstraint: 'Restrict',
fullName: CUSTOM_FIELD_NAMES.LOOKUP,
label: 'Lookup label',
referenceTo: ['Opportunity'],
relationshipName: CUSTOM_FIELD_NAMES.LOOKUP.split(constants.SALESFORCE_CUSTOM_SUFFIX)[0],
required: false,
type: constants.FIELD_TYPE_NAMES.LOOKUP,
} as CustomField
objectToAdd.fields.push(lookupField)
const lookupFilter = {
active: true,
booleanFilter: '1 OR 2',
errorMessage: 'This is the Error message',
infoMessage: 'This is the Info message',
isOptional: false,
filterItems: [{
field: 'Opportunity.OwnerId',
operation: 'equals',
valueField: '$User.Id',
},
{
field: 'Opportunity.NextStep',
operation: 'equals',
value: 'NextStepValue',
}],
}
await verifyObjectsDependentFieldsExist()
await client.upsert(constants.CUSTOM_OBJECT, objectToAdd as MetadataInfo)
await client.upsert(constants.CUSTOM_FIELD, additionalFieldsToAdd as MetadataInfo[])
// Add the fields permissions
const objectFieldNames = objectToAdd.fields
.filter(field => !field.required)
.filter(field => field.type !== constants.FIELD_TYPE_NAMES.MASTER_DETAIL)
.map(field => `${customObjectWithFieldsName}.${field.fullName}`)
const additionalFieldNames = additionalFieldsToAdd
.filter(field => !field.required)
.map(f => f.fullName)
const fieldNames = objectFieldNames.concat(additionalFieldNames)
await client.upsert(
constants.PROFILE_METADATA_TYPE,
{
fullName: constants.ADMIN_PROFILE,
fieldPermissions: fieldNames.map(name => ({
field: name,
editable: true,
readable: true,
})),
} as ProfileInfo,
)
// update lookup filter
await client.upsert(constants.CUSTOM_FIELD,
Object.assign(lookupField,
{ fullName: `${customObjectWithFieldsName}.${CUSTOM_FIELD_NAMES.LOOKUP}`, lookupFilter }))
}
const verifyEmailTemplateAndFolderExist = async (): Promise<void> => {
await client.upsert('EmailFolder', {
fullName: 'TestEmailFolder',
name: 'Test Email Folder Name',
accessType: 'Public',
publicFolderAccess: 'ReadWrite',
} as MetadataInfo)
await client.upsert('EmailTemplate', {
fullName: 'TestEmailFolder/TestEmailTemplate',
name: 'Test Email Template Name',
available: true,
style: 'none',
subject: 'Test Email Template Subject',
uiType: 'Aloha',
encodingKey: 'UTF-8',
type: 'text',
description: 'Test Email Template Description',
content: 'Email Body',
} as MetadataInfo)
}
const verifyReportAndFolderExist = async (): Promise<void> => {
await client.upsert('ReportFolder', {
fullName: 'TestReportFolder',
name: 'Test Report Folder Name',
accessType: 'Public',
publicFolderAccess: 'ReadWrite',
} as MetadataInfo)
await client.upsert('Report', {
fullName: 'TestReportFolder/TestReport',
format: 'Summary',
name: 'Test Report Name',
reportType: 'Opportunity',
} as MetadataInfo)
}
const verifyDashboardAndFolderExist = async (): Promise<void> => {
await client.upsert('DashboardFolder', {
fullName: 'TestDashboardFolder',
name: 'Test Dashboard Folder Name',
accessType: 'Public',
publicFolderAccess: 'ReadWrite',
} as MetadataInfo)
await client.upsert('Dashboard', {
fullName: 'TestDashboardFolder/TestDashboard',
backgroundEndColor: '#FFFFFF',
backgroundFadeDirection: 'Diagonal',
backgroundStartColor: '#FFFFFF',
textColor: '#000000',
title: 'Test Dashboard Title',
titleColor: '#000000',
titleSize: '12',
leftSection: {
columnSize: 'Medium',
components: [],
},
rightSection: {
columnSize: 'Medium',
components: [],
},
} as MetadataInfo)
}
const verifyLeadHasValidationRule = async (): Promise<void> => {
await client.upsert('ValidationRule', {
fullName: 'Lead.TestValidationRule',
active: true,
description: 'ValidationRule that should be fetched in e2e test',
errorConditionFormula: 'false',
errorMessage: 'Error Message!',
} as MetadataInfo)
}
const verifyLeadHasBusinessProcess = async (): Promise<void> => {
await client.upsert('BusinessProcess', {
fullName: 'Lead.TestBusinessProcess',
isActive: true,
description: 'BusinessProcess that should be fetched in e2e test',
values: [
{
fullName: 'Open - Not Contacted',
default: true,
},
{
fullName: 'Closed - Not Converted',
default: false,
},
],
} as MetadataInfo)
}
const verifyLeadHasRecordType = async (): Promise<void> => {
await client.upsert('RecordType', {
fullName: 'Lead.TestRecordType',
active: true,
businessProcess: 'TestBusinessProcess',
description: 'RecordType that should be fetched in e2e test',
label: 'E2E Fetch RecordType',
} as MetadataInfo)
}
const verifyLeadHasWebLink = async (): Promise<void> => {
await client.upsert('WebLink', {
fullName: 'Lead.TestWebLink',
availability: 'online',
description: 'WebLink that should be fetched in e2e test',
displayType: 'button',
encodingKey: 'UTF-8',
hasMenubar: false,
hasScrollbars: true,
hasToolbar: false,
height: 600,
isResizable: true,
linkType: 'url',
masterLabel: 'E2E Fetch WebLink',
openType: 'newWindow',
position: 'none',
protected: false,
url: '{!Lead.CreatedBy} = "MyName"',
} as MetadataInfo)
}
const verifyLeadHasListView = async (): Promise<void> => {
await client.upsert('ListView', {
fullName: 'Lead.TestListView',
label: 'E2E Fetch ListView',
filterScope: 'Everything',
filters: {
field: 'LEAD.STATUS',
operation: 'equals',
value: 'closed',
},
} as MetadataInfo)
}
const verifyLeadHasFieldSet = async (): Promise<void> => {
await client.upsert('FieldSet', {
fullName: 'Lead.TestFieldSet',
description: 'E2E Fetch FieldSet',
displayedFields: [
{
field: 'State',
isFieldManaged: false,
isRequired: false,
},
{
field: 'Status',
isFieldManaged: false,
isRequired: false,
},
],
label: 'E2E Fetch FieldSet',
} as MetadataInfo)
}
const verifyLeadHasCompactLayout = async (): Promise<void> => {
await client.upsert('CompactLayout', {
fullName: 'Lead.TestCompactLayout',
fields: [
'Address',
'Company',
],
label: 'E2E Fetch CompactLayout',
} as MetadataInfo)
}
const verifyCustomObjectInnerTypesExist = async (): Promise<void> => {
await verifyLeadHasBusinessProcess() // RecordType depends on BusinessProcess
await Promise.all([
verifyLeadHasValidationRule(),
verifyLeadHasRecordType(),
verifyLeadHasWebLink(),
verifyLeadHasListView(),
verifyLeadHasFieldSet(),
verifyLeadHasCompactLayout(),
])
}
const verifyFlowExists = async (): Promise<void> => {
await client.upsert('Flow', {
fullName: 'TestFlow',
decisions: {
processMetadataValues: {
name: 'index',
value: {
numberValue: '0.0',
},
},
name: 'myDecision',
label: 'myDecision2',
locationX: '50',
locationY: '0',
defaultConnectorLabel: 'default',
rules: {
name: 'myRule_1',
conditionLogic: 'and',
conditions: {
processMetadataValues: [
{
name: 'inputDataType',
value: {
stringValue: 'String',
},
},
{
name: 'leftHandSideType',
value: {
stringValue: 'String',
},
},
{
name: 'operatorDataType',
value: {
stringValue: 'String',
},
},
{
name: 'rightHandSideType',
value: {
stringValue: 'String',
},
},
],
leftValueReference: 'myVariable_current.FirstName',
operator: 'EqualTo',
rightValue: {
stringValue: 'BLA',
},
},
connector: {
targetReference: 'myRule_1_A1',
},
label: 'NameIsBla',
},
},
interviewLabel: 'TestFlow-1_InterviewLabel',
label: 'TestFlow',
processMetadataValues: [
{
name: 'ObjectType',
value: {
stringValue: 'Contact',
},
},
{
name: 'ObjectVariable',
value: {
elementReference: 'myVariable_current',
},
},
{
name: 'OldObjectVariable',
value: {
elementReference: 'myVariable_old',
},
},
{
name: 'TriggerType',
value: {
stringValue: 'onCreateOnly',
},
},
],
processType: 'Workflow',
recordUpdates: {
processMetadataValues: [
{
name: 'evaluationType',
value: {
stringValue: 'always',
},
},
{
name: 'extraTypeInfo',
},
{
name: 'isChildRelationship',
value: {
booleanValue: 'false',
},
},
{
name: 'reference',
value: {
stringValue: '[Contact]',
},
},
{
name: 'referenceTargetField',
},
],
name: 'myRule_1_A1',
label: 'UpdateLastName',
locationX: '100',
locationY: '200',
filters: {
processMetadataValues: {
name: 'implicit',
value: {
booleanValue: 'true',
},
},
field: 'Id',
operator: 'EqualTo',
value: {
elementReference: 'myVariable_current.Id',
},
},
inputAssignments: {
processMetadataValues: [
{
name: 'dataType',
value: {
stringValue: 'String',
},
},
{
name: 'isRequired',
value: {
booleanValue: 'false',
},
},
{
name: 'leftHandSideLabel',
value: {
stringValue: 'Last Name',
},
},
{
name: 'leftHandSideReferenceTo',
},
{
name: 'rightHandSideType',
value: {
stringValue: 'String',
},
},
],
field: 'LastName',
value: {
stringValue: 'Updated Name',
},
},
object: 'Contact',
},
startElementReference: 'myDecision',
status: 'Draft',
variables: [
{
name: 'myVariable_current',
dataType: 'SObject',
isCollection: 'false',
isInput: 'true',
isOutput: 'true',
objectType: 'Contact',
},
{
name: 'myVariable_old',
dataType: 'SObject',
isCollection: 'false',
isInput: 'true',
isOutput: 'false',
objectType: 'Contact',
},
],
} as MetadataInfo)
}
const verifyRolesExist = async (): Promise<void> => {
await client.upsert('Role', {
fullName: 'TestParentRole',
name: 'TestParentRole',
caseAccessLevel: 'Edit',
contactAccessLevel: 'Edit',
opportunityAccessLevel: 'Edit',
description: 'TestParentRole',
mayForecastManagerShare: 'false',
} as MetadataInfo)
await client.upsert('Role', {
fullName: 'TestChildRole',
name: 'TestChildRole',
caseAccessLevel: 'Edit',
contactAccessLevel: 'Edit',
opportunityAccessLevel: 'Edit',
description: 'TestChildRole',
mayForecastManagerShare: 'false',
parentRole: 'TestParentRole',
} as MetadataInfo)
}
const verifyLeadHasConvertSettings = async (): Promise<void> => {
await client.upsert('LeadConvertSettings', {
fullName: 'LeadConvertSettings',
allowOwnerChange: 'true',
objectMapping: {
inputObject: 'Lead',
mappingFields: [
{
inputField: 'CurrentGenerators__c',
outputField: 'Active__c',
},
],
outputObject: 'Account',
},
opportunityCreationOptions: 'VisibleOptional',
} as MetadataInfo)
}
const verifyDeployableInstancesExist = async (): Promise<void> => {
const instances: [MetadataValues, ObjectType][] = [
[mockDefaultValues.ApexClass, mockTypes.ApexClass],
[mockDefaultValues.ApexPage, mockTypes.ApexPage],
[mockDefaultValues.AuraDefinitionBundle, mockTypes.AuraDefinitionBundle],
[mockDefaultValues.LightningComponentBundle, mockTypes.LightningComponentBundle],
[mockDefaultValues.StaticResource, mockTypes.StaticResource],
]
const pkg = createDeployPackage()
await awu(instances).forEach(async ([values, type]) => {
await pkg.add(createInstanceElement(values, type))
})
await client.deploy(await pkg.getZip())
}
await Promise.all([
addCustomObjectWithVariousFields(),
verifyEmailTemplateAndFolderExist(),
verifyReportAndFolderExist(),
verifyDashboardAndFolderExist(),
verifyCustomObjectInnerTypesExist(),
verifyFlowExists(),
verifyRolesExist(),
verifyLeadHasConvertSettings(),
verifyDeployableInstancesExist(),
])
} | the_stack |
import assert from "assert";
import * as util from "util";
import { Container, ContainerDefinition } from "../../dist-esm/client";
import { DataType, IndexKind } from "../../dist-esm/documents";
import { SqlQuerySpec } from "../../dist-esm/queryExecutionContext";
import { QueryIterator } from "../../dist-esm/queryIterator";
import { bulkInsertItems, getTestContainer, removeAllDatabases, generateDocuments } from "../common/TestHelpers";
import { FeedResponse, FeedOptions } from "../../dist-esm";
function compare(key: string) {
return function(a: any, b: any): number {
if (a[key] > b[key]) {
return 1;
}
if (a[key] < b[key]) {
return -1;
}
return 0;
};
}
describe("Cross Partition", function() {
this.timeout(process.env.MOCHA_TIMEOUT || "30000");
describe("Validate Query", function() {
const documentDefinitions = generateDocuments(20);
const containerDefinition: ContainerDefinition = {
id: "sample container",
indexingPolicy: {
includedPaths: [
{
path: "/",
indexes: [
{
kind: IndexKind.Range,
dataType: DataType.Number
},
{
kind: IndexKind.Range,
dataType: DataType.String
}
]
}
]
},
partitionKey: {
paths: ["/id"]
}
};
const containerOptions = { offerThroughput: 25100 };
let container: Container;
// - removes all the databases,
// - creates a new database,
// - creates a new collecton,
// - bulk inserts documents to the container
before(async function() {
await removeAllDatabases();
container = await getTestContainer("Validate 中文 Query", undefined, containerDefinition, containerOptions);
await bulkInsertItems(container, documentDefinitions);
});
const validateResults = function(actualResults: any[], expectedOrderIds: string[], expectedCount: number) {
assert.equal(
actualResults.length,
expectedCount || (expectedOrderIds && expectedOrderIds.length) || documentDefinitions.length,
"actual results length doesn't match with expected results length."
);
if (expectedOrderIds) assert.deepStrictEqual(actualResults.map(doc => doc.id || doc), expectedOrderIds);
};
const validateFetchAll = async function(
queryIterator: QueryIterator<any>,
options: any,
expectedOrderIds: string[],
expectedCount: number
) {
options.continuation = undefined;
const response = await queryIterator.fetchAll();
const { resources: results } = response;
assert.equal(
results.length,
expectedCount || (expectedOrderIds && expectedOrderIds.length) || documentDefinitions.length,
"invalid number of results"
);
assert.equal(queryIterator.hasMoreResults(), false, "hasMoreResults: no more results is left");
validateResults(results, expectedOrderIds, expectedCount);
return response;
};
const validateFetchNextAndHasMoreResults = async function(
options: any,
queryIterator: QueryIterator<any>,
expectedOrderIds: string[],
fetchAllResponse: FeedResponse<any>,
expectedCount: number,
expectedIteratorCalls: number
) {
const pageSize = options["maxItemCount"];
let totalExecuteNextRequestCharge = 0;
let totalIteratorCalls = 0;
let totalFetchedResults: any[] = [];
const expectedLength =
expectedCount || (expectedOrderIds && expectedOrderIds.length) || documentDefinitions.length;
while (queryIterator.hasMoreResults()) {
const { resources: results, queryMetrics, requestCharge } = await queryIterator.fetchNext();
totalIteratorCalls++;
assert(queryMetrics, "expected response have query metrics");
if (totalFetchedResults.length > expectedLength) {
break;
}
if (results) {
totalFetchedResults = totalFetchedResults.concat(results);
}
totalExecuteNextRequestCharge += requestCharge;
assert(requestCharge >= 0);
if (totalFetchedResults.length < expectedLength) {
if (results) {
assert(results.length <= pageSize, "executeNext: invalid fetch block size");
}
assert(queryIterator.hasMoreResults(), "hasMoreResults expects to return true");
} else {
// no more results
assert.equal(expectedLength, totalFetchedResults.length, "executeNext: didn't fetch all the results");
}
}
if (expectedIteratorCalls) {
assert.equal(totalIteratorCalls, expectedIteratorCalls);
}
// no more results
validateResults(totalFetchedResults, expectedOrderIds, expectedCount);
assert.equal(queryIterator.hasMoreResults(), false, "hasMoreResults: no more results is left");
assert(totalExecuteNextRequestCharge > 0);
const percentDifference =
Math.abs(fetchAllResponse.requestCharge - totalExecuteNextRequestCharge) / totalExecuteNextRequestCharge;
assert(
percentDifference <= 0.01,
"difference between fetchAll request charge and executeNext request charge should be less than 1%"
);
};
const validateAsyncIterator = async function(
queryIterator: QueryIterator<any>,
expectedOrderIds: any[],
expecetedCount: number
) {
const expectedLength =
expecetedCount || (expectedOrderIds && expectedOrderIds.length) || documentDefinitions.length;
const results: any[] = [];
let completed = false;
for await (const { resources: items } of queryIterator.getAsyncIterator()) {
assert.equal(completed, false, "iterator called after all results returned");
results.push(...items);
if (results.length === expectedLength) {
completed = true;
}
}
assert.equal(completed, true, "AsyncIterator should see all expected results");
validateResults(results, expectedOrderIds, expecetedCount);
};
const executeQueryAndValidateResults = async function({
query,
options,
expectedOrderIds,
expectedCount,
expectedRus,
expectedIteratorCalls
}: {
query: string | SqlQuerySpec;
options: any;
expectedOrderIds?: any[];
expectedCount?: number;
expectedRus?: number;
expectedIteratorCalls?: number;
}) {
options.populateQueryMetrics = true;
const queryIterator = container.items.query(query, options);
const fetchAllResponse = await validateFetchAll(queryIterator, options, expectedOrderIds, expectedCount);
if (expectedRus) {
const percentDifference = Math.abs(fetchAllResponse.requestCharge - expectedRus) / expectedRus;
assert(
percentDifference <= 0.05,
"difference between fetchAll request charge and expected request charge should be less than 5%"
);
}
queryIterator.reset();
await validateFetchNextAndHasMoreResults(
options,
queryIterator,
expectedOrderIds,
fetchAllResponse,
expectedCount,
expectedIteratorCalls
);
queryIterator.reset();
await validateAsyncIterator(queryIterator, expectedOrderIds, expectedCount);
};
it("Validate Parallel Query As String With maxDegreeOfParallelism = 0", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 0
};
// validates the results size and order
await executeQueryAndValidateResults({
query,
options
});
});
it("Validate Parallel Query As String With maxDegreeOfParallelism: -1", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r";
const options: FeedOptions = {
maxItemCount: 2,
maxDegreeOfParallelism: -1,
forceQueryPlan: true,
populateQueryMetrics: true
};
// validates the results size and order
await executeQueryAndValidateResults({
query,
options
});
});
it("Validate Parallel Query As String With maxDegreeOfParallelism: 1", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 1
};
// validates the results size and order
await executeQueryAndValidateResults({
query,
options
});
});
it("Validate Parallel Query As String With maxDegreeOfParallelism: 3", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r";
const options: FeedOptions = {
maxItemCount: 2,
maxDegreeOfParallelism: 3,
bufferItems: true
};
// validates the results size and order
await executeQueryAndValidateResults({
query,
options
});
});
it("Validate Simple OrderBy Query As String With maxDegreeOfParallelism = 0", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 0
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate Simple OrderBy Query As String With maxDegreeOfParallelism = 1", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 1
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds, expectedRus: 35 });
});
it("Validate Simple OrderBy Query As String With maxDegreeOfParallelism = 3", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 3
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate Simple OrderBy Query As String With maxDegreeOfParallelism = -1", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: -1
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate DISTINCT Query", async function() {
// simple order by query in string format
const query = "SELECT DISTINCT VALUE r.spam3 FROM root r";
const options = {
maxItemCount: 2
};
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedCount: 3 });
});
it("Validate DISTINCT OrderBy Query", async function() {
// simple order by query in string format
const query = "SELECT DISTINCT VALUE r.spam3 FROM root r order by r.spam3 DESC";
const options = {
maxItemCount: 2
};
const expectedOrderedIds = ["eggs2", "eggs1", "eggs0"];
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate parallel DISTINCT Query", async function() {
// simple order by query in string format
const query = "SELECT DISTINCT VALUE r.spam3 FROM root r order by r.spam3";
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 3,
bufferItems: true
};
const expectedOrderedIds = ["eggs0", "eggs1", "eggs2"];
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate DISTINCT Query with maxItemCount = 1", async function() {
// simple order by query in string format
const query = "SELECT DISTINCT VALUE r.spam3 FROM root r order by r.spam3";
const options = {
maxItemCount: 1
};
const expectedOrderedIds = ["eggs0", "eggs1", "eggs2"];
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate DISTINCT Query with maxItemCount = 20", async function() {
// simple order by query in string format
const query = "SELECT DISTINCT VALUE r.spam3 FROM root r order by r.spam3";
const options = {
maxItemCount: 20
};
const expectedOrderedIds = ["eggs0", "eggs1", "eggs2"];
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate Simple OrderBy Query As String", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate Simple OrderBy Query", async function() {
// simple order by query
const querySpec = {
query: "SELECT * FROM root r order by r.spam"
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy Query With ASC", async function() {
// an order by query with explicit ascending ordering
const querySpec = {
query: "SELECT * FROM root r order by r.spam ASC"
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy Query With DESC", async function() {
// an order by query with explicit descending ordering
const querySpec = {
query: "SELECT * FROM root r order by r.spam DESC"
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.map(function(r) {
return r["id"];
})
.reverse();
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy with top", async function() {
// an order by query with top, total existing docs more than requested top count
const topCount = 9;
const querySpec = {
query: util.format("SELECT top %d * FROM root r order by r.spam", topCount)
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.map(function(r) {
return r["id"];
})
.slice(0, topCount);
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy with Top Query (less results than top counts)", async function() {
// an order by query with top, total existing docs less than requested top count
const topCount = 30;
// sanity check
assert(topCount > documentDefinitions.length, "test setup is wrong");
const querySpec = {
query: util.format("SELECT top %d * FROM root r order by r.spam", topCount)
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate Top Query with maxDegreeOfParallelism = 3", async function() {
// a top query
const topCount = 6;
// sanity check
assert(topCount < documentDefinitions.length, "test setup is wrong");
const query = util.format("SELECT top %d * FROM root r", topCount);
const options = {
maxItemCount: 2,
maxDegreeOfParallelism: 3,
forceQueryPlan: true,
bufferItems: true
};
// prepare expected behaviour verifier
const queryIterator = container.items.query(query, options);
const { resources: results } = await queryIterator.fetchAll();
assert.equal(results.length, topCount);
// select unique ids
const uniqueIds: any = {};
results.forEach(function(item) {
uniqueIds[item.id] = true;
});
// assert no duplicate results
assert.equal(results.length, Object.keys(uniqueIds).length);
});
it("Validate Top Query", async function() {
// a top query
const topCount = 6;
// sanity check
assert(topCount < documentDefinitions.length, "test setup is wrong");
const query = util.format("SELECT top %d * FROM root r", topCount);
const options = {
maxItemCount: 2
};
// prepare expected behaviour verifier
const queryIterator = container.items.query(query, options);
const { resources: results } = await queryIterator.fetchAll();
assert.equal(results.length, topCount);
// select unique ids
const uniqueIds: any = {};
results.forEach(item => {
uniqueIds[item.id] = true;
});
// assert no duplicate results
assert.equal(results.length, Object.keys(uniqueIds).length);
});
it("Validate Top Query (with 0 topCount)", async function() {
// a top query
const topCount = 0;
// sanity check
assert(topCount < documentDefinitions.length, "test setup is wrong");
const query = util.format("SELECT top %d * FROM root r", topCount);
const options = {
maxItemCount: 2
};
// prepare expected behaviour verifier
const queryIterator = container.items.query(query, options);
const { resources: results } = await queryIterator.fetchAll();
assert.equal(results.length, topCount);
// select unique ids
const uniqueIds: any = {};
results.forEach(item => {
uniqueIds[item.id] = true;
});
// assert no duplicate results
assert.equal(results.length, Object.keys(uniqueIds).length);
});
it("Validate Parametrized Top Query", async function() {
// a top query
const topCount = 6;
// sanity check
assert(topCount < documentDefinitions.length, "test setup is wrong");
const querySpec: SqlQuerySpec = {
query: "SELECT top @n * FROM root r",
parameters: [{ name: "@n", value: topCount }]
};
const options = {
maxItemCount: 2
};
// prepare expected behaviour verifier
const queryIterator = container.items.query(querySpec, options);
const { resources: results } = await queryIterator.fetchAll();
assert.equal(results.length, topCount);
// select unique ids
const uniqueIds: any = {};
results.forEach(item => {
uniqueIds[item.id] = true;
});
// assert no duplicate results
assert.equal(results.length, Object.keys(uniqueIds).length);
});
it("Validate OrderBy with Parametrized Top Query", async function() {
// a parametrized top order by query
const topCount = 9;
// sanity check
assert(topCount < documentDefinitions.length, "test setup is wrong");
// a parametrized top order by query
const querySpec = {
query: "SELECT top @n * FROM root r order by r.spam",
parameters: [{ name: "@n", value: topCount }]
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.map(function(r) {
return r["id"];
})
.slice(0, topCount);
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy with Parametrized Predicate", async function() {
// an order by query combined with parametrized predicate
const querySpec = {
query: "SELECT * FROM root r where r.cnt > @cnt order by r.spam",
parameters: [{ name: "@cnt", value: 5 }]
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.filter(function(r) {
return r["cnt"] > 5;
})
.map(function(r) {
return r["id"];
});
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate Error Handling - Orderby where types are noncomparable", async function() {
// test orderby with different order by item type
// an order by query
const query = {
query: "SELECT * FROM root r order by r.spam2"
};
const options = {
maxItemCount: 2
};
// prepare expected behaviour verifier
try {
const queryIterator = container.items.query(query, options);
await queryIterator.fetchAll();
} catch (err) {
assert.notEqual(err, undefined);
}
});
it("Validate OrderBy Integer Query", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.cnt";
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("cnt")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate OrderBy Floating Point Number Query", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.number";
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("number")).map(function(r) {
return r["id"];
});
// validates the results size and order
await executeQueryAndValidateResults({ query, options, expectedOrderIds: expectedOrderedIds });
});
it("Validate OrderBy Boolean Query", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.boolVar";
const options = {
maxItemCount: 2
};
const queryIterator = container.items.query(query, options);
const { resources: results } = await queryIterator.fetchAll();
assert.equal(results.length, documentDefinitions.length);
let index = 0;
while (index < results.length) {
if (results[index].boolVar) {
break;
}
assert(results[index].id % 2 === 1);
index++;
}
while (index < results.length) {
assert(results[index].boolVar);
assert(results[index].id % 2 === 0);
index++;
}
});
it("Validate simple LIMIT OFFSET", async function() {
const limit = 1;
const offset = 7;
const querySpec = {
query: `SELECT * FROM root r OFFSET ${offset} LIMIT ${limit}`
};
const options = {
maxItemCount: 2
};
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedCount: 1,
expectedIteratorCalls: 1
});
});
it("Validate filtered LIMIT OFFSET", async function() {
const limit = 1;
const offset = 2;
// an order by query with explicit ascending ordering
const querySpec = {
query: `SELECT * FROM root r WHERE r.number > 5 OFFSET ${offset} LIMIT ${limit}`
};
const options = {
maxItemCount: 2
};
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedCount: 1
});
});
// TODO Add test for OFFSET LIMT filtered on partition
it("Validate OrderBy Query With ASC and LIMIT 2 and OFFSET 10", async function() {
const limit = 2;
const offset = 10;
// an order by query with explicit ascending ordering
const querySpec = {
query: `SELECT * FROM root r order by r.spam ASC OFFSET ${offset} LIMIT ${limit}`
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.map(function(r) {
return r["id"];
})
.splice(offset, limit);
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate OrderBy Query With ASC and LIMIT 0 and OFFSET 5", async function() {
const limit = 5;
const offset = 0;
// an order by query with explicit ascending ordering
const querySpec = {
query: `SELECT * FROM root r order by r.spam ASC OFFSET ${offset} LIMIT ${limit}`
};
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions
.sort(compare("spam"))
.map(function(r) {
return r["id"];
})
.splice(offset, limit);
// validates the results size and order
await executeQueryAndValidateResults({
query: querySpec,
options,
expectedOrderIds: expectedOrderedIds
});
});
it("Validate Failure", async function() {
// simple order by query in string format
const query = "SELECT * FROM root r order by r.spam";
const options = {
maxItemCount: 2
};
const expectedOrderedIds = documentDefinitions.sort(compare("spam")).map(function(r) {
return r["id"];
});
const queryIterator = container.items.query(query, options);
let firstTime = true;
await queryIterator.fetchNext();
if (firstTime) {
firstTime = false;
}
});
});
}); | the_stack |
import { expect, use } from 'chai';
import chatAsPromised from 'chai-as-promised';
import * as t from 'io-ts';
import 'mocha';
import chaiFpTs from './helpers/chai-fp-ts';
use(chatAsPromised);
use(chaiFpTs);
import * as tPromise from '../src';
describe('io-ts-promise', () => {
describe('readme examples', () => {
const fetch = (url: string): Promise<{ json: () => unknown }> => {
switch (url) {
case 'http://example.com/api/person':
return Promise.resolve({
json: () => ({
name: 'Tester',
age: 24,
}),
});
case 'http://example.com/api/not-a-person':
return Promise.resolve({
json: () => ({}),
});
case 'http://example.com/api/product':
return Promise.resolve({
json: () => ({
name: 'Product',
price: 10,
}),
});
default:
return Promise.reject('404');
}
};
it('provides promise chain decoding', () => {
const Person = t.type({
name: t.string,
age: t.number,
});
const result = fetch('http://example.com/api/person')
.then(response => tPromise.decode(Person, response.json()))
.then(
typeSafeData =>
`${typeSafeData.name} is ${typeSafeData.age} years old`,
);
return expect(result).to.eventually.equal('Tester is 24 years old');
});
it('provides promise chain decoding with carrying', () => {
const Person = t.type({
name: t.string,
age: t.number,
});
const result = fetch('http://example.com/api/person')
.then(response => response.json())
.then(tPromise.decode(Person))
.then(
typeSafeData =>
`${typeSafeData.name} is ${typeSafeData.age} years old`,
);
return expect(result).to.eventually.equal('Tester is 24 years old');
});
it('provides async based decoding', async () => {
const Person = t.type({
name: t.string,
age: t.number,
});
const response = await fetch('http://example.com/api/person');
const typeSafeData = await tPromise.decode(Person, response.json());
const result = `${typeSafeData.name} is ${typeSafeData.age} years old`;
expect(result).to.equal('Tester is 24 years old');
});
it('provides identification of decode errors', () => {
const Person = t.type({
name: t.string,
age: t.number,
});
const result = fetch('http://example.com/api/not-a-person')
.then(response => response.json())
.then(tPromise.decode(Person))
.then(
typeSafeData =>
`${typeSafeData.name} is ${typeSafeData.age} years old`,
)
.catch(error => {
if (tPromise.isDecodeError(error)) {
return 'Request failed due to invalid data.';
} else {
return 'Request failed due to network issues.';
}
});
return expect(result).to.eventually.equal(
'Request failed due to invalid data.',
);
});
it('provides creating custom types by extending existing types', () => {
// New type extending from existing type
const Price = tPromise.extendType(
t.number,
// Decode function takes in number and produces wanted type
(value: number) => ({
currency: 'EUR',
amount: value,
}),
// Encode function does the reverse
price => price.amount,
);
// And use them as part of other types
const Product = t.type({
name: t.string,
price: Price,
});
const result = fetch('http://example.com/api/product')
.then(response => response.json())
.then(tPromise.decode(Product))
.then(
typeSafeData =>
`${typeSafeData.name} costs ${typeSafeData.price.amount} ${typeSafeData.price.currency}`,
);
return expect(result).to.eventually.equal('Product costs 10 EUR');
});
it('provides creating custom types from scratch', () => {
// Custom type from scratch
const Price = tPromise.createType(
// Decode function takes in unknown and produces wanted type
(value: unknown) => {
if (typeof value === 'number') {
return {
currency: 'EUR',
amount: value,
};
} else {
throw new Error('Input is not a number');
}
},
// Encode function does the reverse
price => price.amount,
);
// And use them as part of other types
const Product = t.type({
name: t.string,
price: Price,
});
const result = fetch('http://example.com/api/product')
.then(response => response.json())
.then(tPromise.decode(Product))
.then(
typeSafeData =>
`${typeSafeData.name} costs ${typeSafeData.price.amount} ${typeSafeData.price.currency}`,
);
return expect(result).to.eventually.equal('Product costs 10 EUR');
});
it('provides creating custom decoders by extending existing io-ts types', () => {
const Person = t.type({
name: t.string,
age: t.number,
});
const ExplicitPerson = tPromise.extendDecoder(Person, person => ({
firstName: person.name,
ageInYears: person.age,
}));
const result = fetch('http://example.com/api/person')
.then(response => tPromise.decode(ExplicitPerson, response.json()))
.then(
typeSafeData =>
`${typeSafeData.firstName} is ${typeSafeData.ageInYears} years old`,
);
return expect(result).to.eventually.equal('Tester is 24 years old');
});
});
describe('decode', () => {
it('resolves promise on valid data', () => {
const type = t.string;
const value = 'hello there';
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('resolves promise on falsy string', () => {
const type = t.string;
const value = '';
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('resolves promise on falsy boolean', () => {
const type = t.boolean;
const value = false;
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('resolves promise on falsy number', () => {
const type = t.number;
const value = 0;
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('resolves promise on falsy undefined', () => {
const type = t.undefined;
const value = undefined;
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('resolves promise on falsy null', () => {
const type = t.null;
const value = null;
return expect(tPromise.decode(type, value)).to.eventually.equal(value);
});
it('rejects promise on invalid data', () => {
const type = t.string;
const value = 10;
return expect(
tPromise.decode(type, value),
).to.eventually.be.rejected.and.instanceOf(tPromise.DecodeError);
});
});
describe('decode with curry', () => {
it('resolves promise on valid data', () => {
const type = t.string;
const value = 'hello there';
return expect(tPromise.decode(type)(value)).to.eventually.equal(value);
});
it('rejects promise on invalid data', () => {
const type = t.string;
const value = 10;
return expect(
tPromise.decode(type)(value),
).to.eventually.be.rejected.and.instanceOf(tPromise.DecodeError);
});
});
describe('isDecodeError', () => {
it('identifies errors produced by decode', () => {
const failingPromise = tPromise.decode(t.string, 10);
return expect(failingPromise).to.eventually.be.rejected.and.satisfy(
tPromise.isDecodeError,
);
});
it('identifies other errors', () => {
const nonDecodeError = new Error('test-error');
expect(tPromise.isDecodeError(nonDecodeError)).to.equal(false);
});
});
describe('createType', () => {
const price = tPromise.createType(
(value: unknown) => {
if (typeof value === 'number') {
return {
currency: 'EUR',
value,
};
} else {
throw new Error('Input is not a number');
}
},
value => value.value,
);
runPriceTypeTests(price);
});
describe('extendType', () => {
const price = tPromise.extendType(
t.number,
(value: number) => ({
currency: 'EUR',
value,
}),
value => value.value,
);
runPriceTypeTests(price);
});
function runPriceTypeTests(
price: t.Type<{ currency: string; value: number }, unknown, unknown>,
) {
it('produces type which decodes valid values', () => {
const result = price.decode(10);
expect(result).to.be.right.and.deep.equal({
currency: 'EUR',
value: 10,
});
});
it('produces type which decodes values nested in io-ts types', () => {
const product = t.type({
name: t.string,
price,
});
const result = product.decode({
name: 'thing',
price: 99,
});
expect(result).to.right.and.deep.equal({
name: 'thing',
price: {
currency: 'EUR',
value: 99,
},
});
});
it('fails to decode invalid values', () => {
const result = price.decode('10€');
expect(result).to.be.left.and.instanceOf(Array);
});
it('produces type which identifies matching values with typeguard', () => {
expect(
price.is({
currency: 'EUR',
value: 10,
}),
).to.equal(true);
});
it('produces type which identifies nonmatching values with typeguard', () => {
expect(price.is('10€')).to.equal(false);
expect(price.is(10)).to.equal(false);
expect(
price.is({
sum: 10,
}),
).to.equal(false);
expect(
price.is({
currency: 'USD',
value: 10,
}),
).to.equal(false);
});
}
describe('createDecoder', () => {
const price = tPromise.createDecoder((value: unknown) => {
if (typeof value === 'number') {
return {
currency: 'EUR',
value,
};
} else {
throw new Error('Input is not a number');
}
});
runPriceDecoerTests(price);
});
describe('extendDecoder', () => {
const price = tPromise.extendDecoder(t.number, (value: number) => ({
currency: 'EUR',
value,
}));
runPriceDecoerTests(price);
});
function runPriceDecoerTests(
price: t.Decoder<
unknown,
{
currency: string;
value: number;
}
>,
) {
it('produces decoder which succeeds to decode valid values', () => {
const result = price.decode(10);
expect(result).to.be.right.and.deep.equal({
currency: 'EUR',
value: 10,
});
});
it('produces decoder which fails to decode invalid values', () => {
const result = price.decode('10€');
expect(result).to.be.left.and.instanceOf(Array);
});
}
}); | the_stack |
import * as os from "os";
import * as path from "path";
import * as blessed from "neo-blessed";
import { Widgets } from "neo-blessed";
import { sprintf } from "sprintf-js";
import { File } from "../common/File";
import { Reader } from "../common/Reader";
import { Mcd } from "../panel/Mcd";
import { Widget } from "./widget/Widget";
import { Dir } from "../common/Dir";
import { Color } from "../common/Color";
import { ColorConfig } from "../config/ColorConfig";
import { Logger } from "../common/Logger";
import { KeyMapping, IHelpService, SearchDisallowKeys, RefreshType } from "../config/KeyMapConfig";
import { KeyMappingInfo } from "../config/KeyMapConfig";
import { IBlessedView } from "./IBlessedView";
import mainFrame from "./MainFrame";
import { SearchFileBox } from "./SearchFileBox";
const log = Logger("blessed-mcd");
class SearchDirInfo {
private _index = -1;
private _dirs: Dir[] = [];
constructor(dirs: Dir[]) {
this.dirs = dirs || [];
}
next() {
this.index = this.index + 1;
return this.get();
}
get index() {
return this._index;
}
set index(index) {
if (index >= this._dirs.length) {
this._index = 0;
} else if (index < 0) {
this._index = 0;
} else {
this._index = index;
}
}
get dirs() {
return this._dirs || [];
}
set dirs(dirs: Dir[]) {
if (dirs && dirs.length) {
this._dirs = dirs || [];
this._index = 0;
} else {
this._dirs = [];
this._index = -1;
}
}
get() {
if (this._dirs.length === 0) {
return null;
}
return this._dirs[this.index];
}
}
class McdDirButton extends Widget {
node: Dir;
select: boolean;
showCheck: boolean;
mcdColor: Color;
lineColor: Color;
parentMcd: BlessedMcd;
constructor( opts: Widgets.BoxOptions | any, node: Dir, parent: BlessedMcd ) {
super(opts);
this.mcdColor = ColorConfig.instance().getBaseColor("mcd");
this.lineColor = ColorConfig.instance().getBaseColor("mcd_line");
this.node = node;
this.select = false;
this.showCheck = false;
this.parentMcd = parent;
this.on("widget.click", () => {
if ( !mainFrame().hasLockAndLastFocus() ) {
this.parentMcd && this.parentMcd.onDirButtonClick(this);
}
});
this.on("widget.click", async () => {
if ( !mainFrame().hasLockAndLastFocus() ) {
this.parentMcd && await this.parentMcd.keyEnterPromise();
mainFrame().execRefreshType( RefreshType.ALL );
}
});
}
draw() {
if ( !this.node ) {
return;
}
const width = this.width as number;
this.box.style = this.select ? this.mcdColor.blessedReverse : this.mcdColor.blessed;
let content = "";
const name = this.node.file.name;
const nameSize: any = this.box.strWidth(name);
if ( nameSize < this.width ) {
content = name;
if ( this.node.subDir.length ) {
blessed.box( { parent: this.box, top: 0, left: nameSize, width: width - nameSize, height: 1, content: "─".repeat( width - nameSize ), style: this.lineColor.blessed } );
}
} else {
content = sprintf( `%-${width-1}.${width-1}s~`, name );
}
content = "{bold}" + content + "{/bold}";
this.setContent(content);
}
setDir( node: Dir, select: boolean ) {
this.node = node;
this.select = select;
this.showCheck = true;
}
}
@KeyMapping( KeyMappingInfo.Mcd )
export class BlessedMcd extends Mcd implements IBlessedView, IHelpService {
buttonList: McdDirButton[] = [];
lines: Widgets.BoxElement[] = [];
mcdColor: Color;
lineColor: Color;
mcdHighlightColor: Color;
baseWidget: Widget = null;
mcdWidget: Widget = null;
header: Widget = null;
searchWidget: Widget = null;
pathWidget: Widget = null;
viewDepthSize: number = 0;
firstScanPath: File = null;
public searchFileBox: SearchFileBox = null;
_searchDirs: SearchDirInfo = null;
constructor( opts: Widgets.BoxOptions | any, reader: Reader = null, firstScanPath = null ) {
super( reader );
this.firstScanPath = firstScanPath;
const colorConfig = ColorConfig.instance();
this.mcdColor = colorConfig.getBaseColor("mcd");
this.lineColor = colorConfig.getBaseColor("mcd_line");
this.lineColor = colorConfig.getBaseColor("mcd_line");
this.mcdHighlightColor = colorConfig.getBaseColor("mcd_highlight");
const statColor = colorConfig.getBaseColor("stat");
this.baseWidget = new Widget( { ...opts } );
this.mcdWidget = new Widget( { parent: this.baseWidget, top: 1, left: 0, height: "100%", width: "100%", border: "line", style: { ...this.mcdColor.blessed, border: this.lineColor.blessed } } );
this.pathWidget = new Widget( { parent: this.baseWidget, top: "100%", left: 2, height: 1, style: { ...this.mcdColor.blessed, border: this.lineColor.blessed } } );
this.header = new Widget({
parent: this.baseWidget,
left: 0,
top: 0,
type: "bg",
width: "100%",
height: 1,
bg: statColor.back,
style: {
bg: statColor.back,
fg: statColor.font
}
});
this.initRender();
}
public getConfigPath() {
return os.homedir() + path.sep + ".m" + path.sep + "mcd.json";
}
viewName() {
return "Mcd";
}
setBoxDraw( _boxDraw: boolean ) {
return true;
}
hasBoxDraw(): boolean {
return true;
}
hide() {
this.baseWidget.hide();
}
show() {
this.baseWidget.show();
}
destroy() {
log.debug( "MCD - destroy()" );
this.save();
this.baseWidget.destroy();
}
setReader( reader: Reader ) {
super.setReader( reader );
}
getWidget() {
return this.baseWidget;
}
setFocus() {
this.baseWidget.setFocus();
}
hasFocus(): boolean {
return this.baseWidget.hasFocus();
}
initRender() {
this.baseWidget.on( "prerender", () => {
log.debug( "BlessedMcd prerender - %d", this.baseWidget._viewCount );
this.resize();
this.beforeRender();
});
this.baseWidget.on( "render", () => {
this.afterRender();
});
this.baseWidget.on("detach", () => {
log.debug( "mcd detach !!! - %d", this.baseWidget._viewCount );
});
}
beforeRender() {
let MCD_TEXT_SIZE = 12;
const MAX_MCD_TEXT_SIZE = 40;
const MIN_TEXT_SIZE_OF_WIDTH = 120;
const MCD_BASE_COL_POS = [ 0, 7 ];
this.mcdWidget.height = this.baseWidget.height as number - 1;
const width: number = this.mcdWidget.width as number;
if ( width <= MIN_TEXT_SIZE_OF_WIDTH ) {
MCD_TEXT_SIZE = 12;
} else {
MCD_TEXT_SIZE = MCD_TEXT_SIZE + Math.round( (width - MIN_TEXT_SIZE_OF_WIDTH) / (width / (MAX_MCD_TEXT_SIZE - MCD_TEXT_SIZE)) );
if ( MCD_TEXT_SIZE > MAX_MCD_TEXT_SIZE ) {
MCD_TEXT_SIZE = MAX_MCD_TEXT_SIZE;
}
}
{
let i = 7;
do {
i = i + (MCD_TEXT_SIZE + 2);
MCD_BASE_COL_POS.push( i );
} while( width >= i );
}
this.viewDepthSize = MCD_BASE_COL_POS.reduce( (viewDepthSize: number, col: number, i: number) => {
if ( (this.mcdWidget.width as number) - (MCD_TEXT_SIZE + 6) < col ) {
viewDepthSize = i - 2;
}
return viewDepthSize;
}, 0);
// log.debug( "MCD_TEXT_SIZE: %d, [%d]", MCD_TEXT_SIZE, this.viewDepthSize);
this.lines.map( item => item.destroy() );
this.lines = [];
if (this.buttonList.length) {
this.buttonList.map( i => i.destroy() );
this.buttonList = [];
}
const arrayLineCh = [];
let row = 0, col = 0, nODep = 0;
const height = (this.mcdWidget.height as number);
const curDir: Dir = this.currentDir();
if ( curDir.row - this.scrollRow > height - 3 ) {
this.scrollRow = curDir.row - height + 3;
}
if ( curDir.depth - this.scrollCol > this.viewDepthSize ) {
this.scrollCol = curDir.depth - this.viewDepthSize;
}
if ( curDir.row - this.scrollRow < 0 ) {
this.scrollRow = curDir.row;
}
if ( curDir.depth - this.scrollCol < 1 ) {
this.scrollCol = curDir.depth - 1;
if ( this.scrollCol <= -1) {
this.scrollCol = 0;
}
}
for ( const node of this.arrOrder ) {
if ( nODep < node.depth ) {
arrayLineCh.push( "│" );
} else {
while( node.depth < nODep ) {
nODep--;
arrayLineCh.pop();
}
}
nODep = node.depth;
col = node.depth;
row = node.row;
// log.info("nODep [%d] col [%d] row [%d] scrollRow [%d] scrollCol [%d]", nODep, col, row, this.scrollRow, this.scrollCol);
// log.info("NCurses::Draw pNode->nDepth [%d]", node.depth);
if ( node.index !== 0 && node.parentDir && node.parentDir.subDir[node.parentDir.subDir.length - 1].index === node.index ) {
arrayLineCh[col - 1] = " ";
}
if ( row - this.scrollRow > height - 3 ) {
break;
}
if ( row - this.scrollRow < 0 ) continue;
if ( node.index !== this.rootDir.index && node.parentDir && node.parentDir.subDir[0].index !== node.index ) {
for ( let t = this.scrollCol; t < col && t < this.scrollCol + this.viewDepthSize; t++ ) {
this.lines.push(
blessed.box( { parent: this.mcdWidget.box, top: row - this.scrollRow, left: MCD_BASE_COL_POS[t - this.scrollCol + 1], width: 1, height : 1, content: arrayLineCh[t], style: this.lineColor.blessed } )
);
}
}
if ( col - this.scrollCol > this.viewDepthSize ) continue;
if ( this.scrollCol !== 0 && col - this.scrollCol < 1 ) continue;
const dirButton: McdDirButton = new McdDirButton( { parent: this.mcdWidget, width: MCD_TEXT_SIZE, height: 1 }, node, this );
if ( node.depth === 0 ) {
dirButton.left = row - this.scrollRow + 1;
dirButton.top = 0;
} else {
const opts = {
parent: this.mcdWidget.box,
top: row - this.scrollRow,
left: MCD_BASE_COL_POS[col-this.scrollCol],
width: 1,
height : 1, style: this.lineColor.blessed };
if ( node.parentDir.subDir.length > 1 ) {
if ( node.parentDir.subDir[0].index === node.index ) {
this.lines.push(
blessed.box( { ...opts, content: "┬" } )
);
} else {
const content = node.parentDir.subDir[ node.parentDir.subDir.length - 1].index === node.index ? "└" : "├";
this.lines.push(
blessed.box( { ...opts, content } )
);
}
} else {
this.lines.push(
blessed.box( { ...opts, content: "─" } )
);
}
this.lines.push(
blessed.box( { ...opts, left: opts.left + 1, content: node.check ? "─" : "+", style: node.check ? this.lineColor.blessed : this.mcdHighlightColor.blessed } )
);
dirButton.left = opts.left + 2;
dirButton.top = opts.top;
}
dirButton.setDir( node, node.index === curDir.index ? this.hasFocus() : false );
//log.debug("dirButton : [%20s] row [%d] left [%d] top [%d]", dirButton.node.file.name, node.row, dirButton.left, dirButton.top );
this.buttonList.push( dirButton );
}
this.header.width = this.baseWidget.width;
log.debug("header : %d, %j", this.header.width, this.header.box.style );
this.header.setContent( curDir.file.fullname );
this.pathWidget.top = this.baseWidget.height as number - 1;
this.pathWidget.left = 2;
this.pathWidget.width = curDir.file.fullname.length + 9;
this.pathWidget.setContentFormat( "Path [ {bold}%s{/bold} ]", curDir.file.fullname );
}
onDirButtonClick( button: McdDirButton ) {
if ( button && button.node && button.node.index ) {
this.curDirInx = button.node.index;
mainFrame().execRefreshType( RefreshType.OBJECT );
}
}
searchDirTabKey() {
if (this.searchFileBox.value) {
const dir = this._searchDirs.next();
if ( dir ) {
this.setCurrentDir(dir.file.fullname);
}
}
}
searchDirAndFocus() {
if ( !this.searchFileBox || !this.searchFileBox.value) {
return;
}
const searchExp = new RegExp(this.searchFileBox.value, "i");
this._searchDirs = new SearchDirInfo(this.arrOrder.filter(item => searchExp.test(item.file.name)));
log.debug("SEARCH FILES : length [%d] [%j]", this._searchDirs.dirs?.length, this._searchDirs.get()?.file);
if (!this._searchDirs.get()) {
this.searchFileBox.updateLastChar();
} else {
this.setCurrentDir( this._searchDirs.get().file.fullname );
}
}
async keyInputSearchFile(ch, keyInfo): Promise<number> {
if (!this.searchFileBox || !this.searchFileBox.value) {
const keyName = keyInfo.full || keyInfo.name;
if (SearchDisallowKeys.indexOf(keyName) > -1) {
log.debug("ignore key - [%s]", keyName);
return -1;
}
}
if (!this.searchFileBox) {
this.searchFileBox = new SearchFileBox({ parent: this.baseWidget });
this.searchFileBox.on("TAB_KEY", () => {
this.searchDirTabKey();
});
}
const result = await this.searchFileBox.executePromise(ch, keyInfo);
if (result && keyInfo && keyInfo.name !== "tab") {
this.searchDirAndFocus();
}
if (result) {
this.baseWidget.render();
return 1;
}
if ( this.searchFileBox.value ) {
this.searchFileBox.clear();
return -2;
}
return 0;
}
afterRender() {
log.debug("afterRender !!!");
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
resize() {
}
render() {
this.baseWidget.render();
}
keyPageDown() {
const node = this.getDirRowArea( this.currentDir().row + (this.mcdWidget.box.height as number - 3), this.currentDir().depth, this.currentDir() );
if ( node ) {
this.curDirInx = node.index;
}
}
keyPageUp() {
const node = this.getDirRowArea( this.currentDir().row - (this.mcdWidget.box.height as number + 3), this.currentDir().depth, this.currentDir() );
if ( node ) {
this.curDirInx = node.index;
}
}
async keyEnterPromise() {
await mainFrame().mcdPromise(false);
}
async keyEscapePromise() {
await mainFrame().mcdPromise(true);
}
} | the_stack |
import cp from 'child_process'
import { Document, ServiceStat, Uri, window, workspace } from 'coc.nvim'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { CancellationToken, CancellationTokenSource, Disposable, Emitter, Event } from 'vscode-languageserver-protocol'
import * as fileSchemes from '../utils/fileSchemess'
import { PluginManager } from '../utils/plugins'
import { CallbackMap } from './callbackMap'
import BufferSyncSupport from './features/bufferSyncSupport'
import { DiagnosticKind, DiagnosticsManager } from './features/diagnostics'
import FileConfigurationManager from './features/fileConfigurationManager'
import * as Proto from './protocol'
import { RequestItem, RequestQueue, RequestQueueingType } from './requestQueue'
import { ExecConfig, ITypeScriptServiceClient, ServerResponse } from './typescriptService'
import API from './utils/api'
import { TsServerLogLevel, TypeScriptServiceConfiguration } from './utils/configuration'
import Logger from './utils/logger'
import { fork, getTempDirectory, getTempFile, IForkOptions, makeRandomHexString } from './utils/process'
import Tracer from './utils/tracer'
import { inferredProjectConfig } from './utils/tsconfig'
import { TypeScriptVersion, TypeScriptVersionProvider } from './utils/versionProvider'
import VersionStatus from './utils/versionStatus'
import { ICallback, Reader } from './utils/wireProtocol'
interface ToCancelOnResourceChanged {
readonly resource: string
cancel(): void
}
class ForkedTsServerProcess {
constructor(private childProcess: cp.ChildProcess) {}
public readonly toCancelOnResourceChange = new Set<ToCancelOnResourceChanged>()
public onError(cb: (err: Error) => void): void {
this.childProcess.on('error', cb)
}
public onExit(cb: (err: any) => void): void {
this.childProcess.on('exit', cb)
}
public write(serverRequest: Proto.Request): void {
this.childProcess.stdin.write(
JSON.stringify(serverRequest) + '\r\n',
'utf8'
)
}
public createReader(
callback: ICallback<Proto.Response>,
onError: (error: any) => void
): void {
// tslint:disable-next-line:no-unused-expression
new Reader<Proto.Response>(this.childProcess.stdout, callback, onError)
}
public kill(): void {
this.childProcess.kill()
}
}
export interface TsDiagnostics {
readonly kind: DiagnosticKind
readonly resource: Uri
readonly diagnostics: Proto.Diagnostic[]
}
export default class TypeScriptServiceClient implements ITypeScriptServiceClient {
public state = ServiceStat.Initial
public readonly logger: Logger = new Logger()
public readonly bufferSyncSupport: BufferSyncSupport
public readonly diagnosticsManager: DiagnosticsManager
private fileConfigurationManager: FileConfigurationManager
private pathSeparator: string
private tracer: Tracer
private _configuration: TypeScriptServiceConfiguration
private versionProvider: TypeScriptVersionProvider
private tsServerLogFile: string | null = null
private tsServerProcess: ForkedTsServerProcess | undefined
private servicePromise: Thenable<ForkedTsServerProcess> | null
private lastError: Error | null
private lastStart: number
private numberRestarts: number
private cancellationPipeName: string | null = null
private _callbacks = new CallbackMap<Proto.Response>()
private _requestQueue = new RequestQueue()
private _pendingResponses = new Set<number>()
private versionStatus: VersionStatus
private readonly _onTsServerStarted = new Emitter<API>()
private readonly _onProjectLanguageServiceStateChanged = new Emitter<Proto.ProjectLanguageServiceStateEventBody>()
private readonly _onDidBeginInstallTypings = new Emitter<Proto.BeginInstallTypesEventBody>()
private readonly _onDidEndInstallTypings = new Emitter<Proto.EndInstallTypesEventBody>()
private readonly _onTypesInstallerInitializationFailed = new Emitter<
Proto.TypesInstallerInitializationFailedEventBody
>()
private _apiVersion: API
private _tscPath: string
private readonly disposables: Disposable[] = []
private isRestarting = false
constructor(
public readonly pluginManager: PluginManager,
public readonly modeIds: string[]
) {
this.pathSeparator = path.sep
this.lastStart = Date.now()
this.servicePromise = null
this.lastError = null
this.numberRestarts = 0
this.fileConfigurationManager = new FileConfigurationManager(this)
this._configuration = TypeScriptServiceConfiguration.loadFromWorkspace()
this.versionProvider = new TypeScriptVersionProvider(this._configuration)
this._apiVersion = API.defaultVersion
this.tracer = new Tracer(this.logger)
this.versionStatus = new VersionStatus(this.normalizePath.bind(this), this.fileConfigurationManager.enableJavascript())
pluginManager.onDidUpdateConfig(update => {
this.configurePlugin(update.pluginId, update.config)
}, null, this.disposables)
pluginManager.onDidChangePlugins(() => {
this.restartTsServer()
}, null, this.disposables)
this.bufferSyncSupport = new BufferSyncSupport(this, modeIds)
this.onTsServerStarted(() => {
this.bufferSyncSupport.listen()
})
this.diagnosticsManager = new DiagnosticsManager()
this.bufferSyncSupport.onDelete(resource => {
this.cancelInflightRequestsForResource(resource)
this.diagnosticsManager.delete(resource)
}, null, this.disposables)
this.bufferSyncSupport.onWillChange(resource => {
this.cancelInflightRequestsForResource(resource)
})
}
private _onDiagnosticsReceived = new Emitter<TsDiagnostics>()
public get onDiagnosticsReceived(): Event<TsDiagnostics> {
return this._onDiagnosticsReceived.event
}
private _onConfigDiagnosticsReceived = new Emitter<Proto.ConfigFileDiagnosticEvent>()
public get onConfigDiagnosticsReceived(): Event<Proto.ConfigFileDiagnosticEvent> {
return this._onConfigDiagnosticsReceived.event
}
private _onResendModelsRequested = new Emitter<void>()
public get onResendModelsRequested(): Event<void> {
return this._onResendModelsRequested.event
}
public get configuration(): TypeScriptServiceConfiguration {
return this._configuration
}
public dispose(): void {
if (this.servicePromise) {
this.servicePromise
.then(childProcess => {
childProcess.kill()
})
.then(undefined, () => void 0)
}
this.bufferSyncSupport.dispose()
this.logger.dispose()
this._onTsServerStarted.dispose()
this._onResendModelsRequested.dispose()
this.versionStatus.dispose()
}
private info(message: string, data?: any): void {
this.logger.info(message, data)
}
private error(message: string, data?: any): void {
this.logger.error(message, data)
}
public restartTsServer(): Promise<any> {
const start = () => {
this.servicePromise = this.startService(true)
return this.servicePromise
}
if (this.servicePromise) {
return Promise.resolve(this.servicePromise.then(childProcess => {
this.state = ServiceStat.Stopping
this.info('Killing TS Server')
this.isRestarting = true
childProcess.kill()
this.servicePromise = null
}).then(start))
} else {
return Promise.resolve(start())
}
}
public stop(): Promise<void> {
if (!this.servicePromise) return
return new Promise((resolve, reject) => {
this.servicePromise.then(childProcess => {
if (this.state == ServiceStat.Running) {
this.info('Killing TS Server')
childProcess.onExit(() => {
resolve()
})
childProcess.kill()
this.servicePromise = null
} else {
resolve()
}
}, reject)
})
}
public get onTsServerStarted(): Event<API> {
return this._onTsServerStarted.event
}
public get onProjectLanguageServiceStateChanged(): Event<
Proto.ProjectLanguageServiceStateEventBody
> {
return this._onProjectLanguageServiceStateChanged.event
}
public get onDidBeginInstallTypings(): Event<Proto.BeginInstallTypesEventBody> {
return this._onDidBeginInstallTypings.event
}
public get onDidEndInstallTypings(): Event<Proto.EndInstallTypesEventBody> {
return this._onDidEndInstallTypings.event
}
public get onTypesInstallerInitializationFailed(): Event<Proto.TypesInstallerInitializationFailedEventBody> {
return this._onTypesInstallerInitializationFailed.event
}
public get apiVersion(): API {
return this._apiVersion
}
public get tscPath(): string {
return this._tscPath
}
private service(): Thenable<ForkedTsServerProcess> {
if (this.servicePromise) {
return this.servicePromise
}
if (this.lastError) {
return Promise.reject<ForkedTsServerProcess>(this.lastError)
}
return this.startService().then(() => {
if (this.servicePromise) {
return this.servicePromise
}
})
}
public ensureServiceStarted(): void {
if (!this.servicePromise) {
this.startService().catch(err => {
window.showMessage(`TSServer start failed: ${err.message}`, 'error')
this.error(`Service start failed: ${err.stack}`)
})
}
}
private async startService(resendModels = false): Promise<ForkedTsServerProcess> {
const { ignoreLocalTsserver } = this.configuration
let currentVersion: TypeScriptVersion
if (!ignoreLocalTsserver) currentVersion = this.versionProvider.getLocalVersion()
if (!currentVersion || !fs.existsSync(currentVersion.tsServerPath)) {
currentVersion = this.versionProvider.getDefaultVersion()
}
if (!currentVersion || !currentVersion.isValid) {
if (this.configuration.globalTsdk) {
window.showMessage(`Can not find typescript module, in 'tsserver.tsdk': ${this.configuration.globalTsdk}`, 'error')
} else {
window.showMessage(`Can not find typescript module, run ':CocInstall coc-tsserver' to fix it!`, 'error')
}
return
}
this._apiVersion = currentVersion.version
this._tscPath = currentVersion.tscPath
this.versionStatus.onDidChangeTypeScriptVersion(currentVersion)
this.lastError = null
const tsServerForkArgs = await this.getTsServerArgs(currentVersion)
const debugPort = this._configuration.debugPort
const maxTsServerMemory = this._configuration.maxTsServerMemory
const options = {
execArgv: [
...(debugPort ? [`--inspect=${debugPort}`] : []), // [`--debug-brk=5859`]
...(maxTsServerMemory ? [`--max-old-space-size=${maxTsServerMemory}`] : []),
],
cwd: workspace.root
}
this.servicePromise = this.startProcess(currentVersion, tsServerForkArgs, options, resendModels)
return this.servicePromise
}
private startProcess(currentVersion: TypeScriptVersion, args: string[], options: IForkOptions, resendModels: boolean): Promise<ForkedTsServerProcess> {
this.state = ServiceStat.Starting
return new Promise((resolve, reject) => {
try {
fork(
currentVersion.tsServerPath,
args,
options,
this.logger,
(err: any, childProcess: cp.ChildProcess | null) => {
if (err || !childProcess) {
this.state = ServiceStat.StartFailed
this.lastError = err
this.error('Starting TSServer failed with error.', err.stack)
return
}
this.state = ServiceStat.Running
this.info('Started TSServer', JSON.stringify(currentVersion, null, 2))
const handle = new ForkedTsServerProcess(childProcess)
this.tsServerProcess = handle
this.lastStart = Date.now()
handle.onError((err: Error) => {
this.lastError = err
this.error('TSServer errored with error.', err)
this.error(`TSServer log file: ${this.tsServerLogFile || ''}`)
window.showMessage(`TSServer errored with error. ${err.message}`, 'error')
this.serviceExited(false)
})
handle.onExit((code: any) => {
if (code == null) {
this.info('TSServer normal exit')
} else {
this.error(`TSServer exited with code: ${code}`)
}
this.info(`TSServer log file: ${this.tsServerLogFile || ''}`)
this.serviceExited(!this.isRestarting)
this.isRestarting = false
})
handle.createReader(
msg => {
this.dispatchMessage(msg)
},
error => {
this.error('ReaderError', error)
}
)
resolve(handle)
this.serviceStarted(resendModels)
this._onTsServerStarted.fire(currentVersion.version)
}
)
} catch (e) {
reject(e)
}
})
}
public async openTsServerLogFile(): Promise<boolean> {
const isRoot = process.getuid && process.getuid() == 0
let echoErr = (msg: string) => {
window.showMessage(msg, 'error')
}
if (isRoot) {
echoErr('Log disabled for root user.')
return false
}
if (!this.apiVersion.gte(API.v222)) {
echoErr('TS Server logging requires TS 2.2.2+')
return false
}
if (this._configuration.tsServerLogLevel === TsServerLogLevel.Off) {
echoErr(`TS Server logging is off. Change 'tsserver.log' in 'coc-settings.json' to enable`)
return false
}
if (!this.tsServerLogFile) {
echoErr('TS Server has not started logging.')
return false
}
try {
await workspace.nvim.command(`edit ${this.tsServerLogFile}`)
return true
} catch {
echoErr('Could not open TS Server log file')
return false
}
}
private serviceStarted(resendModels: boolean): void {
this.bufferSyncSupport.reset()
const watchOptions = this.apiVersion.gte(API.v380)
? this.configuration.watchOptions
: undefined
const configureOptions: Proto.ConfigureRequestArguments = {
hostInfo: 'coc-nvim',
preferences: {
providePrefixAndSuffixTextForRename: true,
allowRenameOfImportPath: true,
},
watchOptions
}
this.executeWithoutWaitingForResponse('configure', configureOptions) // tslint:disable-line
this.setCompilerOptionsForInferredProjects(this._configuration)
if (resendModels) {
this._onResendModelsRequested.fire(void 0)
this.fileConfigurationManager.reset()
this.diagnosticsManager.reInitialize()
this.bufferSyncSupport.reinitialize()
}
// Reconfigure any plugins
for (const [config, pluginName] of this.pluginManager.configurations()) {
this.configurePlugin(config, pluginName)
}
}
private setCompilerOptionsForInferredProjects(
configuration: TypeScriptServiceConfiguration
): void {
if (!this.apiVersion.gte(API.v206)) return
const args: Proto.SetCompilerOptionsForInferredProjectsArgs = {
options: this.getCompilerOptionsForInferredProjects(configuration)
}
this.executeWithoutWaitingForResponse('compilerOptionsForInferredProjects', args) // tslint:disable-line
}
private getCompilerOptionsForInferredProjects(
configuration: TypeScriptServiceConfiguration
): Proto.ExternalProjectCompilerOptions {
return {
...inferredProjectConfig(configuration),
allowJs: true,
allowSyntheticDefaultImports: true,
allowNonTsExtensions: true
}
}
private serviceExited(restart: boolean): void {
this.state = ServiceStat.Stopped
this.servicePromise = null
this.tsServerLogFile = null
this._callbacks.destroy('Service died.')
this._callbacks = new CallbackMap<Proto.Response>()
this._requestQueue = new RequestQueue()
this._pendingResponses = new Set<number>()
if (restart) {
const diff = Date.now() - this.lastStart
this.numberRestarts++
let startService = true
if (this.numberRestarts > 5) {
this.numberRestarts = 0
if (diff < 10 * 1000 /* 10 seconds */) {
this.lastStart = Date.now()
startService = false
window.showMessage('The TypeScript language service died 5 times right after it got started.', 'error') // tslint:disable-line
} else if (diff < 60 * 1000 /* 1 Minutes */) {
this.lastStart = Date.now()
window.showMessage('The TypeScript language service died unexpectedly 5 times in the last 5 Minutes.', 'error') // tslint:disable-line
}
}
if (startService) {
this.startService(true) // tslint:disable-line
}
}
}
public toPath(uri: string): string {
return this.normalizePath(Uri.parse(uri))
}
public toOpenedFilePath(uri: string, options: { suppressAlertOnFailure?: boolean } = {}): string | undefined {
if (!this.bufferSyncSupport.ensureHasBuffer(uri)) {
if (!options.suppressAlertOnFailure) {
console.error(`Unexpected resource ${uri}`)
}
return undefined
}
return this.toPath(uri)
}
public toResource(filepath: string): string {
if (this._apiVersion.gte(API.v213)) {
if (filepath.startsWith(this.inMemoryResourcePrefix + 'untitled:')) {
let resource = Uri.parse(filepath)
if (this.inMemoryResourcePrefix) {
const dirName = path.dirname(resource.path)
const fileName = path.basename(resource.path)
if (fileName.startsWith(this.inMemoryResourcePrefix)) {
resource = resource.with({ path: path.posix.join(dirName, fileName.slice(this.inMemoryResourcePrefix.length)) })
}
}
return resource.toString()
}
}
return Uri.file(filepath).toString()
}
public normalizePath(resource: Uri): string | undefined {
if (fileSchemes.disabledSchemes.has(resource.scheme)) {
return undefined
}
switch (resource.scheme) {
case fileSchemes.file: {
let result = resource.fsPath
if (!result) return undefined
result = path.normalize(result)
// Both \ and / must be escaped in regular expressions
return result.replace(new RegExp('\\' + this.pathSeparator, 'g'), '/')
}
default: {
return this.inMemoryResourcePrefix + resource.toString(true)
}
}
}
public getDocument(resource: string): Document | undefined {
if (resource.startsWith('untitled:')) {
let bufnr = parseInt(resource.split(':', 2)[1], 10)
return workspace.getDocument(bufnr)
}
return workspace.getDocument(resource)
}
private get inMemoryResourcePrefix(): string {
return this._apiVersion.gte(API.v270) ? '^' : ''
}
public asUrl(filepath: string): Uri {
if (this._apiVersion.gte(API.v213)) {
if (filepath.startsWith(this.inMemoryResourcePrefix + 'untitled:')) {
let resource = Uri.parse(filepath.slice(this.inMemoryResourcePrefix.length))
if (this.inMemoryResourcePrefix) {
const dirName = path.dirname(resource.path)
const fileName = path.basename(resource.path)
if (fileName.startsWith(this.inMemoryResourcePrefix)) {
resource = resource.with({
path: path.posix.join(
dirName,
fileName.slice(this.inMemoryResourcePrefix.length)
)
})
}
}
return resource
}
}
return Uri.file(filepath)
}
public execute(
command: string, args: any,
token: CancellationToken,
config?: ExecConfig
): Promise<ServerResponse.Response<Proto.Response>> {
let execution: Promise<ServerResponse.Response<Proto.Response>>
if (config?.cancelOnResourceChange) {
const source = new CancellationTokenSource()
token.onCancellationRequested(() => source.cancel())
const inFlight: ToCancelOnResourceChanged = {
resource: config.cancelOnResourceChange,
cancel: () => source.cancel(),
}
this.tsServerProcess?.toCancelOnResourceChange.add(inFlight)
execution = this.executeImpl(command, args, {
isAsync: false,
token: source.token,
expectsResult: true,
...config,
}).finally(() => {
this.tsServerProcess?.toCancelOnResourceChange.delete(inFlight)
source.dispose()
})
} else {
execution = this.executeImpl(command, args, {
isAsync: false,
token,
expectsResult: true,
...config,
})
}
if (config?.nonRecoverable) {
execution.catch(err => this.fatalError(command, err))
}
return execution
}
private fatalError(command: string, error: any): void {
console.error(`A non-recoverable error occured while executing tsserver command: ${command}`)
if (this.state === ServiceStat.Running) {
this.info('Killing TS Server by fatal error:', error)
this.service().then(service => {
service.kill()
})
}
}
public executeAsync(
command: string, args: Proto.GeterrRequestArgs,
token: CancellationToken): Promise<ServerResponse.Response<Proto.Response>> {
return this.executeImpl(command, args, {
isAsync: true,
token,
expectsResult: true
})
}
public executeWithoutWaitingForResponse(command: string, args: any): void {
this.executeImpl(command, args, {
isAsync: false,
token: undefined,
expectsResult: false
})
}
private executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: CancellationToken, expectsResult: false, lowPriority?: boolean }): undefined
private executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: CancellationToken, expectsResult: boolean, lowPriority?: boolean }): Promise<ServerResponse.Response<Proto.Response>>
private executeImpl(command: string, args: any, executeInfo: { isAsync: boolean, token?: CancellationToken, expectsResult: boolean, lowPriority?: boolean }): Promise<ServerResponse.Response<Proto.Response>> | undefined {
if (this.servicePromise == null) {
return Promise.resolve(undefined)
}
this.bufferSyncSupport.beforeCommand(command)
const request = this._requestQueue.createRequest(command, args)
const requestInfo: RequestItem = {
request,
expectsResponse: executeInfo.expectsResult,
isAsync: executeInfo.isAsync,
queueingType: getQueueingType(command, executeInfo.lowPriority)
}
let result: Promise<ServerResponse.Response<Proto.Response>> | undefined
if (executeInfo.expectsResult) {
result = new Promise<ServerResponse.Response<Proto.Response>>((resolve, reject) => {
this._callbacks.add(request.seq, { onSuccess: resolve, onError: reject, startTime: Date.now(), isAsync: executeInfo.isAsync }, executeInfo.isAsync)
if (executeInfo.token) {
executeInfo.token.onCancellationRequested(() => {
this.tryCancelRequest(request.seq, command)
})
}
}).catch((err: Error) => {
throw err
})
}
this._requestQueue.enqueue(requestInfo)
this.sendNextRequests()
return result
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.dequeue()
if (item) {
this.sendRequest(item)
}
}
}
private sendRequest(requestItem: RequestItem): void {
const serverRequest = requestItem.request
this.tracer.traceRequest(serverRequest, requestItem.expectsResponse, this._requestQueue.length)
if (requestItem.expectsResponse && !requestItem.isAsync) {
this._pendingResponses.add(requestItem.request.seq)
}
this.service().then(childProcess => {
try {
childProcess.write(serverRequest)
} catch (err) {
const callback = this.fetchCallback(serverRequest.seq)
if (callback) {
callback.onError(err)
}
}
})
}
private tryCancelRequest(seq: number, command: string): boolean {
try {
if (this._requestQueue.tryDeletePendingRequest(seq)) {
this.tracer.logTrace(`TypeScript Server: canceled request with sequence number ${seq}`)
return true
}
if (this.cancellationPipeName) {
this.tracer.logTrace(`TypeScript Server: trying to cancel ongoing request with sequence number ${seq}`)
try {
fs.writeFileSync(this.cancellationPipeName + seq, '')
} catch {
// noop
}
return true
}
this.tracer.logTrace(`TypeScript Server: tried to cancel request with sequence number ${seq}. But request got already delivered.`)
return false
} finally {
const callback = this.fetchCallback(seq)
if (callback) {
callback.onSuccess(new ServerResponse.Cancelled(`Cancelled request ${seq} - ${command}`))
}
}
}
private fetchCallback(seq: number): any {
const callback = this._callbacks.fetch(seq)
if (!callback) {
return undefined
}
this._pendingResponses.delete(seq)
return callback
}
private dispatchMessage(message: Proto.Message): void {
try {
switch (message.type) {
case 'response':
this.dispatchResponse(message as Proto.Response)
break
case 'event':
const event = message as Proto.Event
if (event.event === 'requestCompleted') {
const seq = (event as Proto.RequestCompletedEvent).body.request_seq
const p = this._callbacks.fetch(seq)
if (p) {
this.tracer.traceRequestCompleted('requestCompleted', seq, p.startTime)
p.onSuccess(undefined)
}
} else {
this.tracer.traceEvent(event)
this.dispatchEvent(event)
}
break
default:
throw new Error(`Unknown message type ${message.type} received`)
}
} finally {
this.sendNextRequests()
}
}
private dispatchResponse(response: Proto.Response): void {
const callback = this.fetchCallback(response.request_seq)
if (!callback) {
return
}
this.tracer.traceResponse(response, callback.startTime)
if (response.success) {
callback.onSuccess(response)
} else if (response.message === 'No content available.') {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(ServerResponse.NoContent)
} else {
callback.onError(new Error(response.message))
}
}
private dispatchEvent(event: Proto.Event): void {
switch (event.event) {
case 'syntaxDiag':
case 'semanticDiag':
case 'suggestionDiag':
const diagnosticEvent = event as Proto.DiagnosticEvent
if (diagnosticEvent.body && diagnosticEvent.body.diagnostics) {
this._onDiagnosticsReceived.fire({
kind: getDiagnosticsKind(event),
resource: this.asUrl(diagnosticEvent.body.file),
diagnostics: diagnosticEvent.body.diagnostics
})
}
break
case 'configFileDiag':
this._onConfigDiagnosticsReceived.fire(
event as Proto.ConfigFileDiagnosticEvent
)
break
case 'projectLanguageServiceState':
if (event.body) {
this._onProjectLanguageServiceStateChanged.fire(
(event as Proto.ProjectLanguageServiceStateEvent).body
)
}
break
case 'beginInstallTypes':
if (event.body) {
this._onDidBeginInstallTypings.fire(
(event as Proto.BeginInstallTypesEvent).body
)
}
break
case 'endInstallTypes':
if (event.body) {
this._onDidEndInstallTypings.fire(
(event as Proto.EndInstallTypesEvent).body
)
}
break
case 'projectsUpdatedInBackground':
const body = (event as Proto.ProjectsUpdatedInBackgroundEvent).body
const resources = body.openFiles.map(Uri.file)
this.bufferSyncSupport.getErr(resources)
break
case 'typesInstallerInitializationFailed':
if (event.body) {
this._onTypesInstallerInitializationFailed.fire(
(event as Proto.TypesInstallerInitializationFailedEvent).body
)
}
break
case 'projectLoadingStart':
this.versionStatus.loading = true
break
case 'projectLoadingFinish':
this.versionStatus.loading = false
break
}
}
private async getTsServerArgs(currentVersion: TypeScriptVersion): Promise<string[]> {
const args: string[] = []
args.push('--allowLocalPluginLoads')
if (this.apiVersion.gte(API.v250)) {
args.push('--useInferredProjectPerProjectRoot')
} else {
args.push('--useSingleInferredProject')
}
if (this.apiVersion.gte(API.v206) && this._configuration.disableAutomaticTypeAcquisition) {
args.push('--disableAutomaticTypingAcquisition')
}
if (this.apiVersion.gte(API.v222)) {
this.cancellationPipeName = getTempFile(`tscancellation-${makeRandomHexString(20)}`)
args.push('--cancellationPipeName', this.cancellationPipeName + '*')
}
if (this.apiVersion.gte(API.v222)) {
const isRoot = process.getuid && process.getuid() == 0
if (this._configuration.tsServerLogLevel !== TsServerLogLevel.Off && !isRoot) {
const logDir = getTempDirectory()
if (logDir) {
this.tsServerLogFile = path.join(logDir, `tsserver.log`)
this.info('TSServer log file :', this.tsServerLogFile)
} else {
this.tsServerLogFile = null
this.error('Could not create TSServer log directory')
}
if (this.tsServerLogFile) {
args.push(
'--logVerbosity',
TsServerLogLevel.toString(this._configuration.tsServerLogLevel)
)
args.push('--logFile', this.tsServerLogFile)
}
}
}
if (this.apiVersion.gte(API.v230)) {
const pluginNames = this.pluginManager.plugins.map(x => x.name)
let pluginPaths = this._configuration.tsServerPluginPaths
pluginPaths = pluginPaths.reduce((p, c) => {
if (path.isAbsolute(c)) {
p.push(c)
} else {
let roots = workspace.workspaceFolders.map(o => Uri.parse(o.uri).fsPath)
p.push(...roots.map(r => path.join(r, c)))
}
return p
}, [])
if (pluginNames.length) {
const isUsingBundledTypeScriptVersion = currentVersion.path == this.versionProvider.bundledVersion.path
args.push('--globalPlugins', pluginNames.join(','))
for (const plugin of this.pluginManager.plugins) {
if (isUsingBundledTypeScriptVersion || plugin.enableForWorkspaceTypeScriptVersions) {
pluginPaths.push(plugin.path)
}
}
}
if (pluginPaths.length) {
args.push('--pluginProbeLocations', pluginPaths.join(','))
}
}
if (this._configuration.locale) {
args.push('--locale', this._configuration.locale)
}
if (this._configuration.typingsCacheLocation) {
args.push('--globalTypingsCacheLocation', `"${this._configuration.typingsCacheLocation}"`)
}
if (this.apiVersion.gte(API.v234)) {
let { npmLocation } = this._configuration
if (npmLocation) {
this.logger.info(`using npm from ${npmLocation}`)
args.push('--npmLocation', `"${npmLocation}"`)
}
}
if (this.apiVersion.gte(API.v291)) {
args.push('--noGetErrOnBackgroundUpdate')
}
if (this.apiVersion.gte(API.v345)) {
args.push('--validateDefaultNpmLocation')
}
return args
}
public getProjectRootPath(uri: string): string | undefined {
let root = workspace.cwd
let u = Uri.parse(uri)
if (u.scheme !== 'file') return undefined
let folder = workspace.getWorkspaceFolder(uri)
if (folder) {
root = Uri.parse(folder.uri).fsPath
} else {
let filepath = Uri.parse(uri).fsPath
if (!filepath.startsWith(root)) {
root = path.dirname(filepath)
}
}
if (root == os.homedir()) return undefined
return root
}
public configurePlugin(pluginName: string, configuration: {}): any {
if (this.apiVersion.gte(API.v314)) {
if (!this.servicePromise) return
this.servicePromise.then(() => {
// tslint:disable-next-line: no-floating-promises
this.executeWithoutWaitingForResponse('configurePlugin', { pluginName, configuration })
})
}
}
public interruptGetErr<R>(f: () => R): R {
return this.bufferSyncSupport.interuptGetErr(f)
}
private cancelInflightRequestsForResource(resource: string): void {
if (this.state !== ServiceStat.Running || !this.tsServerProcess) {
return
}
for (const request of this.tsServerProcess.toCancelOnResourceChange) {
if (request.resource.toString() === resource.toString()) {
request.cancel()
}
}
}
}
function getDiagnosticsKind(event: Proto.Event): DiagnosticKind {
switch (event.event) {
case 'syntaxDiag':
return DiagnosticKind.Syntax
case 'semanticDiag':
return DiagnosticKind.Semantic
case 'suggestionDiag':
return DiagnosticKind.Suggestion
}
throw new Error('Unknown dignostics kind')
}
const fenceCommands = new Set(['change', 'close', 'open'])
function getQueueingType(
command: string,
lowPriority?: boolean
): RequestQueueingType {
if (fenceCommands.has(command)) {
return RequestQueueingType.Fence
}
return lowPriority ? RequestQueueingType.LowPriority : RequestQueueingType.Normal
} | the_stack |
import React, {
useRef,
useMemo,
useState,
useEffect,
RefObject,
MutableRefObject,
} from "react"
/**
* ============================================================================
* Generic Types
* ============================================================================
*/
type ConstRef<T> = Readonly<MutableRefObject<T>>
interface ElementSize {
width: number
height: number
}
interface ElementScroll {
x: number
y: number
}
/**
* ============================================================================
* Generic Utils
* ============================================================================
*/
function isSameElementSize(a: ElementSize, b: ElementSize) {
return a.width === b.width && a.height === b.height
}
function getWindowSize(): ElementSize {
return {
width: window.innerWidth,
height: window.innerHeight,
}
}
function getElementSize(element: Element): ElementSize {
let rect = element.getBoundingClientRect()
return {
width: rect.width,
height: rect.height,
}
}
function isSameElementScroll(a: ElementScroll, b: ElementScroll) {
return a.x === b.x && a.y === b.y
}
function getWindowScroll(): ElementScroll {
return {
x: window.scrollX,
y: window.scrollY,
}
}
function getElementOffset(element: Element) {
return window.scrollY + element.getBoundingClientRect().top
}
/**
* ============================================================================
* Utility Hooks
* ============================================================================
*/
function useConstRef<T>(value: T): ConstRef<T> {
let ref = useRef(value)
ref.current = value
return ref
}
function useWindowSize(): ElementSize {
let [windowSize, setWindowSize] = useState(() => getWindowSize())
let windowSizeRef = useConstRef(windowSize)
useEffect(() => {
function onResize() {
let nextWindowSize = getWindowSize()
if (!isSameElementSize(windowSizeRef.current, nextWindowSize)) {
setWindowSize(nextWindowSize)
}
}
window.addEventListener("resize", onResize)
return () => window.removeEventListener("resize", onResize)
}, [windowSizeRef])
return windowSize
}
function useElementSize(ref: RefObject<Element>): ElementSize | null {
let [elementSize, setElementSize] = useState(() => {
if (ref.current) {
return getElementSize(ref.current)
} else {
return null
}
})
let elementSizeRef = useConstRef(elementSize)
useEffect(() => {
let observer = new ResizeObserver((entries) => {
let nextElementSize = getElementSize(entries[0].target)
if (
elementSizeRef.current === null ||
!isSameElementSize(elementSizeRef.current, nextElementSize)
) {
setElementSize(nextElementSize)
}
})
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
}, [ref])
return elementSize
}
function useWindowScroll(): ElementScroll {
let [scrollPosition, setScrollPosition] = useState(getWindowScroll())
let ref = useConstRef(scrollPosition)
useEffect(() => {
function update() {
let nextScrollPosition = getWindowScroll()
if (!isSameElementScroll(ref.current, nextScrollPosition)) {
setScrollPosition(nextScrollPosition)
}
}
window.addEventListener("scroll", update)
window.addEventListener("resize", update)
return () => {
window.removeEventListener("scroll", update)
window.removeEventListener("resize", update)
}
}, [ref])
return scrollPosition
}
function useElementWindowOffset(ref: RefObject<HTMLElement>) {
let [elementOffset, setElementOffset] = useState(() => {
if (ref.current) {
return getElementOffset(ref.current)
} else {
return null
}
})
useEffect(() => {
let observer = new ResizeObserver((entries) => {
setElementOffset(getElementOffset(entries[0].target))
})
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
}, [ref])
return elementOffset
}
function useIntersecting(ref: RefObject<HTMLElement>, rootMargin: string) {
let [intersecting, setIntersecting] = useState(false)
useEffect(() => {
let observer = new IntersectionObserver(
(entries) => {
setIntersecting(entries[0].isIntersecting)
},
{ rootMargin },
)
if (ref.current) observer.observe(ref.current)
return () => observer.disconnect()
}, [ref, rootMargin])
return intersecting
}
/**
* ============================================================================
* GridList Types
* ============================================================================
*/
interface GridListItemData {
key: string
height: number
}
interface GridListEntry<P> {
item: P
data: GridListItemData
}
interface GridListConfigData<P> {
windowMargin: number
gridGap: number
columnCount: number
entries: GridListEntry<P>[]
}
interface GridListContainerData {
windowSize: ElementSize
elementSize: ElementSize | null
windowScroll: ElementScroll
elementWindowOffset: number | null
}
interface GridListCell<P> {
key: string
columnNumber: number
rowNumber: number
offset: number
height: number
item: P
}
interface GridListLayoutData<P> {
totalHeight: number
cells: GridListCell<P>[]
}
interface GridListRenderData<P> {
cellsToRender: GridListCell<P>[]
firstRenderedRowNumber: number | null
firstRenderedRowOffset: number | null
}
/**
* ============================================================================
* GridList Utils
* ============================================================================
*/
function getColumnWidth(
columnCount: number | null,
gridGap: number | null,
elementWidth: number | null,
) {
if (columnCount === null || gridGap === null || elementWidth === null) {
return null
}
let totalGapSpace = (columnCount - 1) * gridGap
let columnWidth = Math.round((elementWidth - totalGapSpace) / columnCount)
return columnWidth
}
function getGridRowStart<P>(
cell: GridListCell<P>,
renderData: GridListRenderData<P> | null,
) {
if (renderData === null) return undefined
let offset =
renderData.firstRenderedRowNumber !== null
? renderData.firstRenderedRowNumber - 1
: 0
let gridRowStart = cell.rowNumber - offset
return `${gridRowStart}`
}
/**
* ============================================================================
* GridList Hooks
* ============================================================================
*/
function useGridListContainerData(
ref: RefObject<HTMLElement>,
): GridListContainerData {
let windowSize = useWindowSize()
let windowScroll = useWindowScroll()
let elementWindowOffset = useElementWindowOffset(ref)
let elementSize = useElementSize(ref)
return useMemo(() => {
return {
windowSize,
windowScroll,
elementWindowOffset,
elementSize,
}
}, [windowSize, windowScroll, elementWindowOffset, elementSize])
}
function useGridListConfigData<P>(
containerData: GridListContainerData,
props: GridListProps<P>,
): GridListConfigData<P> | null {
let {
items,
getWindowMargin,
getGridGap,
getColumnCount,
getItemData,
} = props
let elementWidth = containerData.elementSize
? containerData.elementSize.width
: null
let windowMargin = useMemo(() => {
if (getWindowMargin) {
return getWindowMargin(containerData.windowSize.height)
} else {
return containerData.windowSize.height
}
}, [containerData.windowSize.height, getWindowMargin])
let gridGap = useMemo(() => {
if (elementWidth === null) return null
if (getGridGap) {
return getGridGap(elementWidth, containerData.windowSize.height)
} else {
return 0
}
}, [elementWidth, containerData.windowSize.height, getGridGap])
let columnCount = useMemo(() => {
if (elementWidth === null) return null
if (gridGap === null) return null
return getColumnCount(elementWidth, gridGap)
}, [getColumnCount, elementWidth, gridGap])
let columnWidth = getColumnWidth(columnCount, gridGap, elementWidth)
let entries = useMemo(() => {
if (columnWidth === null) return null
let safeColumnWidth = columnWidth
return items.map((item) => {
return {
data: getItemData(item, safeColumnWidth),
item,
}
})
}, [items, columnWidth, getItemData])
return useMemo(() => {
if (
windowMargin === null ||
gridGap === null ||
columnCount === null ||
entries === null
) {
return null
}
return {
windowMargin,
gridGap,
columnCount,
entries,
}
}, [windowMargin, gridGap, columnCount, entries])
}
function useGridListLayoutData<P>(
configData: GridListConfigData<P> | null,
): GridListLayoutData<P> | null {
return useMemo(() => {
if (configData === null) return null
let currentRowNumber = 1
let prevRowsTotalHeight = 0
let currentRowMaxHeight = 0
let cells = configData.entries.map((entry, index) => {
let key = entry.data.key
let columnNumber = (index % configData.columnCount) + 1
let rowNumber = Math.floor(index / configData.columnCount) + 1
if (rowNumber !== currentRowNumber) {
currentRowNumber = rowNumber
prevRowsTotalHeight += currentRowMaxHeight + configData.gridGap
currentRowMaxHeight = 0
}
let offset = prevRowsTotalHeight
let height = Math.round(entry.data.height)
currentRowMaxHeight = Math.max(currentRowMaxHeight, height)
return { key, columnNumber, rowNumber, offset, height, item: entry.item }
})
let totalHeight = prevRowsTotalHeight + currentRowMaxHeight
return { totalHeight, cells }
}, [configData])
}
function useGridListRenderData<P>(
containerData: GridListContainerData,
configData: GridListConfigData<P> | null,
layoutData: GridListLayoutData<P> | null,
): GridListRenderData<P> | null {
return useMemo(() => {
if (layoutData === null || configData === null) return null
let cellsToRender: GridListCell<P>[] = []
let firstRenderedRowNumber: null | number = null
let firstRenderedRowOffset: null | number = null
if (containerData.elementWindowOffset !== null) {
let elementWindowOffset = containerData.elementWindowOffset
for (let cell of layoutData.cells) {
let cellTop = elementWindowOffset + cell.offset
let cellBottom = cellTop + cell.height
let windowTop = containerData.windowScroll.y
let windowBottom = windowTop + containerData.windowSize.height
let renderTop = windowTop - configData.windowMargin
let renderBottom = windowBottom + configData.windowMargin
if (cellTop > renderBottom) continue
if (cellBottom < renderTop) continue
if (firstRenderedRowNumber === null) {
firstRenderedRowNumber = cell.rowNumber
}
if (cell.rowNumber === firstRenderedRowNumber) {
firstRenderedRowOffset = firstRenderedRowOffset
? Math.min(firstRenderedRowOffset, cell.offset)
: cell.offset
}
cellsToRender.push(cell)
}
}
return { cellsToRender, firstRenderedRowNumber, firstRenderedRowOffset }
}, [
layoutData,
configData,
containerData.windowScroll.y,
containerData.windowSize.height,
containerData.elementWindowOffset,
])
}
/**
* ============================================================================
* GridList
* ============================================================================
*/
export interface GridListProps<P> {
items: P[]
getGridGap?: (elementWidth: number, windowHeight: number) => number
getWindowMargin?: (windowHeight: number) => number
getColumnCount: (elementWidth: number, gridGap: number) => number
getItemData: (item: P, columnWidth: number) => GridListItemData
renderItem: (item: P) => React.ReactNode
fixedColumnWidth?: number
}
export default function GridList<P>(props: GridListProps<P>) {
let ref = useRef<HTMLDivElement>(null)
let containerData = useGridListContainerData(ref)
let configData = useGridListConfigData(containerData, props)
let layoutData = useGridListLayoutData(configData)
let renderData = useGridListRenderData(containerData, configData, layoutData)
let intersecting = useIntersecting(
ref,
`${configData !== null ? configData.windowMargin : 0}px`,
)
const colWidth = props.fixedColumnWidth
? `${props.fixedColumnWidth}px`
: "1fr"
return (
<div
ref={ref}
style={{
boxSizing: "border-box",
height: layoutData !== null ? layoutData.totalHeight : undefined,
paddingTop:
renderData !== null && renderData.firstRenderedRowOffset !== null
? renderData.firstRenderedRowOffset
: 0,
}}
>
{intersecting && (
<div
style={{
display: "grid",
gridTemplateColumns:
configData !== null
? `repeat(${configData.columnCount}, ${colWidth})`
: undefined,
gridGap: configData ? configData.gridGap : undefined,
justifyContent: "center",
alignItems: "center",
}}
>
{renderData !== null &&
renderData.cellsToRender.map((cell) => {
return (
<div
key={cell.key}
style={{
height: cell.height,
gridColumnStart: `${cell.columnNumber}`,
gridRowStart: getGridRowStart(cell, renderData),
}}
>
{props.renderItem(cell.item)}
</div>
)
})}
</div>
)}
</div>
)
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A Container Analysis note is a high-level piece of metadata that
* describes a type of analysis that can be done for a resource.
*
* To get more information about Note, see:
*
* * [API documentation](https://cloud.google.com/container-analysis/api/reference/rest/)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/container-analysis/)
* * [Creating Attestations (Occurrences)](https://cloud.google.com/binary-authorization/docs/making-attestations)
*
* ## Example Usage
* ### Container Analysis Note Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const note = new gcp.containeranalysis.Note("note", {
* attestationAuthority: {
* hint: {
* humanReadableName: "Attestor Note",
* },
* },
* });
* ```
* ### Container Analysis Note Attestation Full
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const note = new gcp.containeranalysis.Note("note", {
* attestationAuthority: {
* hint: {
* humanReadableName: "Attestor Note",
* },
* },
* expirationTime: "2120-10-02T15:01:23.045123456Z",
* longDescription: "a longer description of test note",
* relatedUrls: [
* {
* label: "foo",
* url: "some.url",
* },
* {
* url: "google.com",
* },
* ],
* shortDescription: "test note",
* });
* ```
*
* ## Import
*
* Note can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:containeranalysis/note:Note default projects/{{project}}/notes/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:containeranalysis/note:Note default {{project}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:containeranalysis/note:Note default {{name}}
* ```
*/
export class Note extends pulumi.CustomResource {
/**
* Get an existing Note 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?: NoteState, opts?: pulumi.CustomResourceOptions): Note {
return new Note(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:containeranalysis/note:Note';
/**
* Returns true if the given object is an instance of Note. 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 Note {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Note.__pulumiType;
}
/**
* Note kind that represents a logical attestation "role" or "authority".
* For example, an organization might have one AttestationAuthority for
* "QA" and one for "build". This Note is intended to act strictly as a
* grouping mechanism for the attached Occurrences (Attestations). This
* grouping mechanism also provides a security boundary, since IAM ACLs
* gate the ability for a principle to attach an Occurrence to a given
* Note. It also provides a single point of lookup to find all attached
* Attestation Occurrences, even if they don't all live in the same
* project.
* Structure is documented below.
*/
public readonly attestationAuthority!: pulumi.Output<outputs.containeranalysis.NoteAttestationAuthority>;
/**
* The time this note was created.
*/
public /*out*/ readonly createTime!: pulumi.Output<string>;
/**
* Time of expiration for this note. Leave empty if note does not expire.
*/
public readonly expirationTime!: pulumi.Output<string | undefined>;
/**
* The type of analysis this note describes
*/
public /*out*/ readonly kind!: pulumi.Output<string>;
/**
* A detailed description of the note
*/
public readonly longDescription!: pulumi.Output<string | undefined>;
/**
* The name of the note.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Names of other notes related to this note.
*/
public readonly relatedNoteNames!: pulumi.Output<string[] | undefined>;
/**
* URLs associated with this note and related metadata.
* Structure is documented below.
*/
public readonly relatedUrls!: pulumi.Output<outputs.containeranalysis.NoteRelatedUrl[] | undefined>;
/**
* A one sentence description of the note.
*/
public readonly shortDescription!: pulumi.Output<string | undefined>;
/**
* The time this note was last updated.
*/
public /*out*/ readonly updateTime!: pulumi.Output<string>;
/**
* Create a Note 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: NoteArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: NoteArgs | NoteState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as NoteState | undefined;
inputs["attestationAuthority"] = state ? state.attestationAuthority : undefined;
inputs["createTime"] = state ? state.createTime : undefined;
inputs["expirationTime"] = state ? state.expirationTime : undefined;
inputs["kind"] = state ? state.kind : undefined;
inputs["longDescription"] = state ? state.longDescription : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["relatedNoteNames"] = state ? state.relatedNoteNames : undefined;
inputs["relatedUrls"] = state ? state.relatedUrls : undefined;
inputs["shortDescription"] = state ? state.shortDescription : undefined;
inputs["updateTime"] = state ? state.updateTime : undefined;
} else {
const args = argsOrState as NoteArgs | undefined;
if ((!args || args.attestationAuthority === undefined) && !opts.urn) {
throw new Error("Missing required property 'attestationAuthority'");
}
inputs["attestationAuthority"] = args ? args.attestationAuthority : undefined;
inputs["expirationTime"] = args ? args.expirationTime : undefined;
inputs["longDescription"] = args ? args.longDescription : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["relatedNoteNames"] = args ? args.relatedNoteNames : undefined;
inputs["relatedUrls"] = args ? args.relatedUrls : undefined;
inputs["shortDescription"] = args ? args.shortDescription : undefined;
inputs["createTime"] = undefined /*out*/;
inputs["kind"] = undefined /*out*/;
inputs["updateTime"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Note.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Note resources.
*/
export interface NoteState {
/**
* Note kind that represents a logical attestation "role" or "authority".
* For example, an organization might have one AttestationAuthority for
* "QA" and one for "build". This Note is intended to act strictly as a
* grouping mechanism for the attached Occurrences (Attestations). This
* grouping mechanism also provides a security boundary, since IAM ACLs
* gate the ability for a principle to attach an Occurrence to a given
* Note. It also provides a single point of lookup to find all attached
* Attestation Occurrences, even if they don't all live in the same
* project.
* Structure is documented below.
*/
attestationAuthority?: pulumi.Input<inputs.containeranalysis.NoteAttestationAuthority>;
/**
* The time this note was created.
*/
createTime?: pulumi.Input<string>;
/**
* Time of expiration for this note. Leave empty if note does not expire.
*/
expirationTime?: pulumi.Input<string>;
/**
* The type of analysis this note describes
*/
kind?: pulumi.Input<string>;
/**
* A detailed description of the note
*/
longDescription?: pulumi.Input<string>;
/**
* The name of the note.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Names of other notes related to this note.
*/
relatedNoteNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* URLs associated with this note and related metadata.
* Structure is documented below.
*/
relatedUrls?: pulumi.Input<pulumi.Input<inputs.containeranalysis.NoteRelatedUrl>[]>;
/**
* A one sentence description of the note.
*/
shortDescription?: pulumi.Input<string>;
/**
* The time this note was last updated.
*/
updateTime?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Note resource.
*/
export interface NoteArgs {
/**
* Note kind that represents a logical attestation "role" or "authority".
* For example, an organization might have one AttestationAuthority for
* "QA" and one for "build". This Note is intended to act strictly as a
* grouping mechanism for the attached Occurrences (Attestations). This
* grouping mechanism also provides a security boundary, since IAM ACLs
* gate the ability for a principle to attach an Occurrence to a given
* Note. It also provides a single point of lookup to find all attached
* Attestation Occurrences, even if they don't all live in the same
* project.
* Structure is documented below.
*/
attestationAuthority: pulumi.Input<inputs.containeranalysis.NoteAttestationAuthority>;
/**
* Time of expiration for this note. Leave empty if note does not expire.
*/
expirationTime?: pulumi.Input<string>;
/**
* A detailed description of the note
*/
longDescription?: pulumi.Input<string>;
/**
* The name of the note.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Names of other notes related to this note.
*/
relatedNoteNames?: pulumi.Input<pulumi.Input<string>[]>;
/**
* URLs associated with this note and related metadata.
* Structure is documented below.
*/
relatedUrls?: pulumi.Input<pulumi.Input<inputs.containeranalysis.NoteRelatedUrl>[]>;
/**
* A one sentence description of the note.
*/
shortDescription?: pulumi.Input<string>;
} | the_stack |
import { Injectable } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Params, Route, Router, Routes } from '@angular/router';
import { EMPTY, Observable } from 'rxjs';
import { filter, first, map, pairwise, startWith } from 'rxjs/operators';
import { ModalRouteActivation } from './modal.interfaces';
@Injectable({ providedIn: 'root' })
export class ModalNavigationService {
constructor(private router: Router, private route: ActivatedRoute) {}
isModalRoute(url: string): boolean {
return url.includes('(modal:');
}
private getCurrentActivatedRoute(): ActivatedRoute {
let childRoute = this.route.root;
while (childRoute.firstChild) {
childRoute = childRoute.firstChild;
}
return childRoute;
}
private async getModalRoutes(
routeConfig: Routes[],
moduleRootRoutePath?: string
): Promise<string[]> {
const flattenedRoutes: Routes = [].concat(...routeConfig);
let modalRoutes: string[] = [];
const moduleRootPaths = await this.getModuleRootPath(flattenedRoutes, moduleRootRoutePath);
if (moduleRootPaths) {
modalRoutes = this.getModalRoutePaths(flattenedRoutes, moduleRootPaths);
}
return modalRoutes;
}
private async getModuleRootPath(routes: Routes, moduleRootRoutePath?: string): Promise<string[]> {
if (moduleRootRoutePath) {
const trimmedPaths = moduleRootRoutePath
.trim()
.split('/')
.filter((path) => !!path);
const rootPath = [''];
return rootPath.concat(trimmedPaths);
}
const currentRoutePaths = await this.getCurrentRoutePaths();
const moduleRootPaths = this.getRoutePathsWithoutChildSegments(currentRoutePaths, routes);
return moduleRootPaths;
}
private async getCurrentRoutePaths(): Promise<string[]> {
const rootPath = [''];
const currentNavigation = this.router.getCurrentNavigation();
if (!this.router.navigated && !currentNavigation) {
// If router hasn't navigated yet and we are not in the middle of navigating, assume root:
return rootPath;
}
if (currentNavigation) {
// Wait for current navigation to finish:
await this.navigationEndListener$.pipe(first()).toPromise();
}
let childRoute = this.route.snapshot.root;
while (childRoute.firstChild) {
childRoute = childRoute.firstChild;
}
const currentBackdropRoutePath = childRoute.pathFromRoot.filter(
(route) => route.outlet !== 'modal'
);
return rootPath.concat(
...currentBackdropRoutePath.map((route) =>
route.url.filter((segment) => !!segment.path).map((segment) => segment.path)
)
);
}
private getRoutePathsWithoutChildSegments(routePaths: string[], routes: Routes): string[] {
if (!routePaths.length) return routePaths;
const matchedChildRoute = this.findChildRouteForUrl(routePaths.join('/'), routes);
if (!matchedChildRoute) return routePaths;
const startSlashRegex = /^\//;
const relativeChildRoute = matchedChildRoute.replace(startSlashRegex, '');
const childSegmentCount = relativeChildRoute.split('/').length;
const routePathsWithoutChildSegments = routePaths.slice(0, -childSegmentCount); // Remove child segments from end of route path array
return routePathsWithoutChildSegments;
}
private findChildRouteForUrl(url: string, routes: Routes) {
const moduleRelativePaths = this.getRoutePaths(routes, [''])
.sort()
.reverse(); // Ensure child paths are evaluated first
let matchedChildRoute = moduleRelativePaths.find((path) => url.endsWith(path));
if (!matchedChildRoute) {
// No static child route found matching current route - look for child route with url params:
const exactMatch = false;
matchedChildRoute = moduleRelativePaths.find(
(path) =>
path.includes('/:') && this.pathContainsChildRouteWithUrlParams(url, path, exactMatch)
);
}
return matchedChildRoute;
}
private pathContainsChildRouteWithUrlParams(
path: string,
childRouteWithUrlParams: string,
exactMatch: boolean
) {
const pathSegments = path.split('/');
const startSlashRegex = /^\//;
let childRouteToMatch = childRouteWithUrlParams;
if (!exactMatch) {
const relativeChildRoute = childRouteWithUrlParams.replace(startSlashRegex, '');
childRouteToMatch = relativeChildRoute;
}
const childRouteSegments = childRouteToMatch.split('/');
// Match each child route segment against url
// Match backwards from end to start of child route, i.e. "url ends with child route":
const pathContainsChildRoute = childRouteSegments.reverse().every((childRouteSegment) => {
const pathSegment = pathSegments.pop();
// url params (e.g. `/:id/`) are treated as a match:
return childRouteSegment.startsWith(':') || childRouteSegment === pathSegment;
});
if (exactMatch) {
// Only match if we've reached the start of the url to match against:
return pathSegments.length === 0 && pathContainsChildRoute;
}
return pathContainsChildRoute;
}
private getRoutePaths(routes: Routes, parentPath: string[]): string[] {
return Array.isArray(routes)
? ([] as string[]).concat(...routes.map((route) => this.getRoutePath(route, parentPath)))
: [];
}
private getRoutePath(route: Route, parentPath: string[]): string[] {
const routes: string[] = [];
if (!!route.outlet) return routes; // Don't return relative paths for outlet routes
const currentPath = [...parentPath];
if (!!route.path) {
currentPath.push(route.path);
routes.push(currentPath.join('/'));
}
return routes.concat(this.getRoutePaths(route.children, currentPath));
}
private getModalRoutePath(route: Route, parentPath: string[]): string[] {
const modalOutletName = 'modal';
if (!!route.path && route.outlet === modalOutletName) {
const modalOutletPath = `(${modalOutletName}:${route.path})`;
const modalRoutePath = [...parentPath, modalOutletPath].join('/');
return [modalRoutePath];
}
const currentPath = [...parentPath];
if (!!route.path) {
currentPath.push(route.path);
}
return ([] as string[]).concat(...this.getModalRoutePaths(route.children, currentPath));
}
private getModalRoutePaths(routes: Routes, parentPath: string[]): string[] {
return Array.isArray(routes)
? ([] as string[]).concat(...routes.map((route) => this.getModalRoutePath(route, parentPath)))
: [];
}
private isNewModalWindow(navigationEnd: NavigationEnd): boolean {
const currentNavigation = this.router.getCurrentNavigation();
if (!currentNavigation || !currentNavigation.previousNavigation) {
return true;
}
const previousRoutePath = (
currentNavigation.previousNavigation.finalUrl ||
currentNavigation.previousNavigation.extractedUrl
).toString();
const wasModalRoute = this.isModalRoute(previousRoutePath);
const isModalRoute = this.isModalRoute(navigationEnd.urlAfterRedirects);
if (!wasModalRoute && isModalRoute) {
return true;
}
const currentModalRouteParent = navigationEnd.urlAfterRedirects.split('/(modal:')[0];
const previousModalRouteParent = previousRoutePath.split('/(modal:')[0];
return previousModalRouteParent !== currentModalRouteParent;
}
private navigationEndListener$ = this.router.events.pipe(
filter((event): event is NavigationEnd => event instanceof NavigationEnd)
);
private async waitForCurrentThenGetNavigationEndStream(): Promise<Observable<NavigationEnd>> {
if (this.router.getCurrentNavigation()) {
const currentNavigationEnd = await this.navigationEndListener$.pipe(first()).toPromise();
return this.navigationEndListener$.pipe(startWith(currentNavigationEnd));
}
return this.navigationEndListener$;
}
private modalRouteActivatedFor(
navigationEnd$: Observable<NavigationEnd>,
modalRouteSet: Set<string>,
modalRoutesContainsUrlParams: boolean
): Observable<ModalRouteActivation> {
return navigationEnd$.pipe(
filter((navigationEnd) =>
this.modalRouteSetContainsPath(modalRouteSet, navigationEnd, modalRoutesContainsUrlParams)
),
map((navigationEnd) => ({
route: this.getCurrentActivatedRoute(),
isNewModal: this.isNewModalWindow(navigationEnd),
}))
);
}
private modalRouteDeactivatedFor(
navigationEnd$: Observable<NavigationEnd>,
modalRouteSet: Set<string>,
modalRoutesContainsUrlParams: boolean
): Observable<boolean> {
return navigationEnd$.pipe(
pairwise(),
filter(([prevNavigation, _]) =>
this.modalRouteSetContainsPath(modalRouteSet, prevNavigation, modalRoutesContainsUrlParams)
), // Only emit if previous route was modal
map(([_, currentNavigation]) => {
const isNewModalRoute = this.isModalRoute(currentNavigation.urlAfterRedirects);
// Deactivate modal route if new route is NOT modal OR is outside current parent route:
return !isNewModalRoute || this.isNewModalWindow(currentNavigation);
}),
filter((isDeactivation) => isDeactivation)
);
}
private modalRouteSetContainsPath(
modalRouteSet: Set<string>,
navigationEnd: NavigationEnd,
modalRoutesContainsUrlParams: boolean
) {
const pathname = navigationEnd.urlAfterRedirects.split('?')[0];
let hasRoute = modalRouteSet.has(pathname);
if (!hasRoute && modalRoutesContainsUrlParams) {
// Use `for ... of` instead of `forEach` so we can break out of the loop if route is found:
for (let route of modalRouteSet) {
const exactMatch = true;
const routeMatchesPath = this.pathContainsChildRouteWithUrlParams(
pathname,
route,
exactMatch
);
if (routeMatchesPath) {
hasRoute = true;
break;
}
}
}
return hasRoute;
}
async getModalNavigation(
routeConfig: Routes[],
moduleRootRoutePath?: string
): Promise<{ activated$: Observable<ModalRouteActivation>; deactivated$: Observable<boolean> }> {
if (Array.isArray(routeConfig)) {
const navigationEnd$ = await this.waitForCurrentThenGetNavigationEndStream();
const modalRoutes = await this.getModalRoutes(routeConfig, moduleRootRoutePath);
const hasModalRoutes = modalRoutes.length > 0;
if (hasModalRoutes) {
const modalRoutesContainsUrlParams = modalRoutes.some((route) => route.includes('/:'));
const modalRouteSet = new Set(modalRoutes);
const activated$ = this.modalRouteActivatedFor(
navigationEnd$,
modalRouteSet,
modalRoutesContainsUrlParams
);
const deactivated$ = this.modalRouteDeactivatedFor(
navigationEnd$,
modalRouteSet,
modalRoutesContainsUrlParams
);
return { activated$, deactivated$ };
}
}
return { activated$: EMPTY, deactivated$: EMPTY };
}
async navigateToModal(path: string | string[], queryParams?: Params): Promise<boolean> {
const commands = Array.isArray(path) ? path : path.split('/');
const childPath = commands.pop();
const result = await this.router.navigate([...commands, { outlets: { modal: [childPath] } }], {
queryParams,
relativeTo: this.getCurrentActivatedRoute(),
});
return result;
}
async navigateWithinModal(relativePath: string, queryParams?: Params): Promise<boolean> {
return this.router.navigate([relativePath], {
queryParams,
relativeTo: this.getCurrentActivatedRoute(),
});
}
async navigateOutOfModalOutlet(): Promise<boolean> {
let result = Promise.resolve(true);
const currentActivatedRoute = this.getCurrentActivatedRoute();
if (currentActivatedRoute.outlet === 'modal') {
const parentRoute = this.getBackdropRoute(currentActivatedRoute);
result = this.router.navigate(['./'], {
relativeTo: parentRoute,
});
}
return result;
}
private getBackdropRoute(currentActivatedRoute: ActivatedRoute) {
let parentRoute = currentActivatedRoute.parent;
while (parentRoute && !parentRoute.component && !!parentRoute.parent) {
parentRoute = parentRoute.parent;
}
return parentRoute;
}
} | the_stack |
import * as moment from 'moment';
import '../libs/jquery.payment.js'
import { CreditCard } from './creditCard';
export namespace Myki {
export class Account {
holder: string;
cards: Array<Card> = [];
loaded: boolean = false;
reset() {
this.holder = null
this.cards = []
this.loaded = false
}
}
export class Card {
loaded: boolean = false;
transactionLoaded: boolean = false;
holder: string;
id: string;
type: string;
cardType: string;
expiry: Date;
status: CardStatus;
moneyBalance: number;
moneyTopUpAppPurchased: number;
moneyTopupInProgress: number;
moneyTotalBalance: number;
passActive: string;
passActiveExpiry: Date;
passInactive: string;
lastTransactionDate: Date;
autoTopup: boolean;
transactions: Array<Transaction> = [];
transactionsGrouped: Array<any>;
idFormatted(): string {
if (!this.id)
return null
let cardId = this.id
return `${cardId.substr(0, 1)} ${cardId.substr(1, 5)} ${cardId.substr(6, 4)} ${cardId.substr(10, 4)} ${cardId.substr(14, 1)}`
}
passActiveFriendlyText(): string {
if (!this.passActiveExpiry)
return 'No pass active'
let daysLeft = moment(this.passActiveExpiry).startOf('day').diff(moment(), 'days') + 1;
return `${daysLeft} day${daysLeft > 1 ? 's' : ''} left`
}
passActiveFriendlyTextShort(): string {
if (!this.passActiveExpiry)
return 'N/A'
let daysLeft = moment(this.passActiveExpiry).startOf('day').diff(moment(), 'days') + 1;
return `${daysLeft} day${daysLeft > 1 ? 's' : ''}`
}
// preprocess transaction groups by day
// we're doing this on demand since a dynamic groupBy pipe is too expensive
groupTransactions() {
var groups = {};
this.transactions.forEach(function (transaction) {
var day = moment(transaction.dateTime).format('dddd ll')
groups[day] = groups[day] ? groups[day] : { day: day, transactions: [] };
groups[day].transactions.push(transaction);
});
this.transactionsGrouped = Object.keys(groups).map(function (key) { return groups[key] });
}
// preprocess transaction list sorting
// the myki site returns touch off default fare out of order (after a touch on)
// we need the touch off default fare before a touch on so our visual timeline works
// all the ordering is reverse because we're displaying in reverse chronological (newest first)
sortTransactions() {
this.transactions.sort((a, b) => {
// first sort by time
if (a.dateTime > b.dateTime) {
// greater than
return -1;
} else if (a.dateTime < b.dateTime) {
// less than
return 1;
} else {
// the same datetime
// sort by type
if (a.type === TransactionType.TouchOffDefaultFare) {
return 1;
} else if ((a.type === TransactionType.TopUpMoney || a.type === TransactionType.TopUpPass) && b.type === TransactionType.TouchOn) {
return 1;
} else if (a.type === TransactionType.TouchOff && (b.type === TransactionType.TopUpMoney || b.type === TransactionType.TopUpPass)) {
return 1;
} else {
return -1;
}
}
})
}
setStatus(status: string) {
switch (status) {
case 'Replaced':
this.status = CardStatus.Replaced;
break;
case 'Refunded':
this.status = CardStatus.Refunded;
break;
case 'Blocked':
this.status = CardStatus.Blocked;
break;
}
}
}
export class Transaction {
dateTime: Date;
type: TransactionType;
service: TransactionService;
zone: string;
description: string;
credit: number;
debit: number;
moneyBalance: number;
setType(type: string) {
switch (type) {
case 'Touch on':
this.type = TransactionType.TouchOn;
break;
case 'Touch off':
this.type = TransactionType.TouchOff;
break;
case 'Touch off (Default Fare)':
this.type = TransactionType.TouchOffDefaultFare;
break;
case 'Top up myki pass':
this.type = TransactionType.TopUpPass;
break;
case 'Top up myki money':
this.type = TransactionType.TopUpMoney;
break;
case 'Cancel top up myki money':
this.type = TransactionType.CancelTopUpMoney;
break;
case 'Cancel Top up myki pass':
this.type = TransactionType.CancelTopUpPass;
break;
case 'Refund myki pass':
this.type = TransactionType.RefundPass;
break;
case 'Card Purchase':
this.type = TransactionType.CardPurchase;
break;
case 'Reimbursement':
this.type = TransactionType.Reimbursement;
break;
case 'Administration Fee':
this.type = TransactionType.AdminFee;
break;
case 'myki money debit':
this.type = TransactionType.MoneyDebit;
break;
case 'Fare Product Sale':
this.type = TransactionType.FareProductSale;
break;
case 'myki money purchase':
this.type = TransactionType.FareProductSale;
break;
case 'Compensation':
this.type = TransactionType.Compensation;
break;
case 'Registration Fee':
this.type = TransactionType.RegistrationFee;
break;
default:
throw new Error('Invalid transaction type "' + type + '"')
}
}
typeToString(): string {
switch (this.type) {
case TransactionType.TouchOn:
return "Touch on";
case TransactionType.TouchOff:
return "Touch off";
case TransactionType.TouchOffDefaultFare:
return "Touch off (default fare)";
case TransactionType.TopUpPass:
return "Top up myki pass"
case TransactionType.TopUpMoney:
return "Top up myki money";
case TransactionType.CancelTopUpMoney:
return "Cancel top up myki money";
case TransactionType.CancelTopUpPass:
return "Cancel top up myki pass";
case TransactionType.RefundPass:
return "Refund myki pass";
case TransactionType.CardPurchase:
return "Card purchase";
case TransactionType.Reimbursement:
return "Reimbursement";
case TransactionType.AdminFee:
return "Administration fee";
case TransactionType.MoneyDebit:
return "Myki money debit";
case TransactionType.FareProductSale:
return "Fare product sale (touch off)";
case TransactionType.MoneyPurchase:
return "Myki money purchase";
case TransactionType.Compensation:
return "Compensation";
case TransactionType.RegistrationFee:
return "Registration fee";
default:
return '';
}
}
setService(service: string) {
switch (service) {
case 'Bus':
this.service = TransactionService.Bus;
break;
case 'Train':
this.service = TransactionService.Train;
break;
case 'Tram':
this.service = TransactionService.Tram;
break;
case 'V/Line':
this.service = TransactionService.VLine;
break;
case 'Auto top up':
this.service = TransactionService.AutoTopUp;
break;
case 'Website':
case 'PTVWebsite':
this.service = TransactionService.Website;
break;
case 'TopCo':
this.service = TransactionService.TopCo;
break;
case 'Retail':
this.service = TransactionService.Retail;
break;
case 'BPay':
this.service = TransactionService.BPay;
break;
case 'TOT':
this.service = TransactionService.TOT;
break;
case 'Others':
this.service = TransactionService.Others;
break;
case 'Call Center':
this.service = TransactionService.CallCenter;
break;
case 'IUSE':
this.service = TransactionService.IUSE;
break;
case '-':
case '':
this.service = null;
break;
default:
throw new Error('Invalid transaction service "' + service + '"')
}
}
serviceToString(): string {
switch (this.service) {
case TransactionService.Bus:
return 'Bus';
case TransactionService.Train:
return 'Train';
case TransactionService.Tram:
return 'Tram';
case TransactionService.VLine:
return 'V/Line';
case TransactionService.AutoTopUp:
return 'Auto top up';
case TransactionService.Website:
return 'Website';
case TransactionService.TopCo:
return 'TopCo (NTS OpCo Portal)';
case TransactionService.Retail:
return 'Retail';
case TransactionService.BPay:
return 'BPay';
case TransactionService.TOT:
return 'Ticket office terminal';
case TransactionService.Others:
return 'Others';
case TransactionService.CallCenter:
return 'Call centre';
case TransactionService.IUSE:
return 'iUSEpass';
default:
return '';
}
}
}
export enum CardStatus {
Active,
Replaced,
Blocked,
Refunded
}
export enum TransactionType {
TouchOn,
TouchOff,
TouchOffDefaultFare,
TopUpPass,
TopUpMoney,
CancelTopUpMoney,
CancelTopUpPass,
RefundPass,
CardPurchase,
Reimbursement,
AdminFee,
MoneyDebit,
FareProductSale,
MoneyPurchase,
Compensation,
RegistrationFee
}
export enum TransactionService {
Bus,
Train,
Tram,
VLine,
AutoTopUp,
Website,
TopCo,
Retail,
BPay,
TOT,
Others,
CallCenter,
IUSE
}
export enum TopupType {
Money,
Pass
}
export class TopupOptions {
topupType: Myki.TopupType
moneyAmount: number
passDuration: number
zoneFrom: number
zoneTo: number
cnToken: string
creditCard: CreditCard = new CreditCard()
reminderType: TopupReminderType
reminderEmail: string
reminderMobile: string
saveCreditCard: boolean
ccNumberNoSpaces(): string {
if (this.creditCard.ccNumber === undefined)
return ''
return this.creditCard.ccNumber.replace(/\s+/g, '');
}
ccExpiryMonth(): string {
// parse the month/year from the credit card expiry
let expiry = $.payment.cardExpiryVal(this.creditCard.ccExpiry)
return expiry.month.toString()
}
ccExpiryYear(): string {
// parse the month/year from the credit card expiry
let expiry = $.payment.cardExpiryVal(this.creditCard.ccExpiry)
return expiry.year.toString()
}
}
export class TopupOrder {
description: string
amount: number
gstAmount: number
}
export enum TopupReminderType {
Email,
Mobile,
None
}
} | the_stack |
namespace mqtt {
/**
* Connect flags
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349229
*/
export const enum ConnectFlags {
UserName = 128,
Password = 64,
WillRetain = 32,
WillQoS2 = 16,
WillQoS1 = 8,
Will = 4,
CleanSession = 2
}
/**
* Connect Return code
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349256
*/
export const enum ConnectReturnCode {
Unknown = -1,
Accepted = 0,
UnacceptableProtocolVersion = 1,
IdentifierRejected = 2,
ServerUnavailable = 3,
BadUserNameOrPassword = 4,
NotAuthorized = 5
}
/**
* A message received in a Publish packet.
*/
export interface IMessage {
pid?: number;
topic: string;
content: Buffer;
qos: number;
retain: number;
}
/**
* MQTT Control Packet type
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc353481061
*/
export const enum ControlPacketType {
Connect = 1,
ConnAck = 2,
Publish = 3,
PubAck = 4,
// PubRec = 5,
// PubRel = 6,
// PubComp = 7,
Subscribe = 8,
SubAck = 9,
Unsubscribe = 10,
UnsubAck = 11,
PingReq = 12,
PingResp = 13,
Disconnect = 14
}
/**
* Optimization, the TypeScript compiler replaces the constant enums.
*/
export const enum Constants {
PingInterval = 40,
WatchDogInterval = 50,
DefaultQos = 0,
Uninitialized = -123,
FixedPackedId = 1,
KeepAlive = 60
}
/**
* The options used to connect to the MQTT broker.
*/
export interface IConnectionOptions {
host: string;
port?: number;
username?: string;
password?: string;
clientId: string;
will?: IConnectionOptionsWill;
}
export interface IConnectionOptionsWill {
topic: string;
message: string;
qos?: number;
retain?: boolean;
}
/**
* The specifics of the MQTT protocol.
*/
export module Protocol {
function strChr(codes: number[]): Buffer {
return pins.createBufferFromArray(codes)
}
/**
* Encode remaining length
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718023
*/
function encodeRemainingLength(remainingLength: number): number[] {
let length: number = remainingLength;
const encBytes: number[] = [];
do {
let encByte: number = length & 127;
length = length >> 7;
// if there are more data to encode, set the top bit of this byte
if (length > 0) {
encByte += 128;
}
encBytes.push(encByte);
} while (length > 0);
return encBytes;
}
/**
* Connect flags
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc385349229
*/
function createConnectFlags(options: IConnectionOptions): number {
let flags: number = 0;
flags |= (options.username) ? ConnectFlags.UserName : 0;
flags |= (options.username && options.password) ? ConnectFlags.Password : 0;
flags |= ConnectFlags.CleanSession;
if (options.will) {
flags |= ConnectFlags.Will;
flags |= (options.will.qos || 0) << 3;
flags |= (options.will.retain) ? ConnectFlags.WillRetain : 0;
}
return flags;
}
// Returns the MSB and LSB.
function getBytes(int16: number): number[] {
return [int16 >> 8, int16 & 255];
}
/**
* Structure of UTF-8 encoded strings
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Figure_1.1_Structure
*/
function pack(s: string): Buffer {
const buf = control.createBufferFromUTF8(s);
return strChr(getBytes(buf.length)).concat(buf);
}
/**
* Structure of an MQTT Control Packet
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800392
*/
function createPacketHeader(byte1: number, variable: Buffer, payloadSize: number): Buffer {
const byte2: number[] = encodeRemainingLength(variable.length + payloadSize);
return strChr([byte1])
.concat(strChr(byte2))
.concat(variable)
}
/**
* Structure of an MQTT Control Packet
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800392
*/
function createPacket(byte1: number, variable: Buffer, payload?: Buffer): Buffer {
if (payload == null) payload = control.createBuffer(0);
return createPacketHeader(byte1, variable, payload.length).concat(payload)
}
/**
* CONNECT - Client requests a connection to a Server
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028
*/
export function createConnect(options: IConnectionOptions): Buffer {
const byte1: number = ControlPacketType.Connect << 4;
const protocolName = pack('MQTT');
const nums = control.createBuffer(4)
nums[0] = 4; // protocol level
nums[1] = createConnectFlags(options)
nums[2] = 0
nums[3] = Constants.KeepAlive
let payload = pack(options.clientId);
if (options.will) {
payload = payload
.concat(pack(options.will.topic)
.concat(pack(options.will.message)));
}
if (options.username) {
payload = payload.concat(pack(options.username));
if (options.password) {
payload = payload.concat(pack(options.password));
}
}
return createPacket(
byte1,
protocolName.concat(nums),
payload
);
}
/** PINGREQ - PING request
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800454
*/
export function createPingReq() {
return strChr([ControlPacketType.PingReq << 4, 0]);
}
/**
* PUBLISH - Publish message header - doesn't include "payload"
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800410
*/
export function createPublishHeader(topic: string, payloadSize: number, qos: number, retained: boolean) {
let byte1: number = ControlPacketType.Publish << 4 | (qos << 1);
byte1 |= (retained) ? 1 : 0;
const pid = strChr(getBytes(Constants.FixedPackedId));
const variable = (qos === 0) ? pack(topic) : pack(topic).concat(pid);
return createPacketHeader(byte1, variable, payloadSize);
}
export function parsePublish(cmd: number, payload: Buffer): IMessage {
const qos: number = (cmd & 0b00000110) >> 1;
const topicLength = payload.getNumber(NumberFormat.UInt16BE, 0);
let variableLength: number = 2 + topicLength;
if (qos > 0) {
variableLength += 2;
}
const message: IMessage = {
topic: payload.slice(2, topicLength).toString(),
content: payload.slice(variableLength),
qos: qos,
retain: cmd & 1
};
if (qos > 0)
message.pid = payload.getNumber(NumberFormat.UInt16BE, variableLength - 2);
return message;
}
/**
* PUBACK - Publish acknowledgement
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800416
*/
export function createPubAck(pid: number) {
const byte1: number = ControlPacketType.PubAck << 4;
return createPacket(byte1, strChr(getBytes(pid)));
}
/**
* SUBSCRIBE - Subscribe to topics
* http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc384800436
*/
export function createSubscribe(topic: string, qos: number): Buffer {
const byte1: number = ControlPacketType.Subscribe << 4 | 2;
const pid = strChr(getBytes(Constants.FixedPackedId));
return createPacket(byte1,
pid,
pack(topic).concat(strChr([qos])))
}
}
export type EventHandler = (arg?: string | IMessage) => void;
export class EventEmitter {
private handlers: { [index: string]: EventHandler[] };
constructor() {
this.handlers = {};
}
public on(event: string, listener: EventHandler): void {
if (!event || !listener) return;
let listeners = this.handlers[event];
if (!listeners)
this.handlers[event] = listeners = [];
listeners.push(listener);
}
protected emit(event: string, arg?: string | IMessage): boolean {
let listeners = this.handlers[event];
if (listeners) {
listeners.forEach(listener => listener(arg));
}
return true;
}
}
enum HandlerStatus {
Normal = 0,
Once = 1,
ToRemove = 2,
}
class MQTTHandler {
public status: HandlerStatus
constructor(
public topic: string,
public handler: (m: IMessage) => void
) {
this.status = HandlerStatus.Normal
}
}
export enum Status {
Disconnected = 0,
Connecting = 1,
Connected = 2,
Sending = 3,
}
export class Client extends EventEmitter {
public logPriority = ConsolePriority.Debug
public tracePriority = -1 as ConsolePriority;
private log(msg: string) {
console.add(this.logPriority, `mqtt: ${msg}`);
}
private trace(msg: string) {
console.add(this.tracePriority, `mqtt: ${msg}`);
}
public opt: IConnectionOptions;
private net: net.Net;
private sct?: net.Socket;
private wdId: number;
private piId: number;
private buf: Buffer;
// we re-send subscriptions on re-connect
private subs: Buffer[] = [];
public status = Status.Disconnected
get connected() {
return this.status >= Status.Connected
}
private mqttHandlers: MQTTHandler[];
constructor(opt: IConnectionOptions) {
super();
this.wdId = Constants.Uninitialized;
this.piId = Constants.Uninitialized;
opt.port = opt.port || 8883;
opt.clientId = opt.clientId;
if (opt.will) {
opt.will.qos = opt.will.qos || Constants.DefaultQos;
opt.will.retain = opt.will.retain || false;
}
this.opt = opt;
this.net = net.instance();
}
private static describe(code: ConnectReturnCode): string {
let error: string = 'Connection refused, ';
switch (code) {
case ConnectReturnCode.UnacceptableProtocolVersion:
error += 'unacceptable protocol version.';
break;
case ConnectReturnCode.IdentifierRejected:
error += 'identifier rejected.';
break;
case ConnectReturnCode.ServerUnavailable:
error += 'server unavailable.';
break;
case ConnectReturnCode.BadUserNameOrPassword:
error += 'bad user name or password.';
break;
case ConnectReturnCode.NotAuthorized:
error += 'not authorized.';
break;
default:
error += `unknown return code: ${code}.`;
}
return error;
}
public disconnect(): void {
this.log("disconnect")
if (this.wdId !== Constants.Uninitialized) {
clearInterval(this.wdId);
this.wdId = Constants.Uninitialized;
}
if (this.piId !== Constants.Uninitialized) {
clearInterval(this.piId);
this.piId = Constants.Uninitialized;
}
const s = this.sct
if (s) {
this.sct = null
s.close()
}
this.status = Status.Disconnected
}
public connect(): void {
if (this.status != Status.Disconnected)
return
this.status = Status.Connecting
this.log(`Connecting to ${this.opt.host}:${this.opt.port}`);
if (this.wdId === Constants.Uninitialized) {
this.wdId = setInterval(() => {
if (!this.connected) {
this.emit('disconnected');
this.emit('error', 'No connection. Retrying.');
this.disconnect();
this.connect();
}
}, Constants.WatchDogInterval * 1000);
}
this.sct = this.net.createSocket(this.opt.host, this.opt.port, true);
this.sct.onOpen(() => {
this.log('Network connection established.');
this.emit('connect');
this.send(Protocol.createConnect(this.opt));
});
this.sct.onMessage((msg: Buffer) => {
this.trace("incoming " + msg.length + " bytes")
this.handleMessage(msg);
});
this.sct.onError(() => {
this.log('Error.');
this.emit('error');
});
this.sct.onClose(() => {
this.log('Close.');
this.emit('disconnected');
this.status = Status.Disconnected
this.sct = null;
});
this.sct.connect();
}
private canSend() {
let cnt = 0
while (true) {
if (this.status == Status.Connected) {
this.status = Status.Sending
return true
}
if (cnt++ < 100 && this.status == Status.Sending)
pause(20)
else {
this.log("drop pkt")
return false
}
}
}
private doneSending() {
this.trace("done send")
if (this.status == Status.Sending)
this.status = Status.Connected
}
// Publish a message
public publish(topic: string, message?: string | Buffer, qos: number = Constants.DefaultQos, retained: boolean = false): void {
const buf = typeof message == "string" ? control.createBufferFromUTF8(message) : message
message = null
if (this.startPublish(topic, buf ? buf.length : 0, qos, retained)) {
if (buf)
this.send(buf);
this.finishPublish()
}
}
public startPublish(topic: string, messageLen: number, qos: number = Constants.DefaultQos, retained: boolean = false) {
if (!this.canSend()) return false
this.trace(`publish: ${topic} ${messageLen}b`)
this.send(Protocol.createPublishHeader(topic, messageLen, qos, retained));
return true
}
public continuePublish(data: Buffer) {
this.send(data)
}
public finishPublish() {
this.doneSending()
this.emit("published")
}
private subscribeCore(topic: string, handler: (msg: IMessage) => void, qos: number = Constants.DefaultQos): MQTTHandler {
this.log(`subscribe: ${topic}`)
const sub = Protocol.createSubscribe(topic, qos)
this.subs.push(sub)
this.send1(sub);
if (handler) {
if (topic[topic.length - 1] == "#")
topic = topic.slice(0, topic.length - 1)
if (!this.mqttHandlers) this.mqttHandlers = []
const h = new MQTTHandler(topic, handler)
this.mqttHandlers.push(h)
return h
} else {
return null
}
}
// Subscribe to topic
public subscribe(topic: string, handler?: (msg: IMessage) => void, qos: number = Constants.DefaultQos): void {
this.subscribeCore(topic, handler, qos)
}
// Subscribe to one update on the topic. Returns function that waits for the topic to be updated.
public awaitUpdate(topic: string, qos: number = Constants.DefaultQos): () => IMessage {
let res: IMessage = null
const evid = control.allocateNotifyEvent()
const h = this.subscribeCore(topic, msg => {
res = msg
control.raiseEvent(DAL.DEVICE_ID_NOTIFY, evid)
}, qos)
h.status = HandlerStatus.Once
return () => {
while (res == null) {
control.waitForEvent(DAL.DEVICE_ID_NOTIFY, evid)
}
return res
}
}
private send(data: Buffer): void {
if (this.sct) {
this.trace("send: " + data[0] + " / " + data.length + " bytes")
// this.log("send: " + data[0] + " / " + data.length + " bytes: " + data.toHex())
this.sct.send(data);
}
}
private handleMessage(data: Buffer) {
if (this.buf)
data = this.buf.concat(data)
this.buf = data
if (data.length < 2)
return
let len = data[1]
let payloadOff = 2
if (len & 0x80) {
if (data.length < 3)
return
if (data[2] & 0x80) {
this.emit('error', `too large packet.`);
this.buf = null
return
}
len = (data[2] << 7) | (len & 0x7f)
payloadOff++
}
const payloadEnd = payloadOff + len
if (data.length < payloadEnd)
return // wait for the rest of data
this.buf = null
const cmd = data[0]
const controlPacketType: ControlPacketType = cmd >> 4;
// this.emit('debug', `Rcvd: ${controlPacketType}: '${data}'.`);
const payload = data.slice(payloadOff, payloadEnd - payloadOff)
switch (controlPacketType) {
case ControlPacketType.ConnAck:
const returnCode: number = payload[1];
if (returnCode === ConnectReturnCode.Accepted) {
this.log('MQTT connection accepted.');
this.emit('connected');
this.status = Status.Connected;
this.piId = setInterval(() => this.ping(), Constants.PingInterval * 1000);
for (const sub of this.subs)
this.send1(sub);
} else {
const connectionError: string = Client.describe(returnCode);
this.log('MQTT connection error: ' + connectionError);
this.emit('error', connectionError);
this.disconnect()
}
break;
case ControlPacketType.Publish:
const message: IMessage = Protocol.parsePublish(cmd, payload);
this.trace(`incoming: ${message.topic}`)
let handled = false
let cleanup = false
if (this.mqttHandlers) {
for (let h of this.mqttHandlers)
if (message.topic.slice(0, h.topic.length) == h.topic) {
h.handler(message)
handled = true
if (h.status == HandlerStatus.Once) {
h.status = HandlerStatus.ToRemove
cleanup = true
}
}
if (cleanup)
this.mqttHandlers = this.mqttHandlers.filter(h => h.status != HandlerStatus.ToRemove)
}
if (!handled)
this.emit('receive', message);
if (message.qos > 0) {
setTimeout(() => {
this.send1(Protocol.createPubAck(message.pid || 0));
}, 0);
}
break;
case ControlPacketType.PingResp:
case ControlPacketType.PubAck:
case ControlPacketType.SubAck:
break;
default:
this.emit('error', `MQTT unexpected packet type: ${controlPacketType}.`);
}
if (data.length > payloadEnd)
this.handleMessage(data.slice(payloadEnd))
}
private send1(msg: Buffer) {
if (this.canSend()) {
this.send(msg)
this.doneSending()
}
}
private ping() {
this.send1(Protocol.createPingReq());
this.emit('debug', 'Sent: Ping request.');
}
}
} | the_stack |
import { ContextLevel } from '@/core/constants';
import { Injectable } from '@angular/core';
import { CoreSyncBlockedError } from '@classes/base-sync';
import { CoreNetworkError } from '@classes/errors/network-error';
import { CoreCourseActivitySyncBaseProvider } from '@features/course/classes/activity-sync';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreRatingSync } from '@features/rating/services/rating-sync';
import { CoreApp } from '@services/app';
import { CoreSites } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { AddonModGlossary, AddonModGlossaryProvider } from './glossary';
import { AddonModGlossaryHelper } from './glossary-helper';
import { AddonModGlossaryOffline, AddonModGlossaryOfflineEntry } from './glossary-offline';
import { CoreFileUploader } from '@features/fileuploader/services/fileuploader';
import { CoreFileEntry } from '@services/file-helper';
/**
* Service to sync glossaries.
*/
@Injectable({ providedIn: 'root' })
export class AddonModGlossarySyncProvider extends CoreCourseActivitySyncBaseProvider<AddonModGlossarySyncResult> {
static readonly AUTO_SYNCED = 'addon_mod_glossary_autom_synced';
protected componentTranslatableString = 'glossary';
constructor() {
super('AddonModGlossarySyncProvider');
}
/**
* Try to synchronize all the glossaries in a certain site or in all sites.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
syncAllGlossaries(siteId?: string, force?: boolean): Promise<void> {
return this.syncOnSites('all glossaries', this.syncAllGlossariesFunc.bind(this, !!force), siteId);
}
/**
* Sync all glossaries on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllGlossariesFunc(force: boolean, siteId: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
await Promise.all([
this.syncAllGlossariesEntries(force, siteId),
this.syncRatings(undefined, force, siteId),
]);
}
/**
* Sync entried of all glossaries on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllGlossariesEntries(force: boolean, siteId: string): Promise<void> {
const entries = await AddonModGlossaryOffline.getAllNewEntries(siteId);
// Do not sync same glossary twice.
const treated: Record<number, boolean> = {};
await Promise.all(entries.map(async (entry) => {
if (treated[entry.glossaryid]) {
return;
}
treated[entry.glossaryid] = true;
const result = force ?
await this.syncGlossaryEntries(entry.glossaryid, entry.userid, siteId) :
await this.syncGlossaryEntriesIfNeeded(entry.glossaryid, entry.userid, siteId);
if (result?.updated) {
// Sync successful, send event.
CoreEvents.trigger(AddonModGlossarySyncProvider.AUTO_SYNCED, {
glossaryId: entry.glossaryid,
userId: entry.userid,
warnings: result.warnings,
}, siteId);
}
}));
}
/**
* Sync a glossary only if a certain time has passed since the last time.
*
* @param glossaryId Glossary ID.
* @param userId User the entry belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the glossary is synced or if it doesn't need to be synced.
*/
async syncGlossaryEntriesIfNeeded(
glossaryId: number,
userId: number,
siteId?: string,
): Promise<AddonModGlossarySyncResult | undefined> {
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getGlossarySyncId(glossaryId, userId);
const needed = await this.isSyncNeeded(syncId, siteId);
if (needed) {
return this.syncGlossaryEntries(glossaryId, userId, siteId);
}
}
/**
* Synchronize all offline entries of a glossary.
*
* @param glossaryId Glossary ID to be synced.
* @param userId User the entries belong to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
syncGlossaryEntries(glossaryId: number, userId?: number, siteId?: string): Promise<AddonModGlossarySyncResult> {
userId = userId || CoreSites.getCurrentSiteUserId();
siteId = siteId || CoreSites.getCurrentSiteId();
const syncId = this.getGlossarySyncId(glossaryId, userId);
const currentSyncPromise = this.getOngoingSync(syncId, siteId);
if (currentSyncPromise) {
// There's already a sync ongoing for this glossary, return the promise.
return currentSyncPromise;
}
// Verify that glossary isn't blocked.
if (CoreSync.isBlocked(AddonModGlossaryProvider.COMPONENT, syncId, siteId)) {
this.logger.debug('Cannot sync glossary ' + glossaryId + ' because it is blocked.');
throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug('Try to sync glossary ' + glossaryId + ' for user ' + userId);
const syncPromise = this.performSyncGlossaryEntries(glossaryId, userId, siteId);
return this.addOngoingSync(syncId, syncPromise, siteId);
}
protected async performSyncGlossaryEntries(
glossaryId: number,
userId: number,
siteId: string,
): Promise<AddonModGlossarySyncResult> {
const result: AddonModGlossarySyncResult = {
warnings: [],
updated: false,
};
const syncId = this.getGlossarySyncId(glossaryId, userId);
// Sync offline logs.
await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModGlossaryProvider.COMPONENT, glossaryId, siteId));
// Get offline responses to be sent.
const entries = await CoreUtils.ignoreErrors(
AddonModGlossaryOffline.getGlossaryNewEntries(glossaryId, siteId, userId),
<AddonModGlossaryOfflineEntry[]> [],
);
if (!entries.length) {
// Nothing to sync.
await CoreUtils.ignoreErrors(this.setSyncTime(syncId, siteId));
return result;
} else if (!CoreApp.isOnline()) {
// Cannot sync in offline.
throw new CoreNetworkError();
}
let courseId: number | undefined;
await Promise.all(entries.map(async (data) => {
courseId = courseId || data.courseid;
try {
// First of all upload the attachments (if any).
const itemId = await this.uploadAttachments(glossaryId, data, siteId);
// Now try to add the entry.
await AddonModGlossary.addEntryOnline(glossaryId, data.concept, data.definition, data.options, itemId, siteId);
result.updated = true;
await this.deleteAddEntry(glossaryId, data.concept, data.timecreated, siteId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, reject.
throw error;
}
// The WebService has thrown an error, this means that responses cannot be submitted. Delete them.
result.updated = true;
await this.deleteAddEntry(glossaryId, data.concept, data.timecreated, siteId);
// Responses deleted, add a warning.
this.addOfflineDataDeletedWarning(result.warnings, data.concept, error);
}
}));
if (result.updated && courseId) {
// Data has been sent to server. Now invalidate the WS calls.
try {
const glossary = await AddonModGlossary.getGlossaryById(courseId, glossaryId);
await AddonModGlossary.invalidateGlossaryEntries(glossary, true);
} catch {
// Ignore errors.
}
}
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(syncId, siteId));
return result;
}
/**
* Synchronize offline ratings.
*
* @param cmId Course module to be synced. If not defined, sync all glossaries.
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncRatings(cmId?: number, force?: boolean, siteId?: string): Promise<AddonModGlossarySyncResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
const results = await CoreRatingSync.syncRatings('mod_glossary', 'entry', ContextLevel.MODULE, cmId, 0, force, siteId);
let updated = false;
const warnings: string[] = [];
await CoreUtils.allPromises(results.map(async (result) => {
if (result.updated.length) {
updated = true;
// Invalidate entry of updated ratings.
await Promise.all(result.updated.map((itemId) => AddonModGlossary.invalidateEntry(itemId, siteId)));
}
if (result.warnings.length) {
const glossary = await AddonModGlossary.getGlossary(result.itemSet.courseId, result.itemSet.instanceId, { siteId });
result.warnings.forEach((warning) => {
this.addOfflineDataDeletedWarning(warnings, glossary.name, warning);
});
}
}));
return { updated, warnings };
}
/**
* Delete a new entry.
*
* @param glossaryId Glossary ID.
* @param concept Glossary entry concept.
* @param timeCreated Time to allow duplicated entries.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when deleted.
*/
protected async deleteAddEntry(glossaryId: number, concept: string, timeCreated: number, siteId?: string): Promise<void> {
await Promise.all([
AddonModGlossaryOffline.deleteNewEntry(glossaryId, concept, timeCreated, siteId),
AddonModGlossaryHelper.deleteStoredFiles(glossaryId, concept, timeCreated, siteId),
]);
}
/**
* Upload attachments of an offline entry.
*
* @param glossaryId Glossary ID.
* @param entry Offline entry.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with draftid if uploaded, resolved with 0 if nothing to upload.
*/
protected async uploadAttachments(glossaryId: number, entry: AddonModGlossaryOfflineEntry, siteId?: string): Promise<number> {
if (!entry.attachments) {
// No attachments.
return 0;
}
// Has some attachments to sync.
let files: CoreFileEntry[] = entry.attachments.online || [];
if (entry.attachments.offline) {
// Has offline files.
const storedFiles = await CoreUtils.ignoreErrors(
AddonModGlossaryHelper.getStoredFiles(glossaryId, entry.concept, entry.timecreated, siteId),
[], // Folder not found, no files to add.
);
files = files.concat(storedFiles);
}
return CoreFileUploader.uploadOrReuploadFiles(files, AddonModGlossaryProvider.COMPONENT, glossaryId, siteId);
}
/**
* Get the ID of a glossary sync.
*
* @param glossaryId Glossary ID.
* @param userId User the entries belong to.. If not defined, current user.
* @return Sync ID.
*/
protected getGlossarySyncId(glossaryId: number, userId?: number): string {
userId = userId || CoreSites.getCurrentSiteUserId();
return 'glossary#' + glossaryId + '#' + userId;
}
}
export const AddonModGlossarySync = makeSingleton(AddonModGlossarySyncProvider);
/**
* Data returned by a glossary sync.
*/
export type AddonModGlossarySyncResult = {
warnings: string[]; // List of warnings.
updated: boolean; // Whether some data was sent to the server or offline data was updated.
};
/**
* Data passed to AUTO_SYNCED event.
*/
export type AddonModGlossaryAutoSyncData = {
glossaryId: number;
userId: number;
warnings: string[];
}; | the_stack |
import {
DydxBridgeAction,
DydxBridgeActionType,
DydxBridgeData,
dydxBridgeDataEncoder,
IAssetDataContract,
} from '@0x/contracts-asset-proxy';
import {
blockchainTests,
constants,
expect,
getRandomFloat,
getRandomInteger,
Numberish,
randomAddress,
} from '@0x/contracts-test-utils';
import { Order } from '@0x/types';
import { BigNumber, fromTokenUnitAmount, toTokenUnitAmount } from '@0x/utils';
import { artifacts as devUtilsArtifacts } from './artifacts';
import { TestDydxContract, TestLibDydxBalanceContract } from './wrappers';
blockchainTests('LibDydxBalance', env => {
interface TestDydxConfig {
marginRatio: BigNumber;
operators: Array<{
owner: string;
operator: string;
}>;
accounts: Array<{
owner: string;
accountId: BigNumber;
balances: BigNumber[];
}>;
markets: Array<{
token: string;
decimals: number;
price: BigNumber;
}>;
}
const MARGIN_RATIO = 1.5;
const PRICE_DECIMALS = 18;
const MAKER_DECIMALS = 6;
const TAKER_DECIMALS = 18;
const INITIAL_TAKER_TOKEN_BALANCE = fromTokenUnitAmount(1000, TAKER_DECIMALS);
const BRIDGE_ADDRESS = randomAddress();
const ACCOUNT_OWNER = randomAddress();
const MAKER_PRICE = 150;
const TAKER_PRICE = 100;
const SOLVENT_ACCOUNT_IDX = 0;
// const MIN_SOLVENT_ACCOUNT_IDX = 1;
const INSOLVENT_ACCOUNT_IDX = 2;
const ZERO_BALANCE_ACCOUNT_IDX = 3;
const DYDX_CONFIG: TestDydxConfig = {
marginRatio: fromTokenUnitAmount(MARGIN_RATIO - 1, PRICE_DECIMALS),
operators: [{ owner: ACCOUNT_OWNER, operator: BRIDGE_ADDRESS }],
accounts: [
{
owner: ACCOUNT_OWNER,
accountId: getRandomInteger(1, 2 ** 64),
// Account exceeds collateralization.
balances: [fromTokenUnitAmount(10, TAKER_DECIMALS), fromTokenUnitAmount(-1, MAKER_DECIMALS)],
},
{
owner: ACCOUNT_OWNER,
accountId: getRandomInteger(1, 2 ** 64),
// Account is at minimum collateralization.
balances: [
fromTokenUnitAmount((MAKER_PRICE / TAKER_PRICE) * MARGIN_RATIO * 5, TAKER_DECIMALS),
fromTokenUnitAmount(-5, MAKER_DECIMALS),
],
},
{
owner: ACCOUNT_OWNER,
accountId: getRandomInteger(1, 2 ** 64),
// Account is undercollateralized..
balances: [fromTokenUnitAmount(1, TAKER_DECIMALS), fromTokenUnitAmount(-2, MAKER_DECIMALS)],
},
{
owner: ACCOUNT_OWNER,
accountId: getRandomInteger(1, 2 ** 64),
// Account has no balance.
balances: [fromTokenUnitAmount(0, TAKER_DECIMALS), fromTokenUnitAmount(0, MAKER_DECIMALS)],
},
],
markets: [
{
token: constants.NULL_ADDRESS, // TBD
decimals: TAKER_DECIMALS,
price: fromTokenUnitAmount(TAKER_PRICE, PRICE_DECIMALS),
},
{
token: constants.NULL_ADDRESS, // TBD
decimals: MAKER_DECIMALS,
price: fromTokenUnitAmount(MAKER_PRICE, PRICE_DECIMALS),
},
],
};
let dydx: TestDydxContract;
let testContract: TestLibDydxBalanceContract;
let assetDataContract: IAssetDataContract;
let takerTokenAddress: string;
let makerTokenAddress: string;
before(async () => {
assetDataContract = new IAssetDataContract(constants.NULL_ADDRESS, env.provider);
testContract = await TestLibDydxBalanceContract.deployWithLibrariesFrom0xArtifactAsync(
devUtilsArtifacts.TestLibDydxBalance,
devUtilsArtifacts,
env.provider,
env.txDefaults,
{},
);
// Create tokens.
takerTokenAddress = await testContract.createToken(TAKER_DECIMALS).callAsync();
await testContract.createToken(TAKER_DECIMALS).awaitTransactionSuccessAsync();
makerTokenAddress = await testContract.createToken(MAKER_DECIMALS).callAsync();
await testContract.createToken(MAKER_DECIMALS).awaitTransactionSuccessAsync();
DYDX_CONFIG.markets[0].token = takerTokenAddress;
DYDX_CONFIG.markets[1].token = makerTokenAddress;
dydx = await TestDydxContract.deployFrom0xArtifactAsync(
devUtilsArtifacts.TestDydx,
env.provider,
env.txDefaults,
{},
DYDX_CONFIG,
);
// Mint taker tokens.
await testContract
.setTokenBalance(takerTokenAddress, ACCOUNT_OWNER, INITIAL_TAKER_TOKEN_BALANCE)
.awaitTransactionSuccessAsync();
// Approve the Dydx contract to spend takerToken.
await testContract
.setTokenApproval(takerTokenAddress, ACCOUNT_OWNER, dydx.address, constants.MAX_UINT256)
.awaitTransactionSuccessAsync();
});
interface BalanceCheckInfo {
dydx: string;
bridgeAddress: string;
makerAddress: string;
makerTokenAddress: string;
takerTokenAddress: string;
orderMakerToTakerRate: BigNumber;
accounts: BigNumber[];
actions: DydxBridgeAction[];
}
function createBalanceCheckInfo(fields: Partial<BalanceCheckInfo> = {}): BalanceCheckInfo {
return {
dydx: dydx.address,
bridgeAddress: BRIDGE_ADDRESS,
makerAddress: ACCOUNT_OWNER,
makerTokenAddress: DYDX_CONFIG.markets[1].token,
takerTokenAddress: DYDX_CONFIG.markets[0].token,
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(10, TAKER_DECIMALS).div(fromTokenUnitAmount(5, MAKER_DECIMALS)),
),
accounts: [DYDX_CONFIG.accounts[SOLVENT_ACCOUNT_IDX].accountId],
actions: [],
...fields,
};
}
function getFilledAccountCollateralizations(
config: TestDydxConfig,
checkInfo: BalanceCheckInfo,
makerAssetFillAmount: BigNumber,
): BigNumber[] {
const values: BigNumber[][] = checkInfo.accounts.map((accountId, accountIdx) => {
const accountBalances = config.accounts[accountIdx].balances.slice();
for (const action of checkInfo.actions) {
const actionMarketId = action.marketId.toNumber();
const actionAccountIdx = action.accountIdx.toNumber();
if (checkInfo.accounts[actionAccountIdx] !== accountId) {
continue;
}
const rate = action.conversionRateDenominator.eq(0)
? new BigNumber(1)
: action.conversionRateNumerator.div(action.conversionRateDenominator);
const change = makerAssetFillAmount.times(
action.actionType === DydxBridgeActionType.Deposit ? rate : rate.negated(),
);
accountBalances[actionMarketId] = change.plus(accountBalances[actionMarketId]);
}
return accountBalances.map((b, marketId) =>
toTokenUnitAmount(b, config.markets[marketId].decimals).times(
toTokenUnitAmount(config.markets[marketId].price, PRICE_DECIMALS),
),
);
});
return values
.map(accountValues => {
return [
// supply
BigNumber.sum(...accountValues.filter(b => b.gte(0))),
// borrow
BigNumber.sum(...accountValues.filter(b => b.lt(0))).abs(),
];
})
.map(([supply, borrow]) => supply.div(borrow));
}
function getRandomRate(): BigNumber {
return getRandomFloat(0, 1);
}
// Computes a deposit rate that is the minimum to keep an account solvent
// perpetually.
function getBalancedDepositRate(withdrawRate: BigNumber, scaling: Numberish = 1): BigNumber {
// Add a small amount to the margin ratio to stay just above insolvency.
return withdrawRate.times((MAKER_PRICE / TAKER_PRICE) * (MARGIN_RATIO + 1.1e-4)).times(scaling);
}
function takerToMakerAmount(takerAmount: BigNumber): BigNumber {
return takerAmount.times(new BigNumber(10).pow(MAKER_DECIMALS - TAKER_DECIMALS));
}
describe('_getSolventMakerAmount()', () => {
it('computes fillable amount for a solvent maker', async () => {
// Deposit collateral at a rate low enough to steadily reduce the
// withdraw account's collateralization ratio.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate, Math.random());
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// The collateralization ratio after filling `makerAssetFillAmount`
// should be exactly at `MARGIN_RATIO`.
const cr = getFilledAccountCollateralizations(DYDX_CONFIG, checkInfo, makerAssetFillAmount);
expect(cr[0].dp(2)).to.bignumber.eq(MARGIN_RATIO);
});
it('computes fillable amount for a solvent maker with zero-sized deposits', async () => {
const withdrawRate = getRandomRate();
const depositRate = new BigNumber(0);
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// The collateralization ratio after filling `makerAssetFillAmount`
// should be exactly at `MARGIN_RATIO`.
const cr = getFilledAccountCollateralizations(DYDX_CONFIG, checkInfo, makerAssetFillAmount);
expect(cr[0].dp(2)).to.bignumber.eq(MARGIN_RATIO);
});
it('computes fillable amount for a solvent maker with no deposits', async () => {
const withdrawRate = getRandomRate();
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// The collateralization ratio after filling `makerAssetFillAmount`
// should be exactly at `MARGIN_RATIO`.
const cr = getFilledAccountCollateralizations(DYDX_CONFIG, checkInfo, makerAssetFillAmount);
expect(cr[0].dp(2)).to.bignumber.eq(MARGIN_RATIO);
});
it('computes fillable amount for a solvent maker with multiple deposits', async () => {
// Deposit collateral at a rate low enough to steadily reduce the
// withdraw account's collateralization ratio.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate, Math.random());
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.75), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.25), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// The collateralization ratio after filling `makerAssetFillAmount`
// should be exactly at `MARGIN_RATIO`.
const cr = getFilledAccountCollateralizations(DYDX_CONFIG, checkInfo, makerAssetFillAmount);
expect(cr[0].dp(2)).to.bignumber.eq(MARGIN_RATIO);
});
it('returns infinite amount for a perpetually solvent maker', async () => {
// Deposit collateral at a rate that keeps the withdraw account's
// collateralization ratio constant.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate);
const checkInfo = createBalanceCheckInfo({
// Deposit/Withdraw at a rate == marginRatio.
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
});
it('returns infinite amount for a perpetually solvent maker with multiple deposits', async () => {
// Deposit collateral at a rate that keeps the withdraw account's
// collateralization ratio constant.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate);
const checkInfo = createBalanceCheckInfo({
// Deposit/Withdraw at a rate == marginRatio.
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.25), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.75), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
});
it('does not count deposits to other accounts', async () => {
// Deposit collateral at a rate that keeps the withdraw account's
// collateralization ratio constant, BUT we split it in two deposits
// and one will go into a different account.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate);
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.5), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Deposit,
// Deposit enough to balance out withdraw, but
// into a different account.
accountIdx: new BigNumber(1),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate.times(0.5), TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
});
it('returns zero on an account that is under-collateralized', async () => {
// Even though the deposit rate is enough to meet the minimum collateralization ratio,
// the account is under-collateralized from the start, so cannot be filled.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate);
const checkInfo = createBalanceCheckInfo({
accounts: [DYDX_CONFIG.accounts[INSOLVENT_ACCOUNT_IDX].accountId],
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(0);
});
it(
'returns zero on an account that has no balance if deposit ' +
'to withdraw ratio is < the minimum collateralization rate',
async () => {
// If the deposit rate is not enough to meet the minimum collateralization ratio,
// the fillable maker amount is zero because it will become insolvent as soon as
// the withdraw occurs.
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate, 0.99);
const checkInfo = createBalanceCheckInfo({
accounts: [DYDX_CONFIG.accounts[ZERO_BALANCE_ACCOUNT_IDX].accountId],
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(0);
},
);
it(
'returns infinite on an account that has no balance if deposit ' +
'to withdraw ratio is >= the minimum collateralization rate',
async () => {
const withdrawRate = getRandomRate();
const depositRate = getBalancedDepositRate(withdrawRate);
const checkInfo = createBalanceCheckInfo({
accounts: [DYDX_CONFIG.accounts[ZERO_BALANCE_ACCOUNT_IDX].accountId],
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: fromTokenUnitAmount(withdrawRate),
conversionRateDenominator: fromTokenUnitAmount(1),
},
],
});
const makerAssetFillAmount = await testContract.getSolventMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
},
);
});
blockchainTests.resets('_getDepositableMakerAmount()', () => {
it('returns infinite if no deposit action', async () => {
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(10, TAKER_DECIMALS).div(fromTokenUnitAmount(100, MAKER_DECIMALS)),
),
actions: [],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
});
it('returns infinite if deposit rate is zero', async () => {
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(10, TAKER_DECIMALS).div(fromTokenUnitAmount(100, MAKER_DECIMALS)),
),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(0, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
});
it('returns infinite if taker tokens cover the deposit rate', async () => {
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(10, TAKER_DECIMALS).div(fromTokenUnitAmount(100, MAKER_DECIMALS)),
),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(Math.random() * 0.1, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(constants.MAX_UINT256);
});
it('returns correct amount if taker tokens only partially cover deposit rate', async () => {
// The taker tokens getting exchanged in will only partially cover the deposit.
const exchangeRate = 0.1;
const depositRate = Math.random() + exchangeRate;
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(exchangeRate, TAKER_DECIMALS).div(fromTokenUnitAmount(1, MAKER_DECIMALS)),
),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// Compute the equivalent taker asset fill amount.
const takerAssetFillAmount = fromTokenUnitAmount(
toTokenUnitAmount(makerAssetFillAmount, MAKER_DECIMALS)
// Reduce the deposit rate by the exchange rate.
.times(depositRate - exchangeRate),
TAKER_DECIMALS,
);
// Which should equal the entire taker token balance of the account owner.
// We do some rounding to account for integer vs FP vs symbolic precision differences.
expect(toTokenUnitAmount(takerAssetFillAmount, TAKER_DECIMALS).dp(5)).to.bignumber.eq(
toTokenUnitAmount(INITIAL_TAKER_TOKEN_BALANCE, TAKER_DECIMALS).dp(5),
);
});
it('returns correct amount if the taker asset not an ERC20', async () => {
const depositRate = 0.1;
const checkInfo = createBalanceCheckInfo({
// The `takerTokenAddress` will be zero if the asset is not an ERC20.
takerTokenAddress: constants.NULL_ADDRESS,
orderMakerToTakerRate: fromTokenUnitAmount(fromTokenUnitAmount(0.1, MAKER_DECIMALS)),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// Compute the equivalent taker asset fill amount.
const takerAssetFillAmount = fromTokenUnitAmount(
toTokenUnitAmount(makerAssetFillAmount, MAKER_DECIMALS)
// Reduce the deposit rate by the exchange rate.
.times(depositRate),
TAKER_DECIMALS,
);
// Which should equal the entire taker token balance of the account owner.
// We do some rounding to account for integer vs FP vs symbolic precision differences.
expect(toTokenUnitAmount(takerAssetFillAmount, TAKER_DECIMALS).dp(6)).to.bignumber.eq(
toTokenUnitAmount(INITIAL_TAKER_TOKEN_BALANCE, TAKER_DECIMALS).dp(6),
);
});
it('returns the correct amount if taker:maker deposit rate is 1:1 and' + 'token != taker token', async () => {
const checkInfo = createBalanceCheckInfo({
takerTokenAddress: randomAddress(),
// These amounts should be effectively ignored in the final computation
// because the token being deposited is not the taker token.
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(10, TAKER_DECIMALS).div(fromTokenUnitAmount(100, MAKER_DECIMALS)),
),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(1, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(takerToMakerAmount(INITIAL_TAKER_TOKEN_BALANCE));
});
it('returns the smallest viable maker amount with multiple deposits', async () => {
// The taker tokens getting exchanged in will only partially cover the deposit.
const exchangeRate = 0.1;
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(
fromTokenUnitAmount(exchangeRate, TAKER_DECIMALS).div(fromTokenUnitAmount(1, MAKER_DECIMALS)),
),
actions: [
// Technically, deposits of the same token are not allowed, but the
// check isn't done in this function so we'll do this to simulate
// two deposits to distinct tokens.
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(Math.random() + exchangeRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(Math.random() + exchangeRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.not.bignumber.eq(constants.MAX_UINT256);
// Extract the deposit rates.
const depositRates = checkInfo.actions.map(a =>
toTokenUnitAmount(a.conversionRateNumerator, TAKER_DECIMALS).div(
toTokenUnitAmount(a.conversionRateDenominator, MAKER_DECIMALS),
),
);
// The largest deposit rate will result in the smallest maker asset fill amount.
const maxDepositRate = BigNumber.max(...depositRates);
// Compute the equivalent taker asset fill amounts.
const takerAssetFillAmount = fromTokenUnitAmount(
toTokenUnitAmount(makerAssetFillAmount, MAKER_DECIMALS)
// Reduce the deposit rate by the exchange rate.
.times(maxDepositRate.minus(exchangeRate)),
TAKER_DECIMALS,
);
// Which should equal the entire taker token balance of the account owner.
// We do some rounding to account for integer vs FP vs symbolic precision differences.
expect(toTokenUnitAmount(takerAssetFillAmount, TAKER_DECIMALS).dp(5)).to.bignumber.eq(
toTokenUnitAmount(INITIAL_TAKER_TOKEN_BALANCE, TAKER_DECIMALS).dp(5),
);
});
it(
'returns zero if the maker has no taker tokens and the deposit rate is' + 'greater than the exchange rate',
async () => {
await testContract
.setTokenBalance(takerTokenAddress, ACCOUNT_OWNER, constants.ZERO_AMOUNT)
.awaitTransactionSuccessAsync();
// The taker tokens getting exchanged in will only partially cover the deposit.
const exchangeRate = 0.1;
const depositRate = Math.random() + exchangeRate;
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(fromTokenUnitAmount(1 / exchangeRate, MAKER_DECIMALS)),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(0);
},
);
it(
'returns zero if dydx has no taker token allowance and the deposit rate is' +
'greater than the exchange rate',
async () => {
await testContract
.setTokenApproval(takerTokenAddress, ACCOUNT_OWNER, dydx.address, constants.ZERO_AMOUNT)
.awaitTransactionSuccessAsync();
// The taker tokens getting exchanged in will only partially cover the deposit.
const exchangeRate = 0.1;
const depositRate = Math.random() + exchangeRate;
const checkInfo = createBalanceCheckInfo({
orderMakerToTakerRate: fromTokenUnitAmount(fromTokenUnitAmount(1 / exchangeRate, MAKER_DECIMALS)),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(depositRate, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
],
});
const makerAssetFillAmount = await testContract.getDepositableMakerAmount(checkInfo).callAsync();
expect(makerAssetFillAmount).to.bignumber.eq(0);
},
);
});
describe('_areActionsWellFormed()', () => {
it('Returns false if no actions', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if there is an account index out of range in deposits', async () => {
const checkInfo = createBalanceCheckInfo({
accounts: DYDX_CONFIG.accounts.slice(0, 2).map(a => a.accountId),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(2),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if a market is not unique among deposits', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if no withdraw at the end', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if a withdraw comes before a deposit', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if more than one withdraw', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if withdraw is not for maker token', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Returns false if withdraw is for an out of range account', async () => {
const checkInfo = createBalanceCheckInfo({
accounts: DYDX_CONFIG.accounts.slice(0, 2).map(a => a.accountId),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(2),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.false();
});
it('Can return true if no deposit', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.true();
});
it('Can return true if no deposit', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.true();
});
it('Can return true with multiple deposits', async () => {
const checkInfo = createBalanceCheckInfo({
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
});
const r = await testContract.areActionsWellFormed(checkInfo).callAsync();
expect(r).to.be.true();
});
});
function createERC20AssetData(tokenAddress: string): string {
return assetDataContract.ERC20Token(tokenAddress).getABIEncodedTransactionData();
}
function createERC721AssetData(tokenAddress: string, tokenId: BigNumber): string {
return assetDataContract.ERC721Token(tokenAddress, tokenId).getABIEncodedTransactionData();
}
function createBridgeAssetData(
makerTokenAddress_: string,
bridgeAddress: string,
data: Partial<DydxBridgeData> = {},
): string {
return assetDataContract
.ERC20Bridge(
makerTokenAddress_,
bridgeAddress,
dydxBridgeDataEncoder.encode({
bridgeData: {
accountNumbers: DYDX_CONFIG.accounts.slice(0, 1).map(a => a.accountId),
actions: [
{
actionType: DydxBridgeActionType.Deposit,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: fromTokenUnitAmount(1, TAKER_DECIMALS),
conversionRateDenominator: fromTokenUnitAmount(1, MAKER_DECIMALS),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
...data,
},
}),
)
.getABIEncodedTransactionData();
}
function createOrder(orderFields: Partial<Order> = {}): Order {
return {
chainId: 1,
exchangeAddress: randomAddress(),
salt: getRandomInteger(1, constants.MAX_UINT256),
expirationTimeSeconds: getRandomInteger(1, constants.MAX_UINT256),
feeRecipientAddress: randomAddress(),
makerAddress: ACCOUNT_OWNER,
takerAddress: constants.NULL_ADDRESS,
senderAddress: constants.NULL_ADDRESS,
makerFee: getRandomInteger(1, constants.MAX_UINT256),
takerFee: getRandomInteger(1, constants.MAX_UINT256),
makerAssetAmount: fromTokenUnitAmount(100, MAKER_DECIMALS),
takerAssetAmount: fromTokenUnitAmount(10, TAKER_DECIMALS),
makerAssetData: createBridgeAssetData(makerTokenAddress, BRIDGE_ADDRESS),
takerAssetData: createERC20AssetData(takerTokenAddress),
makerFeeAssetData: constants.NULL_BYTES,
takerFeeAssetData: constants.NULL_BYTES,
...orderFields,
};
}
describe('getDydxMakerBalance()', () => {
it('returns nonzero with valid order', async () => {
const order = createOrder();
const r = await testContract.getDydxMakerBalance(order, dydx.address).callAsync();
expect(r).to.not.bignumber.eq(0);
});
it('returns nonzero with valid order with an ERC721 taker asset', async () => {
const order = createOrder({
takerAssetData: createERC721AssetData(randomAddress(), getRandomInteger(1, constants.MAX_UINT256)),
});
const r = await testContract.getDydxMakerBalance(order, dydx.address).callAsync();
expect(r).to.not.bignumber.eq(0);
});
it('returns 0 if bridge is not a local operator', async () => {
const order = createOrder({
makerAssetData: createBridgeAssetData(ACCOUNT_OWNER, randomAddress()),
});
const r = await testContract.getDydxMakerBalance(order, dydx.address).callAsync();
expect(r).to.bignumber.eq(0);
});
it('returns 0 if bridge data does not have well-formed actions', async () => {
const order = createOrder({
makerAssetData: createBridgeAssetData(takerTokenAddress, BRIDGE_ADDRESS, {
// Two withdraw actions is invalid.
actions: [
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(0),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0),
conversionRateDenominator: new BigNumber(0),
},
],
}),
});
const r = await testContract.getDydxMakerBalance(order, dydx.address).callAsync();
expect(r).to.bignumber.eq(0);
});
it('returns 0 if the maker token withdraw rate is < 1', async () => {
const order = createOrder({
makerAssetData: createBridgeAssetData(takerTokenAddress, BRIDGE_ADDRESS, {
actions: [
{
actionType: DydxBridgeActionType.Withdraw,
accountIdx: new BigNumber(0),
marketId: new BigNumber(1),
conversionRateNumerator: new BigNumber(0.99e18),
conversionRateDenominator: new BigNumber(1e18),
},
],
}),
});
const r = await testContract.getDydxMakerBalance(order, dydx.address).callAsync();
expect(r).to.bignumber.eq(0);
});
});
});
// tslint:disable-next-line: max-file-line-count | the_stack |
import type { PluginInfo, MdNode, PluginContext } from '@toast-ui/editor';
import Chart, {
BaseOptions,
LineChart,
AreaChart,
BarChart,
PieChart,
ColumnChart,
} from '@toast-ui/chart';
import isString from 'tui-code-snippet/type/isString';
import isUndefined from 'tui-code-snippet/type/isUndefined';
import inArray from 'tui-code-snippet/array/inArray';
import extend from 'tui-code-snippet/object/extend';
// @ts-ignore
import ajax from 'tui-code-snippet/ajax/index.js';
import { PluginOptions } from '@t/index';
import csv from './csv';
import { trimKeepingTabs, isNumeric, clamp } from './util';
// csv configuration
csv.IGNORE_QUOTE_WHITESPACE = false;
csv.IGNORE_RECORD_LENGTH = true;
csv.DETECT_TYPES = false;
const reEOL = /[\n\r]/;
const reGroupByDelimiter = /([^:]+)?:?(.*)/;
const DEFAULT_DELIMITER = /\s+/;
const DELIMITERS = [',', '\t'];
const MINIMUM_DELIM_CNT = 2;
const SUPPORTED_CHART_TYPES = ['bar', 'column', 'line', 'area', 'pie'];
const CATEGORY_CHART_TYPES = ['line', 'area'];
const DEFAULT_DIMENSION_OPTIONS = {
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity,
height: 'auto',
width: 'auto',
};
const RESERVED_KEYS = ['type', 'url'];
const chart = {
bar: Chart.barChart,
column: Chart.columnChart,
area: Chart.areaChart,
line: Chart.lineChart,
pie: Chart.pieChart,
};
const chartMap: Record<string, ChartInstance> = {};
type ChartType = keyof typeof chart;
export type ChartOptions = BaseOptions & { editorChart: { type?: ChartType; url?: string } };
type ChartInstance = BarChart | ColumnChart | AreaChart | LineChart | PieChart;
type ChartData = {
categories: string[];
series: { data: number[]; name?: string }[];
};
type ParserCallback = (parsedInfo?: { data: ChartData; options?: ChartOptions }) => void;
type OnSuccess = (res: { data: any }) => void;
export function parse(text: string, callback: ParserCallback) {
text = trimKeepingTabs(text);
const [firstTexts, secondTexts] = text.split(/\n{2,}/);
const urlOptions = parseToChartOption(firstTexts);
const url = urlOptions?.editorChart?.url;
// if first text is `options` and has `url` option, fetch data from url
if (isString(url)) {
// url option provided
// fetch data from url
const success: OnSuccess = ({ data }) => {
callback({ data: parseToChartData(data), options: parseToChartOption(firstTexts) });
};
const error = () => callback();
ajax.get(url, { success, error });
} else {
const data = parseToChartData(firstTexts);
const options = parseToChartOption(secondTexts);
callback({ data, options });
}
}
export function detectDelimiter(text: string) {
let delimiter: string | RegExp = DEFAULT_DELIMITER;
let delimCnt = 0;
text = trimKeepingTabs(text);
DELIMITERS.forEach((delim) => {
const matched = text.match(new RegExp(delim, 'g'))!;
if (matched?.length > Math.max(MINIMUM_DELIM_CNT, delimCnt)) {
delimiter = delim;
delimCnt = matched.length;
}
});
return delimiter;
}
export function parseToChartData(text: string, delimiter?: string | RegExp) {
// trim all heading/trailing blank lines
text = trimKeepingTabs(text);
// @ts-ignore
csv.COLUMN_SEPARATOR = delimiter || detectDelimiter(text);
let dsv: string[][] = csv.parse(text);
// trim all values in 2D array
dsv = dsv.map((arr) => arr.map((val) => val.trim()));
// test a first row for legends. ['anything', '1', '2', '3'] === false, ['anything', 't1', '2', 't3'] === true
const hasLegends = dsv[0]
.filter((_, i) => i > 0)
.reduce((hasNaN, item) => hasNaN || !isNumeric(item), false);
const legends = hasLegends ? dsv.shift()! : [];
// test a first column for categories
const hasCategories = dsv.slice(1).reduce((hasNaN, row) => hasNaN || !isNumeric(row[0]), false);
const categories = hasCategories ? dsv.map((arr) => arr.shift()!) : [];
if (hasCategories) {
legends.shift();
}
// transpose dsv, parse number
// [['1','2','3'] [[1,4,7]
// ['4','5','6'] => [2,5,8]
// ['7','8','9']] [3,6,9]]
const tdsv = dsv[0].map((_, i) => dsv.map((x) => parseFloat(x[i])));
// make series
const series = tdsv.map((data, i) =>
hasLegends
? {
name: legends[i],
data,
}
: {
data,
}
);
return { categories, series };
}
function createOptionKeys(keyString: string) {
const keys = keyString.trim().split('.');
const [topKey] = keys;
if (inArray(topKey, RESERVED_KEYS) >= 0) {
// reserved keys for chart plugin option
keys.unshift('editorChart');
} else if (keys.length === 1) {
// short names for `chart`
keys.unshift('chart');
} else if (topKey === 'x' || topKey === 'y') {
// short-handed keys
keys[0] = `${topKey}Axis`;
}
return keys;
}
export function parseToChartOption(text: string) {
const options: Record<string, any> = {};
if (!isUndefined(text)) {
const lineTexts = text.split(reEOL);
lineTexts.forEach((lineText) => {
const matched = lineText.match(reGroupByDelimiter);
if (matched) {
// keyString can be nested object keys
// ex) key1.key2.key3: value
// eslint-disable-next-line prefer-const
let [, keyString, value] = matched;
if (value) {
try {
value = JSON.parse(value.trim());
} catch (e) {
value = value.trim();
}
const keys = createOptionKeys(keyString);
let refOptions = options;
keys.forEach((key, index) => {
refOptions[key] = refOptions[key] || (keys.length - 1 === index ? value : {});
// should change the ref option object to assign nested property
refOptions = refOptions[key];
});
}
}
});
}
return options as ChartOptions;
}
function getAdjustedDimension(size: 'auto' | number, containerWidth: number) {
return size === 'auto' ? containerWidth : size;
}
function getChartDimension(
chartOptions: ChartOptions,
pluginOptions: PluginOptions,
chartContainer: HTMLElement
) {
const dimensionOptions = extend({ ...DEFAULT_DIMENSION_OPTIONS }, pluginOptions);
const { maxWidth, minWidth, maxHeight, minHeight } = dimensionOptions;
// if no width or height specified, set width and height to container width
const { width: containerWidth } = chartContainer.getBoundingClientRect();
let { width = dimensionOptions.width, height = dimensionOptions.height } = chartOptions.chart!;
width = getAdjustedDimension(width, containerWidth);
height = getAdjustedDimension(height, containerWidth);
return {
width: clamp(width, minWidth, maxWidth),
height: clamp(height, minHeight, maxHeight),
};
}
export function setDefaultOptions(
chartOptions: ChartOptions,
pluginOptions: PluginOptions,
chartContainer: HTMLElement
) {
chartOptions = extend(
{
editorChart: {},
chart: {},
exportMenu: {},
},
chartOptions
);
const { width, height } = getChartDimension(chartOptions, pluginOptions, chartContainer);
chartOptions.chart!.width = width;
chartOptions.chart!.height = height;
// default chart type
chartOptions.editorChart.type = chartOptions.editorChart.type || 'column';
// default visibility of export menu
chartOptions.exportMenu!.visible = !!chartOptions.exportMenu!.visible;
return chartOptions;
}
function destroyChart() {
Object.keys(chartMap).forEach((id) => {
const container = document.querySelector<HTMLElement>(`[data-chart-id=${id}]`);
if (!container) {
chartMap[id].destroy();
delete chartMap[id];
}
});
}
function renderChart(
id: string,
text: string,
usageStatistics: boolean,
pluginOptions: PluginOptions
) {
// should draw the chart after rendering container element
const chartContainer = document.querySelector<HTMLElement>(`[data-chart-id=${id}]`)!;
destroyChart();
if (chartContainer) {
try {
parse(text, (parsedInfo) => {
const { data, options } = parsedInfo || {};
const chartOptions = setDefaultOptions(options!, pluginOptions, chartContainer);
const chartType = chartOptions.editorChart.type!;
if (
!data ||
(CATEGORY_CHART_TYPES.indexOf(chartType) > -1 &&
data.categories.length !== data.series[0].data.length)
) {
chartContainer.innerHTML = 'invalid chart data';
} else if (SUPPORTED_CHART_TYPES.indexOf(chartType) < 0) {
chartContainer.innerHTML = `invalid chart type. type: bar, column, line, area, pie`;
} else {
const toastuiChart = chart[chartType];
chartOptions.usageStatistics = usageStatistics;
// @ts-ignore
chartMap[id] = toastuiChart({ el: chartContainer, data, options: chartOptions });
}
});
} catch (e) {
chartContainer.innerHTML = 'invalid chart data';
}
}
}
function generateId() {
return `chart-${Math.random().toString(36).substr(2, 10)}`;
}
/**
* Chart plugin
* @param {Object} context - plugin context for communicating with editor
* @param {Object} options - chart options
* @param {number} [options.minWidth=0] - minimum width
* @param {number} [options.minHeight=0] - minimum height
* @param {number} [options.maxWidth=Infinity] - maximum width
* @param {number} [options.maxHeight=Infinity] - maximum height
* @param {number|string} [options.width='auto'] - default width
* @param {number|string} [options.height='auto'] - default height
*/
export default function chartPlugin(
{ usageStatistics = true }: PluginContext,
options: PluginOptions
): PluginInfo {
return {
toHTMLRenderers: {
chart(node: MdNode) {
const id = generateId();
setTimeout(() => {
renderChart(id, node.literal!, usageStatistics, options);
});
return [
{
type: 'openTag',
tagName: 'div',
outerNewLine: true,
attributes: { 'data-chart-id': id },
},
{ type: 'closeTag', tagName: 'div', outerNewLine: true },
];
},
},
};
} | the_stack |
import {Mutable, Class, Proto, Equals, Arrays, ConsumerType, Consumable, Consumer} from "@swim/util";
import {FastenerOwner, FastenerFlags, FastenerInit, FastenerClass, Fastener} from "@swim/component";
import {AnyValue, Value} from "@swim/structure";
import {AnyUri, Uri} from "@swim/uri";
import type {DownlinkObserver, Downlink} from "../downlink/Downlink";
import type {WarpRef} from "../ref/WarpRef";
import type {DownlinkFastenerContext} from "./DownlinkFastenerContext";
/** @beta */
export interface DownlinkFastenerInit extends FastenerInit, DownlinkObserver {
extends?: {prototype: DownlinkFastener<any>} | string | boolean | null;
consumed?: boolean;
hostUri?: AnyUri | (() => AnyUri | null);
nodeUri?: AnyUri | (() => AnyUri | null);
laneUri?: AnyUri | (() => AnyUri | null);
prio?: number | (() => number | undefined);
rate?: number | (() => number | undefined);
body?: AnyValue | (() => AnyValue | null);
willConsume?(conssumer: unknown): void;
didConsume?(conssumer: unknown): void;
willUnconsume?(conssumer: unknown): void;
didUnconsume?(conssumer: unknown): void;
willStartConsuming?(): void;
didStartConsuming?(): void;
willStopConsuming?(): void;
didStopConsuming?(): void;
initDownlink?(downlink: Downlink): Downlink;
}
/** @beta */
export type DownlinkFastenerDescriptor<O = unknown, I = {}> = ThisType<DownlinkFastener<O> & I> & DownlinkFastenerInit & Partial<I>;
/** @beta */
export interface DownlinkFastenerClass<F extends DownlinkFastener<any> = DownlinkFastener<any>> extends FastenerClass<F> {
/** @internal */
readonly ConsumingFlag: FastenerFlags;
/** @internal */
readonly PendingFlag: FastenerFlags;
/** @internal */
readonly RelinkMask: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @beta */
export interface DownlinkFastenerFactory<F extends DownlinkFastener<any> = DownlinkFastener<any>> extends DownlinkFastenerClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): DownlinkFastenerFactory<F> & I;
define<O>(className: string, descriptor: DownlinkFastenerDescriptor<O>): DownlinkFastenerFactory<DownlinkFastener<any>>;
define<O, I = {}>(className: string, descriptor: {implements: unknown} & DownlinkFastenerDescriptor<O, I>): DownlinkFastenerFactory<DownlinkFastener<any> & I>;
<O>(descriptor: DownlinkFastenerDescriptor<O>): PropertyDecorator;
<O, I = {}>(descriptor: {implements: unknown} & DownlinkFastenerDescriptor<O, I>): PropertyDecorator;
}
/** @beta */
export interface DownlinkFastener<O = unknown> extends Fastener<O>, Consumable {
/** @override */
get fastenerType(): Proto<DownlinkFastener<any>>;
/** @override */
readonly consumerType?: Class<Consumer>;
/** @protected @override */
onInherit(superFastener: Fastener): void;
/** @internal */
readonly ownHostUri: Uri | null;
hostUri(): Uri | null;
hostUri(hostUri: AnyUri | null): this;
/** @internal */
readonly ownNodeUri: Uri | null;
nodeUri(): Uri | null;
nodeUri(nodeUri: AnyUri | null): this;
/** @internal */
readonly ownLaneUri: Uri | null;
laneUri(): Uri | null;
laneUri(laneUri: AnyUri | null): this;
/** @internal */
readonly ownPrio: number | undefined;
prio(): number | undefined;
prio(prio: number | undefined): this;
/** @internal */
readonly ownRate: number | undefined;
rate(): number | undefined;
rate(rate: number | undefined): this;
/** @internal */
readonly ownBody: Value | null;
body(): Value | null;
body(body: AnyValue | null): this;
/** @internal */
readonly ownWarp: WarpRef | null;
warp(): WarpRef | null;
warp(warp: WarpRef | null): this;
readonly downlink: Downlink | null;
/** @internal */
link(): void;
/** @internal */
unlink(): void;
/** @internal */
relink(): void;
/** @internal @abstract */
createDownlink(warp: WarpRef): Downlink;
/** @internal */
bindDownlink(downlink: Downlink): Downlink;
/** @override */
recohere(t: number): void;
/** @internal */
readonly consumers: ReadonlyArray<ConsumerType<this>>;
/** @override */
consume(consumer: ConsumerType<this>): void
/** @protected */
willConsume(consumer: ConsumerType<this>): void;
/** @protected */
onConsume(consumer: ConsumerType<this>): void;
/** @protected */
didConsume(consumer: ConsumerType<this>): void;
/** @override */
unconsume(consumer: ConsumerType<this>): void
/** @protected */
willUnconsume(consumer: ConsumerType<this>): void;
/** @protected */
onUnconsume(consumer: ConsumerType<this>): void;
/** @protected */
didUnconsume(consumer: ConsumerType<this>): void;
get consuming(): boolean;
/** @internal */
startConsuming(): void;
/** @protected */
willStartConsuming(): void;
/** @protected */
onStartConsuming(): void;
/** @protected */
didStartConsuming(): void;
/** @internal */
stopConsuming(): void;
/** @protected */
willStopConsuming(): void;
/** @protected */
onStopConsuming(): void;
/** @protected */
didStopConsuming(): void;
/** @protected @override */
onMount(): void;
/** @protected @override */
onUnmount(): void;
/** @internal */
initDownlink?(downlink: Downlink): Downlink;
/** @internal */
initHostUri?(): AnyUri | null;
/** @internal */
initNodeUri?(): AnyUri | null;
/** @internal */
initLaneUri?(): AnyUri | null;
/** @internal */
initPrio?(): number | undefined;
/** @internal */
initRate?(): number | undefined;
/** @internal */
initBody?(): AnyValue | null;
/** @internal @protected */
get consumed(): boolean | undefined; // optional prototype property
/** @internal @override */
get lazy(): boolean; // prototype property
/** @internal @override */
get static(): string | boolean; // prototype property
}
/** @beta */
export const DownlinkFastener = (function (_super: typeof Fastener) {
const DownlinkFastener: DownlinkFastenerFactory = _super.extend("DownlinkFastener");
Object.defineProperty(DownlinkFastener.prototype, "fastenerType", {
get: function (this: DownlinkFastener): Proto<DownlinkFastener<any>> {
return DownlinkFastener;
},
configurable: true,
});
DownlinkFastener.prototype.onInherit = function (this: DownlinkFastener, superFastener: DownlinkFastener): void {
// hook
};
DownlinkFastener.prototype.hostUri = function (this: DownlinkFastener<unknown>, hostUri?: AnyUri | null): Uri | null | typeof this {
if (hostUri === void 0) {
if (this.ownHostUri !== null) {
return this.ownHostUri;
} else {
hostUri = this.initHostUri !== void 0 ? this.initHostUri() : null;
if (hostUri !== null) {
hostUri = Uri.fromAny(hostUri);
(this as Mutable<typeof this>).ownHostUri = hostUri;
}
return hostUri;
}
} else {
if (hostUri !== null) {
hostUri = Uri.fromAny(hostUri);
}
if (!Equals(this.ownHostUri, hostUri)) {
(this as Mutable<typeof this>).ownHostUri = hostUri;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.hostUri;
DownlinkFastener.prototype.nodeUri = function (this: DownlinkFastener<unknown>, nodeUri?: AnyUri | null): Uri | null | typeof this {
if (nodeUri === void 0) {
if (this.ownNodeUri !== null) {
return this.ownNodeUri;
} else {
nodeUri = this.initNodeUri !== void 0 ? this.initNodeUri() : null;
if (nodeUri !== null) {
nodeUri = Uri.fromAny(nodeUri);
(this as Mutable<typeof this>).ownNodeUri = nodeUri;
}
return nodeUri;
}
} else {
if (nodeUri !== null) {
nodeUri = Uri.fromAny(nodeUri);
}
if (!Equals(this.ownNodeUri, nodeUri)) {
(this as Mutable<typeof this>).ownNodeUri = nodeUri;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.nodeUri;
DownlinkFastener.prototype.laneUri = function (this: DownlinkFastener<unknown>, laneUri?: AnyUri | null): Uri | null | typeof this {
if (laneUri === void 0) {
if (this.ownLaneUri !== null) {
return this.ownLaneUri;
} else {
laneUri = this.initLaneUri !== void 0 ? this.initLaneUri() : null;
if (laneUri !== null) {
laneUri = Uri.fromAny(laneUri);
(this as Mutable<typeof this>).ownLaneUri = laneUri;
}
return laneUri;
}
} else {
if (laneUri !== null) {
laneUri = Uri.fromAny(laneUri);
}
if (!Equals(this.ownLaneUri, laneUri)) {
(this as Mutable<typeof this>).ownLaneUri = laneUri;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.laneUri;
DownlinkFastener.prototype.prio = function (this: DownlinkFastener<unknown>, prio?: number | undefined): number | undefined | typeof this {
if (arguments.length === 0) {
if (this.ownPrio !== void 0) {
return this.ownPrio;
} else {
prio = this.initPrio !== void 0 ? this.initPrio() : void 0;
if (prio !== void 0) {
(this as Mutable<typeof this>).ownPrio = prio;
}
return prio;
}
} else {
if (this.ownPrio !== prio) {
(this as Mutable<typeof this>).ownPrio = prio;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.prio;
DownlinkFastener.prototype.rate = function (this: DownlinkFastener<unknown>, rate?: number | undefined): number | undefined | typeof this {
if (arguments.length === 0) {
if (this.ownRate !== void 0) {
return this.ownRate;
} else {
rate = this.initRate !== void 0 ? this.initRate() : void 0;
if (rate !== void 0) {
(this as Mutable<typeof this>).ownRate = rate;
}
return rate;
}
} else {
if (this.ownRate !== rate) {
(this as Mutable<typeof this>).ownRate = rate;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.rate;
DownlinkFastener.prototype.body = function (this: DownlinkFastener<unknown>, body?: AnyValue | null): Value | null | typeof this {
if (body === void 0) {
if (this.ownBody !== null) {
return this.ownBody;
} else {
body = this.initBody !== void 0 ? this.initBody() : null;
if (body !== null) {
body = Value.fromAny(body);
(this as Mutable<typeof this>).ownBody = body;
}
return body;
}
} else {
if (body !== null) {
body = Value.fromAny(body);
}
if (!Equals(this.ownBody, body)) {
(this as Mutable<typeof this>).ownBody = body;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.body;
DownlinkFastener.prototype.warp = function (this: DownlinkFastener<unknown>, warp?: WarpRef | null): WarpRef | null | typeof this {
if (warp === void 0) {
return this.ownWarp;
} else {
if (this.ownWarp !== warp) {
(this as Mutable<typeof this>).ownWarp = warp;
this.relink();
}
return this;
}
} as typeof DownlinkFastener.prototype.warp;
DownlinkFastener.prototype.link = function (this: DownlinkFastener<DownlinkFastenerContext>): void {
if (this.downlink === null) {
let warp = this.ownWarp;
if (warp === null) {
warp = this.owner.warpRef.value;
}
if (warp === null) {
warp = this.owner.warpProvider.service.client;
}
let downlink = this.createDownlink(warp);
downlink = this.bindDownlink(downlink);
if (this.initDownlink !== void 0) {
downlink = this.initDownlink(downlink);
}
downlink = downlink.observe(this as DownlinkObserver);
(this as Mutable<typeof this>).downlink = downlink.open();
this.setFlags(this.flags & ~DownlinkFastener.PendingFlag);
}
};
DownlinkFastener.prototype.unlink = function (this: DownlinkFastener<unknown>): void {
const downlink = this.downlink;
if (downlink !== null) {
downlink.close();
(this as Mutable<typeof this>).downlink = null;
this.setFlags(this.flags | DownlinkFastener.PendingFlag);
}
};
DownlinkFastener.prototype.relink = function (this: DownlinkFastener<unknown>): void {
this.setFlags(this.flags | DownlinkFastener.PendingFlag);
if ((this.flags & DownlinkFastener.ConsumingFlag) !== 0) {
this.setCoherent(false);
this.decohere();
}
};
DownlinkFastener.prototype.bindDownlink = function (this: DownlinkFastener<unknown>, downlink: Downlink): Downlink {
const hostUri = this.hostUri();
if (hostUri !== null) {
downlink = downlink.hostUri(hostUri);
}
const nodeUri = this.nodeUri();
if (nodeUri !== null) {
downlink = downlink.nodeUri(nodeUri);
}
const laneUri = this.laneUri();
if (laneUri !== null) {
downlink = downlink.laneUri(laneUri);
}
const prio = this.prio();
if (prio !== void 0) {
downlink = downlink.prio(prio);
}
const rate = this.rate();
if (rate !== void 0) {
downlink = downlink.rate(rate);
}
const body = this.body();
if (body !== null) {
downlink = downlink.body(body);
}
return downlink;
};
DownlinkFastener.prototype.recohere = function (this: DownlinkFastener<unknown>, t: number): void {
this.setCoherent(true);
if (this.downlink !== null && (this.flags & DownlinkFastener.RelinkMask) === DownlinkFastener.RelinkMask) {
this.unlink();
this.link();
} else if (this.downlink === null && (this.flags & DownlinkFastener.ConsumingFlag) !== 0) {
this.link();
} else if (this.downlink !== null && (this.flags & DownlinkFastener.ConsumingFlag) === 0) {
this.unlink();
}
};
DownlinkFastener.prototype.consume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
const oldConsumers = this.consumers;
const newConsumerrss = Arrays.inserted(downlinkConsumer, oldConsumers);
if (oldConsumers !== newConsumerrss) {
this.willConsume(downlinkConsumer);
(this as Mutable<typeof this>).consumers = newConsumerrss;
this.onConsume(downlinkConsumer);
this.didConsume(downlinkConsumer);
if (oldConsumers.length === 0) {
this.startConsuming();
}
}
};
DownlinkFastener.prototype.willConsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
}
DownlinkFastener.prototype.onConsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
};
DownlinkFastener.prototype.didConsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
};
DownlinkFastener.prototype.unconsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
const oldConsumers = this.consumers;
const newConsumerrss = Arrays.removed(downlinkConsumer, oldConsumers);
if (oldConsumers !== newConsumerrss) {
this.willUnconsume(downlinkConsumer);
(this as Mutable<typeof this>).consumers = newConsumerrss;
this.onUnconsume(downlinkConsumer);
this.didUnconsume(downlinkConsumer);
if (newConsumerrss.length === 0) {
this.stopConsuming();
}
}
};
DownlinkFastener.prototype.willUnconsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
};
DownlinkFastener.prototype.onUnconsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
};
DownlinkFastener.prototype.didUnconsume = function (this: DownlinkFastener<unknown>, downlinkConsumer: ConsumerType<typeof this>): void {
// hook
};
Object.defineProperty(DownlinkFastener.prototype, "consuming", {
get(this: DownlinkFastener<unknown>): boolean {
return (this.flags & DownlinkFastener.ConsumingFlag) !== 0;
},
configurable: true,
})
DownlinkFastener.prototype.startConsuming = function (this: DownlinkFastener<unknown>): void {
if ((this.flags & DownlinkFastener.ConsumingFlag) === 0) {
this.willStartConsuming();
this.setFlags(this.flags | DownlinkFastener.ConsumingFlag);
this.onStartConsuming();
this.didStartConsuming();
}
};
DownlinkFastener.prototype.willStartConsuming = function (this: DownlinkFastener<unknown>): void {
// hook
};
DownlinkFastener.prototype.onStartConsuming = function (this: DownlinkFastener<unknown>): void {
this.setCoherent(false);
this.decohere();
};
DownlinkFastener.prototype.didStartConsuming = function (this: DownlinkFastener<unknown>): void {
// hook
};
DownlinkFastener.prototype.stopConsuming = function (this: DownlinkFastener<unknown>): void {
if ((this.flags & DownlinkFastener.ConsumingFlag) !== 0) {
this.willStopConsuming();
this.setFlags(this.flags & ~DownlinkFastener.ConsumingFlag);
this.onStopConsuming();
this.didStopConsuming();
}
};
DownlinkFastener.prototype.willStopConsuming = function (this: DownlinkFastener<unknown>): void {
// hook
};
DownlinkFastener.prototype.onStopConsuming = function (this: DownlinkFastener<unknown>): void {
this.setCoherent(false);
this.decohere();
};
DownlinkFastener.prototype.didStopConsuming = function (this: DownlinkFastener<unknown>): void {
// hook
};
DownlinkFastener.prototype.onMount = function (this: DownlinkFastener<unknown>): void {
_super.prototype.onMount.call(this);
if ((this.flags & DownlinkFastener.ConsumingFlag) !== 0) {
this.setCoherent(false);
this.decohere();
}
};
DownlinkFastener.prototype.onUnmount = function (this: DownlinkFastener<unknown>): void {
_super.prototype.onUnmount.call(this);
this.unlink();
};
Object.defineProperty(DownlinkFastener.prototype, "lazy", {
get: function (this: DownlinkFastener): boolean {
return false;
},
configurable: true,
});
Object.defineProperty(DownlinkFastener.prototype, "static", {
get: function (this: DownlinkFastener): string | boolean {
return true;
},
configurable: true,
});
DownlinkFastener.construct = function <F extends DownlinkFastener<any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).ownHostUri = null;
(fastener as Mutable<typeof fastener>).ownNodeUri = null;
(fastener as Mutable<typeof fastener>).ownLaneUri = null;
(fastener as Mutable<typeof fastener>).ownPrio = void 0;
(fastener as Mutable<typeof fastener>).ownRate = void 0;
(fastener as Mutable<typeof fastener>).ownBody = null;
(fastener as Mutable<typeof fastener>).ownWarp = null;
(fastener as Mutable<typeof fastener>).downlink = null;
(fastener as Mutable<typeof fastener>).consumers = Arrays.empty;
return fastener;
};
DownlinkFastener.define = function <O>(className: string, descriptor: DownlinkFastenerDescriptor<O>): DownlinkFastenerFactory<DownlinkFastener<any>> {
let superClass = descriptor.extends as DownlinkFastenerFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
let hostUri = descriptor.hostUri;
let nodeUri = descriptor.nodeUri;
let laneUri = descriptor.laneUri;
let prio = descriptor.prio;
let rate = descriptor.rate;
let body = descriptor.body;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.hostUri;
delete descriptor.nodeUri;
delete descriptor.laneUri;
delete descriptor.prio;
delete descriptor.rate;
delete descriptor.body;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: DownlinkFastener<any>}, fastener: DownlinkFastener<O> | null, owner: O): DownlinkFastener<O> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (hostUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownHostUri = hostUri as Uri;
}
if (nodeUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownNodeUri = nodeUri as Uri;
}
if (laneUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownLaneUri = laneUri as Uri;
}
if (prio !== void 0) {
(fastener as Mutable<typeof fastener>).ownPrio = prio as number;
}
if (rate !== void 0) {
(fastener as Mutable<typeof fastener>).ownRate = rate as number;
}
if (body !== void 0) {
(fastener as Mutable<typeof fastener>).ownBody = body as Value;
}
return fastener;
};
if (typeof hostUri === "function") {
fastenerClass.prototype.initHostUri = hostUri;
hostUri = void 0;
} else if (hostUri !== void 0) {
hostUri = Uri.fromAny(hostUri);
}
if (typeof nodeUri === "function") {
fastenerClass.prototype.initNodeUri = nodeUri;
nodeUri = void 0;
} else if (nodeUri !== void 0) {
nodeUri = Uri.fromAny(nodeUri);
}
if (typeof laneUri === "function") {
fastenerClass.prototype.initLaneUri = laneUri;
laneUri = void 0;
} else if (laneUri !== void 0) {
laneUri = Uri.fromAny(laneUri);
}
if (typeof prio === "function") {
fastenerClass.prototype.initPrio = prio;
prio = void 0;
}
if (typeof rate === "function") {
fastenerClass.prototype.initRate = rate;
rate = void 0;
}
if (typeof body === "function") {
fastenerClass.prototype.initBody = body;
body = void 0;
} else if (body !== void 0) {
body = Value.fromAny(body);
}
return fastenerClass;
};
(DownlinkFastener as Mutable<typeof DownlinkFastener>).ConsumingFlag = 1 << (_super.FlagShift + 0);
(DownlinkFastener as Mutable<typeof DownlinkFastener>).PendingFlag = 1 << (_super.FlagShift + 1);
(DownlinkFastener as Mutable<typeof DownlinkFastener>).RelinkMask = DownlinkFastener.ConsumingFlag | DownlinkFastener.PendingFlag;
(DownlinkFastener as Mutable<typeof DownlinkFastener>).FlagShift = _super.FlagShift + 2;
(DownlinkFastener as Mutable<typeof DownlinkFastener>).FlagMask = (1 << DownlinkFastener.FlagShift) - 1;
return DownlinkFastener;
})(Fastener); | the_stack |
export class Martini
{
/**
* Size of the grid to be generated.
*/
public gridSize: number;
/**
* Number of triangles to be used in the tile.
*/
public numTriangles: number;
/**
* Number of triangles in the parent node.
*/
public numParentTriangles: number;
/**
* Indices of the triangles faces.
*/
public indices: Uint32Array;
/**
* Coordinates of the points composing the mesh.
*/
public coords: Uint16Array;
/**
* Constructor for the generator.
*
* @param gridSize - Size of the grid.
*/
public constructor(gridSize: number = 257)
{
this.gridSize = gridSize;
const tileSize = gridSize - 1;
if (tileSize & tileSize - 1)
{
throw new Error(`Expected grid size to be 2^n+1, got ${gridSize}.`);
}
this.numTriangles = tileSize * tileSize * 2 - 2;
this.numParentTriangles = this.numTriangles - tileSize * tileSize;
this.indices = new Uint32Array(this.gridSize * this.gridSize);
// coordinates for all possible triangles in an RTIN tile
this.coords = new Uint16Array(this.numTriangles * 4);
// get triangle coordinates from its index in an implicit binary tree
for (let i = 0; i < this.numTriangles; i++)
{
let id = i + 2;
let ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0;
if (id & 1)
{
bx = by = cx = tileSize; // bottom-left triangle
}
else
{
ax = ay = cy = tileSize; // top-right triangle
}
while ((id >>= 1) > 1)
{
const mx = ax + bx >> 1;
const my = ay + by >> 1;
if (id & 1)
{ // left half
bx = ax; by = ay;
ax = cx; ay = cy;
}
else
{ // right half
ax = bx; ay = by;
bx = cx; by = cy;
}
cx = mx; cy = my;
}
const k = i * 4;
this.coords[k + 0] = ax;
this.coords[k + 1] = ay;
this.coords[k + 2] = bx;
this.coords[k + 3] = by;
}
}
public createTile(terrain): Tile
{
return new Tile(terrain, this);
}
}
/**
* Class describes the generation of a tile using the Martini method.
*/
class Tile
{
/**
* Pointer to the martini generator object.
*/
public martini: Martini;
/**
* Terrain to generate the tile for.
*/
public terrain: Float32Array;
/**
* Errors detected while creating the tile.
*/
public errors: Float32Array;
public constructor(terrain: Float32Array, martini: Martini)
{
const size = martini.gridSize;
if (terrain.length !== size * size)
{
throw new Error(`Expected terrain data of length ${size * size} (${size} x ${size}), got ${terrain.length}.`);
}
this.terrain = terrain;
this.martini = martini;
this.errors = new Float32Array(terrain.length);
this.update();
}
public update(): void
{
const {numTriangles, numParentTriangles, coords, gridSize: size} = this.martini;
const {terrain, errors} = this;
// iterate over all possible triangles, starting from the smallest level
for (let i = numTriangles - 1; i >= 0; i--)
{
const k = i * 4;
const ax = coords[k + 0];
const ay = coords[k + 1];
const bx = coords[k + 2];
const by = coords[k + 3];
const mx = ax + bx >> 1;
const my = ay + by >> 1;
const cx = mx + my - ay;
const cy = my + ax - mx;
// calculate error in the middle of the long edge of the triangle
const interpolatedHeight = (terrain[ay * size + ax] + terrain[by * size + bx]) / 2;
const middleIndex = my * size + mx;
const middleError = Math.abs(interpolatedHeight - terrain[middleIndex]);
errors[middleIndex] = Math.max(errors[middleIndex], middleError);
if (i < numParentTriangles)
{ // bigger triangles; accumulate error with children
const leftChildIndex = (ay + cy >> 1) * size + (ax + cx >> 1);
const rightChildIndex = (by + cy >> 1) * size + (bx + cx >> 1);
errors[middleIndex] = Math.max(errors[middleIndex], errors[leftChildIndex], errors[rightChildIndex]);
}
}
}
public getMesh(maxError: number = 0, withSkirts: boolean = false): {vertices: any, triangles: any, numVerticesWithoutSkirts: number}
{
const {gridSize: size, indices} = this.martini;
const {errors} = this;
let numVertices = 0;
let numTriangles = 0;
const max = size - 1;
let aIndex, bIndex, cIndex = 0;
// Skirt indices
const leftSkirtIndices = [];
const rightSkirtIndices = [];
const bottomSkirtIndices = [];
const topSkirtIndices = [];
// use an index grid to keep track of vertices that were already used to avoid duplication
indices.fill(0);
// retrieve mesh in two stages that both traverse the error map:
// - countElements: find used vertices (and assign each an index), and count triangles (for minimum allocation)
// - processTriangle: fill the allocated vertices & triangles typed arrays
function countElements(ax: number, ay: number, bx: number, by: number, cx: number, cy: number): void
{
const mx = ax + bx >> 1;
const my = ay + by >> 1;
if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError)
{
countElements(cx, cy, ax, ay, mx, my);
countElements(bx, by, cx, cy, mx, my);
}
else
{
aIndex = ay * size + ax;
bIndex = by * size + bx;
cIndex = cy * size + cx;
if (indices[aIndex] === 0)
{
if (withSkirts)
{
if (ax === 0)
{
leftSkirtIndices.push(numVertices);
}
else if (ax === max)
{
rightSkirtIndices.push(numVertices);
} if (ay === 0)
{
bottomSkirtIndices.push(numVertices);
}
else if (ay === max)
{
topSkirtIndices.push(numVertices);
}
}
indices[aIndex] = ++numVertices;
}
if (indices[bIndex] === 0)
{
if (withSkirts)
{
if (bx === 0)
{
leftSkirtIndices.push(numVertices);
}
else if (bx === max)
{
rightSkirtIndices.push(numVertices);
} if (by === 0)
{
bottomSkirtIndices.push(numVertices);
}
else if (by === max)
{
topSkirtIndices.push(numVertices);
}
}
indices[bIndex] = ++numVertices;
}
if (indices[cIndex] === 0)
{
if (withSkirts)
{
if (cx === 0)
{
leftSkirtIndices.push(numVertices);
}
else if (cx === max)
{
rightSkirtIndices.push(numVertices);
} if (cy === 0)
{
bottomSkirtIndices.push(numVertices);
}
else if (cy === max)
{
topSkirtIndices.push(numVertices);
}
}
indices[cIndex] = ++numVertices;
}
numTriangles++;
}
}
countElements(0, 0, max, max, max, 0);
countElements(max, max, 0, 0, 0, max);
let numTotalVertices =numVertices * 2;
let numTotalTriangles = numTriangles * 3;
if (withSkirts)
{
numTotalVertices +=(leftSkirtIndices.length + rightSkirtIndices.length + bottomSkirtIndices.length + topSkirtIndices.length) * 2;
numTotalTriangles += ((leftSkirtIndices.length - 1) * 2 + (rightSkirtIndices.length - 1) * 2 + (bottomSkirtIndices.length - 1) * 2 + (topSkirtIndices.length - 1) * 2) * 3;
}
const vertices = new Uint16Array(numTotalVertices);
const triangles = new Uint32Array(numTotalTriangles);
let triIndex = 0;
function processTriangle(ax: number, ay: number, bx: number, by: number, cx: number, cy: number): void
{
const mx = ax + bx >> 1;
const my = ay + by >> 1;
if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError)
{
// triangle doesn't approximate the surface well enough; drill down further
processTriangle(cx, cy, ax, ay, mx, my);
processTriangle(bx, by, cx, cy, mx, my);
}
else
{
// add a triangle
const a = indices[ay * size + ax] - 1;
const b = indices[by * size + bx] - 1;
const c = indices[cy * size + cx] - 1;
vertices[2 * a] = ax;
vertices[2 * a + 1] = ay;
vertices[2 * b] = bx;
vertices[2 * b + 1] = by;
vertices[2 * c] = cx;
vertices[2 * c + 1] = cy;
triangles[triIndex++] = a;
triangles[triIndex++] = b;
triangles[triIndex++] = c;
}
}
processTriangle(0, 0, max, max, max, 0);
processTriangle(max, max, 0, 0, 0, max);
if (withSkirts)
{
// Sort skirt indices to create adjacent triangles
leftSkirtIndices.sort((a, b) => {return vertices[2 * a + 1] - vertices[2 * b + 1];});
// Reverse (b - a) to match triangle winding
rightSkirtIndices.sort((a, b) => {return vertices[2 * b + 1] - vertices[2 * a + 1];});
bottomSkirtIndices.sort((a, b) => {return vertices[2 * b] - vertices[2 * a];});
// Reverse (b - a) to match triangle winding
topSkirtIndices.sort((a, b) => {return vertices[2 * a] - vertices[2 * b];});
let skirtIndex = numVertices * 2;
// Add skirt vertices from index of last mesh vertex
function constructSkirt(skirt: number[]): void
{
const skirtLength = skirt.length;
// Loop through indices in groups of two to generate triangles
for (let i = 0; i < skirtLength - 1; i++)
{
const currIndex = skirt[i];
const nextIndex = skirt[i + 1];
const currentSkirt = skirtIndex / 2;
const nextSkirt = (skirtIndex + 2) / 2;
vertices[skirtIndex++] = vertices[2 * currIndex];
vertices[skirtIndex++] = vertices[2 * currIndex + 1];
triangles[triIndex++] = currIndex;
triangles[triIndex++] = currentSkirt;
triangles[triIndex++] = nextIndex;
triangles[triIndex++] = currentSkirt;
triangles[triIndex++] = nextSkirt;
triangles[triIndex++] = nextIndex;
}
// Add vertices of last skirt not added above (i < skirtLength - 1)
vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1]];
vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1] + 1];
}
constructSkirt(leftSkirtIndices);
constructSkirt(rightSkirtIndices);
constructSkirt(bottomSkirtIndices);
constructSkirt(topSkirtIndices);
}
// Return vertices and triangles and index into vertices array where skirts start
return {vertices: vertices, triangles: triangles, numVerticesWithoutSkirts: numVertices};
}
} | the_stack |
import Deferred from "./lib/Deferred";
import * as storage from './lib/storage';
import * as animate from './lib/animate';
import * as _ from './lib/utils';
import { saveStorage } from "./lib/storage";
import { prependFn } from "./lib/decorators";
import { IOpt, IMenuItem } from "./Interface";
import './chuncai.scss';
declare function require(filePath: string): string;
const mainContent = require('./tpl/main.html');
const tagContent = require('./tpl/tag.html');
export class Chuncai {
//#region private fields
/**
* 菜单是否展开
*
* @private
* @type {boolean}
* @memberof Chuncai
*/
private menuOn: boolean = false;
/**
* 要循环骚操作的定时器
*
* @private
* @type {number}
* @memberof Chuncai
*/
private freeActionTimer: number;
/**
* 渐显文字的dfd
*
* @private
* @type {Deferred}
* @memberof Chuncai
*/
private freeSayDfd: Deferred = new Deferred().resolve();
/**
* 当前菜单配置
*
* @private
* @type {IOpt}
* @memberof Chuncai
*/
private opt: IOpt;
//#endregion
//#region private get fields
/**
* 春菜文字容器
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeWord() {
return <HTMLElement>document.getElementById('chuncai_word');
}
/**
* 整个春菜
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeMain() {
return <HTMLElement>document.getElementById('chuncai_main');
}
/**
* 春菜身体部分
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeBody() {
return <HTMLElement>document.getElementById('chuncai_body');
}
/**
* 菜单容器
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeMenu() {
return <HTMLElement>document.getElementsByClassName('chuncai-menu')[0];
}
/**
* 菜单toggle按钮
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeMenuBtn() {
return <HTMLElement>document.getElementsByClassName('chuncai-menu-btn')[0];
}
/**
* 召唤按钮
*
* @readonly
* @private
* @memberof Chuncai
*/
private get eleNodeZhaohuan() {
return document.getElementById('chuncai_zhaohuan');
}
//#endregion
//#region private methods
/**
* 填充dom
*
* @private
* @memberof Chuncai
*/
private fillDom(): void {
let wrap = document.createElement('div');
wrap.innerHTML = tagContent;
let tagNode = wrap.children[0];
document.body.appendChild(tagNode);
wrap.innerHTML = mainContent;
let mainNode = wrap.children[0];
document.body.appendChild(mainNode);
}
/**
* 填充菜单
*
* @private
* @param {Array<string>} [subMenus=[]]
* @memberof Chuncai
*/
private fillMenu(subMenus: Array<string> = []): void {
let menu: any = this.opt.menu;
for (let i = 0, len = subMenus.length; i < len; i++) {
menu = menu[subMenus[i]];
}
let menuArr = [];
_.each(menu, (key, val) => {
if (key == '$title') {
return true;
}
let tempArr = subMenus.slice();
tempArr.push(key);
menuArr.push(`<span class="cc-cmd" data-cccmd="${tempArr.join('__')}">${key}</span>`);
});
this.eleNodeMenu.innerHTML = menuArr.join('');
}
/**
* 绑定事件
*
* @private
* @memberof Chuncai
*/
private evtSet(): void {
// 可拖动,并防抖保存位置
_.drag(this.eleNodeBody, this.eleNodeMain, _.debounce(saveStorage, 300));
// 菜单
this.eleNodeMenuBtn
.addEventListener('click', () => {
let dfd = this.toggleMenu();
dfd.then(() => {
if (!this.menuOn) {
this.freeAction(true, true);
}
});
});
// 点击菜单项
this.eleNodeMenu
.addEventListener('click', ex => {
let ele: HTMLElement = <HTMLElement>ex.target;
if (!~ele.className.indexOf('cc-cmd')) {
return;
}
let cccmd = ele.getAttribute('data-cccmd') || '';
this.choseItem(cccmd);
}, true);
this.eleNodeZhaohuan
.addEventListener('click', () => {
this.show();
});
}
/**
* 选择某一项
*
* @private
* @param {string} [cccmd='']
* @memberof Chuncai
*/
@prependFn(Chuncai.prototype.freeAction)
private choseItem(cccmd = '') {
let cmds = cccmd.split('__');
let item: any = this.opt.menu; // 标签对应的指令项
for (let i = 0, len = cmds.length; i < len; i++) {
item = item[cmds[i]];
}
let actionDict = {
/**
* 字符串则直接输出
*
* @param {string} content
*/
string: content => {
this.freeSay(content);
this.hideMenu()
.then(() => {
this.fillMenu();
});
},
/**
* 方法直接调用
*
* @param {function} func
*/
function: func => func(),
/**
* 菜单则填充
*
*/
object: sender => {
this.hideMenu()
.then(() => {
this.fillMenu(cmds);
this.showMenu();
if (sender['$title']) {
this.freeSay(sender['$title']);
}
});
}
};
let itemType = _.getType(item);
actionDict[itemType] && actionDict[itemType](item);
}
/**
* 开始随机行为
*
* @private
* @param {boolean} [rightNow=false] 立即开始
* @param {boolean} [interval=true] 是否循环
* @memberof Chuncai
*/
private freeAction(rightNow: boolean = false, interval: boolean = true): void {
clearInterval(this.freeActionTimer);
let fn = () => {
// 关闭menu
if (this.menuOn) {
this.hideMenu();
}
// 随机语言
let rnd = _.randomInt(this.opt.words.length);
let content = this.opt.words[rnd];
this.freeSay(content);
// 随机表情
rnd = _.randomInt(3);
let eleNode = this.eleNodeBody;
let classStr = eleNode.className;
classStr = classStr.replace(/(chuncai-face-0)\d/, `$1${rnd}`);
eleNode.className = classStr;
};
if (rightNow) {
fn();
}
if (interval) {
this.freeActionTimer = setInterval(() => fn(), 8000);
}
}
/**
* 渐显文字
*
* @private
* @param {string} content
* @memberof Chuncai
*/
private freeSay(content: string): void {
// 禁用之前的渐显
this.freeSayDfd.disable();
// 重置
this.freeSayDfd = new Deferred().resolve();
let delay = 80; // 速度80
for (let i = 0, len = content.length; i < len; i++) {
this.freeSayDfd.then(() => {
this.eleNodeWord.innerHTML = content.substr(0, i + 1);
}).delay(80);
}
}
/**
* 显示/隐藏 菜单
*
* @private
* @returns {Deferred}
* @memberof Chuncai
*/
private toggleMenu(): Deferred {
// return this.menuOn ? this.hideMenu() : this.showMenu();
let dfd: Deferred;
if (this.menuOn) {
dfd = this.hideMenu();
} else {
dfd = this.showMenu();
}
return dfd;
}
/**
* 显示菜单
*
* @private
* @returns {Deferred}
* @memberof Chuncai
*/
@prependFn(Chuncai.prototype.freeAction)
private showMenu(): Deferred {
let dfd = new Deferred();
if (this.menuOn) {
dfd.resolve();
}
else {
animate.slideDown(this.eleNodeMenu, 200, () => {
this.menuOn = true;
dfd.resolve();
});
}
return dfd;
}
/**
* 隐藏菜单
*
* @private
* @returns {Deferred}
* @memberof Chuncai
*/
private hideMenu(): Deferred {
let dfd = new Deferred();
if (!this.menuOn) {
dfd.resolve();
}
else {
animate.slideUp(this.eleNodeMenu, 200, () => {
this.menuOn = false;
this.fillMenu();
dfd.resolve();
});
}
return dfd;
}
//#endregion
//#region public methods
/**
* 初始化
*
* @param {IOpt} opt
* @memberof Chuncai
*/
public init(opt: IOpt): void {
this.opt = opt;
this.fillDom();
this.fillMenu();
this.evtSet();
this.show();
}
/**
* 显示春菜
*
* @memberof Chuncai
*/
@prependFn(Chuncai.prototype.freeAction)
public show(): void {
let pos = storage.getStorage();
if (pos.x !== undefined) {
this.eleNodeMain.style.left = pos.x + 'px';
this.eleNodeMain.style.top = pos.y + 'px';
}
animate.fadeOut(this.eleNodeZhaohuan, 500);
this.eleNodeWord.innerHTML = '';
animate.fadeIn(this.eleNodeMain, 500, () => {
this.freeSay('啊啦我又来啦~');
});
}
/**
* 隐藏
*
* @memberof Chuncai
*/
public hide(): void {
this.freeSay('记得叫我出来哦~');
setTimeout(() => {
animate.fadeOut(this.eleNodeMain, 500);
animate.fadeIn(this.eleNodeZhaohuan, 500);
}, 1000);
}
//#endregion
}
export default new Chuncai(); | the_stack |
import { expectError, expectNoError } from './util';
// ----------------------------------------------------------------------
test('okay to add a new class', () =>
expectNoError(
`
export class Foo1 { }
`,
`
export class Foo1 { }
export class Foo2 { }
`,
));
// ----------------------------------------------------------------------
test('okay to add a new function to a class', () =>
expectNoError(
`
export class Foo { }
`,
`
export class Foo {
public bar(): void { }
}
`,
));
// ----------------------------------------------------------------------
test('not okay to add a required argument to a method', () =>
expectError(
/newly required argument/,
`
export class Foo {
public bar(arg1: string): void {
Array.isArray(arg1);
}
}
`,
`
export class Foo {
public bar(arg1: string, arg2: string): void {
Array.isArray(arg1);
Array.isArray(arg2);
}
}
`,
));
// ----------------------------------------------------------------------
test('okay to make a required argument optional', () =>
expectNoError(
`
export class Foo {
public bar(arg1: string, arg2: string): void {
Array.isArray(arg1);
Array.isArray(arg2);
}
}
`,
`
export class Foo {
public bar(arg1: string, arg2?: string): void {
Array.isArray(arg1);
Array.isArray(arg2);
}
}
`,
));
// ----------------------------------------------------------------------
test('okay to turn required arguments into varargs', () =>
expectNoError(
`
export class Foo {
public bar(arg1: string, arg2: number, arg3: number): void {
Array.isArray(arg1);
Array.isArray(arg2);
Array.isArray(arg3);
}
}
`,
`
export class Foo {
public bar(arg1: string, ...args: number[]): void {
Array.isArray(arg1);
Array.isArray(args);
}
}
`,
));
// ----------------------------------------------------------------------
test('not allowed to change argument type to a different scalar', () =>
expectError(
/method.*foo.*argument arg1, takes number \(formerly string\): string is not assignable to number/i,
`
export class Foo {
public bar(arg1: string): void {
Array.isArray(arg1);
}
}
`,
`
export class Foo {
public bar(arg1: number): void {
Array.isArray(arg1);
}
}
`,
));
// ----------------------------------------------------------------------
test('cannot add any abstract members to a subclassable class', () =>
expectError(
/adds requirement for subclasses to implement 'piet'./,
`
/**
* @subclassable
*/
export abstract class Henk {
abstract readonly name: string;
}
`,
`
/**
* @subclassable
*/
export abstract class Henk {
abstract readonly name: string;
abstract readonly piet: string;
}
`,
));
// ----------------------------------------------------------------------
test('cannot add any members to a subclassable interface, not even optional ones', () =>
expectError(
/adds requirement for subclasses to implement 'piet'./,
`
/**
* @subclassable
*/
export interface IHenk {
name: string;
}
`,
`
/**
* @subclassable
*/
export interface IHenk {
name: string;
piet?: string;
}
`,
));
// ----------------------------------------------------------------------
test('cannot make a member less visible', () =>
expectError(
/changed from 'public' to 'protected'/,
`
export class Henk {
public name: string = 'henk';
}
`,
`
export class Henk {
protected name: string = 'henk';
}
`,
));
// ----------------------------------------------------------------------
describe('implement base types need to be present in updated type system', () => {
test('for interfaces', () =>
expectError(
/not assignable to all base types anymore/,
`
export interface IPapa {
readonly pipe: string;
}
export interface IBebe extends IPapa {
readonly pacifier: string;
}
`,
`
export interface IPapa {
readonly pipe: string;
}
export interface IBebe {
readonly pacifier: string;
}
`,
));
test('for structs', () =>
expectError(
/not assignable to all base types anymore/,
`
export interface Papa {
readonly pipe: string;
}
export interface Bebe extends Papa {
readonly pacifier: string;
}
`,
`
export interface Papa {
readonly pipe: string;
}
export interface Bebe {
readonly pacifier: string;
}
`,
));
test('for classes', () =>
expectError(
/not assignable to all base types anymore/,
`
export interface IPapa {
readonly pipe: string;
}
export class Bebe implements IPapa {
readonly pipe: string = 'pff';
readonly pacifier: string = 'mmm';
}
`,
`
export interface IPapa {
readonly pipe: string;
}
export class Bebe {
readonly pipe: string = 'pff';
readonly pacifier: string = 'mmm';
}
`,
));
test('for base classes', () =>
expectError(
/not assignable to all base types anymore/,
`
export class Papa {
readonly pipe: string = 'pff';
}
export class Bebe extends Papa {
readonly pacifier: string = 'mmm';
}
`,
`
export class Papa {
readonly pipe: string = 'pff';
}
export class Bebe {
readonly pacifier: string = 'mmm';
}
`,
));
test('new levels of inheritance are allowed', () =>
expectNoError(
`
export class Papa {
readonly pipe: string = 'pff';
}
export class Bebe extends Papa {
readonly pacifier: string = 'mmm';
}
`,
`
export class Papa {
readonly pipe: string = 'pff';
}
export class Inbetween extends Papa {
}
export class Bebe extends Inbetween {
readonly pacifier: string = 'mmm';
}
`,
));
test('change direct implementation to inherited implementation via interface', () =>
expectNoError(
`
export interface IPapa {
readonly pipe: string;
}
export class Bebe implements IPapa {
readonly pipe: string = 'pff';
readonly pacifier: string = 'mmm';
}
`,
`
export interface IPapa {
readonly pipe: string;
}
export interface IInbetween extends IPapa {
}
export class Bebe implements IInbetween {
readonly pipe: string = 'pff';
readonly pacifier: string = 'mmm';
}
`,
));
test('change direct implementation to inherited implementation via base class', () =>
expectNoError(
`
export interface IPapa {
readonly pipe: string;
}
export class Bebe implements IPapa {
readonly pipe: string = 'pff';
readonly pacifier: string = 'mmm';
}
`,
`
export interface IPapa {
readonly pipe: string;
}
export class Inbetween implements IPapa {
readonly pipe: string = 'pff';
}
export class Bebe extends Inbetween {
readonly pacifier: string = 'mmm';
}
`,
));
});
// ----------------------------------------------------------------------
test.each([
{
oldDecl: 'name: string',
newDecl: 'name?: string',
error:
/type Optional<string> \(formerly string\): output type is now optional/,
},
{
oldDecl: 'name?: string',
newDecl: 'name: string',
error: undefined, // Strengthening is okay
},
{
oldDecl: 'name: string',
newDecl: 'name: string | number',
error: /string \| number is not assignable to string/,
},
{
oldDecl: 'name: string | number',
newDecl: 'name: string',
error: undefined, // Strengthening is okay
},
])('change class property ', ({ oldDecl, newDecl, error }) =>
expectError(
error,
`
export class Henk {
public readonly ${oldDecl} = 'henk';
}
`,
`
export class Henk {
public readonly ${newDecl} = 'henk';
}
`,
),
);
// ----------------------------------------------------------------------
test.each([
{
oldDecl: 'name: string',
newDecl: 'name?: string',
error: /changed to Optional<string> \(formerly string\)/,
},
{
oldDecl: 'name?: string',
newDecl: 'name: string',
error: /changed to string \(formerly Optional<string>\)/,
},
{
oldDecl: 'name: string',
newDecl: 'name: string | number',
error: /changed to string \| number \(formerly string\)/,
},
{
oldDecl: 'name: string | number',
newDecl: 'name: string',
error: /changed to string \(formerly string \| number\)/,
},
])(
'cannot change a mutable class property type: %p to %p',
({ oldDecl, newDecl, error }) =>
expectError(
error,
`
export class Henk {
public ${oldDecl} = 'henk';
}
`,
`
export class Henk {
public ${newDecl} = 'henk';
}
`,
),
);
// ----------------------------------------------------------------------
test('consider inherited constructor', () =>
expectError(
/number is not assignable to string/,
`
export class Super {
constructor(param: number) {
Array.isArray(param);
}
}
export class Sub extends Super {
}
`,
`
export class Super {
constructor(param: number) {
Array.isArray(param);
}
}
export class Sub extends Super {
constructor(param: string) {
super(5);
Array.isArray(param);
}
}
`,
));
// ----------------------------------------------------------------------
test('consider inherited constructor, the other way', () =>
expectError(
/newly required argument/,
`
export class Super {
constructor(param: number) {
Array.isArray(param);
}
}
export class Sub extends Super {
constructor() {
super(5);
}
}
`,
`
export class Super {
constructor(param: number) {
Array.isArray(param);
}
}
export class Sub extends Super {
}
`,
));
// ----------------------------------------------------------------------
test('method can be moved to supertype', () =>
expectNoError(
`
export class Super {
}
export class Sub extends Super {
public foo(param: number) {
Array.isArray(param);
}
}
`,
`
export class Super {
public foo(param: number) {
Array.isArray(param);
}
}
export class Sub extends Super {
}
`,
));
// ----------------------------------------------------------------------
test('property can be moved to supertype', () =>
expectNoError(
`
export class Super {
}
export class Sub extends Super {
public foo: string = 'foo';
}
`,
`
export class Super {
public foo: string = 'foo';
}
export class Sub extends Super {
}
`,
));
// ----------------------------------------------------------------------
test('subclassable is forever', () =>
expectError(
/has gone from @subclassable to non-@subclassable/,
`
/**
* @subclassable
*/
export class Super {
}
`,
`
export class Super {
}
`,
));
// ----------------------------------------------------------------------
test('change from method to property', () =>
expectError(
/changed from method to property/,
`
export class Boom {
public foo() { return 12; }
}
`,
`
export class Boom {
public get foo() { return 12; }
}
`,
));
// ----------------------------------------------------------------------
test('change from method with arguments to property', () =>
expectError(
/changed from method to property/,
`
export class Boom {
public foo(arg: number) { return 12 * arg; }
}
`,
`
export class Boom {
public get foo() { return 12; }
}
`,
));
// ----------------------------------------------------------------------
test('change from property to method', () =>
expectError(
/changed from property to method/,
`
export class Boom {
public get foo() { return 12; }
}
`,
`
export class Boom {
public foo() { return 12; }
}
`,
));
// ----------------------------------------------------------------------
test.each([
{
oldDecl: 'foo(arg: string) { Array.isArray(arg); }',
newDecl: 'foo(arg: string | number) { Array.isArray(arg); }',
},
{
oldDecl: 'foo(): string { return "x"; }',
newDecl: 'foo(): string | number { return "x"; }',
},
{
oldDecl: 'readonly foo: string = "x";',
newDecl: 'readonly foo: string | number = "x";',
},
])(
'cannot change any type in @subclassable class: %p to %p',
({ oldDecl, newDecl }) =>
expectError(
/type is @subclassable/,
`
/** @subclassable */
export class Boom {
public ${oldDecl}
}
`,
`
/** @subclassable */
export class Boom {
public ${newDecl}
}
`,
),
);
// ----------------------------------------------------------------------
test.each([
{
oldDecl: 'foo(arg: string): void;',
newDecl: 'foo(arg: string | number): void;',
},
{ oldDecl: 'foo(): string;', newDecl: 'foo(): string | number;' },
{
oldDecl: 'readonly foo: string;',
newDecl: 'readonly foo: string | number;',
},
])(
'cannot change any type in @subclassable interface: %p to %p',
({ oldDecl, newDecl }) =>
expectError(
/type is @subclassable/,
`
/** @subclassable */
export interface IBoom {
${oldDecl}
}
`,
`
/** @subclassable */
export interface IBoom {
${newDecl}
}
`,
),
);
// ----------------------------------------------------------------------
test.each([
// No usage => can add field
['', true],
// Return type => can add field
['foo(): TheStruct;', true],
['readonly foo: TheStruct;', true],
// Input type => can NOT add field
['foo: TheStruct;', false],
['foo(arg: TheStruct): void', false],
])(
'add required field to structs: refencing via %p -> allowed %p',
(usageDecl, allowed) =>
expectError(
allowed ? undefined : /newly required property 'fieldTwo' added/,
`
export interface TheStruct {
readonly fieldOne: string;
}
export interface IConsumer {
${usageDecl}
}
`,
`
export interface TheStruct {
readonly fieldOne: string;
readonly fieldTwo: string;
}
export interface IConsumer {
${usageDecl}
}
`,
),
);
// ----------------------------------------------------------------------
test.each([
// No usage => can add field
['', true],
// Return type => can NOT remove information
['foo(): TheStruct;', false],
['readonly foo: TheStruct;', false],
['foo: TheStruct;', false],
// Input type => can make optional
['foo(arg: TheStruct): void', true],
])(
'make required field optional: refencing via %p -> allowed %p',
(usageDecl, allowed) =>
expectError(
allowed ? undefined : /formerly required property 'fieldOne' is optional/,
`
export interface TheStruct {
readonly fieldOne: string;
}
export interface IConsumer {
${usageDecl}
}
`,
`
export interface TheStruct {
readonly fieldOne?: string;
}
export interface IConsumer {
${usageDecl}
}
`,
),
); | the_stack |
import { expect, test } from '@jest/globals';
import 'reflect-metadata';
import { entity, getClassSchema, jsonSerializer, PartialField, PropertySchema, t, uuid, validateMethodArgs } from '../index';
test('Basic array', () => {
class Other {
}
class Controller {
@t.array(Other).decorated
protected readonly bar: Other[] = [];
}
const s = getClassSchema(Controller);
{
const prop = s.getProperty('bar');
expect(prop.name).toBe('bar');
expect(prop.type).toBe('array');
expect(prop.getSubType().type).toBe('class');
expect(prop.getSubType().resolveClassType).toBe(Other);
expect(prop.isArray).toBe(true);
}
});
test('short @f 2', () => {
class Controller {
public foo(@t.array(String) bar: string[]): string {
return '';
}
@t.array(Number)
public foo2(@t.map(String) bar: { [name: string]: string }): number[] {
return [];
}
}
const s = getClassSchema(Controller);
{
const method = s.getMethod('foo');
expect(method.name).toBe('foo');
expect(method.type).toBe('string');
expect(method.isArray).toBe(false);
const props = s.getMethodProperties('foo');
expect(props.length).toBe(1);
expect(props[0].name).toBe('bar');
expect(props[0].getSubType().type).toBe('string');
expect(props[0].isArray).toBe(true);
}
{
const method = s.getMethod('foo2');
expect(method.name).toBe('foo2');
expect(method.getSubType().type).toBe('number');
expect(method.isArray).toBe(true);
const props = s.getMethodProperties('foo2');
expect(props.length).toBe(1);
expect(props[0].name).toBe('bar');
expect(props[0].getSubType().type).toBe('string');
expect(props[0].isMap).toBe(true);
}
{
const errors = validateMethodArgs(Controller, 'foo', []);
expect(errors.length).toBe(1);
expect(errors[0].code).toBe('required');
expect(errors[0].message).toBe('Required value is undefined');
expect(errors[0].path).toBe('#0');
}
{
const errors = validateMethodArgs(Controller, 'foo', ['asd']);
expect(errors.length).toBe(1);
expect(errors[0].code).toBe('invalid_type');
expect(errors[0].message).toBe('Type is not an array');
expect(errors[0].path).toBe('#0');
}
{
const errors = validateMethodArgs(Controller, 'foo', [['asd']]);
expect(errors).toEqual([]);
}
{
const errors = validateMethodArgs(Controller, 'foo', [[1]]);
expect(errors.length).toBe(1);
expect(errors[0].code).toBe('invalid_string');
expect(errors[0].message).toBe('No string given');
expect(errors[0].path).toBe('#0.0');
}
{
const errors = validateMethodArgs(Controller, 'foo', [[{ 'asd': 'sa' }]]);
expect(errors.length).toBe(1);
expect(errors[0].code).toBe('invalid_string');
expect(errors[0].message).toBe('No string given');
expect(errors[0].path).toBe('#0.0');
}
});
test('short @t unmet array definition', () => {
expect(() => {
class Controller {
public foo(@t bar: string[]) {
}
}
}).toThrow('Controller::foo::bar type mismatch. Given nothing, but declared is Array');
});
test('short @f no index on arg', () => {
expect(() => {
class Controller {
public foo(@t.index() bar: string[]) {
}
}
}).toThrow('Index could not be used on method arguments');
});
test('method args', () => {
class Controller {
public foo(@t bar: string) {
}
public foo2(@t bar: string, optional?: true, @t.optional anotherOne?: boolean) {
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('foo');
expect(props.length).toBe(1);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
}
{
const props = s.getMethodProperties('foo2');
expect(props.length).toBe(3);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
expect(props[1].name).toBe('optional');
expect(props[1].type).toBe('boolean');
expect(props[2].name).toBe('anotherOne');
expect(props[2].type).toBe('boolean');
expect(props[2].isOptional).toBe(true);
}
{
const errors = validateMethodArgs(Controller, 'foo2', ['bar']);
expect(errors.length).toBe(1);
expect(errors[0].code).toBe('required');
expect(errors[0].message).toBe('Required value is undefined');
expect(errors[0].path).toBe('#1');
}
{
const errors = validateMethodArgs(Controller, 'foo2', ['bar', true]);
expect(errors.length).toBe(0);
}
});
test('short @f', () => {
class Controller {
public foo(@t bar: string) {
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('foo');
expect(props.length).toBe(1);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
expect(props[0].isArray).toBe(false);
}
});
test('short @f multi', () => {
class Controller {
public foo(@t bar: string, @t foo: number) {
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('foo');
expect(props.length).toBe(2);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
expect(props[0].isArray).toBe(false);
expect(props[1].name).toBe('foo');
expect(props[1].type).toBe('number');
expect(props[1].isArray).toBe(false);
}
});
test('no decorators', () => {
expect(() => {
class Controller {
public foo(bar: string, nothing: boolean) {
}
}
const s = getClassSchema(Controller);
s.getMethodProperties('foo');
}).toThrow('Method Controller.foo has no decorators used');
});
test('partial', () => {
class Config {
@t.required
name!: string;
@t.required
sub!: Config;
@t.required
prio: number = 0;
}
class User {
@t.partial(Config)
config: Partial<Config> = {};
@t.partial(() => Config)
config2: Partial<Config> = {};
}
const s = getClassSchema(User);
const config = getClassSchema(Config);
expect(config.getProperty('name').isOptional).toBe(false);
expect(s.getProperty('config').isPartial).toBe(true);
//partial creates a new schema with all properties being optional
expect(s.getProperty('config').getSubType().getResolvedClassType()).not.toBe(Config);
expect(s.getProperty('config').getSubType().getResolvedClassSchema().getProperty('name').isOptional).toBe(true);
expect(s.getProperty('config2').isPartial).toBe(true);
expect(s.getProperty('config2').getSubType().getResolvedClassType()).not.toBe(Config);
const u = jsonSerializer.for(User).deserialize({
config: {
name: 'peter',
}
});
expect(u.config).not.toBeInstanceOf(Config);
expect(u.config.name).toBe('peter');
expect(u.config.prio).toBeUndefined();
});
test('argument partial', () => {
class Config {
@t.required
name!: string;
@t
sub?: Config;
}
class User {
foo(@t.partial(Config) config: Partial<Config>) {
}
@t
foo2(config: Config) {
}
}
expect(validateMethodArgs(User, 'foo', [{}]).length).toBe(0);
//for optional values its allowed to set to undefined. How else would you reset an already set value?
expect(validateMethodArgs(User, 'foo', [{ name: undefined }])).toEqual([]);
expect(validateMethodArgs(User, 'foo', [{ name: [] }])).toEqual([{ 'code': 'invalid_string', 'message': 'No string given', 'path': '#0.name' }]);
expect(validateMethodArgs(User, 'foo', [{ name: '' }])).toEqual([]);
const userSchema = getClassSchema(User);
const [configProperty] = userSchema.getMethodProperties('foo2');
expect(configProperty.name).toBe('config');
expect(configProperty.isOptional).toBe(false);
const configSchema = getClassSchema(Config);
expect(configSchema.getProperty('name').isOptional).toBe(false);
expect(validateMethodArgs(User, 'foo2', [{}])).toEqual([{ 'code': 'required', 'message': 'Required value is undefined', 'path': '#0.name' }]);
expect(validateMethodArgs(User, 'foo2', [{ name: 'asd', sub: undefined }])).toEqual([]);
expect(validateMethodArgs(User, 'foo2', [{ name: 'asd', sub: { peter: true } }])).toEqual([{
'code': 'required',
'message': 'Required value is undefined',
'path': '#0.sub.name'
}]);
});
test('argument convertion', () => {
class Config {
@t.optional
name?: string;
@t.optional
sub?: Config;
@t
prio: number = 0;
}
class Controller {
@t.partial(Config)
foo(name: string): PartialField<Config> {
return { prio: 2, 'sub.name': name };
}
@t
bar(config: Config): Config {
config.name = 'peter';
return config;
}
}
const schema = getClassSchema(Controller);
expect(schema.getMethodProperties('foo')[0].type).toBe('string');
{
const name = jsonSerializer.for(Controller).serializeMethodArgument('foo', 0, 2);
expect(name).toBe('2');
const res = jsonSerializer.for(Controller).deserializeMethodResult('foo', { name: 3 });
expect(res).toEqual({ name: '3' });
}
{
const config = jsonSerializer.for(Controller).deserializeMethodArgument('bar', 0, { prio: '2' });
expect(config).toBeInstanceOf(Config);
expect(config.prio).toBe(2);
const res = jsonSerializer.for(Controller).deserializeMethodResult('bar', { 'sub': { name: 3 } });
expect(res).toBeInstanceOf(Config);
expect(res.sub).toBeInstanceOf(Config);
expect(res.sub.name).toBe('3');
}
});
test('short @f multi gap', () => {
class Controller {
public foo(@t bar: string, nothing: boolean, @t foo: number) {
}
@t
public undefined(bar: string, nothing: boolean) {
}
public onlyFirst(@t.array(String) bar: string[], nothing: boolean) {
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('foo');
expect(props.length).toBe(3);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
expect(props[0].isArray).toBe(false);
expect(props[1].name).toBe('nothing');
expect(props[1].type).toBe('boolean');
expect(props[2].name).toBe('foo');
expect(props[2].type).toBe('number');
expect(props[2].isArray).toBe(false);
}
{
const props = s.getMethodProperties('undefined');
expect(props.length).toBe(2);
expect(props[0].name).toBe('bar');
expect(props[0].type).toBe('string');
expect(props[1].name).toBe('nothing');
expect(props[1].type).toBe('boolean');
}
{
const props = s.getMethodProperties('onlyFirst');
expect(props.length).toBe(2);
expect(props[0].name).toBe('bar');
expect(props[0].getSubType().type).toBe('string');
expect(props[0].isArray).toBe(true);
expect(props[1].name).toBe('nothing');
expect(props[1].type).toBe('boolean');
}
{
const errors = validateMethodArgs(Controller, 'foo', []);
expect(errors.length).toBe(3);
}
});
test('short @f with type', () => {
class Controller {
public foo(@t.array(String) bar: string[]) {
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('foo');
expect(props.length).toBe(1);
expect(props[0].name).toBe('bar');
expect(props[0].getSubType().type).toBe('string');
expect(props[0].isArray).toBe(true);
}
});
test('hasMethod and templateArgs', () => {
class Peter<T, K> {
}
function myCustom(target: object, p1: any, p2: any) {
}
class Controller {
public foo(@t.array(String) bar: string[]): string[] {
return [];
}
@t.array(String)
public foo2(@t.array(String) bar: string[]): string[] {
return [];
}
@t.type(Peter).template(Boolean, String)
public foo3(@t.array(String) bar: string[]): Peter<boolean, string> {
return new Peter;
}
@myCustom
public async foo4(@t.array(String) bar: string[]): Promise<string> {
return 'sd';
}
}
const s = getClassSchema(Controller);
expect(s.hasMethod('foo')).toBe(false);
expect(s.hasMethod('foo2')).toBe(true);
expect(s.hasMethod('foo3')).toBe(true);
expect(s.hasMethod('foo4')).toBe(false);
expect(s.getMethod('foo3').getTemplateArg(0)!.type).toBe('boolean');
expect(s.getMethod('foo3').getTemplateArg(1)!.type).toBe('string');
s.getMethodProperties('foo2');
s.getMethodProperties('foo3');
s.getMethodProperties('foo4');
expect(s.hasMethod('foo')).toBe(false);
expect(s.hasMethod('foo2')).toBe(true);
expect(s.hasMethod('foo3')).toBe(true);
expect(s.hasMethod('foo4')).toBe(true);
expect(s.getMethod('foo3').getTemplateArg(0)!.type).toBe('boolean');
expect(s.getMethod('foo3').getTemplateArg(1)!.type).toBe('string');
});
test('short @t templateArgs', () => {
class Observable<T> {
constructor(protected cb: (observer: { next: (v: T) => void }) => void) {
}
}
class Controller {
@t.template(Number)
public foo(): Observable<number> {
return new Observable((observer) => {
observer.next(3);
});
}
@t.template(t.string.optional)
public foo2(): Observable<string | undefined> {
return new Observable((observer) => {
observer.next('2');
});
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethod('foo');
expect(props.getResolvedClassType()).toBe(Observable);
expect(props.templateArgs).not.toBeUndefined();
expect(props.templateArgs.length).toBe(1);
if (props.templateArgs) {
expect(props.templateArgs[0]).toBeInstanceOf(PropertySchema);
expect(props.templateArgs[0].name).toBe('foo_0');
expect(props.templateArgs[0].type).toBe('number');
expect(props.templateArgs[0].isOptional).toBe(false);
}
}
{
const props = s.getMethod('foo2');
expect(props.getResolvedClassType()).toBe(Observable);
expect(props.templateArgs).not.toBeUndefined();
expect(props.templateArgs.length).toBe(1);
if (props.templateArgs) {
expect(props.templateArgs[0]).toBeInstanceOf(PropertySchema);
expect(props.templateArgs[0].name).toBe('foo2_0');
expect(props.templateArgs[0].isOptional).toBe(true);
expect(props.templateArgs[0].type).toBe('string');
}
}
});
test('PropertySchema setFromJSValue', () => {
{
const p = new PropertySchema('');
p.setFromJSValue(1);
expect(p.type).toBe('number');
}
{
const p = new PropertySchema('');
p.setFromJSValue('2');
expect(p.type).toBe('string');
}
{
const p = new PropertySchema('');
p.setFromJSValue(true);
expect(p.type).toBe('boolean');
}
{
const p = new PropertySchema('');
p.setFromJSValue({});
expect(p.type).toBe('any');
}
{
const p = new PropertySchema('');
p.setFromJSValue(new Uint8Array());
expect(p.type).toBe('Uint8Array');
}
{
const p = new PropertySchema('');
p.setFromJSValue(new ArrayBuffer(0));
expect(p.type).toBe('arrayBuffer');
}
{
const p = new PropertySchema('');
p.setFromJSValue([]);
expect(p.type).toBe('array');
expect(p.getSubType().type).toBe('any');
}
{
const p = new PropertySchema('');
p.setFromJSValue(null);
expect(p.type).toBe('any');
}
class Peter {
}
{
const p = new PropertySchema('');
p.setFromJSValue(new Peter);
expect(p.type).toBe('class');
expect(p.resolveClassType).toBe(Peter);
}
});
test('set any param', () => {
class Controller {
async streamCsvFile(path: string, @t.any rows: any[][]): Promise<boolean> {
return true;
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('streamCsvFile');
expect(props.length).toBe(2);
expect(props[1].type).toBe('any');
}
});
test('set any [][]', () => {
class Controller {
async streamCsvFile(path: string, @t.array(t.array(t.string)) rows: string[][]): Promise<boolean> {
return true;
}
}
const s = getClassSchema(Controller);
{
const props = s.getMethodProperties('streamCsvFile');
expect(props.length).toBe(2);
expect(props[0].type).toBe('string');
expect(props[1].type).toBe('array');
expect(props[1].getSubType().type).toBe('array');
expect(props[1].getSubType().getSubType().type).toBe('string');
}
});
test('set array result', () => {
function DummyDecorator() {
return (target: Object, property: string) => {
};
}
class Item {
constructor(
@t public title: string
) {
}
}
class Controller {
@DummyDecorator()
items1(): Item[] {
return [];
}
@DummyDecorator()
async items2(): Promise<Item[]> {
return [];
}
@t.any
items3(): Item[] {
return [];
}
@t.any
async items4(): Promise<Item[]> {
return [];
}
}
const s = getClassSchema(Controller);
{
const prop = s.getMethod('items1');
expect(prop.isArray).toBe(true);
expect(prop.getSubType().type).toBe('any');
}
{
expect(s.getMethod('items2').type).toBe('promise');
}
{
const prop = s.getMethod('items3');
expect(prop.type).toBe('any');
expect(prop.isArray).toBe(false); //because we explicitly set any()
}
{
const prop = s.getMethod('items4');
expect(prop.type).toBe('any');
expect(prop.isArray).toBe(false);
}
});
test('base class with constructor', () => {
class UserBase {
@t.primary.uuid
id: string = uuid();
@t
version: number = 1;
constructor(@t public name: string) {
}
}
@entity.name('test_test')
class User extends UserBase {
@t
connections: number = 0;
}
const newProperty = new PropertySchema('v');
newProperty.setFromJSValue(new User('asd'));
const schema = getClassSchema(User);
expect(schema.getProperty('name').type).toBe('string');
const args = schema.getMethodProperties('constructor');
expect(args[0] === schema.getProperty('name')).toBe(true);
expect(args[0].name).toBe('name');
expect(args[0].type).toBe('string');
});
test('promise is correct detected', () => {
class Controller {
@t
async action1() {
return '123';
}
@t.string
async action2() {
return '123';
}
}
const schema = getClassSchema(Controller);
expect(schema.getMethod('action1').type).toBe('promise');
expect(schema.getMethod('action2').type).toBe('string');
});
test('custom parameter name', () => {
class Controller {
@t
async action1(@t.description('asd').name('first') a: string, @t second: string) {
return '123';
}
}
const schema = getClassSchema(Controller);
expect(schema.getMethodProperties('action1')[0].name).toBe('first');
expect(schema.getMethodProperties('action1')[1].name).toBe('second');
});
test('inheritance', () => {
class User {
}
class Controller {
@t.type(User).optional
action1(a: string): User | undefined {
return new User;
}
}
class Extended extends Controller {
@t
action2(b: string): string {
return 'hello';
}
}
{
const schema = getClassSchema(Controller);
expect(schema.getMethod('action1').type).toBe('class');
expect(schema.getMethod('action1').classType).toBe(User);
expect(schema.getMethodProperties('action1')[0].name).toBe('a');
}
{
class E extends Controller {
}
const clone = getClassSchema(Controller).clone(E);
expect(clone.getMethod('action1').type).toBe('class');
}
{
const schema = getClassSchema(Extended);
expect((schema as any).initializedMethods.has('action1')).toBe(false);
expect(schema.getMethod('action1').type).toBe('class');
expect(schema.getMethod('action1').classType).toBe(User);
expect(schema.getMethodProperties('action1')[0].name).toBe('a');
expect(schema.getMethod('action2').type).toBe('string');
expect(schema.getMethodProperties('action2')[0].name).toBe('b');
}
});
test('Promise generic', () => {
class Controller {
@t.generic(t.string)
async action(): Promise<string> {
return '';
}
}
const schema = getClassSchema(Controller);
const property = schema.getMethod('action');
expect(property.type).toBe('promise');
expect(property.templateArgs[0].type).toBe('string');
});
test('Promise type manually should work as well', () => {
//we basically ignore the fact that its a promise and define its type easier
class Controller {
@t.string
async action(): Promise<string> {
return '';
}
}
const schema = getClassSchema(Controller);
const property = schema.getMethod('action');
expect(property.type).toBe('string');
}); | the_stack |
import { EventEmitter } from 'events';
import { Dirent as NodeDirent, ReadStream } from 'fs';
import { Stats as NodeStats, WriteStream } from 'fs';
import { NoParamCallback, BigIntStats as NodeBigIntStats } from 'fs';
import { LinkStrategy } from './algorithms/copyPromise';
import { FSPath, Path, PortablePath, PathUtils, Filename } from './path';
export declare type Stats = NodeStats & {
crc?: number;
};
export declare type BigIntStats = NodeBigIntStats & {
crc?: number;
};
export declare type Dirent = Exclude<NodeDirent, 'name'> & {
name: Filename;
};
export declare type Dir<P extends Path> = {
readonly path: P;
[Symbol.asyncIterator](): AsyncIterableIterator<Dirent>;
close(): Promise<void>;
close(cb: NoParamCallback): void;
closeSync(): void;
read(): Promise<Dirent | null>;
read(cb: (err: NodeJS.ErrnoException | null, dirent: Dirent | null) => void): void;
readSync(): Dirent | null;
};
export declare type OpendirOptions = Partial<{
bufferSize: number;
}>;
export declare type CreateReadStreamOptions = Partial<{
encoding: string;
fd: number;
}>;
export declare type CreateWriteStreamOptions = Partial<{
encoding: string;
fd: number;
flags: 'a';
}>;
export declare type MkdirOptions = Partial<{
recursive: boolean;
mode: number;
}>;
export declare type RmdirOptions = Partial<{
maxRetries: number;
recursive: boolean;
retryDelay: number;
}>;
export declare type WriteFileOptions = Partial<{
encoding: string;
mode: number;
flag: string;
}> | string;
export declare type WatchOptions = Partial<{
persistent: boolean;
recursive: boolean;
encoding: string;
}> | string;
export declare type WatchFileOptions = Partial<{
bigint: boolean;
persistent: boolean;
interval: number;
}>;
export declare type ChangeFileOptions = Partial<{
automaticNewlines: boolean;
}>;
export declare type WatchCallback = (eventType: string, filename: string) => void;
export declare type Watcher = {
on: any;
close: () => void;
};
export declare type WatchFileCallback = (current: Stats, previous: Stats) => void;
export declare type StatWatcher = EventEmitter & {
ref?: () => StatWatcher;
unref?: () => StatWatcher;
};
export declare type ExtractHintOptions = {
relevantExtensions: Set<string>;
};
export declare type SymlinkType = 'file' | 'dir' | 'junction';
export declare abstract class FakeFS<P extends Path> {
static DEFAULT_TIME: number;
readonly pathUtils: PathUtils<P>;
protected constructor(pathUtils: PathUtils<P>);
/**
* @deprecated: Moved to jsInstallUtils
*/
abstract getExtractHint(hints: ExtractHintOptions): boolean;
abstract getRealPath(): P;
abstract resolve(p: P): P;
abstract opendirPromise(p: P, opts?: OpendirOptions): Promise<Dir<P>>;
abstract opendirSync(p: P, opts?: OpendirOptions): Dir<P>;
abstract openPromise(p: P, flags: string, mode?: number): Promise<number>;
abstract openSync(p: P, flags: string, mode?: number): number;
abstract readPromise(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number | null): Promise<number>;
abstract readSync(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number | null): number;
abstract writePromise(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number): Promise<number>;
abstract writePromise(fd: number, buffer: string, position?: number): Promise<number>;
abstract writeSync(fd: number, buffer: Buffer, offset?: number, length?: number, position?: number): number;
abstract writeSync(fd: number, buffer: string, position?: number): number;
abstract closePromise(fd: number): Promise<void>;
abstract closeSync(fd: number): void;
abstract createWriteStream(p: P | null, opts?: CreateWriteStreamOptions): WriteStream;
abstract createReadStream(p: P | null, opts?: CreateReadStreamOptions): ReadStream;
abstract realpathPromise(p: P): Promise<P>;
abstract realpathSync(p: P): P;
abstract readdirPromise(p: P): Promise<Array<Filename>>;
abstract readdirPromise(p: P, opts: {
withFileTypes: false;
}): Promise<Array<Filename>>;
abstract readdirPromise(p: P, opts: {
withFileTypes: true;
}): Promise<Array<Dirent>>;
abstract readdirPromise(p: P, opts: {
withFileTypes: boolean;
}): Promise<Array<Filename> | Array<Dirent>>;
abstract readdirSync(p: P): Array<Filename>;
abstract readdirSync(p: P, opts: {
withFileTypes: false;
}): Array<Filename>;
abstract readdirSync(p: P, opts: {
withFileTypes: true;
}): Array<Dirent>;
abstract readdirSync(p: P, opts: {
withFileTypes: boolean;
}): Array<Filename> | Array<Dirent>;
abstract existsPromise(p: P): Promise<boolean>;
abstract existsSync(p: P): boolean;
abstract accessPromise(p: P, mode?: number): Promise<void>;
abstract accessSync(p: P, mode?: number): void;
abstract statPromise(p: P): Promise<Stats>;
abstract statPromise(p: P, opts: {
bigint: true;
}): Promise<BigIntStats>;
abstract statPromise(p: P, opts?: {
bigint: boolean;
}): Promise<BigIntStats | Stats>;
abstract statSync(p: P): Stats;
abstract statSync(p: P, opts: {
bigint: true;
}): BigIntStats;
abstract statSync(p: P, opts?: {
bigint: boolean;
}): BigIntStats | Stats;
abstract fstatPromise(fd: number): Promise<Stats>;
abstract fstatPromise(fd: number, opts: {
bigint: true;
}): Promise<BigIntStats>;
abstract fstatPromise(fd: number, opts?: {
bigint: boolean;
}): Promise<BigIntStats | Stats>;
abstract fstatSync(fd: number): Stats;
abstract fstatSync(fd: number, opts: {
bigint: true;
}): BigIntStats;
abstract fstatSync(fd: number, opts?: {
bigint: boolean;
}): BigIntStats | Stats;
abstract lstatPromise(p: P): Promise<Stats>;
abstract lstatPromise(p: P, opts: {
bigint: true;
}): Promise<BigIntStats>;
abstract lstatPromise(p: P, opts?: {
bigint: boolean;
}): Promise<BigIntStats | Stats>;
abstract lstatSync(p: P): Stats;
abstract lstatSync(p: P, opts: {
bigint: true;
}): BigIntStats;
abstract lstatSync(p: P, opts?: {
bigint: boolean;
}): BigIntStats | Stats;
abstract chmodPromise(p: P, mask: number): Promise<void>;
abstract chmodSync(p: P, mask: number): void;
abstract chownPromise(p: P, uid: number, gid: number): Promise<void>;
abstract chownSync(p: P, uid: number, gid: number): void;
abstract mkdirPromise(p: P, opts?: MkdirOptions): Promise<void>;
abstract mkdirSync(p: P, opts?: MkdirOptions): void;
abstract rmdirPromise(p: P, opts?: RmdirOptions): Promise<void>;
abstract rmdirSync(p: P, opts?: RmdirOptions): void;
abstract linkPromise(existingP: P, newP: P): Promise<void>;
abstract linkSync(existingP: P, newP: P): void;
abstract symlinkPromise(target: P, p: P, type?: SymlinkType): Promise<void>;
abstract symlinkSync(target: P, p: P, type?: SymlinkType): void;
abstract renamePromise(oldP: P, newP: P): Promise<void>;
abstract renameSync(oldP: P, newP: P): void;
abstract copyFilePromise(sourceP: P, destP: P, flags?: number): Promise<void>;
abstract copyFileSync(sourceP: P, destP: P, flags?: number): void;
abstract appendFilePromise(p: FSPath<P>, content: string | Buffer | ArrayBuffer | DataView, opts?: WriteFileOptions): Promise<void>;
abstract appendFileSync(p: FSPath<P>, content: string | Buffer | ArrayBuffer | DataView, opts?: WriteFileOptions): void;
abstract writeFilePromise(p: FSPath<P>, content: string | Buffer | ArrayBuffer | DataView, opts?: WriteFileOptions): Promise<void>;
abstract writeFileSync(p: FSPath<P>, content: string | Buffer | ArrayBuffer | DataView, opts?: WriteFileOptions): void;
abstract unlinkPromise(p: P): Promise<void>;
abstract unlinkSync(p: P): void;
abstract utimesPromise(p: P, atime: Date | string | number, mtime: Date | string | number): Promise<void>;
abstract utimesSync(p: P, atime: Date | string | number, mtime: Date | string | number): void;
lutimesPromise?(p: P, atime: Date | string | number, mtime: Date | string | number): Promise<void>;
lutimesSync?(p: P, atime: Date | string | number, mtime: Date | string | number): void;
abstract readFilePromise(p: FSPath<P>, encoding: 'utf8'): Promise<string>;
abstract readFilePromise(p: FSPath<P>, encoding?: string): Promise<Buffer>;
abstract readFileSync(p: FSPath<P>, encoding: 'utf8'): string;
abstract readFileSync(p: FSPath<P>, encoding?: string): Buffer;
abstract readlinkPromise(p: P): Promise<P>;
abstract readlinkSync(p: P): P;
abstract truncatePromise(p: P, len?: number): Promise<void>;
abstract truncateSync(p: P, len?: number): void;
abstract watch(p: P, cb?: WatchCallback): Watcher;
abstract watch(p: P, opts: WatchOptions, cb?: WatchCallback): Watcher;
abstract watchFile(p: P, cb: WatchFileCallback): StatWatcher;
abstract watchFile(p: P, opts: WatchFileOptions, cb: WatchFileCallback): StatWatcher;
abstract unwatchFile(p: P, cb?: WatchFileCallback): void;
genTraversePromise(init: P, { stableSort }?: {
stableSort?: boolean;
}): AsyncGenerator<NonNullable<P>, void, unknown>;
removePromise(p: P, { recursive, maxRetries }?: {
recursive?: boolean;
maxRetries?: number;
}): Promise<void>;
removeSync(p: P, { recursive }?: {
recursive?: boolean;
}): void;
mkdirpPromise(p: P, { chmod, utimes }?: {
chmod?: number;
utimes?: [Date | string | number, Date | string | number];
}): Promise<void>;
mkdirpSync(p: P, { chmod, utimes }?: {
chmod?: number;
utimes?: [Date | string | number, Date | string | number];
}): void;
copyPromise(destination: P, source: P, options?: {
baseFs?: undefined;
overwrite?: boolean;
stableSort?: boolean;
stableTime?: boolean;
linkStrategy?: LinkStrategy;
}): Promise<void>;
copyPromise<P2 extends Path>(destination: P, source: P2, options: {
baseFs: FakeFS<P2>;
overwrite?: boolean;
stableSort?: boolean;
stableTime?: boolean;
linkStrategy?: LinkStrategy;
}): Promise<void>;
/** @deprecated Prefer using `copyPromise` instead */
copySync(destination: P, source: P, options?: {
baseFs?: undefined;
overwrite?: boolean;
}): void;
copySync<P2 extends Path>(destination: P, source: P2, options: {
baseFs: FakeFS<P2>;
overwrite?: boolean;
}): void;
changeFilePromise(p: P, content: Buffer): Promise<void>;
changeFilePromise(p: P, content: string, opts?: ChangeFileOptions): Promise<void>;
private changeFileBufferPromise;
private changeFileTextPromise;
changeFileSync(p: P, content: Buffer): void;
changeFileSync(p: P, content: string, opts?: ChangeFileOptions): void;
private changeFileBufferSync;
private changeFileTextSync;
movePromise(fromP: P, toP: P): Promise<void>;
moveSync(fromP: P, toP: P): void;
lockPromise<T>(affectedPath: P, callback: () => Promise<T>): Promise<T>;
readJsonPromise(p: P): Promise<any>;
readJsonSync(p: P): any;
writeJsonPromise(p: P, data: any): Promise<void>;
writeJsonSync(p: P, data: any): void;
preserveTimePromise(p: P, cb: () => Promise<P | void>): Promise<void>;
preserveTimeSync(p: P, cb: () => P | void): Promise<void>;
}
export declare abstract class BasePortableFakeFS extends FakeFS<PortablePath> {
protected constructor();
}
export declare function normalizeLineEndings(originalContent: string, newContent: string): string; | the_stack |
import { Sylvester, OutOfRangeError, DimensionalityMismatchError } from './sylvester';
import { Vector } from './vector';
import { VectorOrList, isVectorLike, MatrixLike, isMatrixLike } from './likeness';
/**
* @private
*/
function sign(x: number) {
return x < 0 ? -1 : 1;
}
/**
* Augment a matrix M with identity rows/cols
* @private
*/
function identSize(e: number[][], m: number, n: number, k: number) {
let i = k - 1;
while (i--) {
const row = [];
for (let j = 0; j < n; j++) {
row.push(j === i ? 1 : 0);
}
e.unshift(row);
}
for (let i = k - 1; i < m; i++) {
while (e[i].length < n) {
e[i].unshift(0);
}
}
return new Matrix(e);
}
/**
* @private
*/
function pca(X: Matrix) {
const Sigma = X.transpose()
.x(X)
.x(1 / X.rows);
const svd = Sigma.svd();
return {
U: svd.U,
S: svd.S,
};
}
/**
* @private
*/
const sizeStr = (matrix: MatrixLike) =>
matrix instanceof Matrix
? `${matrix.rows}x${matrix.cols} matrix`
: `${matrix.length}x${matrix[0].length}`;
/**
* @private
*/
const extractElements = (
matrixOrRows: MatrixLike | VectorOrList,
): ReadonlyArray<ReadonlyArray<number>> => {
const rows = (matrixOrRows as any).elements || matrixOrRows;
if (typeof rows[0][0] === 'undefined') {
return new Matrix(rows).elements;
}
return rows;
};
/**
* Returns a mutable copy of the matrix elements. Used internally only to avoid
* unnecessary duplication. Dangerous to expose.
* @private
*/
const takeOwnership = (matrix: Matrix): number[][] => (matrix as any).elements;
export class Matrix {
/**
* Matrix elements.
*/
public readonly elements: ReadonlyArray<ReadonlyArray<number>>;
/**
* Gets the number of rows in the matrix.
*/
public readonly rows: number;
/**
* Gets the number of columns in the matrix.
*/
public readonly cols: number;
constructor(input: MatrixLike | VectorOrList) {
if (input instanceof Matrix) {
this.elements = input.elements;
} else if (input instanceof Vector) {
this.elements = input.elements.map(e => [e]);
} else if (input[0] instanceof Array) {
this.elements = input as number[][];
} else {
this.elements = (input as number[]).map(e => [e]);
}
this.rows = this.elements.length;
this.cols = this.rows && this.elements[0].length;
}
// solve a system of linear equations (work in progress)
solve(b: Vector) {
const lu = this.lu();
const y = lu.L.forwardSubstitute(lu.P.x(b));
const x = lu.U.backSubstitute(y);
return lu.P.x(x);
// return this.inv().x(b);
}
// project a matrix onto a lower dim
pcaProject(k: number, U = pca(this).U) {
const Ureduce = U.slice(1, U.rows, 1, k);
return {
Z: this.x(Ureduce),
U,
};
}
/**
* Recover a matrix to a higher dimension
*/
public pcaRecover(U: Matrix): Matrix {
const k = this.cols;
const Ureduce = U.slice(1, U.rows, 1, k);
return this.x(Ureduce.transpose());
}
/**
* Grab the upper triangular part of the matrix
* @diagram Matrix.triu
*/
public triu(k: number = 0): Matrix {
return this.map((x, i, j) => {
return j - i >= k ? x : 0;
});
}
/**
* Unroll a matrix into a vector
* @diagram Matrix.unroll
*/
public unroll(): Vector {
const v = [];
for (let i = 1; i <= this.cols; i++) {
for (let j = 1; j <= this.rows; j++) {
v.push(this.e(j, i)!);
}
}
return new Vector(v);
}
/**
* Returns a sub-block of the matrix.
* @param startRow - Top-most starting row.
* @param endRow - Bottom-most ending row. If 0, takes the whole matrix.
* @param startCol - Left-most starting column.
* @param endCol - Right-most ending column. If 0, takes the whole matrix.
* @return {Matrix}
* @diagram Matrix.slice
*/
public slice(startRow: number, endRow: number, startCol: number, endCol: number): Matrix {
const x: number[][] = [];
if (endRow === 0) {
endRow = this.rows;
}
if (endCol === 0) {
endCol = this.cols;
}
for (let i = Math.max(1, startRow); i <= endRow; i++) {
const row: number[] = [];
for (let j = Math.max(1, startCol); j <= endCol; j++) {
row.push(this.e(i, j)!);
}
x.push(row);
}
return new Matrix(x);
}
/**
* Returns the element at (i, j) in the matrix, or null if out of bounds.
* @param {Number} i Matrix row
* @param {Number} j Matrix column
* @diagram Matrix.e
*/
public e(i: number, j: number): number | null {
if (i < 1 || i > this.elements.length || j < 1 || j > this.elements[0].length) {
return null;
}
return this.elements[i - 1][j - 1];
}
/**
* Returns a vector containing the values in row o.
* @throws A {@link OutOfRangeError} if o is out of range
* @diagram Matrix.row
*/
public row(i: number): Vector {
if (i < 1 || i > this.elements.length) {
throw new OutOfRangeError(`Row ${i} is outside the bounds of this ${sizeStr(this)}`);
}
return new Vector(this.elements[i - 1]);
}
/**
* Returns a vector containing the values in column j.
* @throws A {@link OutOfRangeError} if j is out of range
* @diagram Matrix.col
*/
public col(j: number): Vector {
if (j < 1 || j > this.elements[0].length) {
throw new OutOfRangeError(`Column ${j} is outside the bounds of this ${sizeStr(this)}`);
}
const col = [];
const n = this.elements.length;
for (let i = 0; i < n; i++) {
col.push(this.elements[i][j - 1]);
}
return new Vector(col);
}
/**
* Returns whether this matrix is approximately equal to the other one,
* within the given precision.
* @param matrix - Matrix or matrix values to compare
* @param epsilon - The precision to compare each number.
* @return True if the matrices are equal, false if they are not or a different size.
*/
public eql(matrix: unknown, epsilon = Sylvester.approxPrecision) {
if (!isMatrixLike(matrix)) {
return false;
}
const M = extractElements(matrix);
if (this.elements.length !== M.length || this.elements[0].length !== M[0].length) {
return false;
}
let i = this.elements.length;
const nj = this.elements[0].length;
let j;
while (i--) {
j = nj;
while (j--) {
if (Math.abs(this.elements[i][j] - M[i][j]) > epsilon) {
return false;
}
}
}
return true;
}
/**
* Creates a new matrix by applying the mapping function
* on all values in this one.
*/
public map(fn: (value: number, row: number, column: number) => number) {
const els: number[][] = [];
let i = this.elements.length;
const nj = this.elements[0].length;
while (i--) {
let j = nj;
els[i] = [];
while (j--) {
els[i][j] = fn(this.elements[i][j], i + 1, j + 1);
}
}
return new Matrix(els);
}
/**
* Returns whether this matrix is the same size as the other one.
* @diagram Matrix.isSameSizeAs
*/
public isSameSizeAs(matrix: MatrixLike) {
const M = extractElements(matrix);
return this.elements.length === M.length && this.elements[0].length === M[0].length;
}
/**
* Adds the number or matrix to this matrix.
* @throws A {@link DimensionalityMismatchError} If the matrix is a different size than this one
* @diagram Matrix.add
*/
public add(matrix: number | MatrixLike) {
if (typeof matrix === 'number') {
return this.map(x => x + matrix);
}
const M = extractElements(matrix);
if (!this.isSameSizeAs(M)) {
throw new DimensionalityMismatchError(
`Cannot add a ${sizeStr(matrix)} to this (sizeStr(matrix))`,
);
}
return this.map((x, i, j) => x + M[i - 1][j - 1]);
}
/**
* Subtracts the number or matrix to this matrix.
* @throws A {@link DimensionalityMismatchError} If the matrix is a different size than this one
* @diagram Matrix.subtract
*/
public subtract(matrix: number | MatrixLike) {
if (typeof matrix === 'number') {
return this.map(x => x - matrix);
}
const M = extractElements(matrix);
if (!this.isSameSizeAs(M)) {
throw new DimensionalityMismatchError(
`Cannot add a ${sizeStr(matrix)} to this (sizeStr(matrix))`,
);
}
return this.map((x, i, j) => x - M[i - 1][j - 1]);
}
/**
* Returns true if the give matrix can multiply this one from the left.
*/
public canMultiplyFromLeft(matrix: MatrixLike) {
const M = extractElements(matrix);
// this.columns should equal matrix.rows
return this.elements[0].length === M.length;
}
/**
* Returns the result of a multiplication-style operation the matrix from the
* right by the argument.
*
* If the argument is a scalar then just operate on all the elements. If
* the argument is a vector, a vector is returned, which saves you having
* to remember calling col(1) on the result.
*
* @param op - Operation to run, taking the matrix value on the 'left' side
* and the provided multiplicand on the right.
*/
public mulOp(matrix: VectorOrList, op: (left: number, right: number) => number): Vector;
public mulOp(matrix: MatrixLike | number, op: (left: number, right: number) => number): Matrix;
public mulOp(
matrix: MatrixLike | VectorOrList | number,
op: (left: number, right: number) => number,
) {
if (typeof matrix === 'number') {
return this.map(x => {
return op(x, matrix);
});
}
const returnVector = isVectorLike(matrix);
const M = extractElements(matrix);
if (!this.canMultiplyFromLeft(M)) {
throw new DimensionalityMismatchError(
`Cannot multiply a ${sizeStr(this)} by a ${sizeStr(M)}, expected an ${this.cols}xN matrix`,
);
}
const e = this.elements;
let rowThis;
let rowElem;
const elements = [];
let sum;
const m = e.length;
const n = M[0].length;
const o = e[0].length;
let i = m;
let j;
let k;
while (i--) {
rowElem = [];
rowThis = e[i];
j = n;
while (j--) {
sum = 0;
k = o;
while (k--) {
sum += op(rowThis[k], M[k][j]);
}
rowElem[j] = sum;
}
elements[i] = rowElem;
}
const output = new Matrix(elements);
return returnVector ? output.col(1) : output;
}
/**
* Returns the result of dividing the matrix from the right by the argument.
*
* If the argument is a scalar then just operate on all the elements. If
* the argument is a vector, a vector is returned, which saves you having
* to remember calling col(1) on the result.
*
* @throws A {@link DimensionalityMismatchError} If the divisor is an
* inappropriately sized matrix
*/
public div(divisor: VectorOrList): Vector;
public div(divisor: MatrixLike | number): Matrix;
public div(divisor: MatrixLike | VectorOrList | number): Vector | Matrix {
// Cast is needed here since TS gets confused with nested overloads like this
return this.mulOp(divisor as MatrixLike, (x, y) => x / y);
}
/**
* Returns the result of multiplying the matrix from the right by the argument.
*
* If the argument is a scalar then just operate on all the elements. If
* the argument is a vector, a vector is returned, which saves you having
* to remember calling col(1) on the result.
*
* @throws A {@link DimensionalityMismatchError} If the multiplicand is an
* inappropriately sized matrix
* @diagram Matrix.multiply
*/
public multiply(multiplicand: VectorOrList): Vector;
public multiply(multiplicand: MatrixLike | number): Matrix;
public multiply(multiplicand: MatrixLike | VectorOrList | number): Vector | Matrix {
// Cast is needed here since TS gets confused with nested overloads like this
return this.mulOp(multiplicand as MatrixLike, (x, y) => x * y);
}
/**
* Alias to {@link Matrix.multiply}
*/
public x(multiplicand: VectorOrList): Vector;
public x(multiplicand: MatrixLike | number): Matrix;
public x(multiplicand: MatrixLike | VectorOrList | number): Vector | Matrix {
// Cast is needed here since TS gets confused with nested overloads like this
return this.mulOp(multiplicand as MatrixLike, (x, y) => x * y);
}
/**
* Multiplies matrix elements individually.
* @throws A {@link DimensionalityMismatchError} If v is not the same size as this matrix
* @diagram Matrix.elementMultiply
*/
public elementMultiply(v: Matrix) {
if (!this.isSameSizeAs(v)) {
throw new DimensionalityMismatchError(
`Cannot element multiple a ${sizeStr(this)} by a ${sizeStr(v)}, expected the same size`,
);
}
return this.map((k, i, j) => {
return v.e(i, j)! * k;
});
}
/**
* Sums all the elements of the matrix.
* @diagram Matrix.sum
*/
public sum() {
let sum = 0;
for (let i = 0; i < this.rows; i++) {
for (let k = 0; k < this.cols; k++) {
sum += this.elements[i][k];
}
}
return sum;
}
/**
* Returns the arithmetic mean of each column.
* @diagram Matrix.mean
*/
mean() {
const r = [];
for (let i = 1; i <= this.cols; i++) {
r.push(this.col(i).sum() / this.rows);
}
return new Vector(r);
}
/**
* Returns a Vector of each column's standard deviation
* @diagram Matrix.std
*/
public std(): Vector {
const mMean = this.mean();
const r = [];
for (let i = 1; i <= this.cols; i++) {
let meanDiff = this.col(i).subtract(mMean.e(i)!);
meanDiff = meanDiff.multiply(meanDiff);
r.push(Math.sqrt(meanDiff.sum() / this.rows));
}
return new Vector(r);
}
/**
* Runs an element-wise logarithm on the matrix.
* @diagram Matrix.log
*/
public log(base = Math.E): Matrix {
const logBase = Math.log(base); // change of base
return this.map(x => Math.log(x) / logBase);
}
/**
* Returns a submatrix taken from the matrix. Element selection wraps if the
* required index is outside the matrix's bounds, so you could use this to
* perform row/column cycling or copy-augmenting.
* @param nrows - Rows to copy
* @param ncols - Columns to copy
* @diagram Matrix.minor
*/
minor(startRow: number, startCol: number, nrows: number, ncols: number) {
const elements: number[][] = [];
let ni = nrows;
let i: number;
let nj: number;
let j: number;
const rows = this.elements.length;
const cols = this.elements[0].length;
while (ni--) {
i = nrows - ni - 1;
elements[i] = [];
nj = ncols;
while (nj--) {
j = ncols - nj - 1;
elements[i][j] = this.elements[(startRow + i - 1) % rows][(startCol + j - 1) % cols];
}
}
return new Matrix(elements);
}
/**
* Returns the transposition of the matrix.
* @diagram Matrix.transpose
*/
public transpose() {
const rows = this.elements.length;
const cols = this.elements[0].length;
const elements: number[][] = [];
let i = cols;
let j: number;
while (i--) {
j = rows;
elements[i] = [];
while (j--) {
elements[i][j] = this.elements[j][i];
}
}
return new Matrix(elements);
}
/**
* Returns whether this is a square matrix.
* @diagram Matrix.isSquare
*/
isSquare() {
return this.elements.length === this.elements[0].length;
}
/**
* Returns the absolute largest element of the matrix
* @diagram Matrix.max
*/
max() {
let m = 0;
let i = this.elements.length;
const nj = this.elements[0].length;
let j;
while (i--) {
j = nj;
while (j--) {
if (Math.abs(this.elements[i][j]) > Math.abs(m)) {
m = this.elements[i][j];
}
}
}
return m;
}
/**
* Returns the index of the first occurence of x found
* by reading row-by-row from left to right, or null.
* @diagram Matrix.indexOf
*/
public indexOf(x: number) {
const ni = this.elements.length;
let i;
const nj = this.elements[0].length;
let j;
for (i = 0; i < ni; i++) {
for (j = 0; j < nj; j++) {
if (this.elements[i][j] === x) {
return {
i: i + 1,
j: j + 1,
};
}
}
}
return null;
}
/**
* If the matrix is square, returns the diagonal elements as a vector.
* @throws A {@link DimensionalityMismatchError} if the matrix is not square
* @diagram Matrix.diagonal
*/
public diagonal() {
if (!this.isSquare()) {
throw new DimensionalityMismatchError(
`Cannot get the diagonal of a ${sizeStr(this)} matrix, matrix must be square`,
);
}
const els = [];
const n = this.elements.length;
for (let i = 0; i < n; i++) {
els.push(this.elements[i][i]);
}
return new Vector(els);
}
/**
* Make the matrix upper (right) triangular by Gaussian elimination.
* This method only adds multiples of rows to other rows. No rows are
* scaled up or switched, and the determinant is preserved.
* @diagram Matrix.toRightTriangular
*/
public toRightTriangular(): Matrix {
const m = this.toArray();
let els;
const n = this.elements.length;
let i;
let j;
const np = this.elements[0].length;
let p;
for (i = 0; i < n; i++) {
if (m[i][i] === 0) {
for (j = i + 1; j < n; j++) {
if (m[j][i] !== 0) {
els = [];
for (p = 0; p < np; p++) {
els.push(m[i][p] + m[j][p]);
}
m[i] = els;
break;
}
}
}
if (m[i][i] !== 0) {
for (j = i + 1; j < n; j++) {
const multiplier = m[j][i] / m[i][i];
els = [];
for (p = 0; p < np; p++) {
// Elements with column numbers up to an including the number
// of the row that we're subtracting can safely be set straight to
// zero, since that's the point of this routine and it avoids having
// to loop over and correct rounding errors later
els.push(p <= i ? 0 : m[j][p] - m[i][p] * multiplier);
}
m[j] = els;
}
}
}
return new Matrix(m);
}
/**
* Returns the determinant of a square matrix.
* @throws A {@link DimensionalityMismatchError} If the matrix is not square
* @diagram Matrix.determinant
*/
public determinant(): number {
if (!this.isSquare()) {
throw new DimensionalityMismatchError(
`A matrix must be square to have a determinant, this is a ${sizeStr(this)}`,
);
}
if (this.cols === 0 && this.rows === 0) {
return 1;
}
const M = this.toRightTriangular();
let det = M.elements[0][0];
const n = M.elements.length;
for (let i = 1; i < n; i++) {
det *= M.elements[i][i];
}
return det;
}
/**
* Alias for {@link determinant}
* @throws A {@link DimensionalityMismatchError} If the matrix is not square
* @diagram Matrix.determinant
*/
public det(): number {
return this.determinant();
}
/**
* Returns true if the matrix is singular
* @diagram Matrix.isSingular
*/
public isSingular(): boolean {
return this.isSquare() && this.determinant() === 0;
}
/**
* Returns the trace for square matrices
* @throws A {@link DimensionalityMismatchError} if the matrix is not square
* @diagram Matrix.trace
*/
public trace(): number {
if (!this.isSquare()) {
throw new DimensionalityMismatchError(
`Can only get the trace of square matrices, got a ${sizeStr(this)}`,
);
}
let tr = this.elements[0][0];
const n = this.elements.length;
for (let i = 1; i < n; i++) {
tr += this.elements[i][i];
}
return tr;
}
/**
* Returns the rank of the matrix.
* @param epsilon - for comparison against 0
* @diagram Matrix.rank
*/
public rank(epsilon = Sylvester.precision): number {
const M = this.toRightTriangular();
let rank = 0;
let i = this.elements.length;
const nj = this.elements[0].length;
let j;
while (i--) {
j = nj;
while (j--) {
if (Math.abs(M.elements[i][j]) > epsilon) {
rank++;
break;
}
}
}
return rank;
}
/**
* Returns the result of attaching the given argument to the
* right-hand side of the matrix.
* @diagram Matrix.augment
*/
public augment(matrix: MatrixLike): Matrix {
const M = extractElements(matrix);
const T = this.toArray();
const cols = T[0].length;
let i = T.length;
const nj = M[0].length;
let j;
if (i !== M.length) {
throw new DimensionalityMismatchError(`Attached matrix must have ${i} rows, got ${M.length}`);
}
while (i--) {
j = nj;
while (j--) {
T[i][cols + j] = M[i][j];
}
}
return new Matrix(T);
}
/**
* Returns the inverse of the matrix.
* @throws A {@link DimensionalityMismatchError} if the matrix is not invertible
* @diagram Matrix.inverse
*/
public inverse() {
if (!this.isSquare()) {
throw new DimensionalityMismatchError(
`A matrix must be square to be inverted, provided a ${sizeStr(this)}`,
);
}
if (this.isSingular()) {
throw new DimensionalityMismatchError(`Cannot invert the current matrix (determinant=0)`);
}
const n = this.elements.length;
let i = n;
let j;
const M = takeOwnership(this.augment(Matrix.I(n)).toRightTriangular());
const np = M[0].length;
let p;
let els;
let divisor;
const inverseElements: number[][] = [];
// Matrix is non-singular so there will be no zeros on the diagonal
// Cycle through rows from last to first
let newElement: number;
while (i--) {
// First, normalise diagonal elements to 1
els = [];
inverseElements[i] = [];
divisor = M[i][i];
for (p = 0; p < np; p++) {
newElement = M[i][p] / divisor;
els.push(newElement);
// Shuffle off the current row of the right hand side into the results
// array as it will not be modified by later runs through this loop
if (p >= n) {
inverseElements[i].push(newElement);
}
}
M[i] = els;
// Then, subtract this row from those above it to
// give the identity matrix on the left hand side
j = i;
while (j--) {
els = [];
for (p = 0; p < np; p++) {
els.push(M[j][p] - M[i][p] * M[j][i]);
}
M[j] = els;
}
}
return new Matrix(inverseElements);
}
/**
* Rounds all values in the matrix.
* @diagram Matrix.inverse
*/
public round() {
return this.map(x => Math.round(x));
}
/**
* Returns a copy of the matrix with elements set to the given value if they
* differ from it by less than the epsilon.
* @diagram Matrix.snapTo
*/
public snapTo(target: number, epsilon = Sylvester.precision) {
return this.map(p => (Math.abs(p - target) <= epsilon ? target : p));
}
/**
* Returns a string representation of the matrix.
*/
public toString(): string {
const matrixRows = ['Matrix<'];
for (let i = 0; i < this.elements.length; i++) {
matrixRows.push(` [${this.elements[i].join(', ')}]`);
}
matrixRows.push('>');
return matrixRows.join('\n');
}
/**
* Returns a array representation of the matrix
* @return {Number[]}
*/
public toArray(): number[][] {
const matrixRows: number[][] = [];
const n = this.elements.length;
for (let i = 0; i < n; i++) {
matrixRows.push(this.elements[i].slice());
}
return matrixRows;
}
/**
* Return the indexes of the columns with the largest value for each row.
* @diagram Matrix.maxColumnIndexes
*/
public maxColumnIndexes(): Vector {
const maxes = [];
for (let i = 1; i <= this.rows; i++) {
let max = null;
let maxIndex = -1;
for (let j = 1; j <= this.cols; j++) {
if (max === null || this.e(i, j)! > max) {
max = this.e(i, j);
maxIndex = j;
}
}
maxes.push(maxIndex);
}
return new Vector(maxes);
}
/**
* Return the largest values in each row.
* @diagram Matrix.maxColumns
*/
public maxColumns(): Vector {
const maxes = [];
for (let i = 1; i <= this.rows; i++) {
let max = null;
for (let j = 1; j <= this.cols; j++) {
if (max === null || this.e(i, j)! > max) {
max = this.e(i, j);
}
}
maxes.push(max ?? 0);
}
return new Vector(maxes);
}
/**
* Return the indexes of the columns with the smallest values for each row.
* @diagram Matrix.minColumnIndexes
*/
public minColumnIndexes(): Vector {
const mins = [];
for (let i = 1; i <= this.rows; i++) {
let min = null;
let minIndex = -1;
for (let j = 1; j <= this.cols; j++) {
if (min === null || this.e(i, j)! < min) {
min = this.e(i, j);
minIndex = j;
}
}
mins.push(minIndex);
}
return new Vector(mins);
}
/**
* Return the smallest values in each row.
* @diagram Matrix.minColumns
*/
public minColumns(): Vector {
const mins: number[] = [];
for (let i = 1; i <= this.rows; i++) {
let min = null;
for (let j = 1; j <= this.cols; j++) {
if (min === null || this.e(i, j)! < min) {
min = this.e(i, j);
}
}
mins.push(min ?? 0);
}
return new Vector(mins);
}
/**
* Solve lower-triangular matrix * x = b via forward substitution
* @diagram Matrix.forwardSubstitute
*/
public forwardSubstitute(b: Vector): Vector {
const xa = [];
for (let i = 1; i <= this.rows; i++) {
let w = 0;
for (let j = 1; j < i; j++) {
w += this.e(i, j)! * xa[j - 1];
}
xa.push((b.e(i)! - w) / this.e(i, i)!);
}
return new Vector(xa);
}
/**
* Solve an upper-triangular matrix * x = b via back substitution
* @diagram Matrix.backSubstitute
*/
public backSubstitute(b: Vector): Vector {
const xa = [];
for (let i = this.rows; i > 0; i--) {
let w = 0;
for (let j = this.cols; j > i; j--) {
w += this.e(i, j)! * xa[this.rows - j];
}
xa.push((b.e(i)! - w) / this.e(i, i)!);
}
return new Vector(xa.reverse());
}
public svd() {
let V = Matrix.I(this.rows);
let S = this.transpose();
let U = Matrix.I(this.cols);
let err = Number.MAX_VALUE;
let i = 0;
const maxLoop = 100;
while (err > 2.2737e-13 && i < maxLoop) {
let qr = S.transpose().qr();
S = qr.R;
V = V.x(qr.Q);
qr = S.transpose().qr();
U = U.x(qr.Q);
S = qr.R;
const e = S.triu(1)
.unroll()
.magnitude();
let f = S.diagonal().magnitude();
if (f === 0) {
f = 1;
}
err = e / f;
i++;
}
const ss = S.diagonal();
const s = [];
for (let i = 1; i <= ss.cols(); i++) {
const ssn = ss.e(i)!;
s.push(Math.abs(ssn));
const els = takeOwnership(V);
if (ssn < 0) {
for (let j = 0; j < U.rows; j++) {
els[j][i - 1] = -els[j][i - 1];
}
}
}
return {
U,
S: new Vector(s).toDiagonalMatrix(),
V,
};
}
/**
* Runs a QR decomposition (QR facorization) on the matrix.
* @see https://en.wikipedia.org/wiki/QR_decomposition
*/
qr() {
const m = this.rows;
const n = this.cols;
let Q = Matrix.I(m);
let A: Matrix = this;
for (let k = 1; k < Math.min(m, n); k++) {
const ak = A.slice(k, 0, k, k).col(1);
const oneZero = [1];
while (oneZero.length <= m - k) {
oneZero.push(0);
}
const oneZeroVec = new Vector(oneZero);
const vk = ak.add(oneZeroVec.x(ak.magnitude() * sign(ak.e(1)!)));
const Vk = new Matrix(vk);
const Hk = Matrix.I(m - k + 1).subtract(
Vk.x(2)
.x(Vk.transpose())
.div(
Vk.transpose()
.x(Vk)
.e(1, 1)!,
),
);
const Qk = identSize(takeOwnership(Hk), m, n, k);
A = Qk.x(A);
// slow way to compute Q
Q = Q.x(Qk);
}
return {
Q,
R: A,
};
}
/**
* LU factorization for the matrix.
*/
lu() {
const rows = this.rows;
const cols = this.cols;
const L = Matrix.I(rows).toArray();
const A = this.toArray();
const P = Matrix.I(rows).toArray();
const U = Matrix.Zero(rows, this.cols).toArray();
let p = 1;
/**
* Perform a partial pivot on the matrix. Essentially move the largest
* row below-or-including the pivot and replace the pivot's row with it.
* a pivot matrix is returned so multiplication can perform the transform.
*/
const partialPivot = (k: number, j: number) => {
let maxIndex = 0;
let maxValue = 0;
for (let i = k; i <= rows; i++) {
if (Math.abs(A[i - 1][j - 1]) > maxValue) {
maxValue = Math.abs(A[k - 1][j - 1]);
maxIndex = i;
}
}
if (maxIndex !== k) {
const tmp = A[k - 1];
A[k - 1] = A[maxIndex - 1];
A[maxIndex - 1] = tmp;
P[k - 1][k - 1] = 0;
P[k - 1][maxIndex - 1] = 1;
P[maxIndex - 1][maxIndex - 1] = 0;
P[maxIndex - 1][k - 1] = 1;
}
return P;
};
for (let k = 1; k <= Math.min(cols, rows); k++) {
partialPivot(k, p);
for (let i = k + 1; i <= rows; i++) {
const l = A[i - 1][p - 1] / A[k - 1][p - 1];
L[i - 1][k - 1] = l;
for (let j = k + 1; j <= cols; j++) {
A[i - 1][j - 1] -= A[k - 1][j - 1] * l;
}
}
for (let j = k; j <= cols; j++) {
U[k - 1][j - 1] = A[k - 1][j - 1];
}
if (p < cols) {
p++;
}
}
return {
L: new Matrix(L),
U: new Matrix(U),
P: new Matrix(P),
};
}
/**
* Creates am identity matrix of the given size.
*/
static I(size: number) {
const elements = [];
for (let y = 0; y < size; y++) {
const row = [];
for (let x = 0; x < size; x++) {
row.push(x === y ? 1 : 0);
}
elements.push(row);
}
return new Matrix(elements);
}
/**
* Creates a diagonal matrix from the given elements.
* @diagram Matrix.Diagonal
*/
static Diagonal(vector: VectorOrList) {
const elements = Vector.toElements(vector);
const rows = [];
for (let y = 0; y < elements.length; y++) {
const row = [];
for (let x = 0; x < elements.length; x++) {
row.push(x === y ? elements[x] : 0);
}
rows.push(row);
}
return new Matrix(rows);
}
/**
* Creates a rotation matrix around the given axis.
* @param theta - angle in radians
* @param axis - 3-element vector describing the axis to rotate
* around. If not provided, creates a 2D rotation.
* @diagram Matrix.Rotation
*/
static Rotation(theta: number, axis?: Vector) {
if (!axis) {
return new Matrix([
[Math.cos(theta), -Math.sin(theta)],
[Math.sin(theta), Math.cos(theta)],
]);
}
if (axis.elements.length !== 3) {
throw new DimensionalityMismatchError(
`A 3-element vector must be provided to Rotation, got ${axis.elements.length} elements`,
);
}
const mod = axis.magnitude();
const x = axis.elements[0] / mod;
const y = axis.elements[1] / mod;
const z = axis.elements[2] / mod;
const s = Math.sin(theta);
// Formula derived here: https://web.archive.org/web/20060315070756/http://www.gamedev.net/reference/articles/article1199.asp
// That proof rotates the co-ordinate system so theta
// becomes -theta and sin becomes -sin here.
const c = Math.cos(theta);
const t = 1 - c;
return new Matrix([
[t * x * x + c, t * x * y - s * z, t * x * z + s * y],
[t * x * y + s * z, t * y * y + c, t * y * z - s * x],
[t * x * z - s * y, t * y * z + s * x, t * z * z + c],
]);
}
/**
* Creates a three-dimensional rotation matrix that rotates around the x axis.
* @param t - angle in radians
* @diagram Matrix.RotationX
*/
static RotationX(t: number) {
const c = Math.cos(t);
const s = Math.sin(t);
return new Matrix([
[1, 0, 0],
[0, c, -s],
[0, s, c],
]);
}
/**
* Creates a three-dimensional rotation matrix that rotates around the y axis.
* @param t - angle in radians
* @diagram Matrix.RotationY
*/
static RotationY(t: number) {
const c = Math.cos(t);
const s = Math.sin(t);
return new Matrix([
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
]);
}
/**
* Creates a three-dimensional rotation matrix that rotates around the z axis.
* @param t - angle in radians
* @diagram Matrix.RotationZ
*/
static RotationZ(t: number) {
const c = Math.cos(t);
const s = Math.sin(t);
return new Matrix([
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
]);
}
/**
* Creates an `n` by `m` matrix filled with random values between 0 and 1.
* @param n - rows
* @param m - columns
*/
static Random(n: number, m: number) {
if (arguments.length === 1) {
m = n;
}
return Matrix.Zero(n, m).map(() => Math.random());
}
/**
* Creates an `n` by `m` matrix filled with the given value.
* @param n - rows
* @param m - columns
* @diagram Matrix.Fill
*/
static Fill(n: number, m: number, value: number) {
if (arguments.length === 2) {
value = m;
m = n;
}
const els: number[][] = [];
let i = n;
let j;
while (i--) {
j = m;
els[i] = [];
while (j--) {
els[i][j] = value;
}
}
return new Matrix(els);
}
/**
* Creates an `n` by `m` matrix filled with 0's.
* @param n - rows
* @param m - columns
* @diagram Matrix.Zero
*/
static Zero(n: number, m: number) {
return Matrix.Fill(n, m, 0);
}
/**
* Creates an `n` by `m` matrix filled with 1's.
* @param n - rows
* @param m - columns
* @diagram Matrix.One
*/
static One(n: number, m: number) {
return Matrix.Fill(n, m, 1);
}
} | the_stack |
import {
rollup,
Plugin,
InputOptions,
OutputOptions,
RollupBuild,
OutputChunk,
PreRenderedChunk,
} from 'rollup';
import subpathExternals from '../lib/rollup-plugin-subpath-externals';
function stubFile(fileName: string, fileContent: string): Plugin {
return {
name: 'stub-file',
resolveId: (id): string => {
if (id === fileName) {
return fileName;
}
return null;
},
load: (id): string => {
if (id === fileName) {
return fileContent;
}
return null;
},
};
}
function stubInput(fileContent: string): Plugin {
return {
...stubFile('stub.js', fileContent),
name: 'stub-input',
options: (opts: InputOptions): InputOptions => {
// eslint-disable-next-line no-param-reassign
opts.input = 'stub.js';
return opts;
},
};
}
async function getEntryChunk(bundle: RollupBuild, config?: OutputOptions): Promise<OutputChunk> {
const { output } = await bundle.generate(config || { format: 'esm' });
// jesus this is convoluted. apparently interface extension only works for one hop?
return (output as OutputChunk[]).find(chunk => (chunk as PreRenderedChunk).isEntry);
}
describe('rollup-plugin-subpath-externals', () => {
it('overwrites existing opts.external', async () => {
const bundle = await rollup({
external: importee => !!`overwritten-${importee}`,
plugins: [
stubInput(`
import trim from 'lodash/trim';
export default (s) => trim(s);
`),
subpathExternals({
dependencies: { lodash: '*' },
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['lodash/trim']);
});
it('ignores local imports', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import local from './local';
export default (s) => local(s);
`),
stubFile('./local', 'export default function local() {}'),
subpathExternals({
dependencies: { somelib: '*' },
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual([]);
});
it('ignores devDependencies', async () => {
const bundle = await rollup({
plugins: [
stubFile('foo', 'export default function foo() {};'),
stubInput(`
import foo from 'foo';
export default (s) => foo(s);
`),
subpathExternals({
devDependencies: { foo: '*' },
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual([]);
});
it('externalizes exact matches', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import { trim } from 'lodash';
export default (s) => trim(s);
`),
subpathExternals({
dependencies: { lodash: '*' },
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['lodash']);
});
it('externalizes subpath imports', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import trim from 'lodash/trim';
export default (s) => trim(s);
`),
subpathExternals({
dependencies: { lodash: '*' },
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['lodash/trim']);
});
it('externalizes peerDependencies', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import React from 'react';
export default (s) => React.render(s);
`),
subpathExternals({
devDependencies: {
enzyme: '*',
react: '*',
},
peerDependencies: {
react: '^15.0.0 || ^16.0.0',
},
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['react']);
});
it('externalizes _only_ peerDependencies when output.format is "umd"', async () => {
const bundle = await rollup({
plugins: [
{
name: 'stub-whackadoodle',
resolveId(id): string {
if (id === 'whackadoodle') {
return 'whackadoodle';
}
return null;
},
load(id): string {
if (id === 'whackadoodle') {
return 'export default function whackaDoodle(props) { return props.children; };';
}
return null;
},
},
stubInput(`
import React from 'react';
import woo from 'whackadoodle';
export default (s) => React.render(woo(s));
`),
subpathExternals(
{
dependencies: {
whackadoodle: '*',
},
devDependencies: {
react: '*',
},
peerDependencies: {
react: '^15.0.0 || ^16.0.0',
},
},
{ format: 'umd' }
),
],
});
const { code } = await getEntryChunk(bundle, {
format: 'umd',
name: 'StubComponent',
globals: {
react: 'React',
},
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore (it bloody well works, mr. typescript)
indent: ' ',
});
expect(code).toMatchInlineSnapshot(`
"(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
typeof define === 'function' && define.amd ? define(['react'], factory) :
(global = global || self, global.StubComponent = factory(global.React));
}(this, (function (React) { 'use strict';
React = React && React.hasOwnProperty('default') ? React['default'] : React;
function whackaDoodle(props) { return props.children; }
var stub = (s) => React.render(whackaDoodle(s));
return stub;
})));
"
`);
});
it('externalizes node built-ins', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import url from 'url';
import qs from 'querystring';
export default (s) => url.join(s, qs.stringify({ s }));
`),
subpathExternals({}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['url', 'querystring']);
});
it('accepts explicit external config via package prop', async () => {
const bundle = await rollup({
plugins: [
{
name: 'stub-embedded',
resolveId(id): string {
if (id === 'embedded') {
return 'embedded';
}
return null;
},
load(id): string {
if (id === 'embedded') {
return 'export default function embedded(k) { return k; };';
}
return null;
},
},
stubInput(`
import embedded from 'embedded';
import trim from 'lodash/trim';
export default (s) => embedded(trim(s));
`),
subpathExternals({
rollup: {
external: ['lodash'],
},
dependencies: {
embedded: 'test',
lodash: '*',
},
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['lodash/trim']);
expect(chunk.code).toMatchInlineSnapshot(`
"import trim from 'lodash/trim';
function embedded(k) { return k; }
var stub = (s) => embedded(trim(s));
export default stub;
"
`);
});
it('accepts explicit bundle config via package prop', async () => {
const bundle = await rollup({
plugins: [
{
name: 'stub-inlined',
resolveId(id): string {
if (id === 'inlined') {
return 'inlined';
}
return null;
},
load(id): string {
if (id === 'inlined') {
return 'export default function inlined(k) { return k; };';
}
return null;
},
},
stubInput(`
import inlined from 'inlined';
import trim from 'lodash/trim';
export default (s) => inlined(trim(s));
`),
subpathExternals({
rollup: {
bundle: ['inlined'],
},
dependencies: {
inlined: 'test',
lodash: '*',
},
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['lodash/trim']);
expect(chunk.code).toMatchInlineSnapshot(`
"import trim from 'lodash/trim';
function inlined(k) { return k; }
var stub = (s) => inlined(trim(s));
export default stub;
"
`);
});
it('works all together', async () => {
const bundle = await rollup({
plugins: [
stubInput(`
import url from 'url';
import get from 'lodash/get';
import peer from 'a-peer-dependency';
export default function stub() {
return peer(url.resolve('/', get(opts, 'path')));
}
`),
subpathExternals({
peerDependencies: {
'a-peer-dependency': '*',
},
dependencies: {
lodash: '*',
},
}),
],
});
const chunk = await getEntryChunk(bundle);
expect(chunk.imports).toStrictEqual(['url', 'lodash/get', 'a-peer-dependency']);
});
}); | the_stack |
import { ArgumentNullError } from "./Error";
export enum PromiseState {
None,
Resolved,
Rejected,
}
export interface IPromise<T> {
Result(): PromiseResult<T>;
ContinueWith<TContinuationResult>(
continuationCallback: (promiseResult: PromiseResult<T>) => TContinuationResult): IPromise<TContinuationResult>;
ContinueWithPromise<TContinuationResult>(
continuationCallback: (promiseResult: PromiseResult<T>) => IPromise<TContinuationResult>): IPromise<TContinuationResult>;
OnSuccessContinueWith<TContinuationResult>(
continuationCallback: (result: T) => TContinuationResult): IPromise<TContinuationResult>;
OnSuccessContinueWithPromise<TContinuationResult>(
continuationCallback: (result: T) => IPromise<TContinuationResult>): IPromise<TContinuationResult>;
On(successCallback: (result: T) => void, errorCallback: (error: string) => void): IPromise<T>;
Finally(callback: () => void): IPromise<T>;
}
export interface IDeferred<T> {
State(): PromiseState;
Promise(): IPromise<T>;
Resolve(result: T): IDeferred<T>;
Reject(error: string): IDeferred<T>;
}
export class PromiseResult<T> {
protected isCompleted: boolean;
protected isError: boolean;
protected error: string;
protected result: T;
public constructor(promiseResultEventSource: PromiseResultEventSource<T>) {
promiseResultEventSource.On((result: T) => {
if (!this.isCompleted) {
this.isCompleted = true;
this.isError = false;
this.result = result;
}
}, (error: string) => {
if (!this.isCompleted) {
this.isCompleted = true;
this.isError = true;
this.error = error;
}
});
}
public get IsCompleted(): boolean {
return this.isCompleted;
}
public get IsError(): boolean {
return this.isError;
}
public get Error(): string {
return this.error;
}
public get Result(): T {
return this.result;
}
public ThrowIfError = (): void => {
if (this.IsError) {
throw this.Error;
}
}
}
// tslint:disable-next-line:max-classes-per-file
export class PromiseResultEventSource<T> {
private onSetResult: (result: T) => void;
private onSetError: (error: string) => void;
public SetResult = (result: T): void => {
this.onSetResult(result);
}
public SetError = (error: string): void => {
this.onSetError(error);
}
public On = (onSetResult: (result: T) => void, onSetError: (error: string) => void): void => {
this.onSetResult = onSetResult;
this.onSetError = onSetError;
}
}
// tslint:disable-next-line:max-classes-per-file
export class PromiseHelper {
public static WhenAll = (promises: Array<Promise<any>>): Promise<boolean> => {
if (!promises || promises.length === 0) {
throw new ArgumentNullError("promises");
}
const deferred = new Deferred<boolean>();
const errors: string[] = [];
let completedPromises: number = 0;
const checkForCompletion = () => {
completedPromises++;
if (completedPromises === promises.length) {
if (errors.length === 0) {
deferred.Resolve(true);
} else {
deferred.Reject(errors.join(", "));
}
}
};
for (const promise of promises) {
promise.On((r: any) => {
checkForCompletion();
}, (e: string) => {
errors.push(e);
checkForCompletion();
});
}
return deferred.Promise();
}
public static FromResult = <TResult>(result: TResult): Promise<TResult> => {
const deferred = new Deferred<TResult>();
deferred.Resolve(result);
return deferred.Promise();
}
public static FromError = <TResult>(error: string): Promise<TResult> => {
const deferred = new Deferred<TResult>();
deferred.Reject(error);
return deferred.Promise();
}
}
// TODO: replace with ES6 promises
// tslint:disable-next-line:max-classes-per-file
export class Promise<T> implements IPromise<T> {
private sink: Sink<T>;
public constructor(sink: Sink<T>) {
this.sink = sink;
}
public Result = (): PromiseResult<T> => {
return this.sink.Result;
}
public ContinueWith = <TContinuationResult>(
continuationCallback: (promiseResult: PromiseResult<T>) => TContinuationResult): Promise<TContinuationResult> => {
if (!continuationCallback) {
throw new ArgumentNullError("continuationCallback");
}
const continuationDeferral = new Deferred<TContinuationResult>();
this.sink.on(
(r: T) => {
try {
const continuationResult: TContinuationResult = continuationCallback(this.sink.Result);
continuationDeferral.Resolve(continuationResult);
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}'`);
}
},
(error: string) => {
try {
const continuationResult: TContinuationResult = continuationCallback(this.sink.Result);
continuationDeferral.Resolve(continuationResult);
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}. InnerError: ${error}'`);
}
},
);
return continuationDeferral.Promise();
}
public OnSuccessContinueWith = <TContinuationResult>(
continuationCallback: (result: T) => TContinuationResult): Promise<TContinuationResult> => {
if (!continuationCallback) {
throw new ArgumentNullError("continuationCallback");
}
const continuationDeferral = new Deferred<TContinuationResult>();
this.sink.on(
(r: T) => {
try {
const continuationResult: TContinuationResult = continuationCallback(r);
continuationDeferral.Resolve(continuationResult);
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}'`);
}
},
(error: string) => {
continuationDeferral.Reject(`'Unhandled callback error: ${error}'`);
},
);
return continuationDeferral.Promise();
}
public ContinueWithPromise = <TContinuationResult>(
continuationCallback: (promiseResult: PromiseResult<T>) => Promise<TContinuationResult>): Promise<TContinuationResult> => {
if (!continuationCallback) {
throw new ArgumentNullError("continuationCallback");
}
const continuationDeferral = new Deferred<TContinuationResult>();
this.sink.on(
(r: T) => {
try {
const continuationPromise: Promise<TContinuationResult> = continuationCallback(this.sink.Result);
if (!continuationPromise) {
throw new Error("'Continuation callback did not return promise'");
}
continuationPromise.On((continuationResult: TContinuationResult) => {
continuationDeferral.Resolve(continuationResult);
}, (e: string) => {
continuationDeferral.Reject(e);
});
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}'`);
}
},
(error: string) => {
try {
const continuationPromise: Promise<TContinuationResult> = continuationCallback(this.sink.Result);
if (!continuationPromise) {
throw new Error("Continuation callback did not return promise");
}
continuationPromise.On((continuationResult: TContinuationResult) => {
continuationDeferral.Resolve(continuationResult);
}, (e: string) => {
continuationDeferral.Reject(e);
});
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}. InnerError: ${error}'`);
}
},
);
return continuationDeferral.Promise();
}
public OnSuccessContinueWithPromise = <TContinuationResult>(
continuationCallback: (result: T) => Promise<TContinuationResult>): Promise<TContinuationResult> => {
if (!continuationCallback) {
throw new ArgumentNullError("continuationCallback");
}
const continuationDeferral = new Deferred<TContinuationResult>();
this.sink.on(
(r: T) => {
try {
const continuationPromise: Promise<TContinuationResult> = continuationCallback(r);
if (!continuationPromise) {
throw new Error("Continuation callback did not return promise");
}
continuationPromise.On((continuationResult: TContinuationResult) => {
continuationDeferral.Resolve(continuationResult);
}, (e: string) => {
continuationDeferral.Reject(e);
});
} catch (e) {
continuationDeferral.Reject(`'Unhandled callback error: ${e}'`);
}
},
(error: string) => {
continuationDeferral.Reject(`'Unhandled callback error: ${error}.'`);
},
);
return continuationDeferral.Promise();
}
public On = (
successCallback: (result: T) => void,
errorCallback: (error: string) => void): Promise<T> => {
if (!successCallback) {
throw new ArgumentNullError("successCallback");
}
if (!errorCallback) {
throw new ArgumentNullError("errorCallback");
}
this.sink.on(successCallback, errorCallback);
return this;
}
public Finally = (callback: () => void): Promise<T> => {
if (!callback) {
throw new ArgumentNullError("callback");
}
const callbackWrapper = (_: any) => {
callback();
};
return this.On(callbackWrapper, callbackWrapper);
}
}
// tslint:disable-next-line:max-classes-per-file
export class Deferred<T> implements IDeferred<T> {
private promise: Promise<T>;
private sink: Sink<T>;
public constructor() {
this.sink = new Sink<T>();
this.promise = new Promise<T>(this.sink);
}
public State = (): PromiseState => {
return this.sink.State;
}
public Promise = (): Promise<T> => {
return this.promise;
}
public Resolve = (result: T): Deferred<T> => {
this.sink.Resolve(result);
return this;
}
public Reject = (error: string): Deferred<T> => {
this.sink.Reject(error);
return this;
}
}
// tslint:disable-next-line:max-classes-per-file
export class Sink<T> {
private state: PromiseState = PromiseState.None;
private promiseResult: PromiseResult<T> = null;
private promiseResultEvents: PromiseResultEventSource<T> = null;
private successHandlers: Array<((result: T) => void)> = [];
private errorHandlers: Array<(e: string) => void> = [];
public constructor() {
this.promiseResultEvents = new PromiseResultEventSource();
this.promiseResult = new PromiseResult(this.promiseResultEvents);
}
public get State(): PromiseState {
return this.state;
}
public get Result(): PromiseResult<T> {
return this.promiseResult;
}
public Resolve = (result: T): void => {
if (this.state !== PromiseState.None) {
throw new Error("'Cannot resolve a completed promise'");
}
this.state = PromiseState.Resolved;
this.promiseResultEvents.SetResult(result);
for (let i = 0; i < this.successHandlers.length; i++) {
this.ExecuteSuccessCallback(result, this.successHandlers[i], this.errorHandlers[i]);
}
this.DetachHandlers();
}
public Reject = (error: string): void => {
if (this.state !== PromiseState.None) {
throw new Error("'Cannot reject a completed promise'");
}
this.state = PromiseState.Rejected;
this.promiseResultEvents.SetError(error);
for (const errorHandler of this.errorHandlers) {
this.ExecuteErrorCallback(error, errorHandler);
}
this.DetachHandlers();
}
public on = (
successCallback: (result: T) => void,
errorCallback: (error: string) => void): void => {
if (successCallback == null) {
successCallback = (r: T) => { return; };
}
if (this.state === PromiseState.None) {
this.successHandlers.push(successCallback);
this.errorHandlers.push(errorCallback);
} else {
if (this.state === PromiseState.Resolved) {
this.ExecuteSuccessCallback(this.promiseResult.Result, successCallback, errorCallback);
} else if (this.state === PromiseState.Rejected) {
this.ExecuteErrorCallback(this.promiseResult.Error, errorCallback);
}
this.DetachHandlers();
}
}
private ExecuteSuccessCallback = (result: T, successCallback: (result: T) => void, errorCallback: (error: string) => void): void => {
try {
successCallback(result);
} catch (e) {
this.ExecuteErrorCallback(`'Unhandled callback error: ${e}'`, errorCallback);
}
}
private ExecuteErrorCallback = (error: string, errorCallback: (error: string) => void): void => {
if (errorCallback) {
try {
errorCallback(error);
} catch (e) {
throw new Error(`'Unhandled callback error: ${e}. InnerError: ${error}'`);
}
} else {
throw new Error(`'Unhandled error: ${error}'`);
}
}
private DetachHandlers = (): void => {
this.errorHandlers = [];
this.successHandlers = [];
}
} | the_stack |
class ActionPoints {
combat: number = 0; // Combat AP
move: number = 0; // Move AP
attachedCritter: Critter;
constructor(obj: Critter) {
this.attachedCritter = obj
this.resetAP()
}
resetAP() {
var AP = this.getMaxAP()
this.combat = AP.combat
this.move = AP.move
}
getMaxAP(): {combat: number; move: number} {
var bonusCombatAP = 0 // TODO: replace with get function
var bonusMoveAP = 0 // TODO: replace with get function
return {combat: 5 + Math.floor(critterGetStat(this.attachedCritter, "AGI") / 2) + bonusCombatAP, move: bonusMoveAP}
}
getAvailableMoveAP(): number {
return this.combat + this.move
}
getAvailableCombatAP() {
return this.combat
}
subtractMoveAP(value: number): boolean {
if(this.getAvailableMoveAP() < value)
return false
this.move -= value
if(this.move < 0) {
if(this.subtractCombatAP(-this.move)) {
this.move = 0
return true
}
return false
}
return true
}
subtractCombatAP(value: number): boolean {
if(this.combat < value)
return false
this.combat -= value
return true
}
}
class AI {
static aiTxt: any = null; // AI.TXT: packet num -> key/value
combatant: Critter;
info: any;
static init(): void {
// load and parse AI.TXT
if(AI.aiTxt !== null) // already loaded
return;
AI.aiTxt = {}
var ini = parseIni(getFileText("data/data/ai.txt"))
if(ini === null) throw "couldn't load AI.TXT"
for(var key in ini) {
ini[key].keyName = key
AI.aiTxt[ini[key].packet_num] = ini[key]
}
}
static getPacketInfo(aiNum: number): any {
return AI.aiTxt[aiNum] || null
}
constructor(combatant: Critter) {
this.combatant = combatant
// load if necessary
if(AI.aiTxt === null)
AI.init()
this.info = AI.getPacketInfo(this.combatant.aiNum)
if(!this.info)
throw "no AI packet for " + combatant.toString() +
" (packet " + this.combatant.aiNum + ")"
}
}
// A combat encounter
class Combat {
combatants: Critter[];
playerIdx: number;
player: Player;
turnNum: number;
whoseTurn: number;
inPlayerTurn: boolean;
constructor(objects: Obj[]) {
// Gather a list of combatants (critters meeting a certain criteria)
this.combatants = objects.filter(obj => {
if(obj instanceof Critter) {
if(obj.dead || !obj.visible)
return false
// TODO: should we initialize AI elsewhere, like in Critter?
if(!obj.isPlayer && !obj.ai)
obj.ai = new AI(obj)
if(obj.stats === undefined)
throw "no stats"
obj.dead = false
obj.AP = new ActionPoints(obj)
return true
}
return false
}) as Critter[];
this.playerIdx = this.combatants.findIndex(x => x.isPlayer)
if(this.playerIdx === -1)
throw "combat: couldn't find player?"
this.player = this.combatants[this.playerIdx] as Player
this.turnNum = 1
this.whoseTurn = this.playerIdx - 1
this.inPlayerTurn = true
// Stop the player from walking combat is initiating
this.player.clearAnim();
uiStartCombat()
}
log(msg: any) {
// Combat-related debug log
console.log(msg)
}
accountForPartialCover(obj: Critter, target: Critter): number {
// TODO: get list of intervening critters. Substract 10 for each one in the way
return 0
}
getHitDistanceModifier(obj: Critter, target: Critter, weapon: Obj): number {
// we calculate the distance between source and target
// we then substract the source's per modified by the weapon from it (except for scoped weapons)
// NOTE: this function is supposed to have weird behaviour for multihex sources and targets. Let's ignore that.
// 4 if weapon has long_range perk
// 5 if weapon has scope_range perk
var distModifier = 2
// 8 if weapon has scope_range perk
var minDistance = 0
var perception = critterGetStat(obj, "PER")
var distance = hexDistance(obj.position, target.position)
if(distance < minDistance)
distance += minDistance // yes supposedly += not =, this means 7 grid distance is the worst
else
{
var tempPER = perception
if(obj.isPlayer === true)
tempPER -= 2 // supposedly player gets nerfed like this. WTF?
distance -= tempPER * distModifier
}
// this appears not to have any effect but was found so elsewhere
// If anyone can tell me why it exists or what it's for I'd be grateful.
if (-2*perception > distance)
distance = -2*perception
// TODO: needs to add sharpshooter perk bonuses on top
// distance -= 2*sharpshooterRank
// then we multiply a magic number on top. More if there is eye damage involved by the attacker
// this means for each field distance after PER modification we lose 4 points of hitchance
// 12 if we have eyedamage
var objHasEyeDamage = false
if(distance >= 0 && objHasEyeDamage)
distance *= 12
else
distance *= 4
// and if the result is a positive distance, we return that
// closeness can not improve hitchance above normal, so we don't return that
if(distance >= 0)
return distance
else
return 0
}
getHitChance(obj: Critter, target: Critter, region: string) {
// TODO: visibility (= light conditions) and distance
var weaponObj = critterGetEquippedWeapon(obj)
if(weaponObj === null) // no weapon equipped (not even melee)
return {hit: -1, crit: -1}
var weapon = weaponObj.weapon
var weaponSkill
if(!weapon) throw Error("getHitChance: No weapon");
if(weapon.weaponSkillType === undefined) {
this.log("weaponSkillType is undefined")
weaponSkill = 0
}
else
weaponSkill = critterGetSkill(obj, weapon.weaponSkillType)
var hitDistanceModifier = this.getHitDistanceModifier(obj, target, weaponObj)
var bonusAC = 0 // TODO: AP at end of turn bonus
var AC = critterGetStat(target, "AC") + bonusAC
var bonusCrit = 0 // TODO: perk bonuses, other crit influencing things
var baseCrit = critterGetStat(obj, "Critical Chance") + bonusCrit
var hitChance = weaponSkill - AC - CriticalEffects.regionHitChanceDecTable[region] - hitDistanceModifier
var critChance = baseCrit + CriticalEffects.regionHitChanceDecTable[region]
if(isNaN(hitChance))
throw "something went wrong with hit chance calculation"
// 1 in 20 chance of failing needs to be preserved
hitChance = Math.min(95, hitChance)
return {hit: hitChance, crit: critChance}
}
rollHit(obj: Critter, target: Critter, region: string): any {
var critModifer = critterGetStat(obj, "Better Criticals")
var hitChance = this.getHitChance(obj, target, region)
// hey kids! Did you know FO only rolls the dice once here and uses the results two times?
var roll = getRandomInt(1, 101)
if(hitChance.hit - roll > 0) {
var isCrit = false
if(rollSkillCheck(Math.floor(hitChance.hit - roll) / 10, hitChance.crit, false) === true)
isCrit = true
// TODO: if Slayer/Sniper perk -> second chance to crit
if(isCrit === true) {
var critLevel = Math.floor(Math.max(0, getRandomInt(critModifer, 100 + critModifer)) / 20)
this.log("crit level: " + critLevel)
var crit = CriticalEffects.getCritical(critterGetKillType(target)!, region, critLevel)
var critStatus = crit.doEffectsOn(target)
return {hit: true, crit: true, DM: critStatus.DM, msgID: critStatus.msgID} // crit
}
return {hit: true, crit: false} // hit
}
// in reverse because miss -> roll > hitchance.hit
var isCrit = false
if(rollSkillCheck(Math.floor(roll - hitChance.hit) / 10, 0, false))
isCrit = true
// TODO: jinxed/pariah dog give (nonstacking) 50% chance for critical miss upon miss
return {hit: false, crit: isCrit} // miss
}
getDamageDone(obj: Critter, target: Critter, critModifer: number) {
var weapon = critterGetEquippedWeapon(obj)
if(!weapon) throw Error("getDamageDone: No weapon");
var wep = weapon.weapon
if(!wep) throw Error("getDamageDone: Weapon has no weapon data");
var damageType = wep.getDamageType()
var RD = getRandomInt(wep.minDmg, wep.maxDmg) // rand damage min..max
var RB = 0 // ranged bonus (via perk)
var CM = critModifer // critical hit damage multiplier
var ADR = critterGetStat(target, "DR " + damageType) // damage resistance (TODO: armor)
var ADT = critterGetStat(target, "DT " + damageType) // damage threshold (TODO: armor)
var X = 2 // ammo dividend
var Y = 1 // ammo divisor
var RM = 0 // ammo resistance modifier
var CD = 100 // combat difficulty modifier (easy = 75%, normal = 100%, hard = 125%)
var ammoDamageMult = X / Y
var baseDamage = (CM/2) * ammoDamageMult * (RD+RB) * (CD / 100)
var adjustedDamage = Math.max(0, baseDamage - ADT)
console.log(`RD: ${RD} | CM: ${CM} | ADR: ${ADR} | ADT: ${ADT} | Base Dmg: ${baseDamage} Adj Dmg: ${adjustedDamage} | Type: ${damageType}`)
return Math.ceil(adjustedDamage * (1 - (ADR+RM)/100))
}
getCombatMsg(id: number) {
return getMessage("combat", id)
}
attack(obj: Critter, target: Critter, region="torso", callback?: () => void) {
// turn to face the target
var hex = hexNearestNeighbor(obj.position, target.position)
if(hex !== null)
obj.orientation = hex.direction
// attack!
critterStaticAnim(obj, "attack", callback)
var who = obj.isPlayer ? "You" : obj.name
var targetName = target.isPlayer ? "you" : target.name
var hitRoll = this.rollHit(obj, target, region)
this.log("hit% is " + this.getHitChance(obj, target, region).hit)
if(hitRoll.hit === true) {
var critModifier = hitRoll.crit ? hitRoll.DM : 2
var damage = this.getDamageDone(obj, target, critModifier)
var extraMsg = hitRoll.crit === true ? (this.getCombatMsg(hitRoll.msgID) || "") : ""
this.log(who + " hit " + targetName + " for " + damage + " damage" + extraMsg)
critterDamage(target, damage, obj)
if(target.dead)
this.perish(target)
}
else {
this.log(who + " missed " + targetName + (hitRoll.crit === true ? " critically" : ""))
if(hitRoll.crit === true) {
var critFailMod = (critterGetStat(obj, "LUK") - 5) * - 5
var critFailRoll = Math.floor(getRandomInt(1, 100) - critFailMod)
var critFailLevel = 1
if(critFailRoll <= 20)
critFailLevel = 1
else if(critFailRoll <= 50)
critFailLevel = 2
else if(critFailRoll <= 75)
critFailLevel = 3
else if(critFailRoll <= 95)
critFailLevel = 4
else
critFailLevel = 5
this.log(who + " failed at fail level "+critFailLevel);
// TODO: map weapon type to crit fail table types
var critFailEffect = CriticalEffects.criticalFailTable.unarmed[critFailLevel]
CriticalEffects.temporaryDoCritFail(critFailEffect, obj)
}
}
}
perish(obj: Critter) {
this.log("...And killed them.")
}
getCombatAIMessage(id: number) {
return getMessage("combatai", id)
}
maybeTaunt(obj: Critter, type: string, roll: boolean) {
if(roll === false) return
var msgID = getRandomInt(parseInt(obj.ai!.info[type+"_start"]),
parseInt(obj.ai!.info[type+"_end"]))
this.log("[TAUNT " + obj.name + ": " + this.getCombatAIMessage(msgID) + "]")
}
findTarget(obj: Critter): Critter|null {
// TODO: find target according to AI rules
// Find the closest living combatant on a different team
const targets = this.combatants.filter(x => !x.dead && x.teamNum !== obj.teamNum);
if(targets.length === 0)
return null;
targets.sort((a, b) => hexDistance(obj.position, a.position) - hexDistance(obj.position, b.position));
return targets[0];
}
walkUpTo(obj: Critter, idx: number, target: Point, maxDistance: number, callback: () => void): boolean {
// Walk up to `maxDistance` hexes, adjusting AP to fit
if(obj.walkTo(target, false, callback, maxDistance)) {
// OK
if(obj.AP!.subtractMoveAP(obj.path.path.length - 1) === false)
throw "subtraction issue: has AP: " + obj.AP!.getAvailableMoveAP() +
" needs AP:"+obj.path.path.length+" and maxDist was:"+maxDistance
return true
}
return false
}
doAITurn(obj: Critter, idx: number, depth: number): void {
if(depth > Config.combat.maxAIDepth) {
console.warn(`Bailing out of ${depth}-deep AI turn recursion`);
return this.nextTurn();
}
var that = this
var target = this.findTarget(obj)
if(!target) {
console.log("[AI has no target]");
return this.nextTurn();
}
var distance = hexDistance(obj.position, target.position)
var AP = obj.AP!
var messageRoll = rollSkillCheck(obj.ai!.info.chance, 0, false)
if(Config.engine.doLoadScripts === true && obj._script !== undefined) {
// notify the critter script of a combat event
if(Scripting.combatEvent(obj, "turnBegin") === true)
return // end of combat (script override)
}
if(AP.getAvailableMoveAP() <= 0) // out of AP
return this.nextTurn()
// behaviors
if(critterGetStat(obj, "HP") <= obj.ai!.info.min_hp) { // hp <= min fleeing hp, so flee
this.log("[AI FLEES]")
// todo: pick the closest edge of the map
this.maybeTaunt(obj, "run", messageRoll)
const targetPos = {x: 128, y: obj.position.y} // left edge
const callback = () => {
obj.clearAnim();
that.doAITurn(obj, idx, depth+1); // if we can, do another turn
};
if(!this.walkUpTo(obj, idx, targetPos, AP.getAvailableMoveAP(), callback)) {
return this.nextTurn(); // not a valid path, just move on
}
return;
}
var weaponObj = critterGetEquippedWeapon(obj)
if(!weaponObj) throw Error("AI has no weapon")
var weapon = weaponObj.weapon
if(!weapon) throw Error("AI weapon has no weapon data")
var fireDistance = weapon.getMaximumRange(1)
this.log("DEBUG: weapon: " + weapon + " fireDistance: " + fireDistance +
" obj: " + obj.art + " distance: " + distance)
// are we in firing distance?
if(distance > fireDistance) {
this.log("[AI CREEPS]")
var neighbors = hexNeighbors(target.position)
var maxDistance = Math.min(AP.getAvailableMoveAP(), distance - fireDistance)
this.maybeTaunt(obj, "move", messageRoll)
// TODO: check nearest direction first
var didCreep = false
for(var i = 0; i < neighbors.length; i++) {
if(obj.walkTo(neighbors[i], false, function() {
obj.clearAnim()
that.doAITurn(obj, idx, depth+1) // if we can, do another turn
}, maxDistance) !== false) {
// OK
didCreep = true
if(AP.subtractMoveAP(obj.path.path.length - 1) === false)
throw "subtraction issue: has AP: " + AP.getAvailableMoveAP() +
" needs AP:"+obj.path.path.length+" and maxDist was:"+maxDistance
break
}
}
if(!didCreep) {
// no path
this.log("[NO PATH]")
that.doAITurn(obj, idx, depth+1) // if we can, do another turn
}
}
else if(AP.getAvailableCombatAP() >= 4) { // if we are in range, do we have enough AP to attack?
this.log("[ATTACKING]")
AP.subtractCombatAP(4)
if(critterGetEquippedWeapon(obj) === null)
throw "combatant has no equipped weapon"
this.attack(obj, target, "torso", function() {
obj.clearAnim()
that.doAITurn(obj, idx, depth+1) // if we can, do another turn
})
}
else {
console.log("[AI IS STUMPED]")
this.nextTurn()
}
}
static start(forceTurn?: Critter): void {
// begin combat
inCombat = true
combat = new Combat(gMap.getObjects())
if(forceTurn)
combat.forceTurn(forceTurn)
combat.nextTurn()
gMap.updateMap()
}
end() {
// TODO: check number of active combatants to see if we can end
// Set all combatants to non-hostile and remove their outline
for(const combatant of this.combatants) {
combatant.hostile = false;
combatant.outline = null;
}
console.log("[end combat]")
combat = null // todo: invert control
inCombat = false
gMap.updateMap()
uiEndCombat()
}
forceTurn(obj: Critter) {
if(obj.isPlayer)
this.whoseTurn = this.playerIdx - 1
else {
var idx = this.combatants.indexOf(obj)
if(idx === -1) throw "forceTurn: no combatant '" + obj.name + ''
this.whoseTurn = idx - 1
}
}
nextTurn(): void {
// update range checks
var numActive = 0
for(var i = 0; i < this.combatants.length; i++) {
var obj = this.combatants[i]
if(obj.dead || obj.isPlayer) continue
var inRange = hexDistance(obj.position, this.player.position) <= obj.ai!.info.max_dist
if(inRange || obj.hostile) {
obj.hostile = true;
obj.outline = obj.teamNum !== player.teamNum ? "red" : "green";
numActive++;
}
}
if(numActive === 0 && this.turnNum !== 1)
return this.end()
this.turnNum++
this.whoseTurn++
if(this.whoseTurn >= this.combatants.length)
this.whoseTurn = 0
if(this.combatants[this.whoseTurn].isPlayer) {
// player turn
this.inPlayerTurn = true
this.player.AP!.resetAP()
}
else {
this.inPlayerTurn = false
var critter = this.combatants[this.whoseTurn]
if(critter.dead === true || critter.hostile !== true)
return this.nextTurn()
// TODO: convert unused AP into AC
critter.AP!.resetAP()
this.doAITurn(critter, this.whoseTurn, 1)
}
}
} | the_stack |
import type * as Messages from "./messages.ts";
function assert(expr: unknown, msg = ""): asserts expr {
if (!expr) {
throw new Error("assertion failed: " + msg);
}
}
function isCookiePayload(x: Messages.Any): x is Messages.CookiePayload {
return (x as Messages.CookiePayload).cookie;
}
function isCookieResponse(x: Messages.Any): x is Messages.CookieResponse {
return (x as Messages.CookieResponse).cookieResponse;
}
function isResponse(x: Messages.Any): x is Messages.Response {
return typeof (x as Messages.Response).rid === "number";
}
interface Descriptor {
name?: string;
isFunc?: boolean;
}
interface CookieCallback {
(...args: unknown[]): void;
}
interface CookieResponseCallback {
(payload: {
result: unknown;
worldId: string;
}): void;
}
interface Transport<FromChild, ToChild> {
(
receiveFromChild: (payload: FromChild) => unknown,
): (payload: ToChild) => unknown;
}
interface SendToWorld {
(payload: Messages.CookiePayload | Messages.Payload): void;
}
const handleSymbol = Symbol("handle");
export interface HandleProxy {
[handleSymbol]: Handle;
}
// deno-lint-ignore ban-types
type Object = Function | {
constructor: { name: string };
// deno-lint-ignore no-explicit-any
[method: string]: any;
};
/**
* Handle to the object. This handle has methods matching the methods of the
* target object. Calling these methods calls them remotely over the low level
* messaging transprot. Return values are delivered to the caller.
*/
class Handle {
proxy_: HandleProxy;
// deno-lint-ignore ban-types
object_: Object | null = null;
/**
* @param localAddress Address of this handle.
* @param address Address of the primary handle this handle refers
* to. Primary handle is the one that lives in the same world
* as the actual object it refers to.
* @param descriptor Target object spec descriptor (list of methods, etc.)
* @param rpc
*/
constructor(
readonly localAddress_: string[],
readonly address_: string[],
readonly descriptor_: Descriptor,
readonly rpc_: Rpc,
) {
const target = {} as HandleProxy;
target[handleSymbol] = this;
this.proxy_ = new Proxy<HandleProxy>(target, { get: Handle.proxyHandler_ });
}
/**
* We always return proxies to the user to encapsulate handle and marshall
* calls automatically.
*/
static proxyHandler_(
target: HandleProxy | PromiseLike<unknown>,
methodName: string | symbol,
_receiver: unknown,
) {
const handle = (target as HandleProxy)[handleSymbol];
if (methodName === handleSymbol) {
return handle;
}
if (typeof methodName !== "string") {
return;
}
if (methodName === "then") {
return (target as PromiseLike<unknown>)[methodName];
}
return handle.callMethod_.bind(handle, methodName);
}
/**
* Calls method on the target object.
*
* @param method Method to call on the target object.
* @param args Call arguments. These can be either primitive
* types, other handles or JSON structures.
* @return result, also primitive, JSON or handle.
*/
async callMethod_(method: string, ...args: unknown[]): Promise<unknown> {
const message = {
m: method,
p: this.rpc_.wrap_(args) as string,
};
const response = await this.rpc_.sendCommand_(
this.address_,
this.localAddress_,
message,
);
return this.rpc_.unwrap_(response);
}
/**
* Dispatches external message on this handle.
* @param message
* @return result, also primitive, JSON or handle.
*/
async dispatchMessage_(
message: Messages.Payload["message"],
): Promise<unknown> {
assert(this.object_);
if (this.descriptor_.isFunc) {
assert(typeof this.object_ === "function");
const result = await this.object_(...this.rpc_.unwrap_(message.p));
return this.rpc_.wrap_(result);
}
if (message.m.startsWith("_") || message.m.endsWith("_")) {
throw new Error(
`Private members are not exposed over RPC: '${message.m}'`,
);
}
assert(typeof this.object_ === "object");
if (!(message.m in this.object_)) {
throw new Error(
`There is no member '${message.m}' in '${this.descriptor_.name}'`,
);
}
const value = this.object_[message.m];
if (typeof value !== "function") {
if (message.p.length) {
throw new Error(
`'${message.m}' is not a function, can't pass args '${message.p}'`,
);
}
return this.rpc_.wrap_(value);
}
const result = await this.object_[message.m](
...this.rpc_.unwrap_(message.p),
);
return this.rpc_.wrap_(result);
}
/**
* Returns the proxy to this handle that is passed to the userland.
*/
proxy(): HandleProxy {
return this.proxy_;
}
}
/**
* Main Rpc object. Keeps all the book keeping and performs message routing
* between handles beloning to different worlds. Each 'world' has a singleton
* 'rpc' instance.
*/
class Rpc {
lastHandleId_ = 0;
lastWorldId_ = 0;
worlds_ = new Map<string, SendToWorld>();
idToHandle_ = new Map<string, Handle>();
lastMessageId_ = 0;
callbacks_ = new Map();
worldId_ = ".";
cookieResponseCallbacks_ = new Map<string, CookieResponseCallback>();
debug_ = false;
sendToParent_?: (
payload: Messages.CookieResponse | Messages.Payload | Messages.Response,
) => unknown;
cookieCallback_?: null | CookieCallback;
worldParams_: unknown;
/**
* Each singleton rpc object has the world's parameters that parent world sent
* to them.
*/
params(): unknown {
return this.worldParams_;
}
/**
* Called in the parent world.
* Creates a child world with the given root handle.
*
* @param transport
* - receives function that should be called upon messages from
* the world and
* - returns function that should be used to send messages to the
* world
* @param args Params to pass to the child world.
* @return returns the handles / parameters that child
* world returned during the initialization.
*/
createWorld(
transport: Transport<
Messages.Any,
Messages.CookiePayload | Messages.Payload
>,
...args: unknown[]
): Promise<{ worldId: string }> {
const worldId = this.worldId_ + "/" + (++this.lastWorldId_);
const sendToChild = transport(this.routeMessage_.bind(this, false));
this.worlds_.set(worldId, sendToChild);
sendToChild({ cookie: true, args: this.wrap_(args) as unknown[], worldId });
return new Promise((f) => this.cookieResponseCallbacks_.set(worldId, f));
}
/**
* Called in the parent world.
* Disposes a child world with the given id.
*
* @param worldId The world to dispose.
*/
disposeWorld(worldId: string): void {
if (!this.worlds_.has(worldId)) {
throw new Error("No world with given id exists");
}
this.worlds_.delete(worldId);
}
/**
* Called in the child world to initialize it.
* @param transport
* @param initializer
*/
initWorld(
transport: Transport<
Messages.Any,
Messages.CookieResponse | Messages.Payload | Messages.Response
>,
initializer: (...args: unknown[]) => unknown,
): Promise<unknown> {
this.sendToParent_ = transport(this.routeMessage_.bind(this, true));
return new Promise<unknown[]>((f) =>
this.cookieCallback_ = f as CookieCallback
)
.then((args: unknown[]) => initializer ? initializer(...args) : undefined)
.then((response) =>
this.sendToParent_!(
{
cookieResponse: true,
worldId: this.worldId_,
r: this.wrap_(response),
},
)
);
}
/**
* Creates a handle to the object.
* @param object Object to create handle for
*/
// deno-lint-ignore ban-types
handle(object: Object): HandleProxy {
if (!object) {
throw new Error("Can only create handles for objects");
}
if (typeof object === "object" && handleSymbol in object) {
throw new Error("Can not return handle to handle.");
}
const descriptor = this.describe_(object);
const address = [
this.worldId_,
descriptor.name + "#" + (++this.lastHandleId_),
];
const handle = new Handle(address, address, descriptor, this);
handle.object_ = object;
this.idToHandle_.set(address[1], handle);
return handle.proxy();
}
/**
* Returns the object this handle points to. Only works on the local
* handles, otherwise returns null.
*
* @param handle Primary object handle.
*/
// deno-lint-ignore ban-types
object(proxy: HandleProxy): Object | null {
return proxy[handleSymbol].object_ || null;
}
/**
* Disposes a handle to the object.
* @param handle Primary object handle.
*/
dispose(proxy: HandleProxy): void {
const handle = proxy[handleSymbol];
if (!handle.object_) {
throw new Error(
"Can only dipose handle that was explicitly created with rpc.handle()",
);
}
this.idToHandle_.delete(handle.address_[1]);
}
/**
* Builds object descriptor.
*/
// deno-lint-ignore ban-types
describe_(o: Object): Descriptor {
if (typeof o === "function") {
return { isFunc: true };
}
return { name: o.constructor.name };
}
/**
* Wraps call argument as a protocol structures.
*/
wrap_(
// deno-lint-ignore no-explicit-any
param: any,
maxDepth = 1000,
): unknown {
if (!maxDepth) {
throw new Error("Object reference chain is too long");
}
maxDepth--;
if (!param) {
return param;
}
if ((param as HandleProxy)[handleSymbol]) {
const handle = (param as HandleProxy)[handleSymbol];
return {
__rpc_a__: handle.address_,
descriptor: handle.descriptor_,
};
}
if (param instanceof Array) {
return param.map((item) => this.wrap_(item, maxDepth));
}
if (typeof param === "object") {
const result = {} as Record<string, unknown>;
for (const key in param) {
result[key] = this.wrap_(param[key], maxDepth);
}
return result;
}
return param;
}
/**
* Unwraps call argument from the protocol structures.
*/
// deno-lint-ignore no-explicit-any
unwrap_(param: any): any {
if (!param) {
return param;
}
if (param.__rpc_a__) {
const handle = this.createHandle_(param.__rpc_a__, param.descriptor);
if (handle.descriptor_.isFunc) {
return (...args: unknown[]) => handle.callMethod_("call", ...args);
}
return handle.proxy();
}
if (param instanceof Array) {
return param.map((item) => this.unwrap_(item));
}
if (typeof param === "object") {
const result = {} as Record<string, unknown>;
for (const key in param) {
result[key] = this.unwrap_(param[key]);
}
return result;
}
return param;
}
/**
* Unwraps descriptor and creates a local world handle that will be associated
* with the primary handle at given address.
*
* @param address Address of the primary wrapper.
* @param address Address of the primary wrapper.
*/
createHandle_(
address: string[],
descriptor: Descriptor,
): Handle {
if (address[0] === this.worldId_) {
const existing = this.idToHandle_.get(address[1]);
if (existing) {
return existing;
}
}
const localAddress = [
this.worldId_,
descriptor.name + "#" + (++this.lastHandleId_),
];
return new Handle(localAddress, address, descriptor, this);
}
/**
* Sends message to the target handle and receive the response.
*/
sendCommand_(
to: string[],
from: string[],
message: Messages.Payload["message"],
): Promise<unknown> {
const payload: Messages.Payload = {
to,
from,
message,
id: ++this.lastMessageId_,
};
if (this.debug_) {
console.log("\nSEND", payload);
}
const result = new Promise((fulfill, reject) =>
this.callbacks_.set(payload.id, { fulfill, reject })
);
this.routeMessage_(false, payload);
return result;
}
/**
* Routes message between the worlds.
*/
routeMessage_(
fromParent: boolean,
payload: Messages.Any,
): void {
if (this.debug_) {
console.log(`\nROUTE[${this.worldId_}]`, payload);
}
if (isCookiePayload(payload)) {
this.worldId_ = payload.worldId;
this.cookieCallback_!(this.unwrap_(payload.args));
this.cookieCallback_ = null;
return;
}
// If this is a cookie request, the world is being initialized.
if (isCookieResponse(payload)) {
const callback = this.cookieResponseCallbacks_.get(payload.worldId)!;
this.cookieResponseCallbacks_.delete(payload.worldId);
callback({ result: this.unwrap_(payload.r), worldId: payload.worldId });
return;
}
if (!fromParent && !this.isActiveWorld_(payload.from[0])) {
// Dispatching from the disposed world.
if (this.debug_) {
console.log(`DROP ON THE FLOOR`);
}
return;
}
if (payload.to[0] === this.worldId_) {
if (this.debug_) {
console.log(`ROUTED TO SELF`);
}
this.dispatchMessageLocally_(payload);
return;
}
for (const [worldId, worldSend] of this.worlds_) {
if (payload.to[0].startsWith(worldId)) {
if (this.debug_) {
console.log(`ROUTED TO CHILD ${worldId}`);
}
worldSend(payload as Messages.Payload);
return;
}
}
if (payload.to[0].startsWith(this.worldId_)) {
// Sending to the disposed world.
if (this.debug_) {
console.log(`DROP ON THE FLOOR`);
}
return;
}
if (this.debug_) {
console.log(`ROUTED TO PARENT`);
}
this.sendToParent_!(payload);
}
isActiveWorld_(worldId: string): boolean {
if (this.worldId_ === worldId) {
return true;
}
for (const wid of this.worlds_.keys()) {
if (worldId.startsWith(wid)) {
return true;
}
}
return false;
}
/**
* Message is routed from other worlds and hits rpc here.
*/
async dispatchMessageLocally_(
payload: Messages.Payload | Messages.Response,
): Promise<void> {
if (this.debug_) {
console.log("\nDISPATCH", payload);
}
// Dispatch the response.
if (isResponse(payload)) {
const { fulfill, reject } = this.callbacks_.get(payload.rid);
this.callbacks_.delete(payload.rid);
if (payload.e) {
reject(new Error(payload.e));
} else {
fulfill(payload.r);
}
return;
}
const message: Messages.Response = {
from: payload.to,
rid: payload.id,
to: payload.from,
};
const handle = this.idToHandle_.get(payload.to[1]);
if (!handle) {
message.e = "Object has been diposed.";
} else {
try {
message.r = await handle.dispatchMessage_(payload.message);
} catch (e) {
message.e = e.toString() + "\n" + e.stack;
}
}
this.routeMessage_(false, message);
}
}
export default new Rpc(); | the_stack |
import { flatten, isEmpty, keyBy, mapValues, some } from 'lodash';
import { types as CollectiveTypes } from '../constants/collectives';
import models, { Op, sequelize } from '../models';
import { MigrationLogType } from '../models/MigrationLog';
import { DEFAULT_GUEST_NAME } from './guest-accounts';
const countEntities = async (fieldsConfig, entityId) => {
const resultsList = await Promise.all(
Object.keys(fieldsConfig).map(async entity => {
const entityConfig = fieldsConfig[entity];
return { entity, count: await entityConfig.model.count({ where: { [entityConfig.field]: entityId } }) };
}),
);
// Transform the results from `[{entity: 'updates', count: 42}]` to `{updates: 42}`
return mapValues(keyBy(resultsList, 'entity'), 'count');
};
/**
* Get a summary of all items handled by the `mergeAccounts` function
*/
export const getMovableItemsCounts = async (
fromCollective: typeof models.Collective,
): Promise<{
account: Record<keyof CollectiveFieldsConfig, number>;
user: Record<keyof UserFieldsConfig, number>;
}> => {
if (fromCollective.type === CollectiveTypes.USER) {
const user = await fromCollective.getUser({ paranoid: false });
if (!user) {
throw new Error('Cannot find user for this account');
}
return {
account: await countEntities(collectiveFieldsConfig, fromCollective.id),
user: await countEntities(userFieldsConfig, user.id),
};
} else {
return {
account: await countEntities(collectiveFieldsConfig, fromCollective.id),
user: null,
};
}
};
const checkMergeCollective = (from: typeof models.Collective, into: typeof models.Collective): void => {
if (!from || !into) {
throw new Error('Cannot merge profiles, one of them does not exist');
} else if (from.type !== into.type) {
throw new Error('Cannot merge accounts with different types');
} else if (from.id === into.id) {
throw new Error('Cannot merge an account into itself');
} else if (from.id === into.ParentCollectiveId) {
throw new Error('You can not merge an account with its parent');
} else if (from.id === into.HostCollectiveId) {
throw new Error('You can not merge an account with its host');
}
};
/**
* Simulate the `mergeAccounts` function. Returns a summary of the changes as a string
*/
export const simulateMergeAccounts = async (
from: typeof models.Collective,
into: typeof models.Collective,
): Promise<string> => {
// Detect errors that would completely block the process (throws)
checkMergeCollective(from, into);
// Generate a summary of the changes
const movedItemsCounts = await getMovableItemsCounts(from);
let summary = 'The profiles information will be merged.\n\n';
const addLineToSummary = str => {
summary += `${str}\n`;
};
const addCountsToSummary = counts => {
Object.entries(counts).forEach(([key, count]) => {
if (count > 0) {
addLineToSummary(` - ${key}: ${count}`);
}
});
};
if (some(movedItemsCounts.account, count => count > 0)) {
addLineToSummary(`The following items will be moved to @${into.slug}:`);
addCountsToSummary(movedItemsCounts.account);
addLineToSummary('');
}
return summary;
};
/** Legal documents have a unique key on CollectiveId/type/year. We need to ignore the ones that already exist */
const getLegalDocumentsToIgnore = async (from, into, transaction): Promise<number[]> => {
const results = await models.LegalDocument.findAll({
attributes: [[sequelize.fn('ARRAY_AGG', sequelize.col('id')), 'ids']],
where: { CollectiveId: [from.id, into.id] },
group: ['documentType', 'year'],
transaction,
raw: true,
having: sequelize.where(sequelize.fn('COUNT', sequelize.col('id')), { [Op.gt]: 1 }),
});
return flatten(results.map(({ ids }) => ids));
};
// Defines the collective field names used in the DB. Useful to prevent typos in the config below
type CollectiveField =
| 'CollectiveId'
| 'HostCollectiveId'
| 'ParentCollectiveId'
| 'FromCollectiveId'
| 'UsingGiftCardFromCollectiveId'
| 'MemberCollectiveId';
type CollectiveFieldsConfig = Record<
string,
{
model: typeof models.Collective;
field: CollectiveField;
getIdsToIgnore?: (
from: typeof models.Collective,
into: typeof models.Collective,
sqlTransaction,
) => Promise<number[]>;
}
>;
/**
* A map of entities to migrate. The key must be a name given for these entities, and the value
* must include a model, and a field where the old account ID will be replaced by the new one.
*/
const collectiveFieldsConfig: CollectiveFieldsConfig = {
activities: { model: models.Activity, field: 'CollectiveId' },
applications: { model: models.Application, field: 'CollectiveId' },
childrenCollectives: { model: models.Collective, field: 'ParentCollectiveId' },
comments: { model: models.Comment, field: 'CollectiveId' },
commentsCreated: { model: models.Comment, field: 'FromCollectiveId' },
connectedAccounts: { model: models.ConnectedAccount, field: 'CollectiveId' },
conversations: { model: models.Conversation, field: 'CollectiveId' },
conversationsCreated: { model: models.Conversation, field: 'FromCollectiveId' },
creditTransactions: { model: models.Transaction, field: 'FromCollectiveId' },
debitTransactions: { model: models.Transaction, field: 'CollectiveId' },
emojiReactions: { model: models.EmojiReaction, field: 'FromCollectiveId' },
expenses: { model: models.Expense, field: 'CollectiveId' },
expensesCreated: { model: models.Expense, field: 'FromCollectiveId' },
giftCardTransactions: { model: models.Transaction, field: 'UsingGiftCardFromCollectiveId' },
hostApplications: { model: models.HostApplication, field: 'HostCollectiveId' },
hostApplicationsCreated: { model: models.HostApplication, field: 'CollectiveId' },
hostedCollectives: { model: models.Collective, field: 'HostCollectiveId' },
legalDocuments: { model: models.LegalDocument, field: 'CollectiveId', getIdsToIgnore: getLegalDocumentsToIgnore },
memberInvitations: { model: models.MemberInvitation, field: 'MemberCollectiveId' },
members: { model: models.Member, field: 'MemberCollectiveId' },
membershipInvitations: { model: models.MemberInvitation, field: 'CollectiveId' },
memberships: { model: models.Member, field: 'CollectiveId' },
notifications: { model: models.Notification, field: 'CollectiveId' },
ordersCreated: { model: models.Order, field: 'FromCollectiveId' },
ordersReceived: { model: models.Order, field: 'CollectiveId' },
paymentMethods: { model: models.PaymentMethod, field: 'CollectiveId' },
payoutMethods: { model: models.PayoutMethod, field: 'CollectiveId' },
paypalProducts: { model: models.PaypalProduct, field: 'CollectiveId' },
requiredLegalDocuments: { model: models.RequiredLegalDocument, field: 'HostCollectiveId' },
tiers: { model: models.Tier, field: 'CollectiveId' },
updates: { model: models.Update, field: 'CollectiveId' },
updatesCreated: { model: models.Update, field: 'FromCollectiveId' },
virtualCards: { model: models.VirtualCard, field: 'CollectiveId' },
virtualCardsHosted: { model: models.VirtualCard, field: 'HostCollectiveId' },
};
// Defines the collective field names used in the DB. Useful to prevent typos in the config below
type UserField = 'UserId' | 'CreatedByUserId';
type UserFieldsConfig = Record<string, { model: typeof models.User; field: UserField }>;
const userFieldsConfig = {
activities: { model: models.Activity, field: 'UserId' },
applications: { model: models.Application, field: 'CreatedByUserId' },
collectives: { model: models.Collective, field: 'CreatedByUserId' },
comments: { model: models.Comment, field: 'CreatedByUserId' },
conversationFollowers: { model: models.ConversationFollower, field: 'UserId' },
conversations: { model: models.Conversation, field: 'CreatedByUserId' },
emojiReactions: { model: models.EmojiReaction, field: 'UserId' },
expenseAttachedFiles: { model: models.ExpenseAttachedFile, field: 'CreatedByUserId' },
expenseItems: { model: models.ExpenseItem, field: 'CreatedByUserId' },
expenses: { model: models.Expense, field: 'UserId' },
memberInvitations: { model: models.MemberInvitation, field: 'CreatedByUserId' },
members: { model: models.Member, field: 'CreatedByUserId' },
migrationLogs: { model: models.MigrationLog, field: 'CreatedByUserId' },
notifications: { model: models.Notification, field: 'UserId' },
orders: { model: models.Order, field: 'CreatedByUserId' },
paymentMethods: { model: models.PaymentMethod, field: 'CreatedByUserId' },
payoutMethods: { model: models.PayoutMethod, field: 'CreatedByUserId' },
transactions: { model: models.Transaction, field: 'CreatedByUserId' },
updates: { model: models.Update, field: 'CreatedByUserId' },
virtualCards: { model: models.VirtualCard, field: 'UserId' },
};
const mergeCollectiveFields = async (from, into, transaction) => {
const fieldsToUpdate = {};
const isTmpName = name => !name || name === DEFAULT_GUEST_NAME || name === 'Incognito';
if (isTmpName(into.name) && !isTmpName(from.name)) {
fieldsToUpdate['name'] = from.name;
}
if (from.countryISO && !into.countryISO) {
fieldsToUpdate['countryISO'] = from.countryISO;
}
if (from.address && !into.address) {
fieldsToUpdate['address'] = from.address;
}
if (isEmpty(fieldsToUpdate)) {
return into;
}
return into.update(fieldsToUpdate, {
transaction,
hooks: false,
sideEffects: false,
validate: false,
});
};
const moveCollectiveAssociations = async (from, into, transaction) => {
const summary = {};
const warnings = [];
for (const entity of Object.keys(collectiveFieldsConfig)) {
const entityConfig = collectiveFieldsConfig[entity];
const updateWhere = { [entityConfig.field]: from.id };
let idsToIgnore = [];
if (entityConfig.getIdsToIgnore) {
idsToIgnore = await entityConfig.getIdsToIgnore(from, into, transaction);
if (idsToIgnore.length) {
updateWhere.id = { [Op.not]: idsToIgnore };
}
}
try {
const [, results] = await entityConfig.model.update(
{ [entityConfig.field]: into.id },
{
where: updateWhere,
returning: ['id'],
fields: [entityConfig.field],
paranoid: false, // Also update soft-deleted entries
transaction,
// Ignore hooks and validations that could break the process
hooks: false,
sideEffects: false,
validate: false,
},
);
summary[entity] = results.map(r => r.id);
if (idsToIgnore.length) {
summary[`${entity}-deleted`] = idsToIgnore;
await entityConfig.model.destroy({
where: { [entityConfig.field]: from.id, id: idsToIgnore },
transaction,
hooks: false,
sideEffects: false,
validate: false,
});
}
} catch (e) {
if (e.name === 'SequelizeUniqueConstraintError' && entityConfig.model === models.LegalDocument) {
// It's fine if the target profile already has a legal document set for this type/year, just delete the other one
warnings.push(
`A legal document for ${from.slug} could not be transferred as one already exists for the same year/type with ${into.slug}`,
);
} else {
throw e;
}
}
}
return { summary, warnings };
};
type MergeUsersSummary = Record<keyof UserFieldsConfig, number[]>;
const mergeUsers = async (fromUser, toUser, transaction): Promise<MergeUsersSummary> => {
const summary = {};
// Move all `UserId`/`CreatedByUserId` fields
for (const entity of Object.keys(userFieldsConfig)) {
const entityConfig = userFieldsConfig[entity];
const [, results] = await entityConfig.model.update(
{ [entityConfig.field]: toUser.id },
{
where: { [entityConfig.field]: fromUser.id },
returning: ['id'],
fields: [entityConfig.field],
transaction,
paranoid: false, // Also update soft-deleted entries
// Ignore hooks and validations that could break the process
hooks: false,
sideEffects: false,
validate: false,
},
);
summary[entity] = results.map(r => r.id);
}
// Mark fromUser as deleted
const newUserData = { ...(fromUser.data || {}), mergedIntoUserId: toUser.id };
await fromUser.update({ data: newUserData }, { transaction, hooks: false });
await fromUser.destroy({ transaction, hooks: false });
return summary;
};
/**
* An helper to merge a collective with another one, with some limitations.
* @returns an array of warning messages
*/
export const mergeAccounts = async (
from: typeof models.Collective,
into: typeof models.Collective,
userId: number | null = null,
): Promise<string[]> => {
// Make sure all conditions are met before we start
checkMergeCollective(from, into);
// When moving users, we'll also update the user entries
let fromUser, toUser;
if (from.type === CollectiveTypes.USER) {
fromUser = await models.User.findOne({ where: { CollectiveId: from.id } });
toUser = await models.User.findOne({ where: { CollectiveId: into.id } });
if (!fromUser || !toUser) {
throw new Error('Cannot find one of the user entries to merge');
}
}
// Trigger the merge in a transaction
return sequelize.transaction(async transaction => {
// Update collective
await mergeCollectiveFields(from, into, transaction);
// Update all related models
const changesSummary = { fromAccount: from.id, intoAccount: into.id };
const mergeAccountAssociationsResult = await moveCollectiveAssociations(from, into, transaction);
const warnings = mergeAccountAssociationsResult.warnings;
changesSummary['associations'] = mergeAccountAssociationsResult.summary;
// Merge user entries
if (fromUser) {
// Move all `UserId`/`CreatedByUserId` fields
changesSummary['fromUser'] = fromUser.id;
changesSummary['intoUser'] = toUser.id;
changesSummary['userChanges'] = await mergeUsers(fromUser, toUser, transaction);
}
// Mark from profile as deleted
const collectiveData = { ...(from.data || {}), mergedIntoCollectiveId: into.id };
await models.Collective.update(
{ deletedAt: Date.now(), slug: `${from.slug}-merged`, data: collectiveData },
{ where: { id: from.id }, transaction },
);
// Log everything
await models.MigrationLog.create(
{
type: MigrationLogType.MERGE_ACCOUNTS,
description: `Merge ${from.slug} into ${into.slug}`,
CreatedByUserId: userId,
data: changesSummary,
},
{ transaction },
);
return warnings;
});
}; | the_stack |
import { Component, ElementRef, ViewChild, HostListener, Input, Output, EventEmitter, NgZone, AfterViewInit, OnDestroy } from '@angular/core';
import { MempoolBlockDelta, TransactionStripped } from 'src/app/interfaces/websocket.interface';
import { WebsocketService } from 'src/app/services/websocket.service';
import { FastVertexArray } from './fast-vertex-array';
import BlockScene from './block-scene';
import TxSprite from './tx-sprite';
import TxView from './tx-view';
import { Position } from './sprite-types';
@Component({
selector: 'app-block-overview-graph',
templateUrl: './block-overview-graph.component.html',
styleUrls: ['./block-overview-graph.component.scss'],
})
export class BlockOverviewGraphComponent implements AfterViewInit, OnDestroy {
@Input() isLoading: boolean;
@Input() resolution: number;
@Input() blockLimit: number;
@Input() orientation = 'left';
@Input() flip = true;
@Output() txClickEvent = new EventEmitter<TransactionStripped>();
@ViewChild('blockCanvas')
canvas: ElementRef<HTMLCanvasElement>;
gl: WebGLRenderingContext;
animationFrameRequest: number;
animationHeartBeat: number;
displayWidth: number;
displayHeight: number;
cssWidth: number;
cssHeight: number;
shaderProgram: WebGLProgram;
vertexArray: FastVertexArray;
running: boolean;
scene: BlockScene;
hoverTx: TxView | void;
selectedTx: TxView | void;
tooltipPosition: Position;
constructor(
readonly ngZone: NgZone,
readonly elRef: ElementRef,
) {
this.vertexArray = new FastVertexArray(512, TxSprite.dataSize);
}
ngAfterViewInit(): void {
this.canvas.nativeElement.addEventListener('webglcontextlost', this.handleContextLost, false);
this.canvas.nativeElement.addEventListener('webglcontextrestored', this.handleContextRestored, false);
this.gl = this.canvas.nativeElement.getContext('webgl');
this.initCanvas();
this.resizeCanvas();
}
ngOnDestroy(): void {
if (this.animationFrameRequest) {
cancelAnimationFrame(this.animationFrameRequest);
clearTimeout(this.animationHeartBeat);
}
}
clear(direction): void {
this.exit(direction);
this.hoverTx = null;
this.selectedTx = null;
this.start();
}
enter(transactions: TransactionStripped[], direction: string): void {
if (this.scene) {
this.scene.enter(transactions, direction);
this.start();
}
}
exit(direction: string): void {
if (this.scene) {
this.scene.exit(direction);
this.start();
}
}
replace(transactions: TransactionStripped[], direction: string, sort: boolean = true): void {
if (this.scene) {
this.scene.replace(transactions || [], direction, sort);
this.start();
}
}
update(add: TransactionStripped[], remove: string[], direction: string = 'left', resetLayout: boolean = false): void {
if (this.scene) {
this.scene.update(add, remove, direction, resetLayout);
this.start();
}
}
initCanvas(): void {
this.gl.clearColor(0.0, 0.0, 0.0, 0.0);
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
const shaderSet = [
{
type: this.gl.VERTEX_SHADER,
src: vertShaderSrc
},
{
type: this.gl.FRAGMENT_SHADER,
src: fragShaderSrc
}
];
this.shaderProgram = this.buildShaderProgram(shaderSet);
this.gl.useProgram(this.shaderProgram);
// Set up alpha blending
this.gl.enable(this.gl.BLEND);
this.gl.blendFunc(this.gl.ONE, this.gl.ONE_MINUS_SRC_ALPHA);
const glBuffer = this.gl.createBuffer();
this.gl.bindBuffer(this.gl.ARRAY_BUFFER, glBuffer);
/* SET UP SHADER ATTRIBUTES */
Object.keys(attribs).forEach((key, i) => {
attribs[key].pointer = this.gl.getAttribLocation(this.shaderProgram, key);
this.gl.enableVertexAttribArray(attribs[key].pointer);
});
this.start();
}
handleContextLost(event): void {
event.preventDefault();
cancelAnimationFrame(this.animationFrameRequest);
this.animationFrameRequest = null;
this.running = false;
}
handleContextRestored(event): void {
this.initCanvas();
}
@HostListener('window:resize', ['$event'])
resizeCanvas(): void {
this.cssWidth = this.canvas.nativeElement.offsetParent.clientWidth;
this.cssHeight = this.canvas.nativeElement.offsetParent.clientHeight;
this.displayWidth = window.devicePixelRatio * this.cssWidth;
this.displayHeight = window.devicePixelRatio * this.cssHeight;
this.canvas.nativeElement.width = this.displayWidth;
this.canvas.nativeElement.height = this.displayHeight;
if (this.gl) {
this.gl.viewport(0, 0, this.displayWidth, this.displayHeight);
}
if (this.scene) {
this.scene.resize({ width: this.displayWidth, height: this.displayHeight });
this.start();
} else {
this.scene = new BlockScene({ width: this.displayWidth, height: this.displayHeight, resolution: this.resolution,
blockLimit: this.blockLimit, orientation: this.orientation, flip: this.flip, vertexArray: this.vertexArray });
this.start();
}
}
compileShader(src, type): WebGLShader {
const shader = this.gl.createShader(type);
this.gl.shaderSource(shader, src);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
console.log(`Error compiling ${type === this.gl.VERTEX_SHADER ? 'vertex' : 'fragment'} shader:`);
console.log(this.gl.getShaderInfoLog(shader));
}
return shader;
}
buildShaderProgram(shaderInfo): WebGLProgram {
const program = this.gl.createProgram();
shaderInfo.forEach((desc) => {
const shader = this.compileShader(desc.src, desc.type);
if (shader) {
this.gl.attachShader(program, shader);
}
});
this.gl.linkProgram(program);
if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
console.log('Error linking shader program:');
console.log(this.gl.getProgramInfoLog(program));
}
return program;
}
start(): void {
this.running = true;
this.ngZone.runOutsideAngular(() => this.doRun());
}
doRun(): void {
if (this.animationFrameRequest) {
cancelAnimationFrame(this.animationFrameRequest);
}
this.animationFrameRequest = requestAnimationFrame(() => this.run());
}
run(now?: DOMHighResTimeStamp): void {
if (!now) {
now = performance.now();
}
// skip re-render if there's no change to the scene
if (this.scene) {
/* SET UP SHADER UNIFORMS */
// screen dimensions
this.gl.uniform2f(this.gl.getUniformLocation(this.shaderProgram, 'screenSize'), this.displayWidth, this.displayHeight);
// frame timestamp
this.gl.uniform1f(this.gl.getUniformLocation(this.shaderProgram, 'now'), now);
if (this.vertexArray.dirty) {
/* SET UP SHADER ATTRIBUTES */
Object.keys(attribs).forEach((key, i) => {
this.gl.vertexAttribPointer(attribs[key].pointer,
attribs[key].count, // number of primitives in this attribute
this.gl[attribs[key].type], // type of primitive in this attribute (e.g. gl.FLOAT)
false, // never normalised
stride, // distance between values of the same attribute
attribs[key].offset); // offset of the first value
});
const pointArray = this.vertexArray.getVertexData();
if (pointArray.length) {
this.gl.bufferData(this.gl.ARRAY_BUFFER, pointArray, this.gl.DYNAMIC_DRAW);
this.gl.drawArrays(this.gl.TRIANGLES, 0, pointArray.length / TxSprite.vertexSize);
}
this.vertexArray.dirty = false;
} else {
const pointArray = this.vertexArray.getVertexData();
if (pointArray.length) {
this.gl.drawArrays(this.gl.TRIANGLES, 0, pointArray.length / TxSprite.vertexSize);
}
}
}
/* LOOP */
if (this.running && this.scene && now <= (this.scene.animateUntil + 500)) {
this.doRun();
} else {
if (this.animationHeartBeat) {
clearTimeout(this.animationHeartBeat);
}
this.animationHeartBeat = window.setTimeout(() => {
this.start();
}, 1000);
}
}
@HostListener('document:click', ['$event'])
clickAway(event) {
if (!this.elRef.nativeElement.contains(event.target)) {
const currentPreview = this.selectedTx || this.hoverTx;
if (currentPreview && this.scene) {
this.scene.setHover(currentPreview, false);
this.start();
}
this.hoverTx = null;
this.selectedTx = null;
}
}
@HostListener('pointerup', ['$event'])
onClick(event) {
if (event.target === this.canvas.nativeElement && event.pointerType === 'touch') {
this.setPreviewTx(event.offsetX, event.offsetY, true);
} else if (event.target === this.canvas.nativeElement) {
this.onTxClick(event.offsetX, event.offsetY);
}
}
@HostListener('pointermove', ['$event'])
onPointerMove(event) {
if (event.target === this.canvas.nativeElement) {
this.setPreviewTx(event.offsetX, event.offsetY, false);
}
}
@HostListener('pointerleave', ['$event'])
onPointerLeave(event) {
if (event.pointerType !== 'touch') {
this.setPreviewTx(-1, -1, true);
}
}
setPreviewTx(cssX: number, cssY: number, clicked: boolean = false) {
const x = cssX * window.devicePixelRatio;
const y = cssY * window.devicePixelRatio;
if (this.scene && (!this.selectedTx || clicked)) {
this.tooltipPosition = {
x: cssX,
y: cssY
};
const selected = this.scene.getTxAt({ x, y });
const currentPreview = this.selectedTx || this.hoverTx;
if (selected !== currentPreview) {
if (currentPreview && this.scene) {
this.scene.setHover(currentPreview, false);
this.start();
}
if (selected) {
if (selected && this.scene) {
this.scene.setHover(selected, true);
this.start();
}
if (clicked) {
this.selectedTx = selected;
} else {
this.hoverTx = selected;
}
} else {
if (clicked) {
this.selectedTx = null;
}
this.hoverTx = null;
}
} else if (clicked) {
if (selected === this.selectedTx) {
this.hoverTx = this.selectedTx;
this.selectedTx = null;
} else {
this.selectedTx = selected;
}
}
}
}
onTxClick(cssX: number, cssY: number) {
const x = cssX * window.devicePixelRatio;
const y = cssY * window.devicePixelRatio;
const selected = this.scene.getTxAt({ x, y });
if (selected && selected.txid) {
this.txClickEvent.emit(selected);
}
}
}
// WebGL shader attributes
const attribs = {
offset: { type: 'FLOAT', count: 2, pointer: null, offset: 0 },
posX: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
posY: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
posR: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
colR: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
colG: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
colB: { type: 'FLOAT', count: 4, pointer: null, offset: 0 },
colA: { type: 'FLOAT', count: 4, pointer: null, offset: 0 }
};
// Calculate the number of bytes per vertex based on specified attributes
const stride = Object.values(attribs).reduce((total, attrib) => {
return total + (attrib.count * 4);
}, 0);
// Calculate vertex attribute offsets
for (let i = 0, offset = 0; i < Object.keys(attribs).length; i++) {
const attrib = Object.values(attribs)[i];
attrib.offset = offset;
offset += (attrib.count * 4);
}
const vertShaderSrc = `
varying lowp vec4 vColor;
// each attribute contains [x: startValue, y: endValue, z: startTime, w: rate]
// shader interpolates between start and end values at the given rate, from the given time
attribute vec2 offset;
attribute vec4 posX;
attribute vec4 posY;
attribute vec4 posR;
attribute vec4 colR;
attribute vec4 colG;
attribute vec4 colB;
attribute vec4 colA;
uniform vec2 screenSize;
uniform float now;
float smootherstep(float x) {
x = clamp(x, 0.0, 1.0);
float ix = 1.0 - x;
x = x * x;
return x / (x + ix * ix);
}
float interpolateAttribute(vec4 attr) {
float d = (now - attr.z) * attr.w;
float delta = smootherstep(d);
return mix(attr.x, attr.y, delta);
}
void main() {
vec4 screenTransform = vec4(2.0 / screenSize.x, 2.0 / screenSize.y, -1.0, -1.0);
// vec4 screenTransform = vec4(1.0 / screenSize.x, 1.0 / screenSize.y, -0.5, -0.5);
float radius = interpolateAttribute(posR);
vec2 position = vec2(interpolateAttribute(posX), interpolateAttribute(posY)) + (radius * offset);
gl_Position = vec4(position * screenTransform.xy + screenTransform.zw, 1.0, 1.0);
float red = interpolateAttribute(colR);
float green = interpolateAttribute(colG);
float blue = interpolateAttribute(colB);
float alpha = interpolateAttribute(colA);
vColor = vec4(red, green, blue, alpha);
}
`;
const fragShaderSrc = `
varying lowp vec4 vColor;
void main() {
gl_FragColor = vColor;
// premultiply alpha
gl_FragColor.rgb *= gl_FragColor.a;
}
`; | the_stack |
import { animate } from "@okikio/animate";
import { EventEmitter } from "@okikio/emitter";
import { debounce } from "./util/debounce";
import {
ResultEvents,
renderComponent,
setState
} from "./components/SearchResults";
import { hit } from "countapi-js";
import { decode, encode } from "./util/encode-decode";
import { parseInput, parseSearchQuery } from "./util/parse-query";
import ESBUILD_WORKER_URL from "worker:./workers/esbuild.ts";
import WebWorker, { WorkerConfig } from "./util/WebWorker";
import * as Monaco from "./modules/monaco";
import type { editor as Editor } from "monaco-editor";
import type { App, HistoryManager, IHistoryItem } from "@okikio/native";
export let oldShareURL = new URL(String(document.location));
export const BundleEvents = new EventEmitter();
let value = "";
let start = Date.now();
const timeFormatter = new Intl.RelativeTimeFormat("en", {
style: "narrow",
numeric: "auto",
});
let monacoLoadedFirst = false;
let initialized = false;
// The editor's content hasn't changed
let isInitial = true;
// Bundle worker
export const BundleWorker = new WebWorker(...WorkerConfig(ESBUILD_WORKER_URL, "esbuild-worker"));
export const postMessage = (obj: { event: string, details: any }) => {
let messageStr = JSON.stringify(obj);
let encodedMessage = encode(messageStr);
BundleWorker.postMessage(encodedMessage, [encodedMessage.buffer]);
};
// Emit bundle events based on WebWorker messages
BundleWorker.addEventListener("message", ({ data }: MessageEvent<BufferSource>) => {
let { event, details } = JSON.parse(decode(data));
BundleEvents.emit(event, details);
});
window.addEventListener("pageshow", function (event) {
if (!event.persisted) {
BundleWorker?.start?.();
}
});
window.addEventListener("pagehide", function (event) {
if (event.persisted === true) {
console.log("This page *might* be entering the bfcache.");
} else {
console.log("This page will unload normally and be discarded.");
BundleWorker?.terminate?.();
}
});
let fileSizeEl: HTMLElement;
// Bundle Events
BundleEvents.on({
loaded() {
monacoLoadedFirst = true;
if (initialized)
BundleEvents.emit("ready");
},
init() {
console.log("Initalized");
initialized = true;
if (fileSizeEl)
fileSizeEl.textContent = `Wait...`;
if (monacoLoadedFirst)
BundleEvents.emit("ready");
},
ready() {
console.log("Ready");
if (fileSizeEl)
fileSizeEl.textContent = `...`;
if (oldShareURL.search) {
const searchParams = oldShareURL
.searchParams;
let plaintext = searchParams.get("text");
let query = searchParams.get("query") || searchParams.get("q");
let share = searchParams.get("share");
let bundle = searchParams.get("bundle");
if (query || share || plaintext) {
if (bundle != null) {
fileSizeEl.textContent = `Wait...`;
BundleEvents.emit("bundle");
}
isInitial = false;
}
}
},
warn(details) {
let { type, message } = details;
console.warn(`${message.length} ${type}(s)`);
(Array.isArray(message) ? message : [message]).forEach(msg => {
console.warn(msg);
});
},
error(details) {
let { type, error } = details;
console.error(`${error.length} ${type}(s) (if you are having trouble solving this issue, please create a new issue in the repo, https://github.com/okikio/bundle)`);
(Array.isArray(error) ? error : [error]).forEach(err => {
console.error(err);
});
fileSizeEl.textContent = `Error`;
},
});
// Load all heavy main content
export const build = (app: App) => {
let RunBtn = document.querySelector("#run");
let bundleTime = document.querySelector("#bundle-time");
fileSizeEl = fileSizeEl ?? document.querySelector(".file-size");
let editor: Editor.IStandaloneCodeEditor;
let output: Editor.IStandaloneCodeEditor;
// bundles using esbuild and returns the result
BundleEvents.on({
bundle() {
if (!initialized) return;
console.log("Bundle");
value = `` + editor?.getValue();
fileSizeEl.innerHTML = `<div class="loading"></div>`;
bundleTime.textContent = `Bundled in ...`;
start = Date.now();
postMessage({ event: "build", details: value });
},
result(details) {
let { size, content } = details;
output?.setValue?.(content);
bundleTime.textContent = `Bundled ${timeFormatter.format(
(Date.now() - start) / 1000,
"seconds"
)}`;
fileSizeEl.textContent = `` + size;
}
});
let historyManager = app.get("HistoryManager") as HistoryManager;
let replaceState = (url) => {
let { last } = historyManager;
let state = {
...last,
url: url.toString()
}
historyManager.states.pop();
historyManager.states.push({ ...state });
let item: IHistoryItem = {
index: historyManager.pointer,
states: [...historyManager.states]
};
window.history.replaceState(item, "", state.url);
}
let pushState = (url) => {
let { last } = historyManager;
let state = {
...last,
url: url.toString()
}
let len = historyManager.length;
historyManager.states.push({ ...state });
historyManager.pointer = len;
let item: IHistoryItem = {
index: historyManager.pointer,
states: [...historyManager.states]
};
window.history.pushState(item, "", state.url);
}
// Monaco
(async () => {
let flexWrapper = document.querySelector(".flex-wrapper") as HTMLElement;
let loadingContainerEl = Array.from(
document.querySelectorAll(".center-container")
);
let FadeLoadingScreen = animate({
target: loadingContainerEl,
opacity: [1, 0],
easing: "ease-in",
duration: 300,
autoplay: false,
fillMode: "both",
});
const { languages } = Monaco;
const getShareableURL = async (editor: typeof output) => {
try {
const model = editor.getModel();
const worker = await languages.typescript.getTypeScriptWorker();
const thisWorker = await worker(model.uri);
// @ts-ignore
return await thisWorker.getShareableURL(model.uri.toString());
} catch (e) {
console.warn(e)
}
};
const editorBtns = (editor: typeof output, reset: string) => {
let el = editor.getDomNode();
let parentEl = el?.closest(".app").querySelector(".editor-btns");
if (parentEl) {
let clearBtn = parentEl.querySelector(".clear-btn");
let prettierBtn = parentEl.querySelector(".prettier-btn");
let resetBtn = parentEl.querySelector(".reset-btn");
let copyBtn = parentEl.querySelector(".copy-btn");
let codeWrapBtn = parentEl.querySelector(".code-wrap-btn");
let editorInfo = parentEl.querySelector(".editor-info");
clearBtn.addEventListener("click", () => {
editor.setValue("");
});
prettierBtn.addEventListener("click", () => {
(async () => {
try {
const model = editor.getModel();
const worker = await languages.typescript.getTypeScriptWorker();
const thisWorker = await worker(model.uri);
// @ts-ignore
const formattedCode = await thisWorker.format(model.uri.toString());
editor.setValue(formattedCode);
} catch (e) {
console.warn(e)
}
})();
editor.getAction("editor.action.formatDocument").run();
});
resetBtn.addEventListener("click", () => {
editor.setValue(reset);
if (editor != output) {
isInitial = true;
}
});
copyBtn.addEventListener("click", () => {
const range = editor.getModel().getFullModelRange();
editor.setSelection(range);
editor
.getAction(
"editor.action.clipboardCopyWithSyntaxHighlightingAction"
)
.run();
(async () => {
await animate({
target: editorInfo,
translateY: [100, "-100%"],
fillMode: "both",
duration: 500,
easing: "ease-out",
});
await animate({
target: editorInfo,
translateY: ["-100%", 100],
fillMode: "both",
delay: 1000,
});
})();
});
codeWrapBtn.addEventListener("click", () => {
let wordWrap: "on" | "off" =
editor.getRawOptions()["wordWrap"] == "on" ? "off" : "on";
editor.updateOptions({ wordWrap });
});
}
};
// Build the Code Editor
[editor, output] = Monaco.build(oldShareURL);
FadeLoadingScreen.play(); // Fade away the loading screen
await FadeLoadingScreen;
[editor.getDomNode(), output.getDomNode()].forEach((el) => {
el?.parentElement?.classList.add("show");
});
// Add editor buttons to both editors
editorBtns(
editor,
[
'// Click Run for the Bundled, Minified & Gzipped package size',
'export * from "@okikio/animate";'
].join("\n")
);
editorBtns(output, `// Output`);
FadeLoadingScreen.stop();
loadingContainerEl.forEach((x) => x?.remove());
flexWrapper.classList.add("loaded");
const allEditorBtns = Array.from(
document.querySelectorAll(".editor-btns")
);
if (allEditorBtns) {
allEditorBtns?.[1].classList.add("delay");
setTimeout(() => {
allEditorBtns?.[1].classList.remove("delay");
}, 1600);
}
BundleEvents.emit("loaded");
loadingContainerEl = null;
FadeLoadingScreen = null;
editor.onDidChangeModelContent(
debounce((e) => {
(async () => {
replaceState(await getShareableURL(editor));
isInitial = false;
})();
}, 1000)
);
const shareBtn = document.querySelector(
".btn-share#share"
) as HTMLButtonElement;
const shareInput = document.querySelector(
"#copy-input"
) as HTMLInputElement;
shareBtn?.addEventListener("click", () => {
(async () => {
try {
if (navigator.share) {
let shareBtnValue = shareBtn.innerText;
isInitial = false;
await navigator.share({
title: 'bundle',
text: '',
url: await getShareableURL(editor),
});
shareBtn.innerText = "Shared!";
setTimeout(() => {
shareBtn.innerText = shareBtnValue;
}, 600);
} else {
shareInput.value = await getShareableURL(editor);
shareInput.select();
document.execCommand("copy");
let shareBtnValue = shareBtn.innerText;
shareBtn.innerText = "Copied!";
setTimeout(() => {
shareBtn.innerText = shareBtnValue;
}, 600);
}
} catch (error) {
console.log('Error sharing', error);
}
})();
});
// Listen to events for the results
ResultEvents.on("add-module", (v) => {
value = isInitial ? "// Click Run for the Bundled + Minified + Gzipped package size" : `` + editor?.getValue();
editor.setValue((value + "\n" + v).trim());
});
RunBtn.addEventListener("click", () => {
(async () => {
if (!initialized)
fileSizeEl.textContent = `Wait...`;
BundleEvents.emit("bundle");
pushState(await getShareableURL(editor));
})();
});
})();
};
// To speed up rendering, delay Monaco on the main page, only load none critical code
export const InitialRender = (shareURL: URL) => {
oldShareURL = shareURL;
fileSizeEl = fileSizeEl ?? document.querySelector(".file-size");
BundleWorker?.start?.();
if (initialized && fileSizeEl)
fileSizeEl.textContent = `...`;
// SearchResults solidjs component
(async () => {
const searchInput = document.querySelector(
".search input"
) as HTMLInputElement;
searchInput?.addEventListener?.(
"keydown",
debounce(() => {
let { value } = searchInput;
if (value.length <= 0) return;
let { url, version } = parseInput(value);
(async () => {
try {
let response = await fetch(url);
let result = await response.json();
setState(
// result?.results -> api.npms.io
// result?.objects -> registry.npmjs.com
result?.results.map((obj) => {
const { name, description, date, publisher } =
obj.package;
return {
name,
description,
date,
version,
author: publisher?.username,
};
}) ?? []
);
} catch (e) {
console.error(e);
setState([{
type: "Error...",
description: e?.message
}]);
}
})();
}, 250)
);
const SearchContainerEl = document.querySelector(
".search-container"
) as HTMLElement;
const SearchResultContainerEl = SearchContainerEl.querySelector(
".search-results-container"
) as HTMLElement;
if (SearchResultContainerEl) renderComponent(SearchResultContainerEl);
const clearBtn = document.querySelector(".search .clear");
clearBtn?.addEventListener("click", () => {
searchInput.value = "";
setState([]);
});
})();
// countapi-js hit counter. It counts the number of time the website is loaded
(async () => {
try {
let { value } = await hit("bundle.js.org", "visits");
let visitCounterEl = document.querySelector("#visit-counter");
if (visitCounterEl)
visitCounterEl.textContent = `👋 ${value} visits`;
} catch (err) {
console.warn(
"Visit Counter Error (please create a new issue in the repo)",
err
);
}
})();
} | the_stack |
import { Wave, Fiber } from "./wave";
import * as wave from "./wave";
import { constant, FunctionN, flow, Lazy, identity } from "fp-ts/lib/function";
import { Option } from "fp-ts/lib/Option";
import { Exit, Cause } from "./exit";
import * as exit from "./exit";
import { Either } from "fp-ts/lib/Either";
import { Runtime } from "./runtime";
import { tuple2, fst, snd } from "./support/util";
import { MonadThrow3 } from "fp-ts/lib/MonadThrow";
import { Applicative3 } from "fp-ts/lib/Applicative";
import { Monoid } from "fp-ts/lib/Monoid";
import { Semigroup } from "fp-ts/lib/Semigroup";
import * as reader from "fp-ts/lib/Reader"
export type WaveR<R, E, A> = (r: R) => Wave<E, A>;
export type ReturnCovaryE<T, E2> =
T extends WaveR<infer R, infer E, infer A> ?
(E extends E2 ? WaveR<R, E2, A> : WaveR<R, E | E2, A>) : never
/**
* Perform a widening of WaveR<R, E1, A> such that the result includes E2.
*
* This encapsulates normal subtype widening, but will also widen to E1 | E2 as a fallback
* Assumes that this function (which does nothing when compiled to js) will be inlined in hot code
*/
export function covaryE<R, E1, A, E2>(wave: WaveR<R, E1, A>): ReturnCovaryE<typeof wave, E2> {
return wave as unknown as ReturnCovaryE<typeof wave, E2>;
}
/**
* Type inference helper form of covaryToE
*/
export function covaryToE<E2>(): <R, E1, A>(wave: WaveR<R, E1, A>) => ReturnCovaryE<typeof wave, E2> {
return (wave) => covaryE(wave);
}
export type ReturnContravaryR<T, R2> =
T extends WaveR<infer R, infer E, infer A> ?
(R2 extends R ? WaveR<R2, E, A> : WaveR<R & R2, E, A>) : never;
/**
* Perform a widening of WaveR<R, E, A> such that the result includes R2.
*
* This encapsulates normal subtype widening, but will also widen to R1 & R2 as a fallback.
* Assumes that this function (which does nothing when compiled to js) will be inlined in hot code.
*/
export function contravaryR<R, E, A, R2>(wave: WaveR<R, E, A>): ReturnContravaryR<typeof wave, R2> {
return wave as unknown as ReturnContravaryR<typeof wave, R2>;
}
export function contravaryToR<R2>(): <R1, E, A>(wave: WaveR<R1, E, A>) => ReturnContravaryR<typeof wave, R2> {
return (wave) => contravaryR(wave);
}
export function encaseWave<E, A>(w: Wave<E, A>): WaveR<{}, E, A> {
return constant(w);
}
export function encaseWaveR<R, E, A>(w: Wave<E, A>): WaveR<R, E, A> {
return contravaryR(encaseWave(w));
}
export function pure<A>(a: A): WaveR<{}, never, A> {
return encaseWave(wave.pure(a));
}
export function raised<E>(e: Cause<E>): WaveR<{}, E, never> {
return encaseWave(wave.completed(e))
}
export function raiseError<E>(e: E): WaveR<{}, E, never> {
return encaseWave(wave.completed(exit.raise(e)))
}
export function raiseAbort(u: unknown): WaveR<{}, never, never> {
return encaseWave(wave.completed(exit.abort(u)));
}
export const raiseInterrupt: WaveR<{}, never, never> = raised(exit.interrupt);
export function completed<E, A>(exit: Exit<E, A>): WaveR<{}, E, A> {
return constant(wave.completed(exit));
}
export function contramap<R, E, A, R2>(wave: WaveR<R, E, A>, f: FunctionN<[R2], R>): WaveR<R2, E, A> {
return (r2) => wave(f(r2));
}
export function interruptibleRegion<R, E, A>(inner: WaveR<R, E, A>, flag: boolean): WaveR<R, E, A> {
return (r: R) =>
wave.interruptibleRegion(inner(r), flag);
}
export function chain<R, E, A, B>(inner: WaveR<R, E, A>, bind: FunctionN<[A], WaveR<R, E, B>>): WaveR<R, E, B> {
return (r: R) =>
wave.chain(inner(r), (a) => bind(a)(r));
}
export const encaseEither: <E, A>(e: Either<E, A>) => WaveR<{}, E, A> =
flow(wave.encaseEither, encaseWave);
export function encaseOption<E, A>(o: Option<A>, onError: Lazy<E>): WaveR<{}, E, A> {
return encaseWave(wave.encaseOption(o, onError));
}
export function flatten<R, E, A>(inner: WaveR<R, E, WaveR<R, E, A>>): WaveR<R, E, A> {
return chain(inner, identity);
}
export function chainWith<R, E, Z, A>(bind: FunctionN<[Z], WaveR<R, E, A>>): FunctionN<[WaveR<R, E, Z>], WaveR<R, E, A>> {
return (w) => chain(w, bind);
}
export function foldExit<R, E1, E2, A1, A2>(
inner: WaveR<R, E1, A1>,
failure: FunctionN<[Cause<E1>], WaveR<R, E2, A2>>,
success: FunctionN<[A1], WaveR<R, E2, A2>>): WaveR<R, E2, A2> {
return (r: R) =>
wave.foldExit(inner(r), (cause) => failure(cause)(r), (a) => success(a)(r));
}
export function foldExitWith<R, E1, E2, A1, A2>(failure: FunctionN<[Cause<E1>], WaveR<R, E2, A2>>,
success: FunctionN<[A1], WaveR<R, E2, A2>>): FunctionN<[WaveR<R, E1, A1>], WaveR<R, E2, A2>> {
return (w) => foldExit(w, failure, success);
}
export const accessInterruptible: WaveR<{}, never, boolean> = encaseWave(wave.accessInterruptible);
export const accessRuntime: WaveR<{}, never, Runtime> = encaseWave(wave.accessRuntime);
export function map<R, E, A, B>(base: WaveR<R, E, A>, f: FunctionN<[A], B>): WaveR<R, E, B> {
return flow(base, wave.mapWith(f));
}
export function mapWith<A, B>(f: FunctionN<[A], B>): <R, E>(wave: WaveR<R, E, A>) => WaveR<R, E, B> {
return (wave) => map(wave, f);
}
export function as<R, E, A, B>(w: WaveR<R, E, A>, b: B): WaveR<R, E, B> {
return flow(w, wave.to(b));
}
export function to<B>(b: B): <R, E, A>(w: WaveR<R, E, A>) => WaveR<R, E, B> {
return (w) => as(w, b);
}
export function chainTap<R, E, A>(base: WaveR<R, E, A>, bind: FunctionN<[A], WaveR<R, E, unknown>>): WaveR<R, E, A> {
return chain(base, (a) => as(bind(a), a));
}
export function chainTapWith<R, E, A>(bind: FunctionN<[A], WaveR<R, E, unknown>>): (inner: WaveR<R, E, A>) => WaveR<R, E, A> {
return (w) => chainTap(w, bind);
}
export function asUnit<R, E, A>(w: WaveR<R, E, A>): WaveR<R, E, void> {
return as(w, undefined);
}
export const unit: WaveR<{}, never, void> = pure(undefined);
export function chainError<R, E1, E2, A>(w: WaveR<R, E1, A>, f: FunctionN<[E1], WaveR<R, E2, A>>): WaveR<R, E2, A> {
return foldExit(w, (cause) => cause._tag === exit.ExitTag.Raise ? f(cause.error) : completed(cause), (a) => pure(a) as WaveR<R, E2, A>);
}
export function chainErrorWith<R, E1, E2, A>(f: FunctionN<[E1], WaveR<R, E2, A>>): FunctionN<[WaveR<R, E1, A>], WaveR<R, E2, A>> {
return (io) => chainError(io, f);
}
export function mapError<R, E1, E2, A>(io: WaveR<R, E1, A>, f: FunctionN<[E1], E2>): WaveR<R, E2, A> {
return chainError<R, E1, E2, A>(io, flow(f, raiseError));
}
export function mapErrorWith<E1, E2>(f: FunctionN<[E1], E2>): <R, A>(w: WaveR<R, E1, A>) => WaveR<R, E2, A> {
return (w) => mapError(w, f);
}
export function bimap<R, E1, E2, A, B>(io: WaveR<R, E1, A>, leftMap: FunctionN<[E1], E2>, rightMap: FunctionN<[A], B>): WaveR<R, E2, B> {
return foldExit<R, E1, E2, A, B>(io,
(cause) => cause._tag === exit.ExitTag.Raise ? raiseError(leftMap(cause.error)) : completed(cause),
flow(rightMap, pure)
);
}
export function bimapWith<E1, E2, A, B>(leftMap: FunctionN<[E1], E2>,
rightMap: FunctionN<[A], B>): <R>(w: WaveR<R, E1, A>) => WaveR<R, E2, B> {
return (io) => bimap(io, leftMap, rightMap);
}
export function zipWith<R, E, A, B, C>(first: WaveR<R, E, A>, second: WaveR<R, E, B>, f: FunctionN<[A, B], C>): WaveR<R, E, C> {
return chain(first, (a) => map(second, (b) => f(a, b)));
}
export function zip<R, E, A, B>(first: WaveR<R, E, A>, second: WaveR<R, E, B>): WaveR<R, E, readonly [A, B]> {
return zipWith(first, second, tuple2);
}
export function applyFirst<R, E, A, B>(first: WaveR<R, E, A>, second: WaveR<R, E, B>): WaveR<R, E, A> {
return zipWith(first, second, fst);
}
export function applySecond<R, E, A, B>(first: WaveR<R, E, A>, second: WaveR<R, E, B>): WaveR<R, E, B> {
return zipWith(first, second, snd);
}
/**
* Evaluate two IOs in sequence and produce the value of the second.
* This is suitable for cases where second is recursively defined
* @param first
* @param second
*/
export function applySecondL<R, E, A, B>(first: WaveR<R, E, A>, second: Lazy<WaveR<R, E, B>>): WaveR<R, E, B> {
return chain(first, () => second());
}
export function ap<R, E, A, B>(wa: WaveR<R, E, A>, wf: WaveR<R, E, FunctionN<[A], B>>): WaveR<R, E, B> {
return zipWith(wa, wf, (a, f) => f(a));
}
export function ap_<R, E, A, B>( wf: WaveR<R, E, FunctionN<[A], B>>, wa: WaveR<R, E, A>): WaveR<R, E, B> {
return zipWith(wf, wa, (f, a) => f(a));
}
export function flip<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, A, E> {
return foldExit<R, E, A, A, E>(
wa,
(error) => error._tag === exit.ExitTag.Raise ? pure(error.error) : completed(error),
raiseError
);
}
export function forever<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, E, A> {
return chain(wa, () => forever(wa));
}
export function result<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, never, Exit<E, A>> {
return foldExit<R, E, never, A, Exit<E, A>>(wa, (c) => pure(c) as WaveR<R, never, Exit<E, A>>, (d) => pure(exit.done(d)));
}
export function interruptible<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, E, A> {
return interruptibleRegion(wa, true);
}
export function uninterruptible<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, E, A> {
return interruptibleRegion(wa, false);
}
export function after(ms: number): WaveR<{}, never, void> {
return encaseWave(wave.after(ms));
}
export type InterruptMaskCutout<R, E, A> = FunctionN<[WaveR<R, E, A>], WaveR<R, E, A>>;
function makeInterruptMaskCutout<R, E, A>(state: boolean): InterruptMaskCutout<R, E, A> {
return (inner: WaveR<R, E, A>) => interruptibleRegion(inner, state);
}
export function uninterruptibleMask<R, E, A>(f: FunctionN<[InterruptMaskCutout<R, E, A>], WaveR<R, E, A>>): WaveR<R, E, A> {
return chain(accessInterruptible as WaveR<R, E, boolean>,
(flag) => uninterruptible(f(makeInterruptMaskCutout(flag))));
}
export function interruptibleMask<R, E, A>(f: FunctionN<[InterruptMaskCutout<R, E, A>], WaveR<R, E, A>>): WaveR<R, E, A> {
return chain(accessInterruptible as WaveR<R, E, boolean>,
(flag) => interruptible(f(makeInterruptMaskCutout(flag)))
);
}
export function bracketExit<R, E, A, B>(acquire: WaveR<R, E, A>, release: FunctionN<[A, Exit<E, B>], WaveR<R, E, unknown>>, use: FunctionN<[A], WaveR<R, E, B>>): WaveR<R, E, B> {
return (r: R) => wave.bracketExit(
acquire(r),
(a, exit) => release(a, exit)(r),
(a) => use(a)(r)
)
}
export function bracket<R, E, A, B>(acquire: WaveR<R, E, A>, release: FunctionN<[A], WaveR<R, E, unknown>>, use: FunctionN<[A], WaveR<R, E, B>>): WaveR<R, E, B> {
return bracketExit(acquire, (e) => release(e), use);
}
export function onComplete<R, E, A>(wa: WaveR<R, E, A>, finalizer: WaveR<R, E, unknown>): WaveR<R, E, A> {
return (r: R) => wave.onComplete(wa(r), finalizer(r));
}
export function onInterrupted<R, E, A>(wa: WaveR<R, E, A>, finalizer: WaveR<R, E, unknown>): WaveR<R, E, A> {
return (r: R) => wave.onInterrupted(wa(r), finalizer(r));
}
export const shifted: WaveR<{}, never, void> = encaseWave(wave.shifted);
export function shiftBefore<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, E, A> {
return applySecond(shifted as WaveR<R, E, void>, wa);
}
export function shiftAfter<R, E, A>(wa: WaveR<R, E, A>): WaveR<R, E, A> {
return applyFirst(wa, shifted as WaveR<R, E, void>);
}
export const shiftedAsync: WaveR<{}, never, void> = encaseWave(wave.shiftedAsync);
export function shiftAsyncBefore<R, E, A>(io: WaveR<R, E, A>): WaveR<R, E, A> {
return applySecond(shiftedAsync as WaveR<R, E, void>, io);
}
export function shiftAsyncAfter<R, E, A>(io: WaveR<R, E, A>): WaveR<R, E, A> {
return applyFirst(io, shiftedAsync as WaveR<R, E, void>);
}
export const never: WaveR<{}, never, never> = encaseWave(wave.never);
export function delay<R, E, A>(inner: WaveR<R, E, A>, ms: number): WaveR<R, E, A> {
return applySecond(after(ms) as WaveR<R, E, void>, inner);
}
export interface FiberR<E, A> {
readonly name: Option<string>;
readonly interrupt: WaveR<{}, never, void>;
readonly wait: WaveR<{}, never, Exit<E, A>>;
readonly join: WaveR<{}, E, A>;
readonly result: WaveR<{}, E, Option<A>>;
readonly isComplete: WaveR<{}, never, boolean>;
}
/**
* Lift a fiber in the WaveR context
* @param fiber
*/
export function encaseFiber<E, A>(fiber: Fiber<E, A>): FiberR<E, A> {
return {
name: fiber.name,
interrupt: encaseWave(fiber.interrupt),
wait: encaseWave(fiber.wait),
join: encaseWave(fiber.join),
result: encaseWave(fiber.result),
isComplete: encaseWave(fiber.isComplete)
} as const;
}
export function fork<R, E, A>(wa: WaveR<R, E, A>, name?: string): WaveR<R, never, FiberR<E, A>> {
return (r: R) => wave.map(wave.fork(wa(r), name), encaseFiber);
}
export function raceFold<R, E1, E2, A, B, C>(first: WaveR<R, E1, A>, second: WaveR<R, E1, B>,
onFirstWon: FunctionN<[Exit<E1, A>, FiberR<E1, B>], WaveR<R, E2, C>>,
onSecondWon: FunctionN<[Exit<E1, B>, FiberR<E1, A>], WaveR<R, E2, C>>): WaveR<R, E2, C> {
return (r: R) =>
wave.raceFold(first(r), second(r),
(exit, fiber) => onFirstWon(exit, encaseFiber(fiber))(r),
(exit, fiber) => onSecondWon(exit, encaseFiber(fiber))(r));
}
export function timeoutFold<R, E1, E2, A, B>(source: WaveR<R, E1, A>, ms: number, onTimeout: FunctionN<[FiberR<E1, A>], WaveR<R, E2, B>>, onCompleted: FunctionN<[Exit<E1, A>], WaveR<R, E2, B>>): WaveR<R, E2, B> {
return raceFold<R, E1, E2, A, void, B>(
source, after(ms),
(exit, delayFiber) => applySecond(delayFiber.interrupt as WaveR<R, never, void>,
onCompleted(exit)),
(_, fiber) => onTimeout(fiber))
}
export function raceFirst<R, E, A>(io1: WaveR<R, E, A>, io2: WaveR<R, E, A>): WaveR<R, E, A> {
return (r: R) => wave.raceFirst(io1(r), io2(r));
}
export function race<R, E, A>(io1: WaveR<R, E, A>, io2: WaveR<R, E, A>): WaveR<R, E, A> {
return (r: R) => wave.race(io1(r), io2(r));
}
export function parZipWith<R, E, A, B, C>(io1: WaveR<R, E, A>, io2: WaveR<R, E, B>, f: FunctionN<[A, B], C>): WaveR<R, E, C>{
return (r: R) => wave.parZipWith(io1(r), io2(r), f);
}
export function parZip<R, E, A, B>(ioa: WaveR<R, E, A>, iob: WaveR<R, E, B>): WaveR<R, E, readonly [A, B]> {
return parZipWith(ioa, iob, tuple2);
}
export function parApplyFirst<R, E, A, B>(ioa: WaveR<R, E, A>, iob: WaveR<R, E, B>): WaveR<R, E, A> {
return parZipWith(ioa, iob, fst);
}
export function parApplySecond<R, E, A, B>(ioa: WaveR<R, E, A>, iob: WaveR<R, E, B>): WaveR<R, E, B> {
return parZipWith(ioa, iob, snd);
}
export function parAp<R, E, A, B>(ioa: WaveR<R, E, A>, iof: WaveR<R, E, FunctionN<[A], B>>): WaveR<R, E, B> {
return parZipWith(ioa, iof, (a, f) => f(a));
}
export function parAp_<R, E, A, B>(iof: WaveR<R, E, FunctionN<[A], B>>, ioa: WaveR<R, E, A>): WaveR<R, E, B> {
return parZipWith(iof, ioa, (f, a) => f(a));
}
export function orAbort<R, E, A>(ioa: WaveR<R, E, A>): WaveR<R, never, A> {
return flow(ioa, wave.orAbort);
}
export function timeoutOption<R, E, A>(source: WaveR<R, E, A>, ms: number): WaveR<R, E, Option<A>> {
return (r: R) => wave.timeoutOption(source(r), ms);
}
export function fromPromise<R, A>(thunk: FunctionN<[R], Promise<A>>): WaveR<R, unknown, A> {
return (r: R) => wave.fromPromise(() => thunk(r));
}
export function env<R>(): WaveR<R, never, R> {
return wave.pure;
}
export const URI = "WaveR";
export type URI = typeof URI;
declare module "fp-ts/lib/HKT" {
interface URItoKind3<R, E, A> {
WaveR: WaveR<R, E, A>;
}
}
export const instances: MonadThrow3<URI> = {
URI,
map,
of: <R, E, A>(a: A): WaveR<R, E, A> => pure(a),
ap: ap_,
chain,
throwError: <R, E, A>(e: E): WaveR<R, E, A> => raiseError(e)
};
export const waver = instances;
export const parInstances: Applicative3<URI> = {
URI,
map,
of: <R, E, A>(a: A): WaveR<R, E, A> => pure(a),
ap: parAp_
}
export const parWaver = parInstances
export function getSemigroup<R, E, A>(m: Semigroup<A>): Semigroup<WaveR<R, E, A>> {
return reader.getSemigroup(wave.getSemigroup(m));
}
export function getMonoid<R, E, A>(m: Monoid<A>): Monoid<WaveR<R, E, A>> {
return reader.getMonoid(wave.getMonoid(m));
}
export function getRaceMonoid<R, E, A>(): Monoid<WaveR<R, E, A>> {
return {
concat: race,
empty: never
}
} | the_stack |
import parser from './parser/parser.js';
import parserExt from './parser/parserExt.js';
import Attribute from './Attribute.js';
import Relation from './Relation.js';
const Orientation = {
HORIZONTAL: 1,
VERTICAL: 2,
ZINDEX: 4,
};
/**
* Helper function that inserts equal spacers (~).
* @private
*/
function _processEqualSpacer(context, stackView) {
// Determine unique name for the spacer
context.equalSpacerIndex = context.equalSpacerIndex || 1;
const name = '_~' + context.lineIndex + ':' + context.equalSpacerIndex + '~';
if (context.equalSpacerIndex > 1) {
// Ensure that all spacers have the same width/height
context.constraints.push({
view1: '_~' + context.lineIndex + ':1~',
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: name,
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority,
});
}
context.equalSpacerIndex++;
// Enforce view/proportional width/height
if (context.relation.view || (context.relation.multiplier && context.relation.multiplier !== 1)) {
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: context.relation.view,
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority,
multiplier: context.relation.multiplier,
});
context.relation.multiplier = undefined;
} else if (context.relation.constant) {
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: Relation.EQU,
view2: null,
attr2: Attribute.CONST,
priority: context.relation.priority,
constant: context.relation.constant,
});
context.relation.constant = undefined;
}
// Add constraint
for (var i = 0; i < context.prevViews.length; i++) {
const prevView = context.prevViews[i];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = prevView !== stackView ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = Attribute.LEFT;
break;
case Orientation.VERTICAL:
context.prevAttr = prevView !== stackView ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = Attribute.TOP;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = prevView !== stackView ? 'default' : 0;
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: name,
attr2: context.curAttr,
priority: context.relation.priority,
});
}
context.prevViews = [name];
}
/**
* Helper function that inserts proportional spacers (-12%-).
* @private
*/
function _processProportionalSpacer(context, stackView) {
context.proportionalSpacerIndex = context.proportionalSpacerIndex || 1;
const name = '_-' + context.lineIndex + ':' + context.proportionalSpacerIndex + '-';
context.proportionalSpacerIndex++;
context.constraints.push({
view1: name,
attr1: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
relation: context.relation.relation || Relation.EQU,
view2: context.relation.view, // or relative to the stackView... food for thought
attr2: context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT,
priority: context.relation.priority,
multiplier: context.relation.multiplier,
});
context.relation.multiplier = undefined;
// Add constraint
for (var i = 0; i < context.prevViews.length; i++) {
const prevView = context.prevViews[i];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = prevView !== stackView ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = Attribute.LEFT;
break;
case Orientation.VERTICAL:
context.prevAttr = prevView !== stackView ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = Attribute.TOP;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = prevView !== stackView ? 'default' : 0;
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: name,
attr2: context.curAttr,
priority: context.relation.priority,
});
}
context.prevViews = [name];
}
/**
* In case of a stack-view, set constraints for opposite orientations
* @private
*/
function _processStackView(context, name, subView) {
let viewName;
for (var orientation = 1; orientation <= 4; orientation *= 2) {
if (
subView.orientations & orientation &&
subView.stack.orientation !== orientation &&
!(subView.stack.processedOrientations & orientation)
) {
subView.stack.processedOrientations = subView.stack.processedOrientations | orientation;
viewName = viewName || {
name: name,
type: 'stack',
};
for (var i = 0, j = subView.stack.subViews.length; i < j; i++) {
if (orientation === Orientation.ZINDEX) {
context.constraints.push({
view1: viewName,
attr1: Attribute.ZINDEX,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: Attribute.ZINDEX,
});
} else {
context.constraints.push({
view1: viewName,
attr1: orientation === Orientation.VERTICAL ? Attribute.HEIGHT : Attribute.WIDTH,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: orientation === Orientation.VERTICAL ? Attribute.HEIGHT : Attribute.WIDTH,
});
context.constraints.push({
view1: viewName,
attr1: orientation === Orientation.VERTICAL ? Attribute.TOP : Attribute.LEFT,
relation: Relation.EQU,
view2: subView.stack.subViews[i],
attr2: orientation === Orientation.VERTICAL ? Attribute.TOP : Attribute.LEFT,
});
}
}
}
}
}
/**
* Recursive helper function converts a view-name and a range to a series
* of view-names (e.g. [child1, child2, child3, ...]).
* @private
*/
function _getRange(name: string, range) {
if (range === true) {
range = name.match(/\.\.\d+$/);
if (range) {
name = name.substring(0, name.length - range[0].length);
range = parseInt(range[0].substring(2));
}
}
if (!range) {
return [name];
}
var start = name.match(/\d+$/);
var res: string[] = [];
var i;
if (start) {
name = name.substring(0, name.length - start[0].length);
// FIXME
// @ts-expect-error what the heck is being passed into parseInt here?
for (i = parseInt(start); i <= range; i++) {
res.push(name + i);
}
} else {
res.push(name);
for (i = 2; i <= range; i++) {
res.push(name + i);
}
}
return res;
}
/**
* Recursive helper function that processes the cascaded data.
* @private
*/
function _processCascade(context, cascade, parentItem) {
const stackView = parentItem ? parentItem.view : null;
const subViews: any[] = [];
let curViews: any[] = [];
let subView;
if (stackView) {
cascade.push({view: stackView});
curViews.push(stackView);
}
for (var i = 0; i < cascade.length; i++) {
let item = cascade[i];
if (
(!Array.isArray(item) && item.hasOwnProperty('view')) ||
(Array.isArray(item) && item[0].view && !item[0].relation)
) {
const items = Array.isArray(item) ? item : [item];
for (var z = 0; z < items.length; z++) {
item = items[z];
const viewRange = item === ',' ? [] : item.view ? _getRange(item.view, item.range) : [null];
for (var r = 0; r < viewRange.length; r++) {
const curView = viewRange[r];
curViews.push(curView);
//
// Add this view to the collection of subViews
//
if (curView !== stackView) {
subViews.push(curView);
// FIXME
// @ts-expect-error
subView = context.subViews[curView];
if (!subView) {
subView = {orientations: 0};
// FIXME
// @ts-expect-error
context.subViews[curView] = subView;
}
subView.orientations = subView.orientations | context.orientation;
if (subView.stack) {
_processStackView(context, curView, subView);
}
}
//
// Process the relationship between this and the previous views
//
if (context.prevViews !== undefined && curView !== undefined && context.relation) {
if (context.relation.relation !== 'none') {
for (var p = 0; p < context.prevViews.length; p++) {
const prevView = context.prevViews[p];
switch (context.orientation) {
case Orientation.HORIZONTAL:
context.prevAttr = prevView !== stackView ? Attribute.RIGHT : Attribute.LEFT;
context.curAttr = curView !== stackView ? Attribute.LEFT : Attribute.RIGHT;
break;
case Orientation.VERTICAL:
context.prevAttr = prevView !== stackView ? Attribute.BOTTOM : Attribute.TOP;
context.curAttr = curView !== stackView ? Attribute.TOP : Attribute.BOTTOM;
break;
case Orientation.ZINDEX:
context.prevAttr = Attribute.ZINDEX;
context.curAttr = Attribute.ZINDEX;
context.relation.constant = !prevView
? 0
: context.relation.constant || 'default';
break;
}
context.constraints.push({
view1: prevView,
attr1: context.prevAttr,
relation: context.relation.relation,
view2: curView,
attr2: context.curAttr,
multiplier: context.relation.multiplier,
constant:
context.relation.constant === 'default' || !context.relation.constant
? context.relation.constant
: -context.relation.constant,
priority: context.relation.priority,
});
}
}
}
//
// Process view size constraints
//
const constraints = item.constraints;
if (constraints) {
for (var n = 0; n < constraints.length; n++) {
context.prevAttr = context.horizontal ? Attribute.WIDTH : Attribute.HEIGHT;
context.curAttr =
constraints[n].view || constraints[n].multiplier
? constraints[n].attribute || context.prevAttr
: constraints[n].variable
? Attribute.VARIABLE
: Attribute.CONST;
context.constraints.push({
view1: curView,
attr1: context.prevAttr,
relation: constraints[n].relation,
view2: constraints[n].view,
attr2: context.curAttr,
multiplier: constraints[n].multiplier,
constant: constraints[n].constant,
priority: constraints[n].priority,
});
}
}
//
// Process cascaded data (child stack-views)
//
if (item.cascade) {
_processCascade(context, item.cascade, item);
}
}
}
} else if (item !== ',') {
context.prevViews = curViews;
curViews = [];
context.relation = item[0];
if (context.prevViews !== undefined) {
if (context.relation.equalSpacing) {
_processEqualSpacer(context, stackView);
}
if (context.relation.multiplier) {
_processProportionalSpacer(context, stackView);
}
}
}
}
if (stackView) {
subView = context.subViews[stackView];
if (!subView) {
subView = {orientations: context.orientation};
context.subViews[stackView] = subView;
} else if (subView.stack) {
const err = new Error('A stack named "' + stackView + '" has already been created');
// FIXME
// @ts-expect-error
err.column = parentItem.$parserOffset + 1;
throw err;
}
subView.stack = {
orientation: context.orientation,
processedOrientations: context.orientation,
subViews: subViews,
};
_processStackView(context, stackView, subView);
}
}
const metaInfoCategories = ['viewport', 'spacing', 'colors', 'shapes', 'widths', 'heights'];
/**
* VisualFormat
*
* @namespace VisualFormat
*/
class VisualFormat {
/**
* Parses a single line of vfl into an array of constraint definitions.
*
* When the visual-format could not be succesfully parsed an exception is thrown containing
* additional info about the parse error and column position.
*
* @param {String} visualFormat Visual format string (cannot contain line-endings!).
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.extended] When set to true uses the extended syntax (default: false).
* @param {String} [options.outFormat] Output format (`constraints` or `raw`) (default: `constraints`).
* @param {Number} [options.lineIndex] Line-index used when auto generating equal-spacing constraints.
* @return {Array} Array of constraint definitions.
*/
static parseLine(visualFormat, options) {
if (visualFormat.length === 0 || (options && options.extended && visualFormat.indexOf('//') === 0)) {
return [];
}
const res = options && options.extended ? parserExt.parse(visualFormat) : parser.parse(visualFormat);
if (options && options.outFormat === 'raw') {
return [res];
}
let context: {
constraints: any[];
lineIndex: number;
subViews: {};
orientation?: number;
horizontal?: boolean;
} = {
constraints: [],
lineIndex: (options ? options.lineIndex : undefined) || 1,
subViews: (options ? options.subViews : undefined) || {},
};
if (res.type === 'attribute') {
for (let n = 0; n < res.attributes.length; n++) {
const attr = res.attributes[n];
for (let m = 0; m < attr.predicates.length; m++) {
const predicate = attr.predicates[m];
context.constraints.push({
view1: res.view,
attr1: attr.attr,
relation: predicate.relation,
view2: predicate.view,
attr2: predicate.attribute || attr.attr,
multiplier: predicate.multiplier,
constant: predicate.constant,
priority: predicate.priority,
});
}
}
} else {
switch (res.orientation) {
case 'horizontal':
context.orientation = Orientation.HORIZONTAL;
context.horizontal = true;
_processCascade(context, res.cascade, null);
break;
case 'vertical':
context.orientation = Orientation.VERTICAL;
_processCascade(context, res.cascade, null);
break;
case 'horzvert':
context.orientation = Orientation.HORIZONTAL;
context.horizontal = true;
_processCascade(context, res.cascade, null);
context = {
constraints: context.constraints,
lineIndex: context.lineIndex,
subViews: context.subViews,
orientation: Orientation.VERTICAL,
};
_processCascade(context, res.cascade, null);
break;
case 'zIndex':
context.orientation = Orientation.ZINDEX;
_processCascade(context, res.cascade, null);
break;
}
}
return context.constraints;
}
/**
* Parses one or more visual format strings into an array of constraint definitions.
*
* When the visual-format could not be succesfully parsed an exception is thrown containing
* additional info about the parse error and column position.
*
* @param {String|Array} visualFormat One or more visual format strings.
* @param {Object} [options] Configuration options.
* @param {Boolean} [options.extended] When set to true uses the extended syntax (default: false).
* @param {Boolean} [options.strict] When set to false trims any leading/trailing spaces and ignores empty lines (default: true).
* @param {String} [options.lineSeparator] String that defines the end of a line (default `\n`).
* @param {String} [options.outFormat] Output format (`constraints` or `raw`) (default: `constraints`).
* @return {Array} Array of constraint definitions.
*/
static parse(visualFormat, options) {
const lineSeparator = options && options.lineSeparator ? options.lineSeparator : '\n';
if (!Array.isArray(visualFormat) && visualFormat.indexOf(lineSeparator) < 0) {
try {
return this.parseLine(visualFormat, options);
} catch (err) {
// @ts-ignore
err.source = visualFormat;
throw err;
}
}
// Decompose visual-format into an array of strings, and within those strings
// search for line-endings, and treat each line as a seperate visual-format.
visualFormat = Array.isArray(visualFormat) ? visualFormat : [visualFormat];
let lines;
let constraints: any[] = [];
let lineIndex = 0;
let line;
const parseOptions = {
lineIndex: lineIndex,
extended: options && options.extended,
strict: options && options.strict !== undefined ? options.strict : true,
outFormat: options ? options.outFormat : undefined,
subViews: {},
};
try {
for (var i = 0; i < visualFormat.length; i++) {
lines = visualFormat[i].split(lineSeparator);
for (var j = 0; j < lines.length; j++) {
line = lines[j];
lineIndex++;
parseOptions.lineIndex = lineIndex;
if (!parseOptions.strict) {
line = line.trim();
}
if (parseOptions.strict || line.length) {
constraints = constraints.concat(this.parseLine(line, parseOptions));
}
}
}
} catch (err) {
// @ts-ignore
err.source = line;
// @ts-ignore
err.line = lineIndex;
throw err;
}
return constraints;
}
/**
* Parses meta information from the comments in the VFL.
*
* Additional meta information can be specified in the comments
* for previewing and rendering purposes. For instance, the view-port
* aspect-ratio, sub-view widths and colors, can be specified. The
* following example renders three colored circles in the visual-format editor:
*
* ```vfl
* //viewport aspect-ratio:3/1 max-height:300
* //colors red:#FF0000 green:#00FF00 blue:#0000FF
* //shapes red:circle green:circle blue:circle
* H:|-[row:[red(green,blue)]-[green]-[blue]]-|
* V:|[row]|
* ```
*
* Supported categories and properties:
*
* |Category|Property|Example|
* |--------|--------|-------|
* |`viewport`|`aspect-ratio:{width}/{height}`|`//viewport aspect-ratio:16/9`|
* ||`width:[{number}/intrinsic]`|`//viewport width:10`|
* ||`height:[{number}/intrinsic]`|`//viewport height:intrinsic`|
* ||`min-width:{number}`|
* ||`max-width:{number}`|
* ||`min-height:{number}`|
* ||`max-height:{number}`|
* |`spacing`|`[{number}/array]`|`//spacing:8` or `//spacing:[10, 20, 5]`|
* |`widths`|`{view-name}:[{number}/intrinsic]`|`//widths subview1:100`|
* |`heights`|`{view-name}:[{number}/intrinsic]`|`//heights subview1:intrinsic`|
* |`colors`|`{view-name}:{color}`|`//colors redview:#FF0000 blueview:#00FF00`|
* |`shapes`|`{view-name}:[circle/square]`|`//shapes avatar:circle`|
*
* @param {String|Array} visualFormat One or more visual format strings.
* @param {Object} [options] Configuration options.
* @param {String} [options.lineSeparator] String that defines the end of a line (default `\n`).
* @param {String} [options.prefix] When specified, also processes the categories using that prefix (e.g. "-dev-viewport max-height:10").
* @return {Object} meta-info
*/
static parseMetaInfo(visualFormat, options?: any) {
const lineSeparator = options && options.lineSeparator ? options.lineSeparator : '\n';
const prefix = options ? options.prefix : undefined;
visualFormat = Array.isArray(visualFormat) ? visualFormat : [visualFormat];
const metaInfo: {
viewport?: Record<string, any>;
widths?: Record<string, any>;
heights?: Record<string, any>;
spacing?: any;
} = {};
var key;
for (var k = 0; k < visualFormat.length; k++) {
const lines = visualFormat[k].split(lineSeparator);
for (var i = 0; i < lines.length; i++) {
const line = lines[i];
for (var c = 0; c < metaInfoCategories.length; c++) {
for (var s = 0; s < (prefix ? 2 : 1); s++) {
const category = metaInfoCategories[c];
const prefixedCategory = (s === 0 ? '' : prefix) + category;
if (line.indexOf('//' + prefixedCategory + ' ') === 0) {
const items = line.substring(3 + prefixedCategory.length).split(' ');
for (var j = 0; j < items.length; j++) {
metaInfo[category] = metaInfo[category] || {};
const item = items[j].split(':');
const names = _getRange(item[0], true);
for (var r = 0; r < names.length; r++) {
metaInfo[category][names[r]] = item.length > 1 ? item[1] : '';
}
}
} else if (line.indexOf('//' + prefixedCategory + ':') === 0) {
metaInfo[category] = line.substring(3 + prefixedCategory.length);
}
}
}
}
}
if (metaInfo.viewport) {
const viewport = metaInfo.viewport;
var aspectRatio = viewport['aspect-ratio'];
if (aspectRatio) {
aspectRatio = aspectRatio.split('/');
viewport['aspect-ratio'] = parseInt(aspectRatio[0]) / parseInt(aspectRatio[1]);
}
if (viewport.height !== undefined) {
viewport.height = viewport.height === 'intrinsic' ? true : parseInt(viewport.height);
}
if (viewport.width !== undefined) {
viewport.width = viewport.width === 'intrinsic' ? true : parseInt(viewport.width);
}
if (viewport['max-height'] !== undefined) {
viewport['max-height'] = parseInt(viewport['max-height']);
}
if (viewport['max-width'] !== undefined) {
viewport['max-width'] = parseInt(viewport['max-width']);
}
if (viewport['min-height'] !== undefined) {
viewport['min-height'] = parseInt(viewport['min-height']);
}
if (viewport['min-width'] !== undefined) {
viewport['min-width'] = parseInt(viewport['min-width']);
}
}
if (metaInfo.widths) {
for (key in metaInfo.widths) {
const width = metaInfo.widths[key] === 'intrinsic' ? true : parseInt(metaInfo.widths[key]);
metaInfo.widths[key] = width;
// FIXME
// @ts-expect-error
if (width === undefined || isNaN(width)) {
delete metaInfo.widths[key];
}
}
}
if (metaInfo.heights) {
for (key in metaInfo.heights) {
const height = metaInfo.heights[key] === 'intrinsic' ? true : parseInt(metaInfo.heights[key]);
metaInfo.heights[key] = height;
// FIXME
// @ts-expect-error
if (height === undefined || isNaN(height)) {
delete metaInfo.heights[key];
}
}
}
if (metaInfo.spacing) {
const value = JSON.parse(metaInfo.spacing);
metaInfo.spacing = value;
if (Array.isArray(value)) {
for (var sIdx = 0, len = value.length; sIdx < len; sIdx++) {
if (isNaN(value[sIdx])) {
delete metaInfo.spacing;
break;
}
}
} else if (value === undefined || isNaN(value)) {
delete metaInfo.spacing;
}
}
return metaInfo;
}
}
export default VisualFormat; | the_stack |
import * as assert from 'assert';
import * as grpc from '@grpc/grpc-js';
import * as sinon from 'sinon';
import * as stripeState from '../../src/stripeWorkspaceState';
import * as vscode from 'vscode';
import {EventsResendRequest, EventsResendResponse} from '../../src/rpc/events_resend_pb';
import {TriggerRequest, TriggerResponse} from '../../src/rpc/trigger_pb';
import {TriggersListRequest, TriggersListResponse} from '../../src/rpc/triggers_list_pb';
import {Commands} from '../../src/commands';
import {NoOpTelemetry} from '../../src/telemetry';
import {StripeCLIClient} from '../../src/rpc/commands_grpc_pb';
import {StripeDaemon} from '../daemon/stripeDaemon';
import {StripeEvent} from '../../src/rpc/common_pb';
import {StripeTreeItem} from '../../src/stripeTreeItem';
import {SurveyPrompt} from '../../src/surveyPrompt';
import {mocks} from '../mocks/vscode';
const proxyquire = require('proxyquire');
const modulePath = '../../src/commands';
const setupProxies = (proxies: any) => proxyquire(modulePath, proxies);
suite('commands', function () {
this.timeout(20000);
let sandbox: sinon.SinonSandbox;
let extensionContext: vscode.ExtensionContext;
const terminal = <any>{
execute: (command: any, args: Array<string>) => {},
};
const telemetry = new NoOpTelemetry();
const stripeDaemon = <Partial<StripeDaemon>>{
setupClient: () => {},
};
const supportedEvents = ['a'];
const daemonClient = <Partial<StripeCLIClient>>{
triggersList: (
req: TriggersListRequest,
callback: (error: grpc.ServiceError | null, res: TriggersListResponse) => void,
) => {
callback(null, new TriggersListResponse());
},
trigger: (
req: TriggerRequest,
callback: (error: grpc.ServiceError | null, res: TriggerResponse) => void,
) => {
callback(null, new TriggerResponse());
},
eventsResend: (
req: EventsResendRequest,
callback: (error: grpc.ServiceError | null, res: EventsResendResponse) => void,
) => {
callback(null, new EventsResendResponse());
},
};
setup(() => {
sandbox = sinon.createSandbox();
extensionContext = {...mocks.extensionContextMock};
});
teardown(() => {
sandbox.restore();
});
suite('openTriggerEvent', () => {
let stripeOutputChannel: Partial<vscode.OutputChannel>;
setup(() => {
sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient);
stripeOutputChannel = {appendLine: (value: string) => {}, show: () => {}};
const mockTriggerResponse = new TriggerResponse();
mockTriggerResponse.setRequestsList(['fixture_1', 'fixture_2']);
sandbox
.stub(daemonClient, 'trigger')
.value(
(
req: TriggerRequest,
callback: (error: grpc.ServiceError | null, res: TriggerResponse) => void,
) => {
callback(null, mockTriggerResponse);
},
);
});
test('executes and records event', async () => {
const telemetrySpy = sandbox.spy(telemetry, 'sendEvent');
const mockTriggerListResp = new TriggersListResponse();
mockTriggerListResp.setEventsList(supportedEvents);
sandbox
.stub(daemonClient, 'triggersList')
.value(
(
req: TriggersListRequest,
callback: (error: grpc.ServiceError | null, res: TriggersListResponse) => void,
) => {
callback(null, mockTriggerListResp);
},
);
const commands = new Commands(telemetry, terminal, extensionContext);
commands.openTriggerEvent(extensionContext, <any>stripeDaemon, <any>stripeOutputChannel);
// Pick the first item on the list.
await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem');
const eventsInState = stripeState.getRecentEvents(extensionContext);
assert.deepStrictEqual(telemetrySpy.args[0], ['openTriggerEvent']);
assert.deepStrictEqual(eventsInState, supportedEvents);
});
test('uses fallback events list if fails to retrieve list through grpc', async () => {
const telemetrySpy = sandbox.spy(telemetry, 'sendEvent');
const err: Partial<grpc.ServiceError> = {
code: grpc.status.UNKNOWN,
details: 'An unknown error occurred',
};
sandbox
.stub(daemonClient, 'triggersList')
.value(
(
req: TriggersListRequest,
callback: (error: grpc.ServiceError | null, res: TriggersListResponse) => void,
) => {
callback(<any>err, new TriggersListResponse());
},
);
const fallbackEventsList = ['fall', 'back', 'list'];
const commands = new Commands(telemetry, terminal, extensionContext, fallbackEventsList);
commands.openTriggerEvent(extensionContext, <any>stripeDaemon, <any>stripeOutputChannel);
// Pick the first item on the list.
await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem');
const eventsInState = stripeState.getRecentEvents(extensionContext);
assert.deepStrictEqual(telemetrySpy.args[0], ['openTriggerEvent']);
assert.deepStrictEqual(eventsInState[0], 'fall');
});
test('writes stripe trigger output to output channel', async () => {
const appendSpy = sinon.spy(stripeOutputChannel, 'appendLine');
const mockResp = new TriggersListResponse();
mockResp.setEventsList(supportedEvents);
sandbox
.stub(daemonClient, 'triggersList')
.value(
(
req: TriggersListRequest,
callback: (error: grpc.ServiceError | null, res: TriggersListResponse) => void,
) => {
callback(null, mockResp);
},
);
const commands = new Commands(telemetry, terminal, extensionContext);
commands.openTriggerEvent(extensionContext, <any>stripeDaemon, <any>stripeOutputChannel);
// Pick the first item on the list.
await vscode.commands.executeCommand('workbench.action.acceptSelectedQuickOpenItem');
assert.deepStrictEqual(appendSpy.args[0], ['Triggering event a...']);
assert.deepStrictEqual(appendSpy.args[1], ['Ran fixture: fixture_1']);
assert.deepStrictEqual(appendSpy.args[2], ['Ran fixture: fixture_2']);
assert.deepStrictEqual(appendSpy.args[3], [
'Trigger succeeded! Check dashboard for event details.',
]);
});
});
suite('buildTriggerEventsList', () => {
test('returns all original events when no recent events', () => {
const getEventsStub = sandbox.stub(stripeState, 'getRecentEvents').returns([]);
const commands = new Commands(telemetry, terminal, extensionContext);
const supportedEvents = ['a', 'b', 'c', 'd', 'e'];
const events = commands.buildTriggerEventsList(supportedEvents, extensionContext);
assert.strictEqual(getEventsStub.calledOnce, true);
const labels = events.map((x) => x.label);
assert.deepStrictEqual(labels, supportedEvents);
});
test('returns recent events on top', () => {
const getEventsStub = sandbox.stub(stripeState, 'getRecentEvents').returns(['c']);
const commands = new Commands(telemetry, terminal, extensionContext);
const supportedEvents = ['a', 'b', 'c', 'd', 'e'];
const events = commands.buildTriggerEventsList(supportedEvents, extensionContext);
assert.strictEqual(getEventsStub.calledOnce, true);
const labels = events.map((x) => x.label);
assert.deepStrictEqual(labels, ['c', 'a', 'b', 'd', 'e']);
assert.strictEqual(events[0].description, 'recently triggered');
});
test('does not include events that are not supported', () => {
const getEventsStub = sandbox
.stub(stripeState, 'getRecentEvents')
.returns(['c', 'unsupported']);
const commands = new Commands(telemetry, terminal, extensionContext);
const supportedEvents = ['a', 'b', 'c', 'd', 'e'];
const events = commands.buildTriggerEventsList(supportedEvents, extensionContext);
assert.strictEqual(getEventsStub.calledOnce, true);
const labels = events.map((x) => x.label);
assert.deepStrictEqual(labels, ['c', 'a', 'b', 'd', 'e']);
assert.strictEqual(events[0].description, 'recently triggered');
});
});
suite('openSurvey', () => {
test('openSurvey saves survey prompt settings', () => {
sandbox.stub(vscode.env, 'openExternal');
// stub out osName
const osName = sandbox.stub().returns('testOS');
const module = setupProxies({'os-name': osName});
const surveyPrompt = new SurveyPrompt(extensionContext);
const promptSpy = sandbox.spy(surveyPrompt, 'updateSurveySettings');
const commands = new module.Commands(telemetry, terminal, extensionContext);
commands.openSurvey(surveyPrompt);
assert.strictEqual(promptSpy.calledOnce, true);
});
});
suite('resendTriggerEvent', () => {
let stripeOutputChannel: Partial<vscode.OutputChannel>;
setup(() => {
sandbox.stub(stripeDaemon, 'setupClient').resolves(daemonClient);
stripeOutputChannel = {appendLine: (value: string) => {}, show: () => {}};
});
test('resends event and displays output', async () => {
const appendSpy = sinon.spy(stripeOutputChannel, 'appendLine');
const telemetrySpy = sandbox.spy(telemetry, 'sendEvent');
// Mock event response
const eventId = 'evt_123';
const stripeEvent = new StripeEvent();
stripeEvent.setType('balance.available');
stripeEvent.setId(eventId);
const mockResendResponse = new EventsResendResponse();
mockResendResponse.setStripeEvent(stripeEvent);
sandbox
.stub(daemonClient, 'eventsResend')
.value(
(
req: EventsResendRequest,
callback: (error: grpc.ServiceError | null, res: EventsResendResponse) => void,
) => {
callback(null, mockResendResponse);
},
);
// Create treeItem
const treeItem = new StripeTreeItem('label');
treeItem.metadata = {id: eventId};
const commands = new Commands(telemetry, terminal, extensionContext);
await commands.resendEvent(treeItem, <any>stripeDaemon, <any>stripeOutputChannel);
assert.deepStrictEqual(telemetrySpy.args[0], ['resendEvent']);
assert.deepStrictEqual(appendSpy.args[0], [`Resending Event: ${eventId}...`]);
const reponseObject = JSON.parse(appendSpy.args[1][0]);
assert.deepStrictEqual(reponseObject.id, eventId);
});
test('outputs error and records if no event is returned from server', async () => {
const appendSpy = sinon.spy(stripeOutputChannel, 'appendLine');
const telemetrySpy = sandbox.spy(telemetry, 'sendEvent');
const mockResendResponse = new EventsResendResponse();
sandbox
.stub(daemonClient, 'eventsResend')
.value(
(
req: EventsResendRequest,
callback: (error: grpc.ServiceError | null, res: EventsResendResponse) => void,
) => {
callback(null, mockResendResponse);
},
);
// Create treeItem
const treeItem = new StripeTreeItem('label');
treeItem.metadata = {id: '1223'};
const commands = new Commands(telemetry, terminal, extensionContext);
await commands.resendEvent(treeItem, <any>stripeDaemon, <any>stripeOutputChannel);
assert.deepStrictEqual(telemetrySpy.args[0], ['resendEvent']);
assert.deepStrictEqual(telemetrySpy.args[1], ['noResponseFromResendEvent']);
assert.deepStrictEqual(appendSpy.args[1], ['Error: Did not get event back from server.']);
});
test('surfaces error from server', async () => {
const windowSpy = sandbox.spy(vscode.window, 'showErrorMessage');
const erroMessage = 'Something went wrong';
const error = <grpc.ServiceError>{details: erroMessage};
sandbox
.stub(daemonClient, 'eventsResend')
.value(
(
req: EventsResendRequest,
callback: (error: grpc.ServiceError | null, res: EventsResendResponse) => void,
) => {
callback(error, new EventsResendResponse());
},
);
const treeItem = new StripeTreeItem('label');
treeItem.metadata = {id: '1234'};
const commands = new Commands(telemetry, terminal, extensionContext);
await commands.resendEvent(treeItem, <any>stripeDaemon, <any>stripeOutputChannel);
assert.deepStrictEqual(windowSpy.args[0], [`Failed to resend event: 1234. ${erroMessage}`]);
});
});
}); | the_stack |
import { expect } from "chai";
import { ICellCoordinates, IFocusedCellCoordinates } from "../../../src/common/cell";
import * as FocusedCellUtils from "../../../src/common/internal/focusedCellUtils";
import { IRegion, Regions } from "../../../src/regions";
describe("FocusedCellUtils", () => {
describe("expandFocusedRegion", () => {
const FOCUSED_ROW = 3;
const FOCUSED_COL = 3;
const PREV_ROW = FOCUSED_ROW - 2;
const NEXT_ROW = FOCUSED_ROW + 2;
const PREV_COL = FOCUSED_COL - 2;
const NEXT_COL = FOCUSED_COL + 2;
const focusedCell = toCellCoords(FOCUSED_ROW, FOCUSED_COL);
// shorthand
const fn = FocusedCellUtils.expandFocusedRegion;
describe("Expands to a FULL_ROWS selection", () => {
it("upward", () => {
const newRegion = Regions.row(PREV_ROW);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.row(PREV_ROW, FOCUSED_COL));
});
it("downward", () => {
const newRegion = Regions.row(NEXT_ROW);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.row(FOCUSED_ROW, NEXT_ROW));
});
it("same row", () => {
const newRegion = Regions.row(FOCUSED_ROW);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.row(FOCUSED_ROW, FOCUSED_COL));
});
});
describe("Expands to a FULL_COLUMNS selection", () => {
it("leftward", () => {
const newRegion = Regions.column(PREV_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.column(PREV_COL, FOCUSED_COL));
});
it("rightward", () => {
const newRegion = Regions.column(NEXT_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.column(FOCUSED_COL, NEXT_COL));
});
it("same column", () => {
const newRegion = Regions.column(FOCUSED_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.column(FOCUSED_COL, FOCUSED_COL));
});
});
describe("Expands to a CELLS selection", () => {
it("toward top-left", () => {
const newRegion = Regions.cell(PREV_ROW, PREV_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(PREV_ROW, PREV_COL, FOCUSED_ROW, FOCUSED_COL));
});
it("toward top", () => {
const newRegion = Regions.cell(FOCUSED_ROW, PREV_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, PREV_COL, FOCUSED_ROW, FOCUSED_COL));
});
it("toward top-right", () => {
const newRegion = Regions.cell(PREV_ROW, NEXT_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(PREV_ROW, FOCUSED_COL, FOCUSED_ROW, NEXT_COL));
});
it("toward right", () => {
const newRegion = Regions.cell(FOCUSED_ROW, NEXT_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, FOCUSED_COL, FOCUSED_ROW, NEXT_COL));
});
it("toward bottom-right", () => {
const newRegion = Regions.cell(NEXT_ROW, NEXT_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, FOCUSED_COL, NEXT_ROW, NEXT_COL));
});
it("toward bottom", () => {
const newRegion = Regions.cell(NEXT_ROW, FOCUSED_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, FOCUSED_COL, NEXT_ROW, FOCUSED_COL));
});
it("toward bottom-left", () => {
const newRegion = Regions.cell(NEXT_ROW, PREV_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, PREV_COL, NEXT_ROW, FOCUSED_COL));
});
it("toward left", () => {
const newRegion = Regions.cell(FOCUSED_ROW, PREV_COL);
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.cell(FOCUSED_ROW, PREV_COL, FOCUSED_ROW, FOCUSED_COL));
});
});
it("Expands to a FULL_TABLE selection", () => {
const newRegion = Regions.table();
const result = fn(focusedCell, newRegion);
checkEqual(result, Regions.table());
});
function checkEqual(result: IRegion, expected: IRegion) {
expect(result).to.deep.equal(expected);
}
function toCellCoords(row: number, col: number): IFocusedCellCoordinates {
return { row, col, focusSelectionIndex: 0 };
}
});
describe("getFocusedOrLastSelectedIndex", () => {
const fn = FocusedCellUtils.getFocusedOrLastSelectedIndex;
it("always returns `undefined` if selectedRegions is empty", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({ row: 0, col: 0 });
expect(fn([], undefined)).to.equal(undefined);
expect(fn([], focusedCell)).to.equal(undefined);
});
it("returns selectedRegions's last index if focused cell not defined", () => {
const selectedRegions = [Regions.row(0), Regions.row(1), Regions.row(3)];
const lastIndex = selectedRegions.length - 1;
expect(fn(selectedRegions, undefined)).to.deep.equal(lastIndex);
});
it("returns focusSelectionIndex if focused cell is defined", () => {
const INDEX = 1;
const selectedRegions = [Regions.row(0), Regions.row(1), Regions.row(3)];
const focusedCell = { row: 0, col: 0, focusSelectionIndex: INDEX };
expect(fn(selectedRegions, focusedCell)).to.deep.equal(INDEX);
});
});
describe("getInitialFocusedCell", () => {
const FOCUSED_CELL_FROM_PROPS = getFocusedCell(1, 2);
const FOCUSED_CELL_FROM_STATE = getFocusedCell(3, 4);
const SELECTED_REGIONS = [Regions.cell(1, 1, 4, 5), Regions.cell(5, 1, 6, 2)];
it("returns undefined if enableFocusedCell=false", () => {
const focusedCell = FocusedCellUtils.getInitialFocusedCell(
false,
FOCUSED_CELL_FROM_PROPS,
FOCUSED_CELL_FROM_STATE,
SELECTED_REGIONS,
);
expect(focusedCell).to.be.undefined;
});
it("returns the focusedCellFromProps if defined", () => {
const focusedCell = FocusedCellUtils.getInitialFocusedCell(
true,
FOCUSED_CELL_FROM_PROPS,
FOCUSED_CELL_FROM_STATE,
SELECTED_REGIONS,
);
expect(focusedCell).to.deep.equal(FOCUSED_CELL_FROM_PROPS);
});
it("returns the focusedCellFromState if focusedCellFromProps not defined", () => {
const focusedCell = FocusedCellUtils.getInitialFocusedCell(
true,
null,
FOCUSED_CELL_FROM_STATE,
SELECTED_REGIONS,
);
expect(focusedCell).to.deep.equal(FOCUSED_CELL_FROM_STATE);
});
it("returns the focused cell for the last selected region if focusedCell not provided", () => {
const focusedCell = FocusedCellUtils.getInitialFocusedCell(true, null, null, SELECTED_REGIONS);
const lastIndex = SELECTED_REGIONS.length - 1;
const expectedFocusedCell = {
...Regions.getFocusCellCoordinatesFromRegion(SELECTED_REGIONS[lastIndex]),
focusSelectionIndex: lastIndex,
};
expect(focusedCell).to.deep.equal(expectedFocusedCell);
});
it("returns cell (0, 0) if nothing else is defined", () => {
const focusedCell = FocusedCellUtils.getInitialFocusedCell(true, null, null, []);
const expectedFocusedCell = {
col: 0,
focusSelectionIndex: 0,
row: 0,
};
expect(focusedCell).to.deep.equal(expectedFocusedCell);
});
function getFocusedCell(row: number, col: number, focusSelectionIndex: number = 0): IFocusedCellCoordinates {
return { row, col, focusSelectionIndex };
}
});
describe("itFocusedCellAtRegion___", () => {
const ROW_START = 3;
const ROW_END = 5;
const COL_START = 4;
const COL_END = 6;
const cellRegion = Regions.cell(ROW_START, COL_START, ROW_END, COL_END);
const columnRegion = Regions.column(COL_START, COL_END);
const rowRegion = Regions.row(ROW_START, ROW_END);
const tableRegion = Regions.table();
describe("isFocusedCellAtRegionTop", () => {
const fn = FocusedCellUtils.isFocusedCellAtRegionTop;
describe("CELLS region", () => {
it("returns true if focused cell at region top and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns true if focused cell at region top and not inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END + 1,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region top", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START + 1,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.false;
});
});
describe("FULL_COLUMNS region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END + 1,
});
const focusedCell3 = FocusedCellUtils.toFullCoordinates({
row: ROW_START + 1,
col: COL_START,
});
expect(fn(columnRegion, focusedCell1)).to.be.false;
expect(fn(columnRegion, focusedCell2)).to.be.false;
expect(fn(columnRegion, focusedCell3)).to.be.false;
});
});
describe("FULL_ROWS region", () => {
it("returns true if focused cell at region top and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(rowRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region top", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START + 1,
col: COL_START,
});
expect(fn(rowRegion, focusedCell)).to.be.false;
});
});
describe("FULL_TABLE region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({ row: 0, col: 0 });
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(tableRegion, focusedCell1)).to.be.false;
expect(fn(tableRegion, focusedCell2)).to.be.false;
});
});
});
describe("isFocusedCellAtRegionBottom", () => {
const fn = FocusedCellUtils.isFocusedCellAtRegionBottom;
describe("CELLS region", () => {
it("returns true if focused cell at region bottom and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns true if focused cell at region bottom and not inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_END + 1,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region bottom", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END - 1,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.false;
});
});
describe("FULL_COLUMNS region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_START,
});
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_END + 1,
});
const focusedCell3 = FocusedCellUtils.toFullCoordinates({
row: ROW_END - 1,
col: COL_START,
});
expect(fn(columnRegion, focusedCell1)).to.be.false;
expect(fn(columnRegion, focusedCell2)).to.be.false;
expect(fn(columnRegion, focusedCell3)).to.be.false;
});
});
describe("FULL_ROWS region", () => {
it("returns true if focused cell at region bottom and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_START,
});
expect(fn(rowRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region bottom", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END + 1,
col: COL_START,
});
expect(fn(rowRegion, focusedCell)).to.be.false;
});
});
describe("FULL_TABLE region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({ row: 0, col: 0 });
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_END,
col: COL_START,
});
expect(fn(tableRegion, focusedCell1)).to.be.false;
expect(fn(tableRegion, focusedCell2)).to.be.false;
});
});
});
describe("isFocusedCellAtRegionLeft", () => {
const fn = FocusedCellUtils.isFocusedCellAtRegionLeft;
describe("CELLS region", () => {
it("returns true if focused cell at region left and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns true if focused cell at region left and not inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END + 1,
col: COL_START,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region left", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START + 1,
});
expect(fn(cellRegion, focusedCell)).to.be.false;
});
});
describe("FULL_COLUMNS region", () => {
it("returns true if focused cell at region left and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(columnRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region left", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START + 1,
});
expect(fn(columnRegion, focusedCell)).to.be.false;
});
});
describe("FULL_ROWS region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_END + 1,
col: COL_START,
});
const focusedCell3 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START + 1,
});
expect(fn(rowRegion, focusedCell1)).to.be.false;
expect(fn(rowRegion, focusedCell2)).to.be.false;
expect(fn(rowRegion, focusedCell3)).to.be.false;
});
});
describe("FULL_TABLE region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({ row: 0, col: 0 });
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_START,
});
expect(fn(tableRegion, focusedCell1)).to.be.false;
expect(fn(tableRegion, focusedCell2)).to.be.false;
});
});
});
describe("isFocusedCellAtRegionRight", () => {
const fn = FocusedCellUtils.isFocusedCellAtRegionRight;
describe("CELLS region", () => {
it("returns true if focused cell at region right and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns true if focused cell at region right and not inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_END + 1,
col: COL_END,
});
expect(fn(cellRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region right", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END - 1,
});
expect(fn(cellRegion, focusedCell)).to.be.false;
});
});
describe("FULL_COLUMNS region", () => {
it("returns true if focused cell at region right and inside region", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END,
});
expect(fn(columnRegion, focusedCell)).to.be.true;
});
it("returns false if focused cell not at region right", () => {
const focusedCell = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END - 1,
});
expect(fn(columnRegion, focusedCell)).to.be.false;
});
});
describe("FULL_ROWS region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END,
});
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_END + 1,
col: COL_END,
});
const focusedCell3 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END - 1,
});
expect(fn(rowRegion, focusedCell1)).to.be.false;
expect(fn(rowRegion, focusedCell2)).to.be.false;
expect(fn(rowRegion, focusedCell3)).to.be.false;
});
});
describe("FULL_TABLE region", () => {
it("always returns false", () => {
const focusedCell1 = FocusedCellUtils.toFullCoordinates({ row: 0, col: 0 });
const focusedCell2 = FocusedCellUtils.toFullCoordinates({
row: ROW_START,
col: COL_END,
});
expect(fn(tableRegion, focusedCell1)).to.be.false;
expect(fn(tableRegion, focusedCell2)).to.be.false;
});
});
});
});
describe("toFullCoordinates", () => {
it("applies focusSelectionIndex=0 by default", () => {
const cellCoords: ICellCoordinates = { row: 2, col: 3 };
const result = FocusedCellUtils.toFullCoordinates(cellCoords);
expect(result).to.deep.equal({ ...result, focusSelectionIndex: 0 });
});
it("applies a custom focusSelectionIndex if provided", () => {
const cellCoords: ICellCoordinates = { row: 2, col: 3 };
const INDEX = 1;
const result = FocusedCellUtils.toFullCoordinates(cellCoords, INDEX);
expect(result).to.deep.equal({ ...result, focusSelectionIndex: INDEX });
});
});
}); | the_stack |
declare module sequelize
{
interface SequelizeStaticAndInstance {
/**
* A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want
* to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in
* your project.
*/
Utils:Utils;
/**
* A modified version of bluebird promises, that allows listening for sql events.
*
* @see Promise
*/
Promise:Promise;
/**
* Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed
* both on the instance, and on the constructor.
*
* @see Validator
*/
Validator:Validator;
QueryTypes:QueryTypes;
/**
* A general error class.
*/
Error:Error;
/**
* Emitted when a validation fails.
*
* @see ValidationError
*/
ValidationError:ValidationError;
/**
* Creates a object representing a database function. This can be used in search queries, both in where and order
* parts, and as default values in column definitions. If you want to refer to columns in your function, you should
* use sequelize.col, so that the columns are properly interpreted as columns and not a strings.
*
* @param fn The function you want to call.
* @param args All further arguments will be passed as arguments to the function.
*/
fn(fn:string, ...args:Array<any>):any;
/**
* Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since
* raw string arguments to fn will be escaped.
*
* @param col The name of the column
*/
col(col:string):Col;
/**
* Creates a object representing a call to the cast function.
*
* @param val The value to cast.
* @param type The type to cast it to.
*/
cast(val:any, type:string):Cast;
/**
* Creates a object representing a literal, i.e. something that will not be escaped.
*
* @param val Value to convert to a literal.
*/
literal(val:any):Literal;
/**
* An AND query.
*
* @param args Each argument (string or object) will be joined by AND.
*/
and(...args:Array<any>):And;
/**
* An OR query.
*
* @param args Each argument (string or object) will be joined by OR.
*/
or(...args:Array<any>):Or;
/**
* A way of specifying attr = condition. Mostly used internally.
*
* @param attr The attribute
* @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.)
*/
where(attr:string, condition:any):Where;
}
interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes {
/**
* Instantiate sequelize with name of database and username
* @param database database name
* @param username user name
*/
new(database:string, username:string):Sequelize;
/**
* Instantiate sequelize with name of database, username and password
* @param database database name
* @param username user name
* @param password password
*/
new(database:string, username:string, password:string):Sequelize;
/**
* Instantiate sequelize with name of database, username, password, and options.
* @param database database name
* @param username user name
* @param password password
* @param options options. @see Options
*/
new(database:string, username:string, password:string, options:Options):Sequelize;
/**
* Instantiate sequelize with name of database, username, and options.
*
* @param database database name
* @param username user name
* @param options options. @see Options
*/
new(database:string, username:string, options:Options):Sequelize;
/**
* Instantiate sequlize with an URI
* @param connectionString A full database URI
* @param options Options for sequelize. @see Options
*/
new(connectionString:string, options?:Options):Sequelize;
}
interface Sequelize extends SequelizeStaticAndInstance {
/**
* Sequelize configuration (undocumented).
*/
config:Config;
/**
* Sequelize options (undocumented).
*/
options:Options;
/**
* Models are stored here under the name given to sequelize.define
*/
models:Array<Model<any, any>>;
modelManager:ModelManager;
daoFactoryManager: ModelManager;
transactionManager: TransactionManager;
importCache:any;
/**
* A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction.
*
* @see Transaction
*/
Transaction:TransactionStatic;
/**
* Returns the specified dialect.
*/
getDialect():string;
/**
* Returns the singleton instance of QueryInterface.
*/
getQueryInterface():QueryInterface;
/**
* Returns the singleton instance of Migrator.
* @param options Migration options
* @param force A flag that defines if the migrator should get instantiated or not.
*/
getMigrator(options?:MigratorOptions, force?:boolean):Migrator;
/**
* Define a new model, representing a table in the DB.
*
* @param daoName The name of the entity (table). Typically specified in singular form.
* @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute
* or can be an object defining the attribute and its options. Note attributes is not fully
* typed since TypeScript does not support union types--it can be either a string or an
* options object. @see AttributeOptions.
* @param options Table options. @see DefineOptions.
*/
define<TInstance, TPojo>(daoName:string, attributes:any, options?:DefineOptions):Model<TInstance, TPojo>;
/**
* Fetch a DAO factory which is already defined.
*
* @param daoName The name of a model defined with Sequelize.define.
*/
model<TInstance, TPojo>(daoName:string):Model<TInstance, TPojo>;
/**
* Checks whether a model with the given name is defined.
*
* @param daoName The name of a model defined with Sequelize.define.
*/
isDefined(daoName:string):boolean;
/**
* Imports a model defined in another file.
*
* @param path The path to the file that holds the model you want to import. If the part is relative, it will be
* resolved relatively to the calling file
*/
import<TInstance, TPojo>(path:string):Model<TInstance, TPojo>;
/**
* Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
*
* @param sql SQL statement to execute.
*
* @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented
* by the factory. Equivalent to calling Model.build with the values provided by the query.
*
* @param options Query options.
*
* @param replacements Either an object of named parameter replacements in the format :param or an array of
* unnamed replacements to replace ? in your SQL.
*/
query(sql:string, callee?:Function, options?:QueryOptions, replacements?:any):EventEmitter;
/**
* Create a new database schema.
*
* @param schema Name of the schema.
*/
createSchema(schema:string):EventEmitter;
/**
* Show all defined schemas.
*/
showAllSchemas():EventEmitter;
/**
* Drop a single schema.
*
* @param schema Name of the schema.
*/
dropSchema(schema):EventEmitter;
/**
* Drop all schemas.
*/
dropAllSchemas():EventEmitter;
/**
* Sync all defined DAOs to the DB.
*
* @param options Options.
*/
sync(options?:SyncOptions):EventEmitter;
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model.
*
* @param options The options passed to each call to Model.drop.
*/
drop(options:DropOptions):EventEmitter;
/**
* Test the connection by trying to authenticate. Alias for 'validate'.
*/
authenticate():EventEmitter;
/**
* Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'.
*/
validate():EventEmitter;
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order
* for the query to happen under that transaction.
*
* @param callback Called when the transaction has been set up and is ready for use. Callback takes error and
* transaction arguments (overload available for just transaction argument too).
*/
transaction(callback:(err:Error, transaction:Transaction) => void):Transaction;
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order
* for the query to happen under that transaction.
*
* @param options Transaction options.
* @param callback Called when the transaction has been set up and is ready for use. Callback takes error and
* transaction arguments (overload available for just transaction argument too).
*/
transaction(options:TransactionOptions, callback:(err:Error, transaction:Transaction) => void):Transaction;
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order
* for the query to happen under that transaction.
*
* @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction
* argument (overload available for error and transaction arguments too).
*/
transaction(callback:(transaction:Transaction) => void):Transaction;
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order
* for the query to happen under that transaction.
*
* @param options Transaction options.
* @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction
* argument (overload available for error and transaction arguments too).
*/
transaction(options?:TransactionOptions, callback?:(transaction:Transaction) => void):Transaction;
}
interface Config {
database?:string;
username?:string;
password?:string;
host?:string;
port?:number;
pool?:PoolOptions;
protocol?:string;
queue?:boolean;
native?:boolean;
ssl?:boolean;
replication?:ReplicationOptions;
dialectModulePath?:string;
maxConcurrentQueries?:number;
dialectOptions?:any;
}
interface Model<TInstance, TPojo> extends Hooks, Associations {
/**
* A reference to the sequelize instance.
*/
sequelize:Sequelize;
/**
* The name of the model, typically singular.
*/
name:string;
/**
* The name of the underlying database table, typically plural.
*/
tableName:string;
options:DefineOptions;
attributes:any;
rawAttributes:any;
modelManager:ModelManager;
daoFactoryManager:ModelManager;
associations:any;
scopeObj:any;
/**
* Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model
* instance (this).
*/
sync(options?:SyncOptions):PromiseT<Model<TInstance, TPojo>>;
/**
* Drop the table represented by this Model.
*
* @param options
*/
drop(options?:DropOptions):Promise;
/**
* Apply a schema to this model. For postgres, this will actually place the schema in front of the table name -
* "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite -
* 'schema.tablename'.
*
* @param schema The name of the schema.
* @param options Schema options.
*/
schema(schema:string, options?:SchemaOptions):Model<TInstance, TPojo>;
/**
* Get the tablename of the model, taking schema into account. The method will return The name as a string if the
* model has no schema, or an object with tableName, schema and delimiter properties.
*/
getTableName():any;
/**
* Apply a scope created in define to the model.
*
* @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of
* arguments. To apply simple scopes, pass them as strings. For scope function, pass an object,
* with a method property. The value can either be a string, if the method does not take any
* arguments, or an array, where the first element is the name of the method, and consecutive
* elements are arguments to that method. Pass null to remove all scopes, including the default.
*/
scope(options:any):Model<TInstance, TPojo>;
/**
* Search for multiple instances..
*
* @param options A hash of options to describe the scope of the search.
* @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built
* Instances. See sequelize.query for options.
*/
findAll(options?:FindOptions, queryOptions?:QueryOptions):PromiseT<Array<TInstance>>;
/**
* Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.
*
* @param options A hash of options to describe the scope of the search, or a number to search by id.
* @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built
* Instances. See sequelize.query for options
*/
find(options?:FindOptions, queryOptions?:QueryOptions):PromiseT<TInstance>;
/**
* Run an aggregation method on the specified field.
*
* @param field The field to aggregate over. Can be a field name or *.
* @param aggregateFunction The function to use for aggregation, e.g. sum, max etc.
* @param options Query options, particularly options.dataType.
*/
aggregate<V>(field:string, aggregateFunction:string, options:FindOptions):PromiseT<V>;
/**
* Count the number of records matching the provided where clause.
*
* @param options Conditions and options for the query.
*/
count(options?:FindOptions):PromiseT<number>;
/**
* Find all the rows matching your query, within a specified offset / limit, and get the total number of rows
* matching your query. This is very usefull for paging.
*
* @param findOptions Filtering options
* @param queryOptions Query options
*/
findAndCountAll(findOptions?:FindOptions, queryOptions?:QueryOptions):PromiseT<FindAndCountResult<TInstance>>;
/**
* Find the maximum value of field.
*
* @param field
* @param options
*/
max<V>(field:string, options?:FindOptions):PromiseT<V>;
/**
* Find the minimum value of field.
*
* @param field
* @param options
*/
min<V>(field:string, options?:FindOptions):PromiseT<V>;
/**
* Find the sum of field.
*
* @param field
* @param options
*/
sum(field:string, options?:FindOptions):PromiseT<number>;
/**
* Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
*
* @param values any from which to build entity instance.
* @param options any construction options.
*/
build(values:TPojo, options?:BuildOptions):TInstance;
/**
* Builds a new model instance and calls save on it..
*
* @param values
* @param options
*/
create(values:TPojo, options?:CopyOptions):PromiseT<TInstance>;
/**
* Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result
* of the promise will be (instance, initialized) - Make sure to use .spread().
*
* @param where A hash of search attributes. Note that this method differs from finders, in that the syntax
* is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0
* @param defaults Default values to use if building a new instance
* @param options Options passed to the find call
*/
findOrInitialize(where:any, defaults?:TPojo, options?:QueryOptions):PromiseT<TInstance>;
/**
* Find a row that matches the query, or build and save the row if none is found The successfull result of the
* promise will be (instance, created) - Make sure to use .spread().
*
* @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is
* { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0
* @param defaults Default values to use if creating a new instance
* @param options Options passed to the find and create calls.
*/
findOrCreate(where:any, defaults?:TPojo, options?:FindOrCreateOptions):PromiseT<TInstance>;
/**
* Create and insert multiple instances in bulk.
*
* @param records List of objects (key/value pairs) to create instances from.
* @param options
*/
bulkCreate(records:Array<TPojo>, options?:BulkCreateOptions):PromiseT<Array<TInstance>>;
/**
* Delete multiple instances.
*/
destroy(where?:any, options?:DestroyOptions):Promise;
/**
* Update multiple instances that match the where options.
*
* @param attrValueHash A hash of fields to change and their new values
* @param where Options to describe the scope of the search. Note that these options are not wrapped in a
* { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0.
*/
update(attrValueHash:TPojo, where:any, options?:UpdateOptions):Promise;
/**
* Run a describe query on the table. The result will be return to the listener as a hash of attributes and their
* types.
*/
describe():PromiseT<any>;
/**
* A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls.
* The returned instance already has all the fields property populated with the field of the model.
*/
dataset():any;
}
interface Instance<TInstance, TPojo> {
/**
* Returns true if this instance has not yet been persisted to the database.
*/
isNewRecord:boolean;
/**
* Returns the Model the instance was created from.
*/
Model:Model<TInstance, TPojo>;
/**
* A reference to the sequelize instance.
*/
sequelize:Sequelize;
/**
* If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set.
* Otherwise, always returns false.
*/
isDeleted:boolean;
/**
* Get the values of this Instance. Proxies to this.get.
*/
values:TPojo;
/**
* A getter for this.changed(). Returns true if any keys have changed.
*/
isDirty:Boolean;
/**
* Get the values of the primary keys of this instance.
*/
primaryKeyValues:TPojo;
/**
* Get the value of the underlying data value.
*
* @param key Field to retrieve.
*/
getDataValue(key:string):any;
/**
* Update the underlying data value.
*
* @param key Field to set.
* @param value Value to set.
*/
setDataValue(key:string, value:any):void;
/**
* Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also
* invoking virtual getters.
*/
get(key?:string):any;
/**
* Set is used to update values on the instance (the sequelize representation of the instance that is, remember
* that nothing will be persisted before you actually call save).
*/
set(key:string, value:any, options?:SetOptions):void;
/**
* If changed is called with a string it will return a boolean indicating whether the value of that key in
* dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will
* return an array of keys that have changed.
*/
changed(key?:string):any;
/**
* Returns the previous value for key from _previousDataValues.
*/
previous(key:string):any;
/**
* Validate this instance, and if the validation passes, persist it to the database.
*/
save(fields?:Array<string>, options?:SaveOptions):PromiseT<TInstance>;
/**
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same
* object. This is different from doing a find(Instance.id), because that would create and return a new instance.
* With this method, all references to the Instance are updated with the new data and no new objects are created.
*/
reload(options?:FindOptions):PromiseT<TInstance>;
/**
* Validate the attribute of this instance according to validation rules set in the model definition.
*/
validate(options?:ValidateOptions):PromiseT<Error>;
/**
* This is the same as calling setAttributes, then calling save.
*/
updateAttributes(updates:TPojo, options:SaveOptions):PromiseT<TInstance>;
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be
* completely deleted, or have its deletedAt timestamp set to the current time.
*
* @param options Allows caller to specify if delete should be forced.
*/
destroy(options?:DestroyInstanceOptions):Promise;
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use the
* values currently stored on the Instance.
*
* @param fields If a string is provided, that column is incremented by the value of by given in options. If an
* array is provided, the same is true for each column. If and object is provided, each column is
* incremented by the value given.
* @param options Increment options.
*/
increment(fields:any, options?:IncrementOptions):Promise;
/**
* Decrement the value of one or more columns. This is done in the database, which means it does not use the
* values currently stored on the Instance.
*
* @param fields If a string is provided, that column is decremented by the value of by given in options. If an
* array is provided, the same is true for each column. If and object is provided, each column is
* decremented by the value given.
* @param options Decrement options.
*/
decrement(fields:any, options?:IncrementOptions):Promise;
/**
* Check whether all values of this and other Instance are the same.
*/
equal(other:TInstance):boolean;
/**
* Check if this is eqaul to one of others by calling equals.
*
* @param others Other instances to compare to.
*/
equalsOneOf(others:Array<TInstance>):boolean;
/**
* Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values
* gotten from the DB, and apply all custom getters.
*/
toJSON():TPojo;
}
interface Transaction extends TransactionStatic {
/**
* Commit the transaction.
*/
commit():Transaction;
/**
* Rollback (abort) the transaction.
*/
rollback():Transaction;
}
interface TransactionStatic {
/**
* The possible isolation levels to use when starting a transaction
*/
ISOLATION_LEVELS:TransactionIsolationLevels;
/**
* Possible options for row locking. Used in conjuction with find calls.
*/
LOCK:TransactionLocks;
}
interface TransactionIsolationLevels {
READ_UNCOMMITTED:string;// "READ UNCOMMITTED"
READ_COMMITTED:string; // "READ COMMITTED"
REPEATABLE_READ:string; // "REPEATABLE READ"
SERIALIZABLE:string; // "SERIALIZABLE"
}
interface TransactionLocks {
UPDATE:string; // UPDATE
SHARE:string; // SHARE
}
interface Hooks {
/**
* Add a named hook to the model.
*
* @param hooktype
*/
addHook(hooktype:string, name:string, fn:(...args:Array<any>) => void):boolean;
/**
* Add a hook to the model.
*
* @param hooktype
*/
addHook(hooktype:string, fn:(...args:Array<any>) => void):boolean;
/**
* A named hook that is run before validation.
*/
beforeValidate<T>(name:string, validator:(dao:T, callback:(err?:Error) => void) => void):void;
/**
* A hook that is run before validation.
*/
beforeValidate<T>(validator:(dao:T, callback:(err?:Error) => void) => void):void;
/**
* A named hook that is run before validation.
*/
afterValidate<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run before validation.
*/
afterValidate<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run before creating a single instance.
*/
beforeCreate<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run before creating a single instance.
*/
beforeCreate<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run after creating a single instance.
*/
afterCreate<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run after creating a single instance.
*/
afterCreate<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run before destroying a single instance.
*/
beforeDestroy<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run before destroying a single instance.
*/
beforeDestroy<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run after destroying a single instance.
*/
afterDestroy<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run after destroying a single instance.
*/
afterDestroy<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run before updating a single instance.
*/
beforeUpdate<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run before updating a single instance.
*/
beforeUpdate<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run after updating a single instance.
*/
afterUpdate<T>(name:string, validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run after updating a single instance.
*/
afterUpdate<T>(validator:(dao:T, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run before creating instances in bulk.
*/
beforeBulkCreate<T>(name:string, validator:(daos:Array<T>, fields:Array<string>, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run before creating instances in bulk.
*/
beforeBulkCreate<T>(validator:(daos:Array<T>, fields:Array<string>, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run after creating instances in bulk.
*/
afterBulkCreate<T>(name:string, validator:(daos:Array<T>, fields:Array<string>, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A hook that is run after creating instances in bulk.
*/
afterBulkCreate<T>(validator:(daos:Array<T>, fields:Array<string>, callback:(err?:Error, dao?:T) => void) => void):void;
/**
* A named hook that is run before destroying instances in bulk.
*/
beforeBulkDestroy<T>(name:string, validator:(where:any, callback:(err?:Error, where?:any) => void) => void):void;
/**
* A hook that is run before destroying instances in bulk.
*/
beforeBulkDestroy<T>(validator:(where:any, callback:(err?:Error, where?:any) => void) => void):void;
/**
* A named hook that is run after destroying instances in bulk.
*/
afterBulkDestroy<T>(name:string, validator:(where:any, callback:(err?:Error, where?:any) => void) => void):void;
/**
* A hook that is run after destroying instances in bulk.
*/
afterBulkDestroy<T>(validator:(where:any, callback:(err?:Error, where?:any) => void) => void):void;
/**
* A named hook that is run before updating instances in bulk.
*/
beforeBulkUpdate<T>(name:string, validator:(instances:Array<T>, where:any, callback:(err?:Error, instances?:Array<T>, where?:any) => void) => void):void;
/**
* A hook that is run before updating instances in bulk.
*/
beforeBulkUpdate<T>(validator:(instances:Array<T>, where:any, callback:(err?:Error, instances?:Array<T>, where?:any) => void) => void):void;
/**
* A named hook that is run after updating instances in bulk.
*/
afterBulkUpdate<T>(name:string, validator:(instances:Array<T>, where:any, callback:(err?:Error, instances?:Array<T>, where?:any) => void) => void):void;
/**
* A hook that is run after updating instances in bulk.
*/
afterBulkUpdate<T>(validator:(instances:Array<T>, where:any, callback:(err?:Error, instances?:Array<T>, where?:any) => void) => void):void;
}
interface Associations {
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the target.
*
* @param target
* @param options
*/
hasOne<TInstance, TPojo>(target:Model<TInstance, TPojo>, options?:AssociationOptions):void;
/**
* Creates an association between this (the source) and the provided target. The foreign key is added on the source.
*
* @param target
* @param options
*/
belongsTo<TInstance, TPojo>(target:Model<TInstance, TPojo>, options?:AssociationOptions):void;
/**
* Create an association that is either 1:m or n:m.
*
* @param target
* @param options
*/
hasMany<TInstance, TPojo>(target:Model<TInstance, TPojo>, options?:AssociationOptions):void;
}
/**
* Extension of external project that doesn't have definitions.
*
* See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js
*/
interface Validator {
}
/**
* Custom class defined, but no extra methods or functionality even.
*/
interface ValidationError extends Error {
}
interface QueryChainer {
/**
* Add an query to the chainer. This can be done in two ways - either by invoking the method like you would
* normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a
* method on, the name of the method, and its parameters to the chainer. The second form might sound a bit
* cumbersome, but it is used when you want to run queries in serial.
*
* @param emitterOrKlass
* @param method
* @param params
* @param options
*/
add(emitterOrKlass:any, method?:string, params?:any, options?:any):QueryChainer;
/**
* Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries
* began executing as soon as you invoked their methods.
*/
run():EventEmitter;
/**
* Run the chainer serially, so that each query waits for the previous one to finish before it starts.
*
* @param options @see QueryChainerRunSeriallyOptions
*/
runSerially(options?:QueryChainerRunSeriallyOptions):EventEmitter;
}
interface QueryInterface {
/**
* Returns the dialect-specific sql generator.
*/
QueryGenerator:QueryGenerator;
/**
* Queries the schema (table list).
*
* @param schema The schema to query. Applies only to Postgres.
*/
createSchema(schema?:string):EventEmitter;
/**
* Drops the specified schema (table).
*
* @param schema The name of the table to drop.
*/
dropSchema(schema:string):EventEmitter;
/**
* Drops all tables.
*/
dropAllSchemas():EventEmitter;
/**
* Queries all table names in the database.
*
* @param options
*/
showAllSchemas(options?:QueryOptions):EventEmitter;
/**
* Creates a table with specified attributes.
* @param tableName Name of table to create
* @param attributes Hash of attributes, key is attribute name, value is data type
* @param options Query options.
*
* @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite.
*/
createTable(tableName:string, attributes:any, options?:QueryOptions):any;
/**
* Drops the specified table.
*
* @param tableName Table name.
* @param options Query options, particularly "force".
*/
dropTable(tableName:string, options?:QueryOptions):EventEmitter;
dropAllTables(options?:QueryOptions):EventEmitter;
dropAllEnums(options?:QueryOptions):EventEmitter;
renameTable(before:string, after:string):EventEmitter;
showAllTables(options?:QueryOptions):EventEmitter;
describeTable(tableName:string, options?:QueryOptions):EventEmitter;
addColumn(tableName:string, attributeName:any, dataTypeOrOptions?:any):EventEmitter;
removeColumn(tableName:string, attributeName:string):EventEmitter;
changeColumn(tableName:string, attributeName:string, dataTypeOrOptions:any):EventEmitter;
renameColumn(tableName:string, attrNameBefore:string, attrNameAfter:string):EventEmitter;
addIndex(tableName:string, attributes:Array<any>, options?:QueryOptions):EventEmitter;
showIndex(tableName, options?:QueryOptions):EventEmitter;
getForeignKeysForTables(tableNames:Array<string>):EventEmitter;
removeIndex(tableName:string, attributes:Array<string>):EventEmitter;
removeIndex(tableName:string, indexName:string):EventEmitter;
insert<TModel>(dao:TModel, tableName:string, values:any, options?:QueryOptions):EventEmitter;
/**
* Inserts several records into the specified table.
* @param tableName Table to insert into.
* @param records Array of key/value pairs to insert as records.
* @param options Query options
* @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially.
*/
bulkInsert(tableName:string, records:Array<any>, options?:QueryOptions, attributes?:any):EventEmitter;
update<TModel>(dao:TModel, tableName:string, values:Array<any>, where:any, options?:QueryOptions):EventEmitter;
bulkUpdate(tableName:string, values:Array<any>, where:any, options?:QueryOptions, attributes?:any):EventEmitter;
delete<TModel>(dao:TModel, tableName:string, where:any, options?:QueryOptions):EventEmitter;
bulkDelete(tableName:string, where:any, options?:QueryOptions):EventEmitter;
bulkDelete<TModel>(tableName:string, where:any, options:QueryOptions, model:TModel):EventEmitter;
select<TModel>(factory:TModel, tableName:string, scope?:any, queryOptions?:QueryOptions):EventEmitter;
increment<TModel>(dao:TModel, tableName:string, values:Array<any>, where:any, options?:QueryOptions):EventEmitter;
rawSelect<TModel>(tableName:string, options:QueryOptions, attributeSelector:string, model:TModel):EventEmitter;
/**
* Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters.
*
* @param tableName
* @param triggerName
* @param timingType
* @param fireOnArray
* @param functionName
* @param functionParams
* @param optionsArray
*/
createTrigger(tableName:string, triggerName:string, timingType:string, fireOnArray:Array<any>, functionName:string, functionParams:Array<any>, optionsArray:Array<string>):EventEmitter;
/**
* Postgres only. Drops the specified trigger.
*
* @param tableName
* @param triggerName
*/
dropTrigger(tableName:string, triggerName:string):EventEmitter;
renameTrigger(tableName:string, oldTriggerName:string, newTriggerName:string):EventEmitter;
createFunction(functionName:string, params:Array<any>, returnType:string, language:string, body:string, options?:QueryOptions):EventEmitter;
dropFunction(functionName:string, params:Array<any>):EventEmitter;
renameFunction(oldFunctionName:string, params:Array<any>, newFunctionName:string):EventEmitter;
/**
* Escape an identifier (e.g. a table or attribute name). If force is true,
* the identifier will be quoted even if the `quoteIdentifiers` option is
* false.
*/
quoteIdentifier(identifier:string, force:boolean):EventEmitter;
quoteTable(tableName:string):EventEmitter;
quoteIdentifiers(identifiers:string, force:boolean):EventEmitter;
escape(value:string):EventEmitter;
setAutocommit(transaction:Transaction, value:boolean):EventEmitter;
setIsolationLevel(transaction:Transaction, value:string):EventEmitter;
startTransaction(transaction:Transaction, options?:QueryOptions):EventEmitter;
commitTransaction(transaction:Transaction, options?:QueryOptions):EventEmitter;
rollbackTransaction(transaction:Transaction, options?:QueryOptions):EventEmitter;
}
interface QueryGenerator
{
createSchema(schemaName:string):string;
dropSchema(schemaName:string):string;
showSchemasQuery():string;
addSchema<TInstance, TPojo>(param:Model<TInstance, TPojo>):Schema;
createTableQuery(tableName:string, attributes:Array<any>, options?:CreateTableQueryOptions):string;
describeTableQuery(tableName:string, schema:string, schemaDelimiter:string):string;
dropTableQuery(tableName:string, options?:{cascade:string}):string;
renameTableQuery(before:string, after:string):string;
showTablesQuery():string;
addColumnQuery(tableName:string, attributes:any):string;
removeColumnQuery(tableName:string, attributeName:string):string;
changeColumnQuery(tableName:string, attributes:any):string;
renameColumnQuery(tableName:string, attrNameBefore:string, attrNameAfter:string):string;
insertQuery(table:string, valueHash:any, modelAttributes:any):string;
bulkInsertQuery(tableName:string, attrValueHashes:any):string;
updateQuery(tableName:string, attrValueHash:any, where:any, options:InsertOptions, attributes:any):string;
deleteQuery(tableName:string, where:any, options:DestroyOptions):string;
deleteQuery<TInstance, TPojo>(tableName:string, where:any, options:DestroyOptions, model:Model<TInstance, TPojo>):string;
/**
* Creates a query to increment a value. Note "options" here is an additional hash of values to update.
*
* @param tableName
* @param attrValueHash
* @param where
* @param options
*/
incrementQuery(tableName:string, attrValueHash:any, where:any, options?:any):string;
addIndexQuery(tableName:string, attributes:Array<any>, options?:IndexOptions):string;
/**
* Return indices for a table. Not options may be passed but is not used, so can be anything.
* @param tableName
* @param options
*/
showIndexQuery(tableName:string, options?:any):string; // options is actually not used
removeIndexQuery(tableName:string, indexNameOrAttributes:string):string;
removeIndexQuery(tableName:string, indexNameOrAttributes:Array<string>):string;
attributesToSQL(attributes:Array<any>):string;
findAutoIncrementField<TInstance,TPojo>(factory:Model<TInstance,TPojo>):Array<string>;
quoteTable(param:any, as:boolean):string;
quote(obj, parent, force):string;
createTrigger(tableName:string, triggerName:string, timingType:string, fireOnArray:TriggerOptions, functionName:string, functionParams:Array<TriggerParam>):string;
dropTrigger(tableName:string, triggerName:string):string;
renameTrigger(tableName:string, oldTriggerName:string, newTriggerName:string):string;
createFunction(functionName:string, params:Array<TriggerParam>, returnType:string, language:string, body:string, options?:Array<string>):string;
dropFunction(functionName:string, params:Array<TriggerParam>):string;
renameFunction(oldFunctionName:string, params:Array<TriggerParam>, newFunctionName:string):string;
quoteIdentifier(identifier:string, force?:boolean):string;
quoteIdentifiers(identifiers:string, force?:boolean):string;
/**
* Not documented, and reading through the code, I'm not sure what all the options available are for value/field.
*
* @param value
* @param field
*/
escape(value:any, field:any):string;
getForeignKeysQuery(tableName:string, schemaName:string):string;
dropForeignKeyQuery(tableName:string, foreignKey:string):string;
selectQuery<TInstance, TPojo>(tableName:string, options:SelectOptions, model?:Model<TInstance, TPojo>):string;
selectQuery<TInstance, TPojo>(tableName:Array<string>, options:SelectOptions, model?:Model<TInstance, TPojo>):string;
selectQuery<TInstance, TPojo>(tableName:Array<Array<string>>, options:SelectOptions, model?:Model<TInstance, TPojo>):string;
setAutocommitQuery(value:boolean):string;
setIsolationLevelQuery(value:string):string;
/**
* Returns start transaction query. Options is not used.
* @param options
*/
startTransactionQuery(options?:any):string;
/**
* Returns start transaction query. Options is not used.
* @param options
*/
commitTransactionQuery(options?:any):string;
/**
* Returns start transaction query. Options is not used.
* @param options
*/
rollbackTransactionQuery(options?:any):string;
addLimitAndOffset(options:SelectOptions, query?:string):string;
getWhereConditions<TInstance, TPojo>(smth:any, tableName:string, factory:Model<TInstance, TPojo>, options?:any, prepend?:boolean):string;
prependTableNameToHash(tableName:string, hash?:any):string;
findAssociation<TInstance, TPojo>(attribute:string, dao:Model<TInstance, TPojo>):string;
getAssociationFilterDAO<TInstance, TPojo>(filterStr:string, dao:Model<TInstance, TPojo>):string;
isAssociationFilter<TInstance, TPojo>(filterStr:string, dao:Model<TInstance, TPojo>, options?:any):string;
getAssociationFilterColumn<TInstance, TPojo>(filterStr:string, dao:Model<TInstance, TPojo>, options?:{include:boolean}):string;
getConditionalJoins<TInstance, TPojo>(options:{where?:any}, originalDao:Model<TInstance, TPojo>):string;
arrayValue(value:Array<string>, key:string, _key:string, factory?:any, logicResult?:any):string;
hashToWhereConditions<TInstance, TPojo>(hash:any, dao:Model<TInstance, TPojo>, options?:HashToWhereConditionsOption):string;
booleanValue(value):string;
}
interface Schema
{
tableName:string;
table:string;
name:string;
schema:string;
delimiter:string;
}
interface QueryTypes {
SELECT:string;
BULKUPDATE:string;
BULKDELETE:string;
}
interface ModelManager {
daos:Array<Model<any, any>>;
sequelize:Sequelize;
addDAO<TInstance, TPojo>(dao:Model<TInstance, TPojo>):Model<TInstance, TPojo>;
removeDAO<TInstance, TPojo>(dao:Model<TInstance, TPojo>):void;
getDAO<TInstance, TPojo>(daoName:string, options?:ModelMangerGetDaoOptions):Model<TInstance, TPojo>;
all:Array<Model<any, any>>;
/**
* Iterate over DAOs in an order suitable for e.g. creating tables. Will
* take foreign key constraints into account so that dependencies are visited
* before dependents.
*/
forEachDAO(iterator:(dao:Model<any, any>, name:string) => void, options?:ModelManagerForEachDaoOptions):void;
}
interface TransactionManager {
sequelize:Sequelize;
connectorManagers:any;
getConnectorManager(uuid?:string):ConnectorManager;
releaseConnectionManager(uuid?:string):void;
/**
* Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
*
* @param sql SQL statement to execute.
*
* @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented
* by the factory. Equivalent to calling Model.build with the values provided by the query.
*
* @param options Query options.
*
*/
query(sql:string, callee?:Function, options?:QueryOptions):EventEmitter;
}
interface ConnectorManager {
/**
* Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
*
* @param sql SQL statement to execute.
*
* @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented
* by the factory. Equivalent to calling Model.build with the values provided by the query.
*
* @param options Query options.
*
*/
query(sql:string, callee?:Function, options?:QueryOptions):EventEmitter;
afterTransactionSetup(callback:() => void):void;
connect():void;
disconnect():void;
reconnect():void;
cleanup():void;
}
interface Migrator {
queryInterface:QueryInterface;
migrate(options?:MigratorOptions):EventEmitter;
getUndoneMigrations(callback:(err:Error, result:Array<Migrator>) => void):void;
findOrCreateMetaDAO(syncOptions?:SyncOptions):EventEmitter;
exec(filename:string, options?:MigratorExecOptions):EventEmitter;
getLastMigrationFromDatabase():EventEmitter;
getLastMigrationIdFromDatabase():EventEmitter;
getFormattedDateString(s:string):string;
stringToDate(s:string):Date;
saveSuccessfulMigration(from:Migration, to:Migration, callback:(metaData:MetaInstance) => void):void;
deleteUndoneMigration(from:Migration, to:Migration, callback:() => void);
execute(options?:MigrationExecuteOptions):EventEmitter;
isBefore(date:Date, options?:MigrationCompareOptions):boolean;
isAfter(date:Date, options?:MigrationCompareOptions):boolean;
}
interface Migration extends QueryInterface {
migrator:Migrator;
path:string;
filename:string;
migrationId:number;
date:Date;
queryInterface:QueryInterface;
migration:(err:Error, migration:Migration, dataTypes:any, callback:(err:Error) => void) => void;
}
interface EventEmitter extends NodeJS.EventEmitter {
/**
* Create a new emitter instance.
*
* @param handler
*/
new(handler:(emitter:EventEmitter) => void):EventEmitter;
/**
* Run the function that was passed when the emitter was instantiated.
*/
run():EventEmitter;
/**
* Listen for success events.
*
* @param onSuccess
*/
success(onSuccess:(result:any) => void):EventEmitter;
/**
* Alias for success(handler). Listen for success events.
*
* @param onSuccess
*/
ok(onSuccess:(result:any) => void):EventEmitter;
/**
* Listen for error events.
*
* @param onError
*/
error(onError:(err:Error) => void):EventEmitter;
/**
* Alias for error(handler). Listen for error events.
*
* @param onError
*/
fail(onError:(err:Error) => void):EventEmitter;
/**
* Alias for error(handler). Listen for error events.
*
* @param onError
*/
failure(onError:(err:Error) => void):EventEmitter;
/**
* Listen for both success and error events.
*
* @param onDone
*/
done(onDone:(err:Error, result:any) => void):EventEmitter;
/**
* Alias for done(handler). Listen for both success and error events.
*
* @param onDone
*/
complete(onDone:(err:Error, result:any) => void):EventEmitter;
/**
* Attach a function that is called every time the function that created this emitter executes a query.
*
* @param onSQL
*/
sql(onSQL:(sql:string) => void):EventEmitter;
/**
* Proxy every event of this event emitter to another one.
*
* @param emitter The event emitter that should receive the events.
* @param options Contains an array of the events to proxy. Defaults to sql, error and success
*/
proxy(emitter:EventEmitter, options?:ProxyOptions):EventEmitter;
}
interface Options {
/**
* The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb.
* Default is mysql.
*/
dialect?: string;
/**
* If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when
* connecting to a pg database, you should specify 'pg.js' here
*/
dialectModulePath?:string;
/**
* The host of the relational database. Default 'localhost'.
*/
host?:string;
/**
* Integer The port of the relational database.
*/
port?:number;
/**
* The protocol of the relational database. Default 'tcp'.
*/
protocol?:string;
/**
* Default options for model definitions. See sequelize.define for options.
*/
define?:DefineOptions;
/**
* Default options for sequelize.query
*/
query?:QueryOptions;
/**
* Default options for sequelize.sync
*/
sync?:SyncOptions;
/**
* Logging options. Function used to log. Default is console.log. Signature is (message:string) => void.
*
* Set to "false" to disable logging.
*/
logging?:any;
/** logging=console.log] Function A function that gets executed everytime Sequelize would log something.
* A flag that defines if null values should be passed to SQL queries or not.
*/
omitNull?:boolean;
/**
* Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all
* queries will be executed immediately.
*/
queue?:boolean;
/**
* The maximum number of queries that should be executed at once if queue is true.
*/
maxConcurrentQueries?:number;
/**
* A flag that defines if native library shall be used or not. Currently only has an effect for postgres
*/
native?:boolean;
/**
* Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write
* should be an object (a single server for handling writes), and read an array of object (several servers to
* handle reads). Each read/write server can have the following properties?: host, port, username, password, database
*/
replication?:ReplicationOptions;
/**
* Connection pool options.
*
*/
pool?:PoolOptions;
/**
* Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them.
* Default true.
*/
quoteIdentifiers?:boolean;
/**
* Language. Default "en".
*/
language?:string;
}
interface PoolOptions {
maxConnections?:number;
minConnections?:number;
/**
* The maximum time, in milliseconds, that a connection can be idle before being released.
*/
maxIdleTime?:number;
/**
* A function that validates a connection. Called with client. The default function checks that client is an
* object, and that its state is not disconnected.
*
* Note, this is not documented, and after reading code I'm not sure what client's type is.
*/
validateConnection?:(client?:any) => boolean;
}
interface AttributeOptions {
/**
* A string or a data type
*/
type?:string;
/**
* If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance
* is saved.
*/
allowNull?:boolean;
/**
* A literal default value, a javascript function, or an SQL function (see sequelize.fn)
*/
defaultValue?:any;
/**
* If true, the column will get a unique constraint. If a string is provided, the column will be part of a
* composite unique index. If multiple columns have the same string, they will be part of the same unique index.
*/
unique?:any;
primaryKey?:boolean;
/**
* If set, sequelize will map the attribute name to a different name in the database.
*/
field?:string;
autoIncrement?:boolean;
comment?:string;
/**
* If this column references another table, provide it here as a Model, or a string.
*/
references?:any;
/**
* The column of the foreign table that this column references. Default 'id'.
*/
referencesKey?:string;
/**
* What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION.
*/
onUpdate?:string;
/**
* What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION.
*/
onDelete?:string;
/**
* Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values.
*/
get?:() => any;
/**
* Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values.
*/
set?:(value?:any) => void;
/**
* An object of validations to execute for this column every time the model is saved. Can be either the name of a
* validation provided by validator.js, a validation function provided by extending validator.js (see the
* DAOValidator property for more details), or a custom validation function. Custom validation functions are called
* with the value of the field, and can possibly take a second callback argument, to signal that they are
* asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async,
* the callback should be called with the error text.
*/
validate?:any;
}
interface DefineOptions {
/**
* Define the default search scope to use for this model. Scopes have the same form as the options passed to
* find / findAll.
*/
defaultScope?:FindOptions;
/**
* More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how
* scopes are defined, and what you can do with them
*/
scopes?:any;
/**
* Don't persits null values. This means that all columns with null values will not be saved.
*/
omitNull?:boolean;
/**
* Adds createdAt and updatedAt timestamps to the model. Default true.
*/
timestamps?:boolean;
/**
* Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs
* timestamps=true to work. Default false.
*/
paranoid?:boolean;
/**
* Converts all camelCased columns to underscored if true. Default false.
*/
underscored?:boolean;
/**
* Converts camelCased model names to underscored tablenames if true. Default false.
*/
underscoredAll?:boolean;
/**
* If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the
* dao name will be pluralized. Default false.
*/
freezeTableName?:boolean;
/**
* Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true.
*/
createdAt?:any;
/**
* Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true.
*/
updatedAt?:any;
/**
* Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true.
*/
deletedAt?:any;
/**
* Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim.
*/
tableName?:string;
/**
* Provide getter functions that work like those defined per column. If you provide a getter method with the same
* name as a column, it will be used to access the value of that column. If you provide a name that does not match
* a column, this function will act as a virtual getter, that can fetch multiple other values.
*/
getterMethods?:any;
/**
* Provide setter functions that work like those defined per column. If you provide a setter method with the same
* name as a column, it will be used to update the value of that column. If you provide a name that does not match
* a column, this function will act as a virtual setter, that can act on and set other values, but will not be
* persisted
*/
setterMethods?:any;
/**
* Provide functions that are added to each instance (DAO).
*/
instanceMethods?:any;
/**
* Provide functions that are added to the model (Model).
*/
classMethods?:any;
/**
* Default 'public'.
*/
schema?:string;
schemaDelimiter?:string;
engine?:string;
charset?:string;
comment?:string;
collate?:string;
whereCollection?:any;
language?:string;
/**
* An object of hook function that are called before and after certain lifecycle events. The possible hooks are?:
* beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate,
* beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and
* afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can
* either be a function, or an array of functions.
*/
hooks?:Hooks;
/**
* An object of model wide validations. Validations have access to all model values via this. If the validator
* function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional
* error.
*/
validate?:any;
// not documented, but in code
syncOnAssociation?:boolean;
}
interface QueryOptions {
/**
* If true, sequelize will not try to format the results of the query, or build an instance of a model from the
* result.
*/
raw?:boolean;
/**
* The transaction that the query should be executed under.
*/
transaction?:Transaction;
/**
* The type of query you are executing. The query type affects how results are formatted before they are passed
* back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to
* SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options
* are SELECT, BULKUPDATE and BULKDELETE.
*
* Default is SELECT.
*/
type?:string;
/**
* Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and
* transaction.LOCK.SHARE. See transaction.LOCK for an example.
*/
lock?:string;
/**
* For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the
* type of that field, otherwise defaults to float.
*/
dataType?:any;
}
interface SyncOptions {
/**
* If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table.
* Default false.
*/
force?:boolean;
/**
* A function that logs sql queries, or false for no logging.
*/
logging?:any;
/**
* The schema that the tables should be created in. This can be overriden for each table in sequelize.define.
* Default 'public'.
*/
schema?:string;
}
interface ReplicationOptions {
read?:Array<Server>;
write?:Server;
}
interface Server {
host?:string;
port?:number;
database?:string;
username?:string;
password?:string;
}
interface DropOptions {
/**
* Also drop all objects depending on this table, such as views. Only works in postgres.
*
* Default false.
*/
cascade?:boolean;
}
interface SchemaOptions {
/**
* The character(s) that separates the schema name from the table name. Default '.'.
*/
schemaDelimiter?:string;
}
interface FindOptions {
/**
* A hash of attributes to describe your search.
*/
where?:any;
/**
* A list of the attributes (columns) that you want to select. Each item can be a string for the name to include,
* or an array where the first item is string name to include or an expression, and second item in inner array
* is the alias.
*/
attributes?:Array<any>;
/**
* A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?:
* [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z },
* you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also
* specify attributes to specify what columns to load, where to limit the relations, and include to load further
* nested relations
*/
include?:any;
/**
* Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several
* columns / functions to order by. Each element can be further wrapped in a two-element array. The first element
* is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In
* this way the column will be escaped, but the direction will not.
*/
order?:any;
limit?:number;
offset?:number;
}
interface BuildOptions {
/**
* If set to true, values will ignore field and virtual setters. Default false.
*/
raw?:boolean;
/**
* Default true.
*/
isNewRecord?:boolean;
/**
* Default true.
*/
isDirty?:boolean;
/**
* an array of include options - Used to build prefetched/included model instances. See set.
*/
include?:Array<any>;
}
interface CopyOptions extends BuildOptions {
/**
* If set, only columns matching those in fields will be saved.
*/
fields?:Array<string>;
/**
*
*/
transaction?:Transaction;
}
interface FindOrCreateOptions extends FindOptions, QueryOptions {
}
interface BulkCreateOptions {
/**
* Fields to insert (defaults to all fields).
*/
fields?:Array<string>;
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails
* validation. Default false.
*/
validate?:boolean;
/**
* Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false;
*/
hooks?:boolean;
/**
* Ignore duplicate values for primary keys? (not supported by postgres). Default false.
*/
ignoreDuplicates?:boolean;
}
interface DestroyOptions {
/**
* If set to true, destroy will find all records within the where parameter and will execute before-/ after
* bulkDestroy hooks on each row.
*/
hooks?:boolean;
/**
* How many rows to delete
*/
limit?:number;
/**
* If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the
* where and limit options are ignored.
*/
truncate?:boolean;
}
interface DestroyInstanceOptions {
/**
* If set to true, paranoid models will actually be deleted.
*/
force:boolean;
}
interface InsertOptions
{
limit?:number;
returning?:string;
allowNull?:string;
}
interface UpdateOptions
{
/**
* Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails
* validation. Default true.
*/
validate?:boolean;
/**
* Run before / after bulkUpdate hooks? Default false.
*/
hooks?:boolean;
/**
* How many rows to update (only for mysql and mariadb).
*/
limit?:number;
}
interface SetOptions {
/**
* If set to true, field and virtual setters will be ignored. Default false.
*/
raw?:boolean;
/**
* Clear all previously set data values. Default false.
*/
reset?:boolean;
include?:any;
}
interface SaveOptions {
/**
* An alternative way of setting which fields should be persisted.
*/
fields?:any;
/**
* If true, the updatedAt timestamp will not be updated. Default false.
*/
silent?:boolean;
transaction?:Transaction;
}
interface ValidateOptions {
/**
* An array of strings. All properties that are in this array will not be validated.
*/
skip:Array<string>;
}
interface IncrementOptions {
/**
* The number to increment by. Default 1.
*/
by?:number;
transaction?:Transaction;
}
interface IndexOptions
{
indicesType?:string;
indexType?:string;
indexName?:string;
parser?:any;
}
interface ProxyOptions {
/**
* An array of the events to proxy. Defaults to sql, error and success.
*/
events:Array<string>;
}
interface AssociationOptions {
/**
* Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For
* example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile
* will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks.
* Default false.
*/
hooks?:boolean;
/**
* The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model
* if you want to define the junction table yourself and add extra attributes to it.
*/
through?:any;
/**
* The alias of this model. If you create multiple associations between the same tables, you should provide an
* alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should
* provide the same alias when eager loading and when getting assocated models. Defaults to the singularized
* version of target.name
*/
as?:string;
/**
* The name of the foreign key in the target table. Defaults to the name of source + primary key of source.
*/
foreignKey?:string;
/**
* What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION. Default SET NULL.
*/
onDelete?:string;
/**
* What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or
* NO ACTION. Default CASCADE.
*/
onUpdate?:string;
/**
* Should on update and on delete constraints be enabled on the foreign key.
*/
constraints?:boolean;
}
interface TriggerOptions
{
insert?:Array<string>;
update?:Array<string>;
delete?:Array<string>;
truncate?:Array<string>;
}
interface TriggerParam
{
type:string;
direction?:string;
name?:string;
}
interface SelectOptions
{
limit?:number;
offset?:number;
attributes?:Array<any>;
hasIncludeWhere?:boolean;
hasIncludeRequired?:boolean;
hasMultiAssociation?:boolean;
tableAs?:string;
table?:string;
include?:Array<any>;
includeIgnoreAttributes?:boolean;
where?:any;
/**
* String field name or array of strings of field names.
*/
group?:any;
having?:any;
order?:any;
lock?:string;
}
interface HashToWhereConditionsOption
{
include?:boolean;
keysEscaped?:boolean;
}
interface ModelMangerGetDaoOptions {
attribute:string;
}
interface ModelManagerForEachDaoOptions {
/**
* Default true.
*/
reverse:boolean;
}
interface MigratorOptions {
/**
* A flag that defines if the migrator should get instantiated or not..
*/
force:boolean;
}
interface FindAndCountResult<T> {
/**
* The matching model instances.
*/
rows?:Array<T>;
/**
* The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied.
*/
count?:number;
}
interface Col {
/**
* Column name.
*/
col:string;
}
interface Cast {
/**
* The value to cast.
*/
val:any;
/**
* The type to cast it to.
*/
type:string;
}
interface Literal {
val: any;
}
interface And {
/**
* Each argument (string or object) will be joined by AND.
*/
args:Array<any>;
}
interface Or {
/**
* Each argument (string or object) will be joined by OR.
*/
args:Array<any>;
}
interface Where {
/**
* The attribute.
*/
attribute:string;
/**
* The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.).
*/
logic:any;
}
interface TransactionOptions {
/**
*
*/
autocommit?:boolean;
/**
* One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'.
*/
isolationLevel?:string;
}
interface QueryChainerRunSeriallyOptions {
/**
* If set to true, all pending emitters will be skipped if a previous emitter failed. Default false.
*/
skipOnError:boolean;
}
interface CreateTableQueryOptions
{
comment?:string;
uniqueKeys?:Array<any>;
charset?:string;
}
interface MigratorExecOptions {
before?:(migrator:Migrator) => void;
after?:(migrator:Migrator) => void;
success?:(migrator:Migrator) => void;
}
interface MigrationExecuteOptions {
method: string;
}
interface MigrationCompareOptions {
/**
* Default false.
*/
withoutEquals: boolean;
}
interface Promise {
/**
* Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter.
*
* @param evt Event
* @param fct Handler
*/
on(evt:string, fct:() => void):void;
/**
* Emit an event from the emitter.
*
* @param type The type of event.
* @param value All other arguments will be passed to the event listeners.
*/
emit(type:string, ...value:Array<any>):void;
/**
* Listen for success events.
*/
success(onSuccess:() => void):Promise;
/**
* Alias for success(handler). Listen for success events.
*/
ok(onSuccess:() => void):Promise;
/**
* Listen for error events.
*
* @param onError Error handler.
*/
error(onError:(err?:Error) => void):Promise;
/**
* Alias for error(handler). Listen for error events.
*
* @param onError Error handler.
*/
fail(onError:(err?:Error) => void):Promise;
/**
* Alias for error(handler). Listen for error events.
*
* @param onError Error handler.
*/
failure(onError:(err?:Error) => void):Promise;
/**
* Listen for both success and error events..
*/
done(handler:(err:Error, result?:any) => void):Promise;
/**
* Alias for done(handler). Listen for both success and error events..
*/
complete(handler:(err:Error, result?:any) => void):Promise;
/**
* Attach a function that is called every time the function that created this emitter executes a query.
*
* @param onSQL
*/
sql(onSQL:(sql:string) => void):Promise;
/**
* Proxy every event of this promise to another one.
*
* @param promise The promise that should receive the events.
* @param options Contains an array of the events to proxy. Defaults to sql, error and success
*/
proxy(promise:Promise, options?:ProxyOptions):Promise;
}
interface PromiseT<T> extends Promise {
/**
* Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter.
*
* @param evt Event
* @param fct Handler
*/
on(evt:string, fct:(t:T) => void):void;
/**
* Emit an event from the emitter.
*
* @param type The type of event.
* @param value All other arguments will be passed to the event listeners.
*/
emit(type:string, ...value:Array<T>):void;
/**
* Listen for success events.
*/
success(onSuccess:(t:T) => void):PromiseT<T>;
/**
* Alias for success(handler). Listen for success events.
*/
ok(onSuccess:(t:T) => void):PromiseT<T>;
/**
* Listen for both success and error events..
*/
done(handler:(err:Error, result:T) => void):PromiseT<T>;
/**
* Alias for done(handler). Listen for both success and error events..
*/
complete(handler:(err:Error, result:T) => void):PromiseT<T>;
/**
* Attach a function that is called every time the function that created this emitter executes a query.
*
* @param onSQL
*/
sql(onSQL:(sql:string) => void):PromiseT<T>;
/**
* Proxy every event of this promise to another one.
*
* @param promise The promise that should receive the events.
* @param options Contains an array of the events to proxy. Defaults to sql, error and success
*/
proxy(promise:PromiseT<T>, options?:ProxyOptions):PromiseT<T>;
}
interface Utils {
_:Lodash;
/**
* Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect.
* @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders.
* @param dialect SQL Dialect.
*/
format(arr:Array<any>, dialect?:string):string;
/**
* Formats a SQL string replacing named placeholders with values from the parameters object with matching key names.
*
* @param sql String to format.
* @param parameters Key/value hash with values to replace in string.
* @param dialect SQL Dialect
*/
formatNamedParameters(sql:string, parameters:any, dialect?:string):string;
injectScope(scope:string, merge:boolean):any;
smartWhere(whereArg:any, dialect:string):any;
getWhereLogic(logic:string, val?:any):string;
isHash(obj:any):boolean;
hasChanged(attrValue:any, value:any):boolean;
argsArePrimaryKeys(args:Array<any>, primaryKeys:any):boolean;
/**
* Consistently combines two table names such that the alphabetically first name always comes first when combined.
*
* @param table1
* @param table2
*/
combineTableNames(table1:string, table2:string):string;
singularize(s:string, language?:string):string;
pluralize(s:string, language:string):string;
removeCommentsFromFunctionString(s:string):string;
toDefaultValue(value:any):any;
defaultValueSchemable(value:any):boolean;
setAttributes(hash:any, identifier:string, instance:any, prefix:string):any;
removeNullValuesFromHash(hash:any, omitNull:boolean, options:any):any;
firstValueOfHash(obj:any):any;
inherit(subClass:any, superClass:any):any;
stack():string;
now(dialect:string):Date;
/**
* Runs provided function on next tick, depending on environment.
*
* @param f
*/
tick(f:Function):void;
/**
* Surrounds a string with tick marks while removing all existing tick marks from the string.
* @param s String to tick
* @param tickChar Tick mark. Default `
*/
addTicks(s:string, tickChar?:string):string;
removeTicks(s:string, tickChar?:string):string;
generateUUID():string;
validateParameter(value:any, expectation:any):boolean;
CustomEventEmitter:EventEmitter;
Promise:Promise;
QueryChainer:QueryChainer;
Lingo:any; // external project, no definitions yet}
}
interface Lodash extends _.LoDashStatic, UnderscoreStringStaticExports {
includes(str:string, needle:string): boolean;
camelizeIf(str:string, condition:boolean):string;
camelizeIf(str:string, condition:any):string;
underscoredIf(str:string, condition:boolean):string;
underscoredIf(str:string, condition:any):string;
/**
* * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey.
*
* @param arr Array to compact.
*/
compactLite<T>(arr:Array<T>):Array<T>;
}
interface MetaPojo {
from: string;
to: string;
}
interface MetaInstance extends MetaPojo, Model<MetaInstance, MetaPojo> {
}
interface DataTypeStringBase {
BINARY:DataTypeString;
}
interface DataTypeNumberBase {
UNSIGNED:boolean;
ZEROFILL:boolean;
}
interface DataTypeString extends DataTypeStringBase {
}
interface DataTypeChar extends DataTypeStringBase {
}
interface DataTypeInteger extends DataTypeNumberBase {
}
interface DataTypeBigInt extends DataTypeNumberBase {
}
interface DataTypeFloat extends DataTypeNumberBase {
}
interface DataTypeBlob {
}
interface DataTypeDecimal {
PRECISION:number;
SCALE:number;
}
interface DataTypeVirtual {
}
interface DataTypeEnum {
(...values:Array<string>):DataTypeEnum;
}
interface DataTypeArray {
}
interface DataTypeHstore {
}
interface DataTypes {
STRING: DataTypeString;
CHAR: DataTypeChar;
TEXT: string;
INTEGER: DataTypeInteger;
BIGINT: DataTypeBigInt;
DATE: string;
BOOLEAN: string;
FLOAT: DataTypeFloat;
NOW: string;
BLOB: DataTypeBlob;
DECIMAL: DataTypeDecimal;
UUID: string;
UUIDV1: string;
UUIDV4: string;
VIRTUAL: DataTypeVirtual;
NONE: DataTypeVirtual;
ENUM:DataTypeEnum;
ARRAY:DataTypeArray;
HSTORE:DataTypeHstore;
}
} | the_stack |
import React, { useState, useEffect, useLayoutEffect, useMemo } from "react";
import { OrgComponent } from "@ui_types";
import { Api, Client, Model, Rbac } from "@core/types";
import * as g from "@core/lib/graph";
import * as R from "ramda";
import { pick } from "@core/lib/utils/pick";
import { getEnvParentPath } from "@ui_lib/paths";
import { SvgImage } from "@images";
import { MIN_ACTION_DELAY_MS } from "@constants";
import { wait } from "@core/lib/utils/wait";
import * as styles from "@styles";
import { logAndAlertError } from "@ui_lib/errors";
type PermissionsByAppRoleId = Record<string, Rbac.EnvironmentPermission[]>;
const BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL = {
none: ["read_inherits"],
read_meta_only: ["read_inherits", "read_meta"],
read_only: ["read_inherits", "read_meta", "read"],
read_write: ["read_inherits", "read_meta", "read", "read_history", "write"],
};
const SUB_ENV_PERMISSIONS_BY_ACCESS_LEVEL = {
none: [],
read_meta_only: ["read_branches_inherits", "read_branches_meta"],
read_only: ["read_branches_inherits", "read_branches_meta", "read_branches"],
read_write: [
"read_branches_inherits",
"read_branches_meta",
"read_branches",
"read_branches_history",
"write_branches",
],
};
type AccessLevel = keyof typeof BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL;
const ACCESS_LEVELS = Object.keys(
BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL
) as AccessLevel[];
export const EnvironmentRoleForm: OrgComponent<{
appId?: string;
blockId?: string;
editingId?: string;
}> = (props) => {
const envParentId = props.routeParams.appId ?? props.routeParams.blockId;
const { graph, graphUpdatedAt } = props.core;
const editing = props.routeParams.editingId
? (graph[props.routeParams.editingId] as Rbac.EnvironmentRole)
: undefined;
const envParent = envParentId
? (graph[envParentId] as Model.EnvParent)
: undefined;
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, []);
const { appRoles, permissionsByAppRoleId, defaultPermissionsByAppRoleId } =
useMemo(() => {
let { appRoles, appRoleEnvironmentRoles } = g.graphTypes(graph);
appRoles = appRoles.filter(
R.complement(R.prop("hasFullEnvironmentPermissions"))
);
const appRoleIds = new Set(appRoles.map(R.prop("id")));
return {
appRoles,
permissionsByAppRoleId: editing
? appRoleEnvironmentRoles.reduce(
(agg, { environmentRoleId, appRoleId, permissions }) =>
environmentRoleId == editing.id && appRoleIds.has(appRoleId)
? { ...agg, [appRoleId]: permissions }
: agg,
{} as PermissionsByAppRoleId
)
: undefined,
defaultPermissionsByAppRoleId: editing
? {}
: appRoles.reduce(
(agg, { id: appRoleId }) => ({
...agg,
[appRoleId]: ["read_inherits"] as Rbac.EnvironmentPermission[],
}),
{} as PermissionsByAppRoleId
),
};
}, [graphUpdatedAt, editing?.id]);
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [hasLocalKeys, setHasLocalKeys] = useState(false);
const [hasServers, setHasServers] = useState(true);
const [userModifiedServerName, setUserModifiedServerName] = useState(false);
const [defaultAllApps, setDefaultAllApps] = useState(false);
const [defaultAllBlocks, setDefaultAllBlocks] = useState(false);
const [autoCommit, setAutoCommit] = useState(false);
const [permissionsByAppRoleIdState, setPermissionsByAppRoleIdState] =
useState(permissionsByAppRoleId ?? defaultPermissionsByAppRoleId);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
setName(editing?.name ?? "");
setDescription(editing?.description ?? "");
setHasServers(editing?.hasServers ?? true);
setUserModifiedServerName(false);
setHasLocalKeys(editing?.hasLocalKeys ?? false);
setDefaultAllApps(editing?.defaultAllApps ?? !envParent);
setDefaultAllBlocks(editing?.defaultAllBlocks ?? !envParent);
setAutoCommit(editing?.settings?.autoCommit ?? false);
setPermissionsByAppRoleIdState(
permissionsByAppRoleId ?? defaultPermissionsByAppRoleId
);
}, [editing?.id]);
const hasUpdate =
!editing ||
!R.equals(
{
name,
description,
hasLocalKeys,
hasServers,
defaultAllApps,
defaultAllBlocks,
autoCommit,
permissionsByAppRoleId: permissionsByAppRoleIdState,
},
{
...pick(
[
"name",
"description",
"hasLocalKeys",
"hasServers",
"defaultAllApps",
"defaultAllBlocks",
],
editing
),
autoCommit: editing.settings?.autoCommit ?? false,
permissionsByAppRoleId,
}
);
const canSubmit = Boolean(!submitting && hasUpdate && name.trim());
let submitLabel: string;
if (editing) {
submitLabel = submitting ? "Updating" : "Update";
} else {
submitLabel = submitting ? "Creating" : "Create";
}
const goBack = () => {
props.history.push(
props.orgRoute(
envParent
? getEnvParentPath(envParent) + "/settings"
: "/my-org/environment-settings"
)
);
};
const renderAppRole = (appRole: Rbac.AppRole) => {
const permissions = permissionsByAppRoleIdState[appRole.id];
const permissionsSet = new Set(permissions);
let baseAccessLevel: AccessLevel = "none";
for (let level of ACCESS_LEVELS) {
const levelPermissions = BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
level
] as Rbac.EnvironmentPermission[];
if (
R.intersection(permissions, levelPermissions).length ==
levelPermissions.length
) {
baseAccessLevel = level;
}
}
let subAccessLevel: AccessLevel = "none";
for (let level of ACCESS_LEVELS) {
const levelPermissions = SUB_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
level
] as Rbac.EnvironmentPermission[];
if (
R.intersection(permissions, levelPermissions).length ==
levelPermissions.length
) {
subAccessLevel = level;
}
}
return (
<div>
<h4>{appRole.name} Permissions</h4>
<div>
<div className="field">
{baseAccessLevel == "none" ? (
""
) : (
<label>Base Environment Permissions</label>
)}
<div className="select">
<select
disabled={appRole.hasFullEnvironmentPermissions || submitting}
onChange={(e) => {
const selectedLevel = e.target.value as AccessLevel;
let basePermissions = BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
selectedLevel
] as Rbac.EnvironmentPermission[];
let subPermissions = SUB_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
selectedLevel
] as Rbac.EnvironmentPermission[];
if (
basePermissions.includes("read") &&
!basePermissions.includes("read_history")
) {
basePermissions = basePermissions.concat(["read_history"]);
}
if (
subPermissions.includes("read_branches") &&
!subPermissions.includes("read_branches_history")
) {
subPermissions = subPermissions.concat([
"read_branches_history",
]);
}
setPermissionsByAppRoleIdState({
...permissionsByAppRoleIdState,
[appRole.id]: basePermissions.concat(subPermissions),
});
}}
value={baseAccessLevel}
>
<option value="none">No Access</option>
<option value="read_meta_only">Read Metadata Only</option>
<option value="read_only">Read Only</option>
<option value="read_write">Read / Write</option>
</select>
<SvgImage type="down-caret" />
</div>
</div>
{permissionsSet.has("read") && !permissionsSet.has("write") ? (
<div
className={
"field checkbox" +
(permissionsSet.has("read_history") ? " selected" : "") +
(submitting ? " disabled" : "")
}
onClick={() => {
setPermissionsByAppRoleIdState({
...permissionsByAppRoleIdState,
[appRole.id]: permissionsSet.has("read_history")
? R.without(["read_history"], permissions)
: [...permissions, "read_history"],
});
}}
>
<label>Can read version history</label>
<input
type="checkbox"
checked={permissionsSet.has("read_history")}
/>
</div>
) : (
""
)}
</div>
{baseAccessLevel == "none" ? (
""
) : (
<div>
<div className="field">
<label>Branch Permissions</label>
<div className="select">
<select
disabled={appRole.hasFullEnvironmentPermissions || submitting}
onChange={(e) => {
const selectedLevel = e.target.value as AccessLevel;
const basePermissions =
BASE_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
baseAccessLevel
] as Rbac.EnvironmentPermission[];
const subPermissions = SUB_ENV_PERMISSIONS_BY_ACCESS_LEVEL[
selectedLevel
] as Rbac.EnvironmentPermission[];
if (
subPermissions.includes("read_branches") &&
!subPermissions.includes("read_branches_history")
) {
subPermissions.push("read_branches_history");
}
setPermissionsByAppRoleIdState({
...permissionsByAppRoleIdState,
[appRole.id]: basePermissions.concat(subPermissions),
});
}}
value={subAccessLevel}
>
<option value="none">No Access</option>
<option value="read_meta_only">Read Metadata Only</option>
{permissionsSet.has("read") ? (
<option value="read_only">Read Only</option>
) : (
""
)}
{permissionsSet.has("write") ? (
<option value="read_write">Read / Write</option>
) : (
""
)}
</select>
<SvgImage type="down-caret" />
</div>
</div>
{permissionsSet.has("read_branches") &&
!permissionsSet.has("write_branches") ? (
<div
className={
"field checkbox" +
(permissionsSet.has("read_branches_history")
? " selected"
: "") +
(submitting ? " disabled" : "")
}
onClick={() => {
setPermissionsByAppRoleIdState({
...permissionsByAppRoleIdState,
[appRole.id]: permissionsSet.has("read_branches_history")
? R.without(["read_branches_history"], permissions)
: [...permissions, "read_branches_history"],
});
}}
>
<label>Can read branch version history</label>
<input
type="checkbox"
checked={permissionsSet.has("read_branches_history")}
/>
</div>
) : (
""
)}
</div>
)}
</div>
);
};
return (
<div className={styles.OrgContainer}>
{editing ? (
<h3>
Editing <strong>{editing.name}</strong>
</h3>
) : (
<h3>
New <strong>Environment</strong>
</h3>
)}
{editing && hasUpdate ? (
<span className="unsaved-changes">Unsaved changes</span>
) : (
""
)}
{editing?.isDefault ? (
<div>
<div className="field">
<label>Default Name</label>
<p>{editing.defaultName}</p>
</div>
<div className="field">
<label>Default Description</label>
<p>{editing.defaultDescription}</p>
</div>
</div>
) : (
""
)}
<div className="field">
<label>{editing?.isDefault ? "Visible Name" : "Name"}</label>
<input
type="text"
disabled={submitting}
autoFocus={!editing}
placeholder="Enter environment name (required)..."
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="field">
<label>
{editing?.isDefault ? "Visible Description" : "Description"}
</label>
<textarea
placeholder="Enter a description (optional)... "
disabled={submitting}
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
</div>
{/* <div
className={
"field checkbox" +
(hasLocalKeys ? " selected" : "") +
(submitting || editing?.isDefault ? " disabled" : "")
}
onClick={() => {
if (editing?.isDefault) {
return;
}
setHasLocalKeys(!hasLocalKeys);
}}
>
<label>Is Local Development Environment</label>
<input type="checkbox" checked={hasLocalKeys} />
</div> */}
{/* <div
className={
"field checkbox" +
(hasServers ? " selected" : "") +
(submitting || editing?.isDefault ? " disabled" : "")
}
onClick={() => {
if (editing?.isDefault) {
return;
}
setHasServers(!hasServers);
}}
>
<label>Can Have Servers</label>
<input type="checkbox" checked={hasServers} />
</div> */}
<div
className={
"field checkbox" +
(defaultAllApps ? " selected" : "") +
(submitting ? " disabled" : "")
}
onClick={() => {
setDefaultAllApps(!defaultAllApps);
}}
>
<label>Include In All Apps By Default</label>
<input type="checkbox" checked={defaultAllApps} />
</div>
<div
className={
"field checkbox" +
(defaultAllBlocks ? " selected" : "") +
(submitting ? " disabled" : "")
}
onClick={() => {
setDefaultAllBlocks(!defaultAllBlocks);
}}
>
<label>Include In All Blocks By Default</label>
<input type="checkbox" checked={defaultAllBlocks} />
</div>
{/* <div
className={
"field checkbox" +
(autoCommit ? " selected" : "") +
(submitting ? " disabled" : "")
}
onClick={() => {
setAutoCommit(!autoCommit);
}}
>
<label>Default Auto-Commit On Change</label>
<input type="checkbox" checked={autoCommit} />
</div> */}
<div>{appRoles.map(renderAppRole)}</div>
<div className="buttons">
<button className="secondary" onClick={goBack}>
← Back
</button>
<button
className="primary"
disabled={!canSubmit || submitting}
onClick={async () => {
setSubmitting(true);
const basePayload = {
name,
description,
hasLocalKeys,
settings: { autoCommit },
defaultAllApps,
defaultAllBlocks,
appRoleEnvironmentRoles: permissionsByAppRoleIdState,
hasServers,
};
const minDelayPromise = wait(MIN_ACTION_DELAY_MS);
const res = await props
.dispatch(
editing
? {
type: Client.ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE,
payload: { ...basePayload, id: editing.id },
}
: {
type: Api.ActionType.RBAC_CREATE_ENVIRONMENT_ROLE,
payload: basePayload,
}
)
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem ${
editing ? "updating" : "creating"
} the environment role.`,
(res.resultAction as any)?.payload
);
}
return res;
});
if (
!editing &&
envParent &&
res.success &&
((envParent.type == "app" && !defaultAllApps) ||
(envParent.type == "block" && !defaultAllBlocks))
) {
const created = g
.graphTypes(res.state.graph)
.environmentRoles.find(
({ createdAt }) => createdAt === res.state.graphUpdatedAt
);
if (created) {
await props
.dispatch({
type: Api.ActionType.CREATE_ENVIRONMENT,
payload: {
environmentRoleId: created.id,
envParentId: envParent.id,
},
})
.then((res) => {
if (!res.success) {
logAndAlertError(
`There was a problem creating the environment.`,
(res.resultAction as any)?.payload
);
}
});
}
}
await minDelayPromise;
if (editing) {
setSubmitting(false);
} else {
goBack();
}
}}
>
{submitLabel} Environment{submitting ? "..." : ""}
</button>
</div>
</div>
);
}; | the_stack |
import React, { Component } from 'react';
import {
Animated,
StyleSheet,
PanResponder,
PanResponderInstance,
View,
Easing,
NativeModules,
} from 'react-native';
import _ from 'lodash';
import { Utils } from 'tuya-panel-utils';
import { ISliderProps, sliderDefault, ISliderState } from './interface';
const shallowCompare = require('react-addons-shallow-compare');
const styleEqual = require('style-equal');
const TRACK_SIZE = 4;
const THUMB_SIZE = 20;
const { inMaxMin } = Utils.NumberUtils;
const DEFAULT_ANIMATION_CONFIGS = {
spring: {
friction: 7,
tension: 100,
},
timing: {
duration: 150,
easing: Easing.inOut(Easing.ease),
delay: 0,
},
};
class Rect {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
x: number;
y: number;
width: number;
height: number;
containsPoint(x, y) {
return x >= this.x && y >= this.y && x <= this.x + this.width && y <= this.y + this.height;
}
}
export default class Slider extends Component<ISliderProps, ISliderState> {
static defaultProps = sliderDefault;
constructor(props) {
super(props);
this._measureContainer = this._measureContainer.bind(this);
this._measureTrack = this._measureTrack.bind(this);
this._measureThumb = this._measureThumb.bind(this);
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder.bind(this),
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder.bind(this),
onPanResponderGrant: this._handlePanResponderGrant.bind(this),
onPanResponderMove: this._handlePanResponderMove.bind(this),
onPanResponderRelease: this._handlePanResponderEnd.bind(this),
onPanResponderTerminationRequest: this._handlePanResponderRequestEnd.bind(this),
onPanResponderTerminate: this._handlePanResponderEnd.bind(this),
onMoveShouldSetPanResponderCapture: this._handlePanResponderRequestEnd.bind(this),
});
this.oldValue = this._testValue(props.value, props);
this.touchLocked = false;
this.state = {
containerSize: { width: 0, height: 0 },
trackSize: { width: 0, height: 0 },
thumbSize: { width: 0, height: 0 },
allMeasured: false,
value: new Animated.Value(this.oldValue),
actualValue: this.oldValue,
};
}
componentWillReceiveProps(nextProps) {
if (this.props.value !== nextProps.value && !this.touchLocked) {
const newValue = this._testValue(nextProps.value, nextProps);
this.oldValue = newValue;
this.setState({
actualValue: newValue,
});
if (this.props.animateTransitions) {
this._setCurrentValueAnimated(newValue);
} else {
this._setCurrentValue(newValue);
}
}
}
shouldComponentUpdate(nextProps, nextState) {
return (
shallowCompare(
{ props: this._getPropsForComponentUpdate(this.props), state: this.state },
this._getPropsForComponentUpdate(nextProps),
nextState
) ||
!styleEqual(this.props.style, nextProps.style) ||
!styleEqual(this.props.trackStyle, nextProps.trackStyle) ||
!styleEqual(this.props.thumbStyle, nextProps.thumbStyle) ||
!styleEqual(this.props.thumbTouchSize, nextProps.thumbTouchSize)
);
}
setValue(value) {
if (this.touchLocked) return;
if (this.props.animateTransitions) {
this._setCurrentValueAnimated(value);
} else {
this._setCurrentValue(value);
}
}
/* istanbul ignore next */
// eslint-disable-next-line
setGestureGrant(gestureDistance) {
this._previousLeft = this._getThumbLeft(this._getCurrentValue());
this._fireChangeEvent('onSlidingStart');
}
/* istanbul ignore next */
setGestureMove(gestureDistance) {
const thumbLeft = this._previousLeft + gestureDistance;
this._setCurrentValue(this.__getValue(thumbLeft));
this._fireValueChange();
}
/* istanbul ignore next */
setGestureEnd(gestureDistance) {
const thumbLeft = this._previousLeft + gestureDistance;
this._setCurrentValue(this.__getValue(thumbLeft));
this._fireChangeEvent('onSlidingComplete');
}
static Horizontal: React.ElementType<ISliderProps>;
static Vertical: React.ElementType<ISliderProps>;
static dpView: any;
oldValue: number;
touchLocked: boolean;
_previousLeft: number;
_containerSize: { width: number; height: number };
_trackSize: { width: number; height: number };
_thumbSize: { width: number; height: number };
_panResponder: PanResponderInstance;
_testValue(value, props) {
const v = props.reverseValue ? props.maximumValue + props.minimumValue - value : value;
return inMaxMin(props.minimumValue, props.maximumValue, v);
}
_getPropsForComponentUpdate(props) {
const {
value, // eslint-disable-line
onValueChange, // eslint-disable-line
onSlidingStart, // eslint-disable-line
onSlidingComplete, // eslint-disable-line
onScrollEvent, // eslint-disable-line
style, // eslint-disable-line
trackStyle, // eslint-disable-line
thumbStyle, // eslint-disable-line
renderMinimumTrack, // eslint-disable-line
renderMaximumTrack, // eslint-disable-line
renderThumb, // eslint-disable-line
onLayout, // eslint-disable-line
thumbTouchSize, // eslint-disable-line
...neededProps
} = props;
return neededProps;
}
_handleStartShouldSetPanResponder(e) {
if (this.props.disabled) return false;
if (this.props.canTouchTrack) return true;
return this._thumbHitTest(e);
}
_handleMoveShouldSetPanResponder() {
return false;
}
// eslint-disable-next-line
_handlePanResponderGrant(event, gestureState) {
this.touchLocked = true;
if (this.props.canTouchTrack) {
const newValue = this._getValueByGestureEvent(event);
if (this.props.animateTransitions) {
this._setCurrentValueAnimated(newValue);
} else {
this._setCurrentValue(newValue);
}
this._previousLeft = this._getThumbLeft(newValue);
} else {
this._previousLeft = this._getThumbLeft(this._getCurrentValue());
}
this._fireChangeEvent('onSlidingStart');
}
_handlePanResponderMove(event, gestureState) {
this._setCurrentValue(this._getValueByGestureState(gestureState));
this._fireValueChange();
}
_handlePanResponderRequestEnd() {
return false;
}
_handlePanResponderEnd(event, gestureState) {
this._setCurrentValue(this._getValueByGestureState(gestureState));
this._fireChangeEvent('onSlidingComplete');
this.touchLocked = false;
}
_measureContainer(x) {
this._handleMeasure('containerSize', x);
if (this.props.onLayout) this.props.onLayout(x);
}
_measureTrack(x) {
this._handleMeasure('trackSize', x);
}
_measureThumb(x) {
this._handleMeasure('thumbSize', x);
}
_handleMeasure(name, x) {
const { width, height } = x.nativeEvent.layout;
const size = { width, height };
const storeName = `_${name}`;
const currentSize = this[storeName];
if (currentSize && width === currentSize.width && height === currentSize.height) {
return;
}
this[storeName] = size;
if (this._containerSize && this._trackSize && this._thumbSize) {
this.setState({
containerSize: this._containerSize,
trackSize: this._trackSize,
thumbSize: this._thumbSize,
allMeasured: true,
});
}
}
_getRatio(value) {
return (value - this.props.minimumValue) / (this.props.maximumValue - this.props.minimumValue);
}
_getThumbLeft(value) {
return this._getThumbTranslate(value);
}
_getThumbTranslate(value) {
const ratio = this._getRatio(value);
const length = this.props.horizontal
? this.state.containerSize.width - this.state.thumbSize.width
: this.state.containerSize.height - this.state.thumbSize.height;
return ratio * length;
}
_getValueByGestureEvent(e) {
const thumbLeft = this.props.horizontal
? e.nativeEvent.locationX - this.props.thumbTouchSize.width / 2
: e.nativeEvent.locationY - this.props.thumbTouchSize.height / 2;
return this.__getValue(thumbLeft);
}
_getValueByGestureState(gestureState) {
const dsize = this.props.horizontal ? gestureState.dx : gestureState.dy;
const thumbLeft = this._previousLeft + dsize;
return this.__getValue(thumbLeft);
}
__getValue(thumbLeft) {
const length = this.props.horizontal
? this.state.containerSize.width - this.state.thumbSize.width
: this.state.containerSize.height - this.state.thumbSize.height;
const ratio = thumbLeft / length;
if (this.props.stepValue) {
return Math.max(
this.props.minimumValue,
Math.min(
this.props.maximumValue,
Math.round(
(ratio * (this.props.maximumValue - this.props.minimumValue)) / this.props.stepValue
) *
this.props.stepValue +
this.props.minimumValue
)
);
}
return Math.max(
this.props.minimumValue,
Math.min(
this.props.maximumValue,
ratio * (this.props.maximumValue - this.props.minimumValue) + this.props.minimumValue
)
);
}
_getCurrentValue() {
// @ts-ignore
return this.state.value.__getValue();
}
_setCurrentValue(value) {
this.setState({
actualValue: value,
});
this.state.value.setValue(value);
}
_setCurrentValueAnimated(value) {
const { animationType } = this.props;
const animationConfig = {
...DEFAULT_ANIMATION_CONFIGS[animationType],
...this.props.animationConfig,
toValue: value,
};
// @ts-ignore
Animated[animationType](this.state.value, animationConfig).start();
}
_fireValueChange() {
const { isVibration, minimumValue, maximumValue } = this.props;
const value = this._getCurrentValue();
const newValue = this._testValue(value, this.props);
if (this.props.onValueChange && this.oldValue !== value) {
this.oldValue = value;
if (NativeModules.TYRCTHapticsManager && isVibration) {
if (newValue === minimumValue || newValue === maximumValue) {
NativeModules.TYRCTHapticsManager.impact('Heavy');
}
}
this.props.onValueChange(newValue);
}
if (this.props.onScrollEvent) {
this.props.onScrollEvent({ value: newValue });
}
}
_fireChangeEvent(event) {
const value = this._getCurrentValue();
const newValue = this._testValue(value, this.props);
if (this.props[event]) {
this.props[event](newValue);
}
if (this.props.onScrollEvent) {
this.props.onScrollEvent({ value: newValue });
}
}
_getTouchOverflowSize() {
const { state, props } = this;
const size: { width?: number; height?: number } = {};
if (state.allMeasured === true) {
if (this.props.horizontal) {
size.width = Math.max(0, props.thumbTouchSize.width - state.thumbSize.width);
size.height = Math.max(0, props.thumbTouchSize.height - state.containerSize.height);
} else {
size.width = Math.max(0, props.thumbTouchSize.width - state.containerSize.width);
size.height = Math.max(0, props.thumbTouchSize.height - state.thumbSize.height);
}
}
return size;
}
_getTouchOverflowStyle() {
const { width, height } = this._getTouchOverflowSize();
const touchOverflowStyle: {
marginTop?: number;
marginBottom?: number;
marginLeft?: number;
marginRight?: number;
backgroundColor?: string;
opacity?: number;
} = {};
if (width !== undefined && height !== undefined) {
const verticalMargin = -height / 2;
touchOverflowStyle.marginTop = verticalMargin;
touchOverflowStyle.marginBottom = verticalMargin;
const horizontalMargin = -width / 2;
touchOverflowStyle.marginLeft = horizontalMargin;
touchOverflowStyle.marginRight = horizontalMargin;
}
if (this.props.debugTouchArea === true) {
touchOverflowStyle.backgroundColor = 'orange';
touchOverflowStyle.opacity = 0.5;
}
return touchOverflowStyle;
}
_thumbHitTest(e) {
const { nativeEvent } = e;
const thumbTouchRect = this._getThumbTouchRect();
return thumbTouchRect.containsPoint(nativeEvent.locationX, nativeEvent.locationY);
}
_getThumbTouchRect() {
const { state, props } = this;
const touchOverflowSize = this._getTouchOverflowSize();
const rect = this.props.horizontal
? new Rect(
touchOverflowSize.width / 2 +
this._getThumbLeft(this._getCurrentValue()) +
(state.thumbSize.width - props.thumbTouchSize.width) / 2,
touchOverflowSize.height / 2 +
(state.containerSize.height - props.thumbTouchSize.height) / 2,
props.thumbTouchSize.width,
props.thumbTouchSize.height
)
: new Rect(
touchOverflowSize.width / 2 +
(state.containerSize.width - props.thumbTouchSize.width) / 2,
touchOverflowSize.height / 2 +
this._getThumbLeft(this._getCurrentValue()) +
(state.thumbSize.height - props.thumbTouchSize.height) / 2,
props.thumbTouchSize.width,
props.thumbTouchSize.height
);
return rect;
}
_renderDebugThumbTouchRect(thumbLeft) {
const thumbTouchRect = this._getThumbTouchRect();
const positionStyle = this.props.horizontal
? {
left: thumbLeft,
top: thumbTouchRect.y,
width: thumbTouchRect.width,
height: thumbTouchRect.height,
}
: {
left: thumbTouchRect.x,
top: thumbLeft,
width: thumbTouchRect.width,
height: thumbTouchRect.height,
};
return (
<Animated.View
style={[defaultStyles.debugThumbTouchArea, positionStyle]}
pointerEvents="none"
/>
);
}
renderMaxNounView = () => {
const {
horizontal,
maxNounStyle,
stepValue,
minimumValue,
maximumValue,
type,
thumbTouchSize,
reverseValue,
} = this.props;
const { trackSize } = this.state;
const time = Math.floor((maximumValue - minimumValue) / stepValue);
if (horizontal) {
if (type === 'parcel') {
return _.times(time + 1, n => {
return (
<View
key={n}
style={[
{
width: 3,
height: 14,
borderRadius: 1.5,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
right:
thumbTouchSize.width / 2 +
(n * (trackSize.width - thumbTouchSize.width)) / time,
}
: {
left:
thumbTouchSize.width / 2 +
(n * (trackSize.width - thumbTouchSize.width)) / time,
},
maxNounStyle,
]}
/>
);
});
}
return _.times(time + 1, n => {
return (
<View
key={n}
style={[
{
width: trackSize.height,
height: trackSize.height,
borderRadius: trackSize.height,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
right:
n * trackSize.height +
(n * (trackSize.width - trackSize.height * (time + 1))) / time,
}
: {
left:
n * trackSize.height +
(n * (trackSize.width - trackSize.height * (time + 1))) / time,
},
maxNounStyle,
]}
/>
);
});
}
if (type === 'parcel') {
return _.times(time + 1, n => {
return (
<View
key={n}
style={[
{
width: 14,
height: 3,
borderRadius: 1.5,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
bottom:
thumbTouchSize.height / 2 +
(n * (trackSize.height - thumbTouchSize.height)) / time,
}
: {
top:
thumbTouchSize.height / 2 +
(n * (trackSize.height - thumbTouchSize.height)) / time,
},
maxNounStyle,
]}
/>
);
});
}
return _.times(time + 1, n => {
return (
<View
key={n}
style={[
{
width: trackSize.width,
height: trackSize.width,
borderRadius: trackSize.width,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
bottom:
n * trackSize.width +
(n * (trackSize.height - trackSize.width * (time + 1))) / time,
}
: {
top:
n * trackSize.width +
(n * (trackSize.height - trackSize.width * (time + 1))) / time,
},
maxNounStyle,
]}
/>
);
});
};
renderMinNounView = () => {
const {
horizontal,
minNounStyle,
stepValue,
minimumValue,
maximumValue,
type,
reverseValue,
thumbTouchSize,
} = this.props;
const { actualValue, trackSize } = this.state;
const actualNounNum = reverseValue
? Math.floor(maximumValue - actualValue) / stepValue + 1
: Math.floor(actualValue - minimumValue) / stepValue + 1;
const time = Math.floor(maximumValue - minimumValue) / stepValue;
if (horizontal) {
if (type === 'parcel') {
return _.times(actualNounNum, n => {
return (
<View
key={n}
style={[
{
width: 3,
height: 14,
borderRadius: 1.5,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
right:
thumbTouchSize.width / 2 +
(n * (trackSize.width - thumbTouchSize.width)) / time,
}
: {
left:
thumbTouchSize.width / 2 +
(n * (trackSize.width - thumbTouchSize.width)) / time,
},
minNounStyle,
]}
/>
);
});
}
return _.times(actualNounNum, n => {
if (n === actualNounNum - 1) return null;
return (
<View
key={n}
style={[
{
width: trackSize.height,
height: trackSize.height,
borderRadius: trackSize.height,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
right:
n * trackSize.height +
(n * (trackSize.width - trackSize.height * (time + 1))) / time,
}
: {
left:
n * trackSize.height +
(n * (trackSize.width - trackSize.height * (time + 1))) / time,
},
minNounStyle,
]}
/>
);
});
}
if (type === 'parcel') {
return _.times(actualNounNum, n => {
return (
<View
key={n}
style={[
{
width: 14,
height: 3,
borderRadius: 1.5,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
bottom:
thumbTouchSize.height / 2 +
n * 3 +
(n * (trackSize.height - 3 * (time + 1) - thumbTouchSize.height)) / time,
}
: {
top:
thumbTouchSize.height / 2 +
n * 3 +
(n * (trackSize.height - 3 * (time + 1) - thumbTouchSize.height)) / time,
},
minNounStyle,
]}
/>
);
});
}
return _.times(actualNounNum, n => {
if (n === actualNounNum - 1) return null;
return (
<View
key={n}
style={[
{
width: trackSize.width,
height: trackSize.width,
borderRadius: trackSize.width,
},
defaultStyles.parcelNumStyle,
reverseValue
? {
bottom:
n * trackSize.width +
(n * (trackSize.height - trackSize.width * (time + 1))) / time,
}
: {
top:
n * trackSize.width +
(n * (trackSize.height - trackSize.width * (time + 1))) / time,
},
minNounStyle,
]}
/>
);
});
};
render() {
const {
minimumValue,
maximumValue,
minimumTrackTintColor,
maximumTrackTintColor,
thumbTintColor,
styles, //eslint-disable-line
style,
trackStyle,
thumbStyle,
debugTouchArea,
renderMinimumTrack,
renderMaximumTrack,
renderThumb,
horizontal,
thumbTouchSize,
onlyMaximumTrack,
type,
reverseValue,
stepValue,
useNoun,
} = this.props;
const { value, containerSize, thumbSize, allMeasured } = this.state;
const mainStyles = styles || defaultStyles;
const valueVisibleStyle: { opacity?: number } = {};
let containerStyle = {};
let minimumTrackStyle = {};
let thumbTransformStyle = {};
let thumbTranslate: any = 0;
if (horizontal) {
containerStyle = { height: thumbTouchSize.height, flexDirection: 'column' };
const marginHeight = (containerSize.height - thumbSize.height) / 2;
if (allMeasured) {
thumbTranslate =
type === 'normal'
? value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [0, containerSize.width - thumbSize.width],
})
: value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [marginHeight, containerSize.width - thumbSize.width - marginHeight],
});
thumbTransformStyle = {
transform: [
{ translateX: thumbTranslate },
// 暂时注释 Y 轴 transform 保证基础样式渲染正常,不知什么原因
// { translateY: -(trackSize.height + thumbSize.height) / 2 },
],
};
if (!onlyMaximumTrack) {
if (type === 'normal') {
minimumTrackStyle = {
width: Animated.add(thumbTranslate, thumbSize.width / 2),
};
} else if (type === 'parcel' && reverseValue) {
minimumTrackStyle = {
overflow: 'hidden',
position: 'absolute',
right: 0,
width: Animated.add(
value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [containerSize.width - thumbSize.width - marginHeight, marginHeight],
}),
thumbSize.width + marginHeight
),
};
} else if (type === 'parcel' && !reverseValue) {
minimumTrackStyle = {
width: Animated.add(thumbTranslate, thumbSize.width + marginHeight),
};
}
}
}
} else {
containerStyle = { width: thumbTouchSize.width, flexDirection: 'row' };
const marginWidth = (containerSize.width - thumbSize.width) / 2;
if (allMeasured) {
thumbTranslate =
type === 'normal'
? value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [0, containerSize.height - thumbSize.height],
})
: value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [marginWidth, containerSize.height - thumbSize.height - marginWidth],
});
thumbTransformStyle = {
transform: [
{ translateY: thumbTranslate },
// { translateX: -(trackSize.width + thumbSize.width) / 2 },
],
};
if (!onlyMaximumTrack) {
if (type === 'normal') {
minimumTrackStyle = {
overflow: 'hidden',
position: 'absolute',
height: Animated.add(thumbTranslate, thumbSize.height / 2),
};
} else if (type === 'parcel' && reverseValue) {
minimumTrackStyle = {
overflow: 'hidden',
position: 'absolute',
bottom: 0,
height: Animated.add(
value.interpolate({
inputRange: [minimumValue, maximumValue],
outputRange: [containerSize.height - thumbSize.height - marginWidth, marginWidth],
}),
thumbSize.height + marginWidth
),
};
} else if (type === 'parcel' && !reverseValue) {
minimumTrackStyle = {
overflow: 'hidden',
position: 'absolute',
height: Animated.add(thumbTranslate, thumbSize.height + marginWidth),
};
}
}
}
}
if (!allMeasured) {
valueVisibleStyle.opacity = 0;
}
const touchOverflowStyle = this._getTouchOverflowStyle();
return (
<View
accessibilityLabel={this.props.accessibilityLabel}
onLayout={this._measureContainer}
style={[mainStyles.container, containerStyle, style]}
>
<View
style={[
{ overflow: 'hidden', backgroundColor: maximumTrackTintColor },
mainStyles.track,
trackStyle,
]}
onLayout={this._measureTrack}
>
{!!renderMaximumTrack && renderMaximumTrack()}
</View>
{!!stepValue && !!useNoun && this.renderMaxNounView()}
{!onlyMaximumTrack && (
<Animated.View
style={[
{
overflow: 'hidden',
position: 'absolute',
backgroundColor: minimumTrackTintColor,
},
horizontal ? { justifyContent: 'center' } : { alignItems: 'center' },
mainStyles.track,
trackStyle,
minimumTrackStyle,
valueVisibleStyle,
]}
>
{!!renderMinimumTrack && renderMinimumTrack()}
</Animated.View>
)}
{!!stepValue && !!useNoun && reverseValue && type !== 'parcel' && this.renderMaxNounView()}
<Animated.View
renderToHardwareTextureAndroid
style={[
{ position: 'absolute', backgroundColor: thumbTintColor },
mainStyles.thumb,
thumbStyle,
thumbTransformStyle,
valueVisibleStyle,
]}
onLayout={this._measureThumb}
>
{!!renderThumb && renderThumb()}
</Animated.View>
{!!stepValue && !!useNoun && this.renderMinNounView()}
<View
style={[defaultStyles.touchArea, touchOverflowStyle]}
{...this._panResponder.panHandlers}
>
{debugTouchArea === true && this._renderDebugThumbTouchRect(thumbTranslate)}
</View>
</View>
);
}
}
Slider.Vertical = _props => (
// @ts-ignore
<Slider {..._props} ref={_props.sliderRef} horizontal={false} styles={verticalStyles} />
);
// @ts-ignore
Slider.Horizontal = _props => <Slider {..._props} ref={_props.sliderRef} horizontal />;
Slider.dpView = WrappedComponent => _props => (
<WrappedComponent
{..._props}
minimumValue={_props.min || _props.minimumValue}
maximumValue={_props.max || _props.maximumValue}
stepValue={_props.step || _props.stepValue}
/>
);
const defaultStyles = StyleSheet.create({
// eslint-disable-next-line
container: {
flexDirection: 'column',
justifyContent: 'center',
},
// eslint-disable-next-line
track: {
borderRadius: TRACK_SIZE / 2,
height: TRACK_SIZE,
},
// eslint-disable-next-line
thumb: {
borderRadius: THUMB_SIZE / 2,
elevation: 2,
height: THUMB_SIZE,
shadowColor: 'rgba(0,0,0,0.3)',
shadowOffset: {
width: 2,
height: 2,
},
shadowOpacity: 1,
shadowRadius: 2,
width: THUMB_SIZE,
},
touchArea: {
backgroundColor: 'transparent',
bottom: 0,
left: 0,
position: 'absolute',
right: 0,
top: 0,
},
debugThumbTouchArea: {
backgroundColor: 'green',
opacity: 0.5,
position: 'absolute',
},
parcelNumStyle: {
backgroundColor: '#FFF',
justifyContent: 'center',
position: 'absolute',
},
});
export const verticalStyles = StyleSheet.create({
// eslint-disable-next-line
container: {
flexDirection: 'row',
justifyContent: 'center',
},
// eslint-disable-next-line
track: {
borderRadius: TRACK_SIZE / 2,
width: TRACK_SIZE,
},
// eslint-disable-next-line
thumb: {
borderRadius: THUMB_SIZE / 2,
elevation: 2,
height: THUMB_SIZE,
shadowColor: 'rgba(0,0,0,0.3)',
shadowOffset: {
width: 2,
height: 2,
},
shadowOpacity: 1,
shadowRadius: 2,
width: THUMB_SIZE,
},
}); | the_stack |
import fs from 'fs-extra';
import {
has, toString, pDelay, set
} from '@terascope/utils';
import TerasliceUtil from './teraslice-util';
import Display from '../helpers/display';
import reply from '../helpers/reply';
const display = new Display();
export default class Jobs {
/**
*
* @param {object} cliConfig config object
*
*/
config: Record<string, any>;
teraslice: TerasliceUtil;
jobsList: any[]; // list of jobs
jobsListInitial: string[];
allJobsStopped: boolean;
activeStatus: string[];
jobsListChecked: string[];
constructor(cliConfig: Record<string, any>) {
this.config = cliConfig;
this.teraslice = new TerasliceUtil(this.config);
this.jobsList = []; // list of jobs
this.jobsListInitial = [];
this.allJobsStopped = false;
this.activeStatus = ['running', 'failing'];
this.jobsListChecked = [];
}
get list(): any[] {
return this.jobsList;
}
async workers(): Promise<string> {
const response = await this.teraslice.client.jobs.wrap(this.config.args.id)
.changeWorkers(this.config.args.action, this.config.args.number);
return typeof response === 'string' ? response : response.message;
}
async pause(): Promise<void> {
await this.stop('pause');
}
async resume(): Promise<void> {
await this.start('resume');
}
async restart(): Promise<void> {
await this.stop();
if (this.allJobsStopped) {
await this.start();
}
}
async recover(): Promise<void> {
const response = await this.teraslice.client.jobs.wrap(this.config.args.id).recover();
if (has(response, 'job_id')) {
reply.info(`> job_id ${this.config.args.id} recovered`);
} else {
reply.info(toString(response));
}
}
async run(): Promise<void> {
await this.start();
}
async save(): Promise<void> {
return this.status(true, true);
}
awaitStatus(): Promise<string> {
return this.teraslice.client.jobs.wrap(this.config.args.id)
.waitForStatus(this.config.args.status, 5000, this.config.args.timeout);
}
async status(saveState = false, showJobs = true): Promise<void> {
let controllers = [];
const header = ['job_id', 'name', 'lifecycle', 'slicers', 'workers', '_created', '_updated'];
const active = false;
const parse = false;
this.jobsList = [];
const format = `${this.config.args.output}Horizontal`;
try {
controllers = await this.teraslice.client.cluster.controllers();
} catch (e) {
controllers = await this.teraslice.client.cluster.slicers();
}
const statusList = this.config.args.status.split(',');
for (const jobStatus of statusList) {
const exResult = await this.teraslice.client.executions.list(jobStatus);
const jobsTemp = await this.controllerStatus(exResult, jobStatus, controllers);
jobsTemp.forEach((job) => {
this.jobsList.push(job);
});
}
if (this.jobsList.length > 0) {
if (showJobs) {
const rows = await display.parseResponse(header, this.jobsList, active);
await display.display(header, rows, format, active, parse);
}
if (saveState) {
reply.green(`\n> saved state to ${this.config.jobStateFile}`);
await fs.writeJson(this.config.jobStateFile, this.jobsList, { spaces: 4 });
}
}
}
async statusCheck(statusList: string[]): Promise<any[]> {
let controllers = [];
const jobs: any[] = [];
try {
controllers = await this.teraslice.client.cluster.controllers();
} catch (e) {
controllers = await this.teraslice.client.cluster.slicers();
}
for (const jobStatus of statusList) {
const exResult = await this.teraslice.client.executions.list(jobStatus);
const jobsTemp = await this.controllerStatus(exResult, jobStatus, controllers);
jobsTemp.forEach((job) => {
jobs.push(job);
});
}
return jobs;
}
async start(action = 'start'): Promise<void> {
// start job with job file
if (!this.config.args.all) {
const id: any = await this.teraslice.client.jobs.wrap(this.config.args.id).config();
if (id != null) {
id.slicer = {};
id.slicer.workers_active = id.workers;
this.jobsList.push(id);
}
} else {
this.jobsList = await fs.readJson(this.config.jobStateFile);
}
await this.checkJobsStart(this.activeStatus);
if (this.jobsListChecked.length === 0) {
reply.error(`No jobs to ${action}`);
return;
}
if (this.jobsListChecked.length === 1) {
this.config.yes = true;
}
if (this.config.yes || await display.showPrompt(action, `all jobs on ${this.config.args.clusterAlias}`)) {
await this.changeStatus(this.jobsListChecked, action);
let waitCount = 0;
const waitMax = 10;
let allWorkersStarted = false;
this.jobsListInitial = this.jobsListChecked;
reply.info('> Waiting for workers to start');
while (!allWorkersStarted || waitCount < waitMax) {
await this.status(false, false);
waitCount += 1;
allWorkersStarted = await this.checkWorkerCount(this.jobsListInitial,
this.jobsListChecked);
}
let allAddedWorkersStarted = false;
if (allWorkersStarted) {
// add extra workers
waitCount = 0;
await this.addWorkers(this.jobsListInitial, this.jobsListChecked);
while (!allAddedWorkersStarted || waitCount < waitMax) {
await this.status(false, false);
waitCount += 1;
allAddedWorkersStarted = await this.checkWorkerCount(this.jobsListInitial,
this.jobsListChecked, true);
}
}
if (allAddedWorkersStarted) {
await this.status(false, true);
await reply.info(`> All jobs and workers ${toString(await display.setAction(action, 'past'))}`);
}
} else {
reply.info('bye!');
}
}
async stop(action = 'stop'): Promise<void> {
let waitCountStop = 0;
const waitMaxStop = 10;
let stopTimedOut = false;
if (this.config.args.all) {
await this.save();
} else {
const id: any = await this.teraslice.client.jobs.wrap(this.config.args.id).config();
if (id != null) {
id.slicer = {};
id.slicer.workers_active = id.workers;
this.jobsList.push(id);
}
}
await this.checkJobsStop(this.activeStatus);
if (this.jobsListChecked.length === 0) {
if (this.config.args.all) {
reply.error(`No jobs to ${action}`);
} else {
reply.error(`job: ${this.config.args.id} is not running, unable to stop`);
}
return;
}
if (this.jobsListChecked.length === 1) {
this.config.args.yes = true;
}
if (this.config.args.yes || await display.showPrompt(action, `all jobs on ${this.config.args.clusterAlias}`)) {
while (!stopTimedOut) {
if (waitCountStop >= waitMaxStop) {
break;
}
try {
await this.changeStatus(this.jobsListChecked, action);
stopTimedOut = true;
} catch (err) {
stopTimedOut = false;
reply.error(`> ${action} job(s) had an error [${err.message}]`);
await this.status(false, false);
}
waitCountStop += 1;
}
let waitCount = 0;
const waitMax = 15;
while (!this.allJobsStopped) {
await this.status(false, false);
await pDelay(50);
if (this.jobsList.length === 0) {
this.allJobsStopped = true;
}
if (waitCount >= waitMax) {
break;
}
waitCount += 1;
}
if (this.allJobsStopped) {
reply.info(`> All jobs ${toString(await display.setAction(action, 'past'))}.`);
}
}
}
// TODO: fixme
async addWorkers(
expectedJobs: any[], actualJobs: any[]
): Promise<void> {
for (const job of actualJobs) {
for (const expectedJob of expectedJobs) {
let addWorkersOnce = true;
if (expectedJob.job_id === job.job_id) {
if (addWorkersOnce) {
let workers2add = 0;
if (has(expectedJob, 'slicer.workers_active')) {
workers2add = expectedJob.slicer.workers_active - expectedJob.workers;
}
if (workers2add > 0) {
reply.info(`> Adding ${workers2add} worker(s) to ${job.job_id}`);
await this.teraslice.client.jobs.wrap(job.job_id).changeWorkers('add', workers2add);
await pDelay(50);
}
addWorkersOnce = false;
}
}
}
}
}
async checkWorkerCount(
expectedJobs: any[], actualJobs: any[], addedWorkers = false
): Promise<boolean> {
let allWorkersStartedCount = 0;
let allWorkers = false;
let expectedWorkers = 0;
let activeWorkers = 0;
for (const job of actualJobs) {
for (const expectedJob of expectedJobs) {
if (expectedJob.job_id === job.job_id) {
if (addedWorkers) {
if (expectedJob.slicer?.workers_active != null) {
expectedWorkers = job.slicer.workers_active;
} else {
reply.fatal('no expected workers');
}
} else {
expectedWorkers = expectedJob.workers;
}
if (job.slicer?.workers_active != null) {
activeWorkers = job.slicer.workers_active;
}
if (expectedWorkers === activeWorkers) {
allWorkersStartedCount += 1;
}
}
}
}
if (allWorkersStartedCount === expectedJobs.length) {
allWorkers = true;
}
return allWorkers;
}
async controllerStatus(
result: any[], jobStatus: string, controllerList: any[]
): Promise<any[]> {
const jobs: any[] = [];
for (const item of result) {
// TODO, use args instead of hardcoding
if (jobStatus === 'running' || jobStatus === 'failing') {
set(item, 'slicer', controllerList.find((slicer: any) => slicer.job_id === `${item.job_id}`));
} else {
item.slicer = 0;
}
jobs.push(item);
}
return jobs;
}
async checkJobsStop(statusList: any[]): Promise<void> {
const activeJobs = await this.statusCheck(statusList);
for (const job of this.jobsList) {
for (const cjob of activeJobs) {
if (job.job_id === cjob.job_id) {
reply.info(`job: ${job.job_id} ${statusList}`);
this.jobsListChecked.push(job);
}
}
}
}
async checkJobsStart(statusList: any[]): Promise<void> {
const activeJobs = await this.statusCheck(statusList);
for (const job of this.jobsList) {
let found = false;
for (const cjob of activeJobs) {
if (job.job_id === cjob.job_id) {
reply.info(`job: ${job.job_id} ${statusList}`);
found = true;
}
}
if (!found) {
this.jobsListChecked.push(job);
}
}
}
async changeStatus(jobs: any[], action: string): Promise<void> {
reply.info(`> Waiting for jobs to ${action}`);
const response = jobs.map((job) => {
if (action === 'stop') {
return this.teraslice.client.jobs.wrap(job.job_id).stop()
.then((stopResponse) => {
if ((stopResponse.status as any)?.status === 'stopped' || stopResponse.status === 'stopped') {
const setActionResult = display.setAction(action, 'past');
reply.info(`> job: ${job.job_id} ${setActionResult}`);
return;
}
const setActionResult = display.setAction(action, 'present');
reply.info(`> job: ${job.job_id} error ${setActionResult}`);
});
}
if (action === 'start') {
return this.teraslice.client.jobs.wrap(job.job_id).start()
.then((startResponse) => {
if (startResponse.job_id === job.job_id) {
const setActionResult = display.setAction(action, 'past');
reply.info(`> job: ${job.job_id} ${setActionResult}`);
return;
}
const setActionResult = display.setAction(action, 'present');
reply.info(`> job: ${job.job_id} error ${setActionResult}`);
});
}
if (action === 'resume') {
return this.teraslice.client.jobs.wrap(job.job_id).resume()
.then((resumeResponse) => {
if ((resumeResponse.status as any)?.status === 'running' || resumeResponse.status === 'running') {
const setActionResult = display.setAction(action, 'past');
reply.info(`> job: ${job.job_id} ${setActionResult}`);
return;
}
const setActionResult = display.setAction(action, 'present');
reply.info(`> job: ${job.job_id} error ${setActionResult}`);
});
}
if (action === 'pause') {
return this.teraslice.client.jobs.wrap(job.job_id).pause()
.then((pauseResponse) => {
if ((pauseResponse.status as any)?.status === 'paused' || pauseResponse.status === 'paused') {
const setActionResult = display.setAction(action, 'past');
reply.info(`> job: ${job.job_id} ${setActionResult}`);
return;
}
const setActionResult = display.setAction(action, 'present');
reply.info(`> job: ${job.job_id} error ${setActionResult}`);
});
}
return null;
});
await Promise.all(response);
}
} | the_stack |
'use strict'
import StageBuilder from './stage-builder'
import { Pipeline } from '../pipeline/pipeline'
import { PipelineStage } from '../pipeline/pipeline-engine'
// import { some } from 'lodash'
import { Algebra } from 'sparqljs'
import Graph from '../../rdf/graph'
import { Bindings, BindingBase } from '../../rdf/bindings'
import { GRAPH_CAPABILITY } from '../../rdf/graph_capability'
import { parseHints } from '../context/query-hints'
import { fts } from './rewritings'
import ExecutionContext from '../context/execution-context'
import ContextSymbols from '../context/symbols'
import { rdf, evaluation } from '../../utils'
import { isNaN, isNull, isInteger } from 'lodash'
import boundJoin from '../../operators/join/bound-join'
/**
* Basic {@link PipelineStage} used to evaluate Basic graph patterns using the "evalBGP" method
* available
* @private
*/
function bgpEvaluation (source: PipelineStage<Bindings>, bgp: Algebra.TripleObject[], graph: Graph, builder: BGPStageBuilder, context: ExecutionContext) {
const engine = Pipeline.getInstance()
return engine.mergeMap(source, (bindings: Bindings) => {
let boundedBGP = bgp.map(t => bindings.bound(t))
// check the cache
let iterator
if (context.cachingEnabled()) {
iterator = evaluation.cacheEvalBGP(boundedBGP, graph, context.cache!, builder, context)
} else {
iterator = graph.evalBGP(boundedBGP, context)
}
// build join results
return engine.map(iterator, (item: Bindings) => {
// if (item.size === 0 && hasVars) return null
return item.union(bindings)
})
})
}
/**
* A BGPStageBuilder evaluates Basic Graph Patterns in a SPARQL query.
* Users can extend this class and overrides the "_buildIterator" method to customize BGP evaluation.
* @author Thomas Minier
* @author Corentin Marionneau
*/
export default class BGPStageBuilder extends StageBuilder {
/**
* Return the RDF Graph to be used for BGP evaluation.
* * If `iris` is empty, returns the default graph
* * If `iris` has a single entry, returns the corresponding named graph
* * Otherwise, returns an UnionGraph based on the provided iris
* @param iris - List of Graph's iris
* @return An RDF Graph
*/
_getGraph (iris: string[]): Graph {
if (iris.length === 0) {
return this.dataset.getDefaultGraph()
} else if (iris.length === 1) {
return this.dataset.getNamedGraph(iris[0])
}
return this.dataset.getUnionGraph(iris)
}
/**
* Build a {@link PipelineStage} to evaluate a BGP
* @param source - Input {@link PipelineStage}
* @param patterns - Set of triple patterns
* @param options - Execution options
* @return A {@link PipelineStage} used to evaluate a Basic Graph pattern
*/
execute (source: PipelineStage<Bindings>, patterns: Algebra.TripleObject[], context: ExecutionContext): PipelineStage<Bindings> {
// avoids sending a request with an empty array
if (patterns.length === 0) return source
// extract eventual query hints from the BGP & merge them into the context
let extraction = parseHints(patterns, context.hints)
context.hints = extraction[1]
// extract full text search queries from the BGP
// they will be executed after the main BGP, to ensure an average best join ordering
const extractionResults = fts.extractFullTextSearchQueries(extraction[0])
// rewrite the BGP to remove blank node addedd by the Turtle notation
const [bgp, artificals] = this._replaceBlankNodes(extractionResults.classicPatterns)
// if the graph is a variable, go through each binding and look for its value
if (context.defaultGraphs.length > 0 && rdf.isVariable(context.defaultGraphs[0])) {
const engine = Pipeline.getInstance()
return engine.mergeMap(source, (value: Bindings) => {
const iri = value.get(context.defaultGraphs[0])
// if the graph doesn't exist in the dataset, then create one with the createGraph factrory
const graphs = this.dataset.getAllGraphs().filter(g => g.iri === iri)
const graph = (graphs.length > 0) ? graphs[0] : (iri !== null) ? this.dataset.createGraph(iri) : null
if (graph) {
let iterator = this._buildIterator(engine.from([value]), graph, bgp, context)
if (artificals.length > 0) {
iterator = engine.map(iterator, (b: Bindings) => b.filter(variable => artificals.indexOf(variable) < 0))
}
return iterator
}
throw new Error(`Cant' find or create the graph ${iri}`)
})
}
// select the graph to use for BGP evaluation
const graph = (context.defaultGraphs.length > 0) ? this._getGraph(context.defaultGraphs) : this.dataset.getDefaultGraph()
let iterator = this._buildIterator(source, graph, bgp, context)
// evaluate all full text search queries found previously
if (extractionResults.queries.length > 0) {
iterator = extractionResults.queries.reduce((prev, query) => {
return this._buildFullTextSearchIterator(prev, graph, query.pattern, query.variable, query.magicTriples, context)
}, iterator)
}
// remove artificials variables from bindings
if (artificals.length > 0) {
iterator = Pipeline.getInstance().map(iterator, (b: Bindings) => b.filter(variable => artificals.indexOf(variable) < 0))
}
return iterator
}
/**
* Replace the blank nodes in a BGP by SPARQL variables
* @param patterns - BGP to rewrite, i.e., a set of triple patterns
* @return A Tuple [Rewritten BGP, List of SPARQL variable added]
*/
_replaceBlankNodes (patterns: Algebra.TripleObject[]): [Algebra.TripleObject[], string[]] {
const newVariables: string[] = []
function rewrite (term: string): string {
let res = term
if (term.startsWith('_:')) {
res = '?' + term.slice(2)
if (newVariables.indexOf(res) < 0) {
newVariables.push(res)
}
}
return res
}
const newBGP = patterns.map(p => {
return {
subject: rewrite(p.subject),
predicate: rewrite(p.predicate),
object: rewrite(p.object)
}
})
return [newBGP, newVariables]
}
/**
* Returns a {@link PipelineStage} used to evaluate a Basic Graph pattern
* @param source - Input {@link PipelineStage}
* @param graph - The graph on which the BGP should be executed
* @param patterns - Set of triple patterns
* @param context - Execution options
* @return A {@link PipelineStage} used to evaluate a Basic Graph pattern
*/
_buildIterator (source: PipelineStage<Bindings>, graph: Graph, patterns: Algebra.TripleObject[], context: ExecutionContext): PipelineStage<Bindings> {
if (graph._isCapable(GRAPH_CAPABILITY.UNION) && !context.hasProperty(ContextSymbols.FORCE_INDEX_JOIN)) {
return boundJoin(source, patterns, graph, this, context)
}
return bgpEvaluation(source, patterns, graph, this, context)
}
/**
* Returns a {@link PipelineStage} used to evaluate a Full Text Search query from a set of magic patterns.
* @param source - Input {@link PipelineStage}
* @param graph - The graph on which the full text search should be executed
* @param pattern - Input triple pattern
* @param queryVariable - SPARQL variable on which the full text search is performed
* @param magicTriples - Set of magic triple patterns used to configure the full text search
* @param context - Execution options
* @return A {@link PipelineStage} used to evaluate the Full Text Search query
*/
_buildFullTextSearchIterator (source: PipelineStage<Bindings>, graph: Graph, pattern: Algebra.TripleObject, queryVariable: string, magicTriples: Algebra.TripleObject[], context: ExecutionContext): PipelineStage<Bindings> {
// full text search default parameters
let keywords: string[] = []
let matchAll = false
let minScore: number | null = null
let maxScore: number | null = null
let minRank: number | null = null
let maxRank: number | null = null
// flags & variables used to add the score and/or rank to the solutions
let addScore = false
let addRank = false
let scoreVariable = ''
let rankVariable = ''
// compute all other parameters from the set of magic triples
magicTriples.forEach(triple => {
// assert that the magic triple is correct
if (triple.subject !== queryVariable) {
throw new SyntaxError(`Invalid Full Text Search query: the query variable ${queryVariable} is not the subject of the magic triple ${triple}`)
}
switch (triple.predicate) {
// keywords: ?o ses:search “neil gaiman”
case rdf.SES('search'): {
if (!rdf.isLiteral(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a RDF Literal.`)
}
keywords = rdf.getLiteralValue(triple.object).split(' ')
break
}
// match all keywords: ?o ses:matchAllTerms "true"
case rdf.SES('matchAllTerms'): {
const value = rdf.getLiteralValue(triple.object).toLowerCase()
matchAll = value === 'true' || value === '1'
break
}
// min relevance score: ?o ses:minRelevance “0.25”
case rdf.SES('minRelevance'): {
if (!rdf.isLiteral(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a RDF Literal.`)
}
minScore = Number(rdf.getLiteralValue(triple.object))
// assert that the magic triple's object is a valid number
if (isNaN(minScore)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a valid number.`)
}
break
}
// max relevance score: ?o ses:maxRelevance “0.75”
case rdf.SES('maxRelevance'): {
if (!rdf.isLiteral(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a RDF Literal.`)
}
maxScore = Number(rdf.getLiteralValue(triple.object))
// assert that the magic triple's object is a valid number
if (isNaN(maxScore)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a valid number.`)
}
break
}
// min rank: ?o ses:minRank "5" .
case rdf.SES('minRank'): {
if (!rdf.isLiteral(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a RDF Literal.`)
}
minRank = Number(rdf.getLiteralValue(triple.object))
// assert that the magic triple's object is a valid positive integre
if (isNaN(minRank) || !isInteger(minRank) || minRank < 0) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a valid positive integer.`)
}
break
}
// max rank: ?o ses:maxRank “1000” .
case rdf.SES('maxRank'): {
if (!rdf.isLiteral(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a RDF Literal.`)
}
maxRank = Number(rdf.getLiteralValue(triple.object))
// assert that the magic triple's object is a valid positive integer
if (isNaN(maxRank) || !isInteger(maxRank) || maxRank < 0) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a valid positive integer.`)
}
break
}
// include relevance score: ?o ses:relevance ?score .
case rdf.SES('relevance'): {
if (!rdf.isVariable(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a SPARQL variable.`)
}
addScore = true
scoreVariable = triple.object
break
}
// include rank: ?o ses:rank ?rank .
case rdf.SES('rank'): {
if (!rdf.isVariable(triple.object)) {
throw new SyntaxError(`Invalid Full Text Search query: the object of the magic triple ${triple} must be a SPARQL variable.`)
}
addRank = true
rankVariable = triple.object
// Set minRank to its base value if needed, to force
// the default Graph#fullTextSearch implementation to compute relevant ranks.
// With no custom implementations, this will not be an issue
if (minRank === null) {
minRank = 0
}
break
}
// do nothing for unknown magic triples
default: {
break
}
}
})
// assert that minScore <= maxScore
if (!isNull(minScore) && !isNull(maxScore) && minScore > maxScore) {
throw new SyntaxError(`Invalid Full Text Search query: the maximum relevance score should be greater than or equal to the minimum relevance score (for query on pattern ${pattern} with min_score=${minScore} and max_score=${maxScore})`)
}
// assert than minRank <= maxRank
if (!isNull(minRank) && !isNull(maxRank) && minRank > maxRank) {
throw new SyntaxError(`Invalid Full Text Search query: the maximum rank should be be greater than or equal to the minimum rank (for query on pattern ${pattern} with min_rank=${minRank} and max_rank=${maxRank})`)
}
// join the input bindings with the full text search operation
return Pipeline.getInstance().mergeMap(source, bindings => {
let boundedPattern = bindings.bound(pattern)
// delegate the actual full text search to the RDF graph
const iterator = graph.fullTextSearch(boundedPattern, queryVariable, keywords, matchAll, minScore, maxScore, minRank, maxRank, context)
return Pipeline.getInstance().map(iterator, item => {
// unpack search results
const [triple, score, rank] = item
// build solutions bindings from the matching RDF triple
const mu = new BindingBase()
if (rdf.isVariable(boundedPattern.subject) && !rdf.isVariable(triple.subject)) {
mu.set(boundedPattern.subject, triple.subject)
}
if (rdf.isVariable(boundedPattern.predicate) && !rdf.isVariable(triple.predicate)) {
mu.set(boundedPattern.predicate, triple.predicate)
}
if (rdf.isVariable(boundedPattern.object) && !rdf.isVariable(triple.object)) {
mu.set(boundedPattern.object, triple.object)
}
// add score and rank if required
if (addScore) {
mu.set(scoreVariable, `"${score}"^^${rdf.XSD('float')}`)
}
if (addRank) {
mu.set(rankVariable, `"${rank}"^^${rdf.XSD('integer')}`)
}
// Merge with input bindings and then return the final results
return bindings.union(mu)
})
})
}
} | the_stack |
import React, { useEffect } from 'react'
import List from '@material-ui/core/List'
import Divider from '@material-ui/core/Divider'
import ListItem from '@material-ui/core/ListItem'
import ListItemIcon from '@material-ui/core/ListItemIcon'
import ListItemText from '@material-ui/core/ListItemText'
import { useTranslation } from 'react-i18next'
import {
Accessibility,
CalendarViewDay,
Code,
Dashboard as DashboardIcon,
DirectionsRun,
GroupAdd,
NearMe,
PersonAdd,
PhotoAlbum,
PhotoLibrary,
Settings,
SupervisorAccount,
Toys,
Casino,
Shuffle
} from '@material-ui/icons'
import { Link, withRouter } from 'react-router-dom'
import { useStylesForDashboard } from './styles'
import ListSubheader from '@material-ui/core/ListSubheader'
import RemoveFromQueueIcon from '@material-ui/icons/RemoveFromQueue'
import ViewModuleIcon from '@material-ui/icons/ViewModule'
import EmojiPeopleIcon from '@material-ui/icons/EmojiPeople'
import ExpandLess from '@material-ui/icons/ExpandLess'
import ExpandMore from '@material-ui/icons/ExpandMore'
import Collapse from '@material-ui/core/Collapse'
import { useAuthState } from '../../state/AuthState'
interface Props {
authState?: any
location: any
}
const SideMenuItem = (props: Props) => {
const { location } = props
const { pathname } = location
const scopes = useAuthState().user?.scopes?.value || []
let allowedRoutes = {
routes: true,
location: false,
user: false,
bot: false,
scene: false,
party: false,
contentPacks: false,
groups: false,
instance: false,
invite: false,
globalAvatars: false,
projects: false
}
scopes.forEach((scope) => {
if (Object.keys(allowedRoutes).includes(scope.type.split(':')[0])) {
if (scope.type.split(':')[1] === 'read') {
allowedRoutes = {
...allowedRoutes,
[scope.type.split(':')[0]]: true
}
}
}
})
const classes = useStylesForDashboard()
const { t } = useTranslation()
const [openSetting, setOpenSeting] = React.useState(false)
const [openScene, setOpenScene] = React.useState(false)
const [openUser, setOpenUser] = React.useState(false)
const [openLocation, setOpenLocation] = React.useState(false)
const handleSetting = () => {
setOpenSeting(!openSetting)
setOpenScene(false)
setOpenUser(false)
setOpenLocation(false)
}
const handleScene = () => {
setOpenScene(!openScene)
setOpenSeting(false)
setOpenUser(false)
setOpenLocation(false)
}
const handleUser = () => {
setOpenUser(!openUser)
setOpenSeting(false)
setOpenScene(false)
setOpenLocation(false)
}
const handleLocation = () => {
setOpenLocation(!openLocation)
setOpenSeting(false)
setOpenScene(false)
setOpenUser(false)
}
return (
<>
<Divider />
<List>
<Link to="/admin" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
style={{ color: 'white' }}
selected={'/admin' === pathname}
button
>
<ListItemIcon>
<DashboardIcon style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Dashboard" />
</ListItem>
</Link>
{allowedRoutes.routes && (
<Link to="/admin/routes" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/routes' === pathname}
style={{ color: 'white' }}
button
>
<Shuffle>
<CalendarViewDay style={{ color: 'white' }} />
</Shuffle>
<ListItemText primary={t('user:dashboard.routes')} />
</ListItem>
</Link>
)}
{allowedRoutes.location || allowedRoutes.instance ? (
<ListItem style={{ color: 'white' }} button onClick={() => setOpenLocation(!openLocation)}>
<ListItemIcon>
<NearMe style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Location" />
{openLocation ? <ExpandLess /> : <ExpandMore />}
</ListItem>
) : (
''
)}
<Collapse in={openLocation} timeout="auto" unmountOnExit>
{allowedRoutes.location && (
<Link to="/admin/locations" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/locations' === pathname}
className={classes.nested}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<NearMe style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.locations')} />
</ListItem>
</Link>
)}
{allowedRoutes.instance && (
<Link to="/admin/instance" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/instance' === pathname}
className={classes.nested}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<DirectionsRun style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.instance')} />
</ListItem>
</Link>
)}
</Collapse>
{/* <Link to="/admin/sessions" className={classes.textLink}>
<ListItem style={{ color: 'white' }} button>
<ListItemIcon>
<DragIndicator style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.sessions')} />
</ListItem>
</Link> */}
{allowedRoutes.party && (
<Link to="/admin/parties" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/parties' === pathname}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<CalendarViewDay style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.parties')} />
</ListItem>
</Link>
)}
{/* <Link to="/admin/chats" className={classes.textLink}>
<ListItem style={{ color: 'white' }} button>
<ListItemIcon>
<Forum style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.chats')} />
</ListItem>
</Link> */}
{/* {allowedRoutes.user || allowedRoutes.invite || allowedRoutes.groups ? ( */}
<Link to="/admin/users" className={classes.textLink}>
<ListItem style={{ color: 'white' }} button onClick={() => setOpenUser(!openUser)}>
<ListItemIcon>
<SupervisorAccount style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Users" />
{openUser ? <ExpandLess /> : <ExpandMore />}
</ListItem>
</Link>
{/* ) : (
''
)} */}
<Collapse in={openUser} timeout="auto" unmountOnExit>
{allowedRoutes.user && (
<Link to="/admin/users" className={classes.textLink}>
<ListItem
style={{ color: 'white' }}
className={classes.nested}
classes={{ selected: classes.selected }}
selected={'/admin/users' === pathname}
button
>
<ListItemIcon>
<SupervisorAccount style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.users')} />
</ListItem>
</Link>
)}
{allowedRoutes.invite && (
<Link to="/admin/invites" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/invites' === pathname}
style={{ color: 'white' }}
className={classes.nested}
button
>
<ListItemIcon>
<PersonAdd style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.invites')} />
</ListItem>
</Link>
)}
{allowedRoutes.groups && (
<Link to="/admin/groups" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/groups' === pathname}
style={{ color: 'white' }}
className={classes.nested}
button
>
<ListItemIcon>
<GroupAdd style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.groups')} />
</ListItem>
</Link>
)}
</Collapse>
{allowedRoutes.scene || allowedRoutes.globalAvatars || allowedRoutes.contentPacks ? (
<ListItem style={{ color: 'white' }} button onClick={() => setOpenScene(!openScene)}>
<ListItemIcon>
<Casino style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Scene" />
{openScene ? <ExpandLess /> : <ExpandMore />}
</ListItem>
) : (
''
)}
<Collapse in={openScene} timeout="auto" unmountOnExit>
<Link to="/admin/scenes" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/scenes' === pathname}
style={{ color: 'white', background: '#15171B !important' }}
className={classes.nested}
button
>
<ListItemIcon>
<PhotoLibrary style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.scenes')} />
</ListItem>
</Link>
{allowedRoutes.globalAvatars && (
<Link to="/admin/avatars" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/avatars' === pathname}
className={classes.nested}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<Accessibility style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.avatars')} />
</ListItem>
</Link>
)}
{allowedRoutes.projects && (
<Link to="/admin/projects" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/projects' === pathname}
className={classes.nested}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<Code style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.projects')} />
</ListItem>
</Link>
)}
{allowedRoutes.contentPacks && (
<Link to="/admin/content-packs" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
selected={'/admin/content-packs' === pathname}
className={classes.nested}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<PhotoAlbum style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.content')} />
</ListItem>
</Link>
)}
</Collapse>
<ListItem style={{ color: 'white' }} button onClick={handleSetting}>
<ListItemIcon>
<Settings style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Setting" />
{openSetting ? <ExpandLess /> : <ExpandMore />}
</ListItem>
<Collapse in={openSetting} timeout="auto" unmountOnExit>
<Link to="/admin/settings" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
className={classes.nested}
selected={'/admin/settings' === pathname}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<Settings style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={'Setting'} />
</ListItem>
</Link>
{/* <Link to="/admin/bots" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
className={classes.nested}
selected={'/admin/setting' === pathname}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<Settings style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={'Setting'} />
</ListItem>
</Link> */}
{allowedRoutes.bot && (
<Link to="/admin/bots" className={classes.textLink}>
<ListItem
classes={{ selected: classes.selected }}
className={classes.nested}
selected={'/admin/bots' === pathname}
style={{ color: 'white' }}
button
>
<ListItemIcon>
<Toys style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('user:dashboard.bots')} />
</ListItem>
</Link>
)}
</Collapse>
</List>
<Divider style={{ background: '#C0C0C0', marginTop: '2rem' }} />
<List>
<ListSubheader inset style={{ color: '#C0C0C0' }}>
Social
</ListSubheader>
<List>
<Link style={{ textDecoration: 'none' }} to="/admin/feeds">
<ListItem
style={{ color: 'white' }}
// onClick={changeComponent}
classes={{ selected: classes.selected }}
selected={'/admin/feeds' === pathname}
button
>
<ListItemIcon>
<ViewModuleIcon style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('social:dashboard.feeds')} />
</ListItem>
</Link>
<Link style={{ textDecoration: 'none' }} to="/admin/armedia">
<ListItem
style={{ color: 'white' }}
// onClick={changeComponent}
classes={{ selected: classes.selected }}
selected={'/admin/armedia' === pathname}
button
>
<ListItemIcon>
<EmojiPeopleIcon style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary={t('social:dashboard.arMedia')} />
</ListItem>
</Link>
<Link style={{ textDecoration: 'none' }} to="/admin/creator">
<ListItem
style={{ color: 'white' }}
// onClick={changeComponent}
classes={{ selected: classes.selected }}
selected={'/admin/creator' === pathname}
button
>
<ListItemIcon>
<RemoveFromQueueIcon style={{ color: 'white' }} />
</ListItemIcon>
<ListItemText primary="Creator" />
</ListItem>
</Link>
</List>
</List>
</>
)
}
export default withRouter(SideMenuItem) | the_stack |
import type { Block, File, Geopoint, Image, Reference, Slug } from '../types'
import type {
ArrayRule,
Validator,
DatetimeRule,
NumberRule,
StringRule,
URLRule,
} from './validation'
type Component = () => any
interface Fieldset {
name: string
title?: string
options?: {
/**
* If set to true, the object will make the fieldsets collapsible. By default, objects will be collapsible when reaching a depth/nesting level of 3. This can be overridden by setting collapsible: false
*/
collapsible?: boolean
/**
* Set to true to display fieldsets as collapsed initially. This requires the collapsible option to be set to true and determines whether the fieldsets should be collapsed to begin with.
*/
collapsed?: boolean
}
}
export interface BaseField {
/**
* Required. The field name. This will be the key in the data record.
*/
name: string
/**
* Human readable label for the field.
*/
title?: string
/**
* If set to true, this field will be hidden in the studio.
*/
hidden?: boolean
/**
* If set to true, this field will not be editable in the content studio.
*/
readOnly?: boolean
/**
* Short description to editors how the field is to be used.
*/
description?: string
// Studio options
icon?: Component
inputComponent?: Component
options?: {
[key: string]: any
}
}
export interface ArrayField<
CustomObjectName extends string = never,
CustomDocuments extends { type: string } = never
> extends BaseField {
type: 'array'
/**
* Defines which types are allowed as members of the array.
*/
of: Array<
| Omit<ReferenceField<CustomDocuments>, 'name'>
| (PureType<CustomObjectName> & Partial<BaseField>)
| (Pick<Field, 'type'> & Partial<Field>)
>
options?: {
/**
* Controls whether the user is allowed to reorder the items in the array. Defaults to true.
*/
sortable?: boolean
/**
* If set to tags, renders the array as a single, tokenized input field. This option only works if the array contains strings.
If set to grid it will display in a grid
*/
layout?: 'grid' | 'tags'
/**
* [ {value: <value>, title: <title>}, { … } ] renders check boxes for titles and populates a string array with selected values
*/
list?: Array<{ value: string; title: string }>
/**
* Controls how the modal (for array content editing) is rendered. You can choose between dialog, fullscreen or popover. Default is dialog.
*/
editModal?: 'dialog' | 'fullscreen' | 'popover'
}
validation?: Validator<ArrayRule>
}
interface BlockEditor {
icon?: Component
render?: Component
}
interface BlockStyle {
title: string
value: string
blockEditor?: BlockEditor
}
interface Marks {
annotations?: Array<Field & { blockEditor?: BlockEditor }>
decorators?: BlockStyle[]
}
export interface BlockField extends BaseField {
type: 'block'
/**
* This defines which styles that applies to blocks. A style is an object with a title (will be displayed in the style dropdown) and a value, e.g.: styles: [{title: 'Quote', value: 'blockquote'}]. If no styles are given, the default styles are H1 up to H6 and blockquote. A style named normal is reserved, always included and represents "unstyled" text. If you don't want any styles, set this to an empty array e.g.: styles: [].
*/
styles?: Array<BlockStyle>
/**
* What list types that can be applied to blocks. Like styles above, this also is an array of "name", "title" pairs, e.g.: {title: 'Bullet', value: 'bullet'}. Default list types are bullet and number.
*/
lists?: Array<BlockStyle>
/**
* An object defining which .decorators (array) and .annotations (array) are allowed.
*/
marks?: Marks
/**
* An array of inline content types that you can place in running text from the Insert menu.
*/
of?: Array<{ type: Field['type'] } & Partial<Field>>
/**
* To return icon showed in menus and toolbar
*/
icon?: Component
validation?: Validator
}
interface BooleanField extends BaseField {
type: 'boolean'
options?: {
/**
* Either switch (default) or checkbox
This lets you control the visual appearance of the input. By default the input for boolean fields will display as a switch, but you can also make it appear as a checkbox
*/
layout: 'switch' | 'checkbox'
}
validation?: Validator
}
interface DateField extends BaseField {
type: 'date'
options?: {
/**
* Controls how the date input field formats the displayed date. Use any valid Moment format option. Default is YYYY-MM-DD.
*/
dateFormat?: string
/**
* Label for the "jump to today" button on the date input widget. Default is Today.
*/
calendarTodayLabel?: string
}
validation?: Validator
}
interface DatetimeField extends BaseField {
type: 'datetime'
options?: {
/**
* Controls how the date input field formats the displayed date. Use any valid Moment format option. Default is YYYY-MM-DD.
*/
dateFormat?: string
/**
* Controls how the time input field formats the displayed date. Use any valid Moment format option. Default is HH:mm.
*/
timeFormat?: string
/**
* Number of minutes between each entry in the time input. Default is 15 which lets the user choose between 09:00, 09:15, 09:30 and so on.
*/
timeStep?: number
/**
* Label for the "jump to today" button on the date input widget. Default is today.
*/
calendarTodayLabel?: string
}
validation?: Validator<DatetimeRule>
}
export interface DocumentField<T extends Record<string, any>>
extends BaseField {
type: 'document'
initialValue?: Record<string, any> | (() => Record<string, any>)
/**
* A declaration of possible ways to order documents of this type.
*/
orderings?: any[]
/**
* The fields of this object. At least one field is required.
*/
fields: DefinedFields<T> | Field[]
/**
* A list of fieldsets that fields may belong to.
*/
fieldsets?: Fieldset[]
/**
* Use this to implement an override for the default preview for this type.
*/
preview?: any
}
interface FileField<T extends Record<string, any>> extends BaseField {
type: 'file'
/**
* An array of optional fields to add to the file field. The fields added here follow the same pattern as fields defined on objects. This is useful for allowing users to add custom metadata related to the usage of this file (see example below).
*/
fields?: DefinedFields<T> | Field[]
options?: {
/**
* This will store the original filename in the asset document. Please be aware that the name of uploaded files could reveal potentially sensitive information (e.g. top_secret_planned_featureX.pdf). Default is true.
*/
storeOriginalFilename?: boolean
/**
* This specifies which mime types the file input can accept. Just like the accept attribute on native DOM file inputs and you can specify any valid file type specifier: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
*/
accept?: string
}
validation?: Validator
}
interface GeopointField extends BaseField {
type: 'geopoint'
validation?: Validator
}
interface ImageField<T extends Record<string, any>> extends BaseField {
type: 'image'
/**
* An array of optional fields to add to the image record. The fields added here follow the same pattern as fields defined on objects. This is useful for adding custom properties like caption, attribution, etc. to the image record itself (see example below). In addition to the common field attributes, each field may also have an isHighlighted option which dictates whether it should be prominent in the edit UI or hidden in a dialog modal behind an edit button (see example below).
*/
fields?: DefinedFields<T> | Field[]
// TODO:
// ObjectField<any>['fields'][0] & { options?: { isHighlighted?: boolean } }
options?: {
/**
* This option defines what metadata the server attempts to extract from the image. The extracted data is writtten into the image asset. This field must be an array of strings where accepted values are exif, location, lqip and palette.
*/
metadata?: Array<'exif' | 'location' | 'lqip' | 'palette'>
/**
* Enables the user interface for selecting what areas of an image should always be cropped, what areas should never be cropped and the center of the area to crop around when resizing. The hotspot data is stored in the image field itself, not in the image asset, so images can have different crop and center for each place they are used.
Hotspot makes it possible to responsively adapt the images to different aspect ratios at display time. The default is value for hotspot is false.
*/
hotspot?: boolean
/**
* This will store the original filename in the asset document. Please be aware that the name of uploaded files could reveal potentially sensitive information (e.g. top_secret_planned_featureX.pdf). Default is true.
*/
storeOriginalFilename?: boolean
/**
* This specifies which mime types the image input can accept. Just like the accept attribute on native DOM file inputs and you can specify any valid file type specifier: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers
*/
accept?: string
/**
* Lock the asset sources available to this type to a spesific subset. Import the plugins by their part name, and use the import variable name as array entries. The built in default asset source has the part name part:@sanity/form-builder/input/image/asset-source-default
*/
sources?: any[]
}
validation?: Validator
}
interface NumberField extends BaseField {
type: 'number'
validation?: Validator<NumberRule>
}
interface ObjectField<T extends Record<string, any>> extends BaseField {
type: 'object'
/**
* The fields of this object. At least one field is required.
*/
fields: DefinedFields<T> | Field[]
/**
* A list of fieldsets that fields may belong to.
*/
fieldsets?: Fieldset[]
/**
* Use this to implement an override for the default preview for this type.
*/
preview?: any
options?: {
/**
* If set to true, the object will make the fields collapsible. By default, objects will be collapsible when reaching a depth/nesting level of 3. This can be overridden by setting collapsible: false
*/
collapsible?: boolean
/**
* Set to true to display fields as collapsed initially. This requires the collapsible option to be set to true and determines whether the fields should be collapsed to begin with.
*/
collapsed?: boolean
}
validation?: Validator
}
interface ReferenceField<CustomType extends { type: string } = never>
extends BaseField {
type: 'reference'
/**
* Required. Must contain an array naming all the types which may be referenced e.g. [{type: 'person'}]. See more examples below.
*/
to: Array<PureType<CustomType['type']>>
/**
* Default false. If set to true the reference will be made weak. This means you can discard the object being referred to without first deleting the reference, thereby leaving a dangling pointer.
*/
weak?: boolean
options?: {
/**
* Additional GROQ-filter to use when searching for target documents. The filter will be added to the already existing type name clause.
If a function is provided, it is called with an object containing document, parent and parentPath properties, and should return an object containing filter and params.
Note: The filter only constrains the list of documents returned at the time you search. It does not guarantee that the referenced document will always match the filter provided.
*/
filter?:
| string
| ((context: {
document: DocumentField<Record<string, unknown>>
parent: Field
parentPath: string
}) => { filter: string; params: Record<string, any> })
/**
* Object of parameters for the GROQ-filter specified in filter.
*/
filterParams?: Record<string, any>
}
validation?: Validator
}
interface SlugField extends BaseField {
type: 'slug'
options?: {
/**
* The name of the field which the slug value is derived from. You can supply a function, instead of a string. If so, the source function is called with two parameters: doc (object - the current document) and options (object - with parent and parentPath keys for easy access to sibling fields).
*/
source?:
| string
| ((
doc: DocumentField<Record<string, unknown>>,
options: { parent: Field; parentPath: string }
) => string)
/**
* Maximum number of characters the slug may contain. Defaults to 200.
*/
maxLength?: number
/**
* Supply a custom override function which handles string normalization. slugify is called with two parameters: input (string) and type (object - schema type). If slugify is set, the maxLength option is ignored.
*/
slugify?: (input: string, type: Field) => string
/**
* Supply a custom function which checks whether or not the slug is unique. Receives the proposed slug as the first argument and an options object.
*/
isUnique?: (slug: string, options: SlugField['options']) => boolean
}
validation?: Validator
}
interface SpanField extends BaseField {
type: 'span'
validation?: Validator
}
interface StringField extends BaseField {
type: 'string'
options?: {
/**
* A list of predefined values that the user can choose from. The array can either include string values ['sci-fi', 'western'] or objects [{title: 'Sci-Fi', value: 'sci-fi'}, ...]
*/
list?: Array<string | { title: string; value: string }>
/**
* Controls how the items defined in the list option are presented. If set to 'radio' the list will render radio buttons. If set to 'dropdown' you'll get a dropdown menu instead. Default is dropdown.
*/
layout?: 'radio' | 'dropdown'
/**
* Controls how radio buttons are lined up. Use direction: 'horizontal|vertical' to render radio buttons in a row or a column. Default is vertical. Will only take effect if the layout option is set to radio.
*/
direction?: 'horizontal' | 'vertical'
}
validation?: Validator<StringRule>
}
interface TextField extends BaseField {
type: 'text'
rows?: number
validation?: Validator<StringRule>
}
export interface URLField extends BaseField {
type: 'url'
validation?: Validator<URLRule>
}
export interface CustomField<A extends string> extends BaseField {
type: A
validation?: Validator
}
export type Nameless<T> = Omit<T, 'name'>
export type UnnamedField<
CustomObjects extends { type: string } = { type: never },
CustomDocuments extends { type: string } = { type: never }
> =
| Nameless<ArrayField<CustomObjects['type'], CustomDocuments>>
| Nameless<BlockField>
| Nameless<BooleanField>
| Nameless<DateField>
| Nameless<DatetimeField>
// | Nameless<DocumentField>
| Nameless<FileField<any>>
| Nameless<GeopointField>
| Nameless<ImageField<any>>
| Nameless<NumberField>
| Nameless<ObjectField<any>>
| Nameless<ReferenceField<CustomDocuments>>
| Nameless<SlugField>
| Nameless<SpanField>
| Nameless<StringField>
| Nameless<TextField>
| Nameless<URLField>
| CustomObjects
type PureType<T extends string> = { type: T }
export const type = Symbol('the type of the property')
export type Field = UnnamedField & { name: string }
export type DefinedFields<T> = Array<Field & { [type]: T }>
type CustomTypeName<T extends { _type: string }> = { type: T['_type'] }
export type FieldType<
T extends UnnamedField<any>,
CustomObjects extends { _type: string }
> =
//
T extends PureType<'array'> & { of: Array<infer B> }
? Array<FieldType<B, CustomObjects>>
: T extends PureType<'block'>
? Block
: T extends PureType<'boolean'>
? boolean
: T extends
| PureType<'date'>
| PureType<'datetime'>
| PureType<'string'>
| PureType<'text'>
| PureType<'url'>
? string
: T extends PureType<'file'>
? File
: T extends PureType<'geopoint'>
? Geopoint
: T extends Nameless<ImageField<infer A>>
? Image & A
: T extends PureType<'image'>
? Image
: T extends PureType<'number'>
? number
: T extends Nameless<ObjectField<infer A>>
? A
: T extends PureType<'reference'> & { to: Array<infer B> }
? Reference<FieldType<B, CustomObjects>>
: T extends PureType<'slug'>
? Slug
: T extends { [type]: infer B }
? B
: T extends CustomTypeName<CustomObjects>
? Extract<CustomObjects, { _type: T['type'] }>
: Record<string, any> | the_stack |
import cx from 'classnames';
import { debounce } from 'lodash-es';
import { waitFor, waitSelector, triggerMouseEvent } from '../utils/contentScript';
import styles from './docs.module.scss';
import { Token } from 'client-oauth2';
import { GapiClient } from '../utils/gapi';
import { Singleflight } from '@zcong/singleflight';
import { getManifestInfo, ManifestDrive, ManifestData } from '../utils/manifest';
import ReactDOM from 'react-dom';
import { useEffect, useState, useMemo } from 'react';
import { useToken } from '../utils/hooks/oauth';
import { Folders16, Launch16, WarningAltFilled16 } from '@carbon/icons-react';
import Button from 'carbon-components-react/lib/components/Button';
import { log } from '../utils/log';
const sf = new Singleflight();
type FileHasId = gapi.client.drive.File & {
id: string;
}
type TreePathItem = {
name: string;
url: string;
};
type FileInfo = {
fileInfo?: BasicFileInfo
parentTree?: ParentTree
sharedExternally?: gapi.client.drive.Permission[]
}
type ParentTree = {
folder?: TreePathItem;
parents: Array<TreePathItem>;
}
type BasicFileInfo = {
isOrphanAndOwner?: boolean;
privateOwners?: null | gapi.client.drive.User[];
trashed?: boolean;
discoveredDrive: ManifestDrive | null;
discoveredWorkspace: string | null;
file: TreePathItem;
};
function buildFolderUrl(id: string, drive: ManifestDrive | null) {
return drive
? `${drive.workspace}/view/${id}`
: `https://drive.google.com/drive/folders/${id}`;
}
function buildFileUrl(id: string, drive: ManifestDrive | null) {
return drive
? `${drive.workspace}/view/${id}`
: `https://drive.google.com/file/d/${id}`;
}
interface HasEmailAddress {
emailAddress?: string
}
function getDomainFromUser(user: HasEmailAddress): string | null {
const domain = user.emailAddress?.split("@")?.[1]
return (!domain || domain === "") ? null : domain
}
function getDomainFromPermission(permission: gapi.client.drive.Permission): string | null {
return permission.domain ?? getDomainFromUser(permission)
}
function partitionEquals<Eq, Item>(value: Eq, array: Item[], pluck: (arg: Item) => Eq): [Item[], Item[]] {
const equals = []
const notEquals = []
for (const item of array) {
if (pluck(item) === value) {
equals.push(item)
} else {
notEquals.push(item)
}
}
return [equals, notEquals]
}
function initialFileInfo(
manifestData: ManifestData | null,
file: FileHasId,
): BasicFileInfo {
const drives = manifestData?.drives ?? {};
let discoveredDrive: ManifestDrive | null = null;
let discoveredWorkspace: string | null = null;
for (const name in drives) {
if (drives[name].driveId === file.driveId) {
discoveredDrive = drives[name];
discoveredWorkspace = name;
break;
}
}
const driveForFile = discoveredDrive || drives[Object.keys(drives)[0]];
const fileUrl = buildFileUrl(file.id, driveForFile)
let fi: BasicFileInfo = {
discoveredDrive,
discoveredWorkspace,
file: {
name: file.name ?? file.id,
url: fileUrl,
},
}
if (file.trashed) {
log.info('Skipped the file since it is trashed');
return {
...fi,
trashed: true,
};
}
if (file.ownedByMe) {
log.info('File is owned by current user, and it should be orphaned');
return {
...fi,
isOrphanAndOwner: true,
};
}
if (!file.driveId) {
log.info(
'File does not have a drive id, maybe the owner did not put it in the Wiki, skip listing parents'
);
const domain = manifestData?.gapiHostedDomain
const orgOwners = !domain
? (file.owners || null)
: partitionEquals(domain, file.owners ?? [], (user) => getDomainFromUser(user))[0]
return {
...fi,
privateOwners: orgOwners,
};
}
return fi
}
async function loadFileInfo(
client: GapiClient,
fileInfo: BasicFileInfo,
file: FileHasId,
): Promise<ParentTree | undefined> {
// Now we know the drive of the file, let's list parents.
log.info(`Analyzing parents for file ${file.id}`, file.parents);
const parents: Array<TreePathItem> = [];
const visitedParentIds = new Set<string>();
let currentFile = file as gapi.client.drive.File;
while (true) {
const parentId = currentFile.parents?.[0];
if (!parentId) {
log.info(`break: no parent id`);
break;
}
if (visitedParentIds.has(parentId)) {
log.info('Parent has been visited, break the loop', currentFile.parents);
break;
}
visitedParentIds.add(parentId);
const { discoveredDrive, discoveredWorkspace } = fileInfo
if (discoveredDrive && (discoveredDrive.driveId === parentId || discoveredDrive.rootId === parentId)) {
log.info(`Parent is the workspace, finished`, discoveredWorkspace, discoveredDrive, parentId);
parents.push({
name: discoveredWorkspace!,
url: buildFolderUrl(parentId, discoveredDrive),
});
break;
}
try {
log.info(`Getting parent file info (parent id = ${parentId})`);
const parentFile = await client.getDriveFile(parentId, {
fields: '*',
supportsAllDrives: true,
});
parents.push({
name: parentFile.name!,
url: buildFolderUrl(parentId, discoveredDrive),
});
currentFile = parentFile;
} catch (e) {
log.error(e);
break;
}
}
parents.reverse();
log.info(`Parents list has been built`, parents);
return {
folder: parents.pop(),
parents
};
}
async function commentPleaseShare(fileId: string, token: Token, content: string): Promise<null> {
const client = new GapiClient(token);
log.info(`Getting file info for base file ${fileId}`);
return await client.addComment(fileId, content);
}
function useFileInfo(fileId: string, token?: Token): [FileInfo, boolean] {
const [loading, setLoading] = useState(true);
const [loadToken, setLoadToken] = useState(0); // Used to reload the file
const [file, setFile] = useState<FileHasId | undefined | null>(undefined);
const [sharedExternally, setSharedExternally] = useState<gapi.client.drive.Permission[] | undefined>(undefined);
const [manifestData, setManifestData] = useState<ManifestData | null | undefined>(undefined);
const [fileInfo, setFileInfo] = useState<BasicFileInfo | undefined>(undefined);
const [parentFi, setParentFi] = useState<ParentTree | undefined>(undefined);
const client = useMemo(
() => token ? new GapiClient(token!) : null,
[token],
)
useEffect(function doGetManifest() {
async function getManifest() {
const manifest = await getManifestInfo();
if (!manifest) {
log.warn('manifest is unavailable');
setManifestData(null)
} else {
const fi = initialFileInfo(manifest.data, file!)
setFileInfo(fi)
setManifestData(manifest.data)
}
}
if (file) {
sf.do('doGetManifest' + file.id, getManifest);
}
}, [file])
useEffect(function doLoadFile() {
async function loadFile() {
if (!client) {
return
}
setLoading(true);
try {
log.info('Get Google drive file', fileId);
const f = await client!.getDriveFile(fileId, {
fields: '*',
supportsAllDrives: true,
});
if (!f.id) {
throw new Error (`file does not have id ${f}`);
} else {
setFile(f as FileHasId)
}
} catch (e) {
log.error(e);
setFile(null);
}
}
if (fileId) {
sf.do('doLoadFile' + fileId, loadFile);
}
}, [fileId, client, loadToken]);
useEffect(function doLoadFileInfo() {
async function run() {
if (!file || !client || !fileInfo) {
return
}
setLoading(true);
try {
const parentTree = await loadFileInfo(client, fileInfo, file);
setParentFi(parentTree);
} catch (e) {
log.error(e);
} finally {
setLoading(false);
}
}
if (file) {
sf.do('doLoadFileInfo' + file.id, run);
}
}, [file, client, fileInfo]);
useEffect(function checkShareExternalFromDrive() {
const domain = manifestData?.gapiHostedDomain
if (!domain || !file) {
return
}
async function checkSharing() {
if (!file || !file.hasAugmentedPermissions || !client || !domain) {
return
}
// This is for a folder in a shared drive
log.debug(`file has ${file.permissionIds?.length} augmented permissions`)
try {
const data = await client.getFilePermissions(file.id, {
fields: 'permissions(permissionDetails, id, type, kind, emailAddress, domain, role, displayName)',
supportsAllDrives: true,
});
const anyPerm = data.permissions.filter((perm) => perm.type === 'anyone');
if (anyPerm.length > 0) {
log.info('shared to any', anyPerm);
setSharedExternally(anyPerm);
} else {
// Filter out permissions not associated to an email
const permissions = data.permissions.filter((perm) => {
const inherited = !!perm.permissionDetails?.[0]?.inherited
return !!getDomainFromPermission(perm) || (function(){
if (inherited) {
// TODO: inherited permissions probably require that we look at the folder
log.info('ignore inherited permission', perm);
return false;
}
log.info('unknown permission', perm);
return false;
})()
})
const [, notOrgMembers] = partitionEquals(domain, permissions, getDomainFromPermission)
if (notOrgMembers.length > 0) {
log.info('shared to not org', notOrgMembers);
setSharedExternally(notOrgMembers);
}
}
} catch (e) {
console.error('error getting file permissions', e)
}
}
if (file.shared && file.permissions) {
const [, notOrgMembers] = partitionEquals(domain, file.permissions, getDomainFromPermission)
if (notOrgMembers.length > 0) {
setSharedExternally(notOrgMembers)
}
log.info(`file has been shared ${file.permissionIds?.length}`, notOrgMembers)
} else {
sf.do('checkShareExternalFromDrive' + file.id, checkSharing);
}
}, [file, manifestData, client])
useEffect(function addFileNameToParam() {
if (!file) {
return
}
// Put the document name in the URL
// Then when we send the link to others they will see the title
try {
var urlParams = new URLSearchParams(window.location.search);
if (file.name && !urlParams.get('n')) {
// Change invalid characters to '_' but don't show 2 of those next to each other
// Change '_-_' to '-'
const paramValue = encodeURIComponent(file.name.replaceAll('%', '_'))
.replaceAll(/%../g, '_')
.replaceAll(/_+/g, '_')
.replaceAll(/_-/g, '-')
.replaceAll(/-_+/g, '-')
.replace(/_+$/, '')
.replace(/^_+/, '');
urlParams.set('n', paramValue);
const newUrl = window.location.origin + window.location.pathname + '?' + urlParams.toString();
window.history.replaceState({path: newUrl}, "", newUrl);
}
} catch (e) {
log.warn("error trying to add doc name to parameters ", e);
}
}, [file]);
useEffect(function observeDirectoryChange() {
const handlePickerHide = debounce(() => {
// When picker is closed, trigger reload
setLoadToken((t) => t + 1);
}, 5000);
const el = document.querySelector('#docs-chrome');
if (!el) {
log.error('GdocWiki failed to discover docs header, ignoring file location change');
return;
}
const ms = new MutationObserver((records) => {
for (let r of records) {
const el = r.target as HTMLDivElement;
if (!el.classList.contains('picker-iframe')) {
continue;
}
if (el.style.visibility === 'hidden') {
handlePickerHide();
}
}
});
ms.observe(el, {
attributes: true,
subtree: true,
attributeFilter: ['style'],
});
}, []);
return [{ sharedExternally, fileInfo, parentTree: parentFi }, loading];
}
function App(props: { id: string }) {
const [token, isTokenLoading] = useToken();
const [{ sharedExternally, fileInfo, parentTree }] = useFileInfo(props.id, token);
if (!token || isTokenLoading) {
return <Loading token={token} isTokenLoading={isTokenLoading} />
}
if (!fileInfo || fileInfo.trashed) {
return null
}
return (
<>
<SharedExternally shares={sharedExternally} />
{fileInfo.isOrphanAndOwner && (
<span className={cx(styles.tag, styles.warning)}>
<WarningAltFilled16 style={{ marginRight: 6 }} />
Not in a shared drive
</span>
)}
{fileInfo.privateOwners && <PrivateOwners id={props.id} token={token} privateOwners={fileInfo.privateOwners} />}
{parentTree && <Folders file={fileInfo.file} parentTree={parentTree} />}
<a href={fileInfo.file.url} target="_blank" rel="noreferrer" className={styles.wikiTreeIcon}>
<Launch16/>
</a>
</>
);
}
function Loading(props: { isTokenLoading?: boolean; token?: Token; }) {
if (props.isTokenLoading || !props.token) {
return null
}
return (
<a
className={cx(styles.tag, styles.danger, styles.clickable)}
href={chrome.runtime.getURL('options.html')}
target="_blank"
rel="noreferrer"
>
<Launch16 style={{ marginRight: 6 }} />
GdocWiki Extension Not Enabled
</a>
)
}
function SharedExternally(props: { shares?: gapi.client.drive.Permission[]; }) {
const [showExtra, setShowExtra] = useState(false);
if (!props.shares || props.shares.length === 0) {
return null
}
function shareSummary(share: gapi.client.drive.Permission): string {
return share.type === 'anyone' ? (
'anyone with the link'
) : (
`to ${share?.emailAddress || share?.domain || share?.type}`
)
}
return showExtra ?
<>
<WarningAltFilled16 style={{ marginRight: 6 }} />
<span className={cx(styles.tag)} onClick={() => {setShowExtra(v => !v)}}>
Shared externally to {shareSummary(props.shares[0])}
{props.shares.length > 1 && (' and others')}
</span>
</> :
<>
<Button className={cx(styles.tag, styles.warning)} onClick={() => {setShowExtra(v => !v)}}>
<WarningAltFilled16 style={{ marginRight: 6 }} />
Externally Shared
</Button>
</>
}
function PrivateOwners(props: { id: string, token: Token, privateOwners: gapi.client.drive.User[]; }) {
const [showExtra, setShowExtra] = useState(false);
const [askShared, setAskShared] = useState(false);
const { privateOwners, token, id } = props;
async function askSharedDrive(user: gapi.client.drive.User) {
const ask = "@" + user.displayName + " Please add this file to a shared drive. That helps organize information, make it more discoverable, and manage permissions."
setAskShared(v => !v)
try {
log.info('Comment to move file to a shared drive', props.id);
await commentPleaseShare(id, token, ask);
} catch (e) {
log.error(e);
} finally {
log.info("finally commented")
}
}
return showExtra ?
<>
<WarningAltFilled16 style={{ marginRight: 6 }} />
<span className={cx(styles.tag)} onClick={() => {setShowExtra(v => !v)}}>
Owned by {privateOwners?.[0].displayName} {privateOwners?.[0].emailAddress}
</span>
{!askShared &&
<Button className={cx(styles.tag)} onClick={() => {askSharedDrive(privateOwners?.[0]!)}}>
Ask for shared drive
</Button>
}
</> :
<>
<Button className={cx(styles.tag, styles.warning)} onClick={() => {setShowExtra(v => !v)}}>
<WarningAltFilled16 style={{ marginRight: 6 }} />
Not in a shared drive
</Button>
</>
}
function Folders(props: {file: TreePathItem, parentTree: ParentTree}) {
const { parentTree, file } = props;
if (!parentTree.folder) {
return null
}
return (
<div className={styles.wikiTree}>
<a href={file.url} style={{ paddingRight: '3px', color: 'black' }} target="_blank" rel="noreferrer" className={styles.wikiTreeIcon}>
<Folders16 />
</a>
{parentTree.parents?.map((pi) => {
return (
<div key={pi.url}>
<a href={pi.url} target="_blank" rel="noreferrer" className={styles.wikiTreeItem}>
{pi.name}
/
</a>
</div>
);
})}
<a href={parentTree.folder.url} target="_blank" rel="noreferrer" className={styles.wikiTreeItem}>
{parentTree.folder.name}
/
</a>
</div>
)
}
export async function runDocs(id: string) {
const isIframe = (window !== window.parent);
// Users can add ?versions to the url params to deep-link to the versions page
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('versions')) {
log.debug('wait to click on versions link');
const docsNotice = await waitFor(() => {
const docsNotice = document.getElementById('docs-notice');
if (!docsNotice || docsNotice.textContent === "" || docsNotice.getAttribute("aria-disabled") === "true") {
throw new Error("No docs notice");
}
return docsNotice
})
if (docsNotice) {
log.debug("found versions link, triggering click")
triggerMouseEvent(docsNotice, "mousedown", {})
setTimeout(function(){
log.info("mouseup")
triggerMouseEvent(docsNotice, "mouseup", {})
}, 100)
} else {
log.debug("no docs version link found")
}
}
/* TODO: this does not properly wait for the menu item to be clickable
if (urlParams.has('suggesting')) {
log.info('wait for suggesting dropdown');
const dropdown = await waitFor(() => {
const modeSwitch = document.getElementById('docs-toolbar-mode-switcher');
if (!modeSwitch || modeSwitch.style.display === 'none') {
throw new Error("No mode switcher");
}
const dropdown = modeSwitch.querySelector('.goog-toolbar-menu-button-dropdown')
if (!dropdown || (dropdown as HTMLElement).style.display === 'none') {
throw new Error("No mode switcher dropdown");
}
return dropdown
})
if (!dropdown) {
log.info('no suggesting dropdown');
} else {
log.info('clicking on suggesting dropdown');
triggerMouseEvent(dropdown, "mousedown", {})
// TODO: actually select suggesting
}
}
*/
// We assume an iframe means embedded inside gdocwiki.
// TODO: if that is not the case, this code should be ran
if (isIframe) {
log.info('in Iframe, not loading all functionality');
} else {
const elements = await waitSelector('.docs-title-outer');
const containerElement = elements[0] as HTMLDivElement;
const appContainer = document.createElement('div');
appContainer.classList.add(styles.container);
containerElement.prepend(appContainer);
ReactDOM.render(<App id={id} />, appContainer);
}
} | the_stack |
import { Request, Response } from "express";
import FileService from "../services/FileService";
import MongoService from "../services/ChunkService/MongoService";
import FileSystemService from "../services/ChunkService/FileSystemService";
import S3Service from "../services/ChunkService/S3Service";
import User, {UserInterface} from "../models/user";
import sendShareEmail from "../utils/sendShareEmail";
import { createStreamVideoCookie, removeStreamVideoCookie } from "../cookies/createCookies";
const fileService = new FileService()
type userAccessType = {
_id: string,
emailVerified: boolean,
email: string,
s3Enabled: boolean,
}
interface RequestTypeFullUser extends Request {
user?: UserInterface,
encryptedToken?: string,
accessTokenStreamVideo?: string
}
interface RequestType extends Request {
user?: userAccessType,
encryptedToken?: string
}
type ChunkServiceType = MongoService | FileSystemService | S3Service;
class FileController {
chunkService: ChunkServiceType;
constructor(chunkService: ChunkServiceType) {
this.chunkService = chunkService;
}
getThumbnail = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user;
const id = req.params.id;
const decryptedThumbnail = await this.chunkService.getThumbnail(user, id);
res.send(decryptedThumbnail);
} catch (e) {
console.log("\nGet Thumbnail Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getFullThumbnail = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user;
const fileID = req.params.id;
await this.chunkService.getFullThumbnail(user, fileID, res);
} catch (e) {
console.log("\nGet Thumbnail Full Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
uploadFile = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return
}
try {
const user = req.user;
const busboy = req.busboy;
req.pipe(busboy);
const file = await this.chunkService.uploadFile(user, busboy, req);
res.send(file);
} catch (e) {
console.log("\nUploading File Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.writeHead(code, {'Connection': 'close'})
res.end();
}
}
getPublicDownload = async(req: RequestType, res: Response) => {
try {
const ID = req.params.id;
const tempToken = req.params.tempToken;
await this.chunkService.getPublicDownload(ID, tempToken, res);
} catch (e) {
console.log("\nGet Public Download Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
removeLink = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const id = req.params.id;
const userID = req.user._id;
await fileService.removeLink(userID, id)
res.send();
} catch (e) {
console.log("\nRemove Public Link Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
makePublic = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const fileID = req.params.id;
const userID = req.user._id;
const token = await fileService.makePublic(userID, fileID);
res.send(token);
} catch (e) {
console.log("\nMake Public Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getPublicInfo = async(req: RequestType, res: Response) => {
try {
const id = req.params.id;
const tempToken = req.params.tempToken;
const file = await fileService.getPublicInfo(id, tempToken);
res.send(file);
} catch (e) {
console.log("\nGet Public Info Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
makeOneTimePublic = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const id = req.params.id;
const userID = req.user._id;
const token = await fileService.makeOneTimePublic(userID, id);
res.send(token);
} catch (e) {
console.log("\nMake One Time Public Link Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getFileInfo = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const fileID = req.params.id;
const userID = req.user._id;
const file = await fileService.getFileInfo(userID, fileID);
res.send(file);
} catch (e) {
console.log("\nGet File Info Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getQuickList = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user;
const quickList = await fileService.getQuickList(user);
res.send(quickList);
} catch (e) {
console.log("\nGet Quick List Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getList = async(req: RequestType, res: Response) => {
if (!req.user) {
return
}
try {
const user = req.user;
const query = req.query;
const fileList = await fileService.getList(user, query);
res.send(fileList);
} catch (e) {
console.log("\nGet File List Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getDownloadToken = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return
}
try {
const user = req.user;
const tempToken = await fileService.getDownloadToken(user);
res.send({tempToken});
} catch (e) {
console.log("\nGet Download Token Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getAccessTokenStreamVideo = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) return;
try {
const user = req.user;
const currentUUID = req.headers.uuid as string;
const streamVideoAccessToken = await user.generateAuthTokenStreamVideo(currentUUID);
createStreamVideoCookie(res, streamVideoAccessToken);
res.send();
} catch (e) {
console.log("\nGet Access Token Stream Video Fle Route Error:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
removeStreamVideoAccessToken = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) return;
try {
const userID = req.user._id;
const accessTokenStreamVideo = req.accessTokenStreamVideo!;
await User.updateOne({_id: userID}, {$pull: {tempTokens: {token: accessTokenStreamVideo}}});
removeStreamVideoCookie(res);
res.send();
} catch (e) {
console.log("\Remove Video Token File Router Error:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
// No longer needed, left for reference
// getDownloadTokenVideo = async(req: RequestTypeFullUser, res: Response) => {
// if (!req.user) {
// return
// }
// try {
// const user = req.user;
// const cookie = req.headers.uuid as string;
// const tempToken = await fileService.getDownloadTokenVideo(user, cookie);
// res.send({tempToken});
// } catch (e) {
// const code = e.code || 500;
// console.log(e);
// res.status(code).send()
// }
// }
removeTempToken = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return
}
try {
const user = req.user
const tempToken = req.params.tempToken;
const currentUUID = req.params.uuid;
await fileService.removeTempToken(user, tempToken, currentUUID);
res.send();
} catch (e) {
console.log("\nRemove Temp Token Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
streamVideo = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user;
const fileID = req.params.id;
const headers = req.headers;
await this.chunkService.streamVideo(user, fileID, headers, res, req);
} catch (e) {
console.log("\nStream Video Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
downloadFile = async(req: RequestTypeFullUser, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user;
const fileID = req.params.id;
await this.chunkService.downloadFile(user, fileID, res);
} catch (e) {
console.log("\nDownload File Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
getSuggestedList = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const userID = req.user._id;
let searchQuery = req.query.search || "";
const {fileList, folderList} = await fileService.getSuggestedList(userID, searchQuery);
return res.send({folderList, fileList})
} catch (e) {
console.log("\nGet Suggested List Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
renameFile = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const fileID = req.body.id;
const title = req.body.title
const userID = req.user._id;
await fileService.renameFile(userID, fileID, title)
res.send();
} catch (e) {
console.log("\nRename File Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
sendEmailShare = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const user = req.user!;
const fileID = req.body.file._id;
const respient = req.body.file.resp;
const file = await fileService.getFileInfo(user._id, fileID);
await sendShareEmail(file, respient)
res.send()
} catch (e) {
console.log("\nSend Share Email Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
moveFile = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const fileID = req.body.id;
const userID = req.user._id;
const parentID = req.body.parent;
await fileService.moveFile(userID, fileID, parentID);
res.send();
} catch (e) {
console.log("\nMove File Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
deleteFile = async(req: RequestType, res: Response) => {
if (!req.user) {
return;
}
try {
const userID = req.user._id;
const fileID = req.body.id;
await this.chunkService.deleteFile(userID, fileID);
res.send()
} catch (e) {
console.log("\nDelete File Error File Route:", e.message);
const code = !e.code ? 500 : e.code >= 400 && e.code <= 599 ? e.code : 500;
res.status(code).send();
}
}
}
export default FileController; | the_stack |
import path from 'path'
import Debug from 'debug'
import fs from 'fs-extra'
import imageSize from 'probe-image-size'
import Vibrant from 'node-vibrant'
import sharp from 'sharp'
import termimg from 'term-img'
import Table from 'cli-table3'
import chalk from 'chalk'
import { Palette } from '@vibrant/color'
import { OptionDefinition } from 'command-line-args'
import { locateFiles } from './helpers'
export { loadSVG, parseColor } from './helpers'
const debug = Debug('sqip')
const mainKeys = ['originalWidth', 'originalHeight', 'width', 'height', 'type']
const PALETTE_KEYS: (keyof Palette)[] = [
'Vibrant',
'DarkVibrant',
'LightVibrant',
'Muted',
'DarkMuted',
'LightMuted'
]
export interface SqipResult {
content: Buffer
metadata: SqipImageMetadata
}
export interface SqipCliOptionDefinition extends OptionDefinition {
description?: string
required?: boolean
default?: boolean
}
export interface PluginOptions {
[key: string]: unknown
}
interface PluginResolver {
name: string
options?: PluginOptions
}
interface SqipOptions {
input: string | Buffer
outputFileName?: string
output?: string
silent?: boolean
parseableOutput?: boolean
plugins?: PluginType[]
width?: number
}
interface SqipConfig {
input: string | Buffer
outputFileName?: string
output?: string
silent?: boolean
parseableOutput?: boolean
plugins: PluginType[]
width?: number
}
interface ProcessFileOptions {
buffer: Buffer
outputFileName: string
config: SqipConfig
}
export interface SqipImageMetadata {
originalWidth: number
originalHeight: number
palette: Palette
height: number
width: number
type: 'unknown' | 'pixel' | 'svg'
[key: string]: unknown
}
type PluginType = PluginResolver | string
export interface SqipPluginOptions {
pluginOptions: PluginOptions
options: PluginOptions
sqipConfig: SqipConfig
}
interface SqipPluginInterface {
sqipConfig: SqipConfig
apply(
imageBuffer: Buffer,
metadata?: SqipImageMetadata
): Promise<Buffer> | Buffer
}
export class SqipPlugin implements SqipPluginInterface {
public sqipConfig: SqipConfig
public options: PluginOptions
static cliOptions: SqipCliOptionDefinition[]
constructor(options: SqipPluginOptions) {
const { sqipConfig } = options
this.sqipConfig = sqipConfig || {}
this.options = {}
}
apply(
imageBuffer: Buffer,
metadata: SqipImageMetadata
): Promise<Buffer> | Buffer {
console.log(metadata)
return imageBuffer
}
}
// Resolves plugins based on a given config
// Array of plugin names or config objects, even mixed.
export async function resolvePlugins(
plugins: PluginType[]
): Promise<(PluginResolver & { Plugin: typeof SqipPlugin })[]> {
return Promise.all(
plugins.map(async (plugin) => {
if (typeof plugin === 'string') {
plugin = { name: plugin }
}
const { name } = plugin
if (!name) {
throw new Error(
`Unable to read plugin name from:\n${JSON.stringify(plugin, null, 2)}`
)
}
const moduleName =
name.indexOf('sqip-plugin-') !== -1 ? name : `sqip-plugin-${name}`
try {
debug(`Loading ${moduleName}`)
const Plugin = await import(moduleName)
return { ...plugin, Plugin: Plugin.default }
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
throw new Error(
`Unable to load plugin "${moduleName}". Try installing it via:\n\n npm install ${moduleName}`
)
}
throw err
}
})
)
}
async function processFile({
buffer,
outputFileName,
config
}: ProcessFileOptions) {
const { output, silent, parseableOutput } = config
const result = await processImage({ buffer, config })
const { content, metadata } = result
let outputPath
debug(`Processed ${outputFileName}`)
// Write result svg if desired
if (output) {
try {
// Test if output path already exists
const stats = await fs.stat(output)
// Throw if it is a file and already exists
if (!stats.isDirectory()) {
throw new Error(
`File ${output} already exists. Overwriting is not yet supported.`
)
}
outputPath = path.resolve(output, `${outputFileName}.svg`)
} catch (err) {
// Output directory or file does not exist. We will create it later on.
outputPath = output
}
debug(`Writing ${outputPath}`)
await fs.writeFile(outputPath, content)
}
// Gather CLI output information
if (!silent) {
if (outputPath) {
console.log(`Stored at: ${outputPath}`)
}
// Generate preview
if (!parseableOutput) {
// Convert to png for image preview
const preview = await sharp(Buffer.from(content)).png().toBuffer()
try {
termimg(preview, {
fallback: () => {
// SVG results can still be outputted as string
if (metadata.type === 'svg') {
console.log(content.toString())
return
}
// No fallback preview solution yet for non-svg files.
console.log(
`Unable to render a preview for ${metadata.type} files on this machine. Try using https://iterm2.com/`
)
}
})
} catch (err) {
if (err.name !== 'UnsupportedTerminalError') {
throw err
}
}
}
// Metadata
const tableConfig = parseableOutput
? {
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
bottom: '',
'bottom-mid': '',
'bottom-left': '',
'bottom-right': '',
left: '',
'left-mid': '',
mid: '',
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' '
},
style: { 'padding-left': 0, 'padding-right': 0 }
}
: undefined
// Figure out which metadata keys to show
// @todo why is this unused?
// const allKeys = [...mainKeys, 'palette']
const mainTable = new Table(tableConfig)
mainTable.push(mainKeys)
mainTable.push(
mainKeys.map((key) => String(metadata[key]) || 'can not display')
)
console.log(mainTable.toString())
// Show color palette
const paletteTable = new Table(tableConfig)
paletteTable.push(PALETTE_KEYS)
paletteTable.push(
PALETTE_KEYS.map((key) => metadata.palette[key]?.hex)
.filter<string>((hex): hex is string => typeof hex === 'string')
.map((hex) => chalk.hex(hex)(hex))
)
console.log(paletteTable.toString())
Object.keys(metadata)
.filter((key) => ![...mainKeys, 'palette'].includes(key))
.forEach((key) => {
console.log(chalk.bold(`${key}:`))
console.log(metadata[key])
})
}
return result
}
interface ProcessImageOptions {
buffer: Buffer
config: SqipConfig
}
async function processImage({
buffer,
config
}: ProcessImageOptions): Promise<SqipResult> {
const originalSizes = imageSize.sync(buffer)
// Extract the palette from the image. We delegate to node-vibrant (which is
// using jimp internally), and it only supports some image formats. In
// particular, it does not support WebP and HEIC yet.
//
// So we try with the given image buffer, and if the code throws an exception
// we try again after converting to TIFF. If that fails again we give up.
const palette = await (async () => {
const getPalette = (buffer: Buffer) =>
Vibrant.from(buffer).quality(0).getPalette()
try {
return await getPalette(buffer)
} catch {
return getPalette(await sharp(buffer).tiff().toBuffer())
}
})()
if (!originalSizes) {
throw new Error('Unable to get image size')
}
const metadata: SqipImageMetadata = {
originalWidth: originalSizes.width,
originalHeight: originalSizes.height,
palette,
// @todo this should be set by plugins and detected initially
type: 'unknown',
width: 0,
height: 0
}
// Load plugins
const plugins = await resolvePlugins(config.plugins)
// Determine output image size
if (config.width && config.width > 0) {
// Resize to desired output width
try {
buffer = await sharp(buffer).resize(config.width).toBuffer()
const resizedMetadata = await sharp(buffer).metadata()
metadata.width = resizedMetadata.width || 0
metadata.height = resizedMetadata.height || 0
} catch (err) {
throw new Error('Unable to resize')
}
} else {
// Fall back to original size, keep image as is
metadata.width = originalSizes.width
metadata.height = originalSizes.height
}
// Interate through plugins and apply them to last returned image
for (const { name, options: pluginOptions, Plugin } of plugins) {
debug(`Construct ${name}`)
const plugin = new Plugin({
sqipConfig: config,
pluginOptions: pluginOptions || {},
options: {}
})
debug(`Apply ${name}`)
buffer = await plugin.apply(buffer, metadata)
}
return { content: buffer, metadata }
}
export async function sqip(
options: SqipOptions
): Promise<SqipResult | SqipResult[]> {
// Build configuration based on passed options and default options
const defaultOptions = {
plugins: [
{ name: 'primitive', options: { numberOfPrimitives: 8, mode: 0 } },
'blur',
'svgo',
'data-uri'
],
width: 300,
parseableOutput: false,
silent: true
}
const config: SqipConfig = Object.assign({}, defaultOptions, options)
const { input, outputFileName, parseableOutput, silent } = config
if (parseableOutput) {
chalk.level = 0
}
// Validate configuration
if (!input || input.length === 0) {
throw new Error(
'Please provide an input image, e.g. sqip({ input: "input.jpg" })'
)
}
// If input is a Buffer
if (Buffer.isBuffer(input)) {
if (!outputFileName) {
throw new Error(
`${outputFileName} is required when passing image as buffer`
)
}
return processFile({
buffer: input,
outputFileName,
config
})
}
const files = await locateFiles(input)
debug('Found files:')
debug(files)
// Test if all files are accessable
for (const file of files) {
try {
debug('check file ' + file)
await fs.access(file, fs.constants.R_OK)
} catch (err) {
throw new Error(`Unable to read file ${file}`)
}
}
// Iterate over all files
const results = []
for (const filePath of files) {
// Apply plugins to files
if (!silent) {
console.log(`Processing: ${filePath}`)
} else {
debug(`Processing ${filePath}`)
}
const buffer = await fs.readFile(filePath)
const result = await processFile({
buffer,
outputFileName: outputFileName || path.parse(filePath).name,
config
})
results.push(result)
}
debug(`Finished`)
// Return as array when input was array or results is only one file
if (Array.isArray(input) || results.length === 0) {
return results
}
return results[0]
}
export * from './helpers' | the_stack |
import { d3, setMouseEvent, initChart } from './c3-helper'
describe('c3 chart tooltip', function() {
'use strict'
var chart
var tooltipConfiguration = {}
var dataOrder: any = 'desc'
var dataGroups
var args = function() {
return {
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250], // 1130
['data2', 50, 20, 10, 40, 15, 25], // 160
['data3', 150, 120, 110, 140, 115, 125] // 760
],
order: dataOrder,
groups: dataGroups
},
tooltip: tooltipConfiguration
}
}
beforeEach(function(done) {
chart = initChart(chart, args(), done)
dataOrder = 'desc'
dataGroups = undefined
})
describe('tooltip position', function() {
beforeAll(function() {
tooltipConfiguration = {}
})
describe('without left margin', function() {
it('should show tooltip on proper position', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(1),
y = chart.internal.y(200)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var tooltipContainer = d3.select('.c3-tooltip-container'),
top = Math.floor(+tooltipContainer.style('top').replace(/px/, '')),
left = Math.floor(+tooltipContainer.style('left').replace(/px/, ''))
expect(top).toBeGreaterThan(0)
expect(left).toBeGreaterThan(0)
})
})
describe('with left margin', function() {
beforeAll(function() {
d3.select('#chart').style('margin-left', '300px')
})
it('should show tooltip on proper position', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(1) + 300, // add margin-left
y = chart.internal.y(200)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var tooltipContainer = d3.select('.c3-tooltip-container'),
top = Math.floor(+tooltipContainer.style('top').replace(/px/, '')),
left = Math.floor(+tooltipContainer.style('left').replace(/px/, ''))
expect(top).toBeGreaterThan(0)
expect(left).toBeGreaterThan(0)
})
afterAll(function() {
d3.select('#chart').style('margin-left', null)
})
})
})
describe('tooltip positionFunction', function() {
var topExpected = 37,
leftExpected = 79
beforeAll(function() {
tooltipConfiguration = {
position: function(data, width, height, element) {
expect(data.length).toBe(args().data.columns.length)
expect(data[0]).toEqual(
jasmine.objectContaining({
index: 2,
value: 100,
id: 'data1'
})
)
expect(width).toBeGreaterThan(0)
expect(height).toBeGreaterThan(0)
expect(element).toBe(d3.select('.c3-event-rect').node())
return { top: topExpected, left: leftExpected }
}
}
})
it('should be set to the coordinate where the function returned', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var tooltipContainer = d3.select('.c3-tooltip-container'),
top = Math.floor(+tooltipContainer.style('top').replace(/px/, '')),
left = Math.floor(+tooltipContainer.style('left').replace(/px/, ''))
expect(top).toBeGreaterThan(0)
expect(left).toBeGreaterThan(0)
})
})
describe('tooltip getTooltipContent', function() {
beforeAll(function() {
tooltipConfiguration = {
data_order: 'desc'
}
})
it('should sort values desc', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data3')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data2')
})
})
describe('tooltip with data_order as desc with grouped data', function() {
beforeAll(function() {
dataOrder = 'desc'
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each data in descending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data1') // 1130
expect(classes[2]).toBe('c3-tooltip-name--data3') // 760
expect(classes[3]).toBe('c3-tooltip-name--data2') // 160
})
})
describe('tooltip with data_order as asc with grouped data', function() {
beforeAll(function() {
dataOrder = 'asc'
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each data in ascending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2') // 160
expect(classes[2]).toBe('c3-tooltip-name--data3') // 760
expect(classes[3]).toBe('c3-tooltip-name--data1') // 1130
})
})
describe('tooltip with data_order as NULL with grouped data', function() {
beforeAll(function() {
dataOrder = null
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each data in given order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data1')
expect(classes[2]).toBe('c3-tooltip-name--data2')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with data_order as Function with grouped data', function() {
beforeAll(function() {
var order = ['data2', 'data1', 'data3']
dataOrder = function(data1, data2) {
return order.indexOf(data1.id) - order.indexOf(data2.id)
}
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each data in order given by function', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with data_order as Array with grouped data', function() {
beforeAll(function() {
dataOrder = ['data2', 'data1', 'data3']
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each data in order given by array', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with data_order as desc with un-grouped data', function() {
beforeAll(function() {
dataOrder = 'desc'
})
it('should display each tooltip value descending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data3') // 110
expect(classes[2]).toBe('c3-tooltip-name--data1') // 100
expect(classes[3]).toBe('c3-tooltip-name--data2') // 10
})
})
describe('tooltip with data_order as asc with un-grouped data', function() {
beforeAll(function() {
dataOrder = 'asc'
})
it('should display each tooltip value in ascending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2') // 10
expect(classes[2]).toBe('c3-tooltip-name--data1') // 100
expect(classes[3]).toBe('c3-tooltip-name--data3') // 110
})
})
describe('tooltip with data_order as NULL with un-grouped data', function() {
beforeAll(function() {
dataOrder = null
})
it('should display each tooltip value in given data order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data1')
expect(classes[2]).toBe('c3-tooltip-name--data2')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with data_order as Function with un-grouped data', function() {
beforeAll(function() {
var order = ['data2', 'data1', 'data3']
dataOrder = function(data1, data2) {
return order.indexOf(data1.id) - order.indexOf(data2.id)
}
})
it('should display each tooltip value in data order given by function', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with data_order as Array with un-grouped data', function() {
beforeAll(function() {
dataOrder = ['data2', 'data1', 'data3']
})
it('should display each tooltip value in data order given by array', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with tooltip_order as desc', function() {
beforeAll(function() {
tooltipConfiguration = {
order: 'desc'
}
// this should be ignored
dataOrder = 'asc'
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each tooltip value descending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data3') // 110
expect(classes[2]).toBe('c3-tooltip-name--data1') // 100
expect(classes[3]).toBe('c3-tooltip-name--data2') // 10
})
})
describe('tooltip with tooltip_order as asc', function() {
beforeAll(function() {
tooltipConfiguration = {
order: 'asc'
}
// this should be ignored
dataOrder = 'desc'
dataGroups = [['data1', 'data2', 'data3']]
})
it('should display each tooltip value in ascending order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(220)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2') // 10
expect(classes[2]).toBe('c3-tooltip-name--data1') // 100
expect(classes[3]).toBe('c3-tooltip-name--data3') // 110
})
})
describe('tooltip with tooltip_order as NULL', function() {
beforeAll(function() {
tooltipConfiguration = {
order: null
}
})
it('should display each tooltip value in given order', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data1')
expect(classes[2]).toBe('c3-tooltip-name--data2')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with tooltip_order as Function', function() {
beforeAll(function() {
var order = ['data2', 'data1', 'data3']
tooltipConfiguration = {
order: function(data1, data2) {
return order.indexOf(data1.id) - order.indexOf(data2.id)
}
}
})
it('should display each tooltip value in data order given by function', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
describe('tooltip with tooltip_order as Array', function() {
beforeAll(function() {
tooltipConfiguration = {
order: ['data2', 'data1', 'data3']
}
})
it('should display each tooltip value in data order given by array', function() {
var eventRect = d3.select('.c3-event-rect').node(),
x = chart.internal.x(2),
y = chart.internal.y(100)
setMouseEvent(chart, 'mousemove', x, y, eventRect)
var classes = d3
.selectAll('.c3-tooltip tr')
.nodes()
.map(function(node) {
return (node as any).className
})
expect(classes[0]).toBe('') // header
expect(classes[1]).toBe('c3-tooltip-name--data2')
expect(classes[2]).toBe('c3-tooltip-name--data1')
expect(classes[3]).toBe('c3-tooltip-name--data3')
})
})
}) | the_stack |
import * as React from 'react';
import { Select, Spin, Form, Tooltip } from 'component/antd';
import { message } from 'antd';
import { IFormItem } from 'component/x-form';
import { cluster } from 'store/cluster';
import { alarm } from 'store/alarm';
import { topic } from 'store/topic';
import { observer } from 'mobx-react';
import { IRequestParams, IStrategyFilter } from 'types/alarm';
import { filterKeys } from 'constants/strategy';
import { VirtualScrollSelect } from 'component/virtual-scroll-select';
import { IsNotNaN } from 'lib/utils';
import { searchProps } from 'constants/table';
import { toJS } from 'mobx';
interface IDynamicProps {
form?: any;
formData?: any;
}
interface IFormSelect extends IFormItem {
options: Array<{ key?: string | number, value: string | number, label: string }>;
}
interface IVritualScrollSelect extends IFormSelect {
getData: () => any;
isDisabled: boolean;
refetchData?: boolean;
}
@observer
export class DynamicSetFilter extends React.Component<IDynamicProps> {
public isDetailPage = window.location.pathname.includes('/alarm-detail'); // 判断是否为详情
public monitorType: string = null;
public clusterId: number = null;
public clusterName: string = null;
public clusterIdentification: string | number = null;
public topicName: string = null;
public consumerGroup: string = null;
public location: string = null;
public getFormValidateData() {
const filterList = [] as IStrategyFilter[];
let monitorType = '' as string;
let filterObj = {} as any;
this.props.form.validateFields((err: Error, values: any) => {
if (!err) {
monitorType = values.monitorType;
const index = cluster.clusterData.findIndex(item => item.clusterIdentification === values.cluster);
if (index > -1) {
values.clusterIdentification = cluster.clusterData[index].clusterIdentification;
values.clusterName = cluster.clusterData[index].clusterName;
}
for (const key of Object.keys(values)) {
if (filterKeys.indexOf(key) > -1) { // 只有这几种值可以设置
filterList.push({
tkey: key === 'clusterName' ? 'cluster' : key, // clusterIdentification
topt: '=',
tval: [values[key]],
clusterIdentification: values.clusterIdentification
});
}
}
}
});
return filterObj = {
monitorType,
filterList,
};
}
public resetForm() {
const { resetFields } = this.props.form;
this.clearFormData();
resetFields();
}
public resetFormValue(
monitorType: string = null,
clusterIdentification: any = null,
topicName: string = null,
consumerGroup: string = null,
location: string = null) {
const { setFieldsValue } = this.props.form;
setFieldsValue({
cluster: clusterIdentification,
topic: topicName,
consumerGroup,
location,
monitorType,
});
}
public getClusterId = async (clusterIdentification: any) => {
let clusterId = null;
const index = cluster.clusterData.findIndex(item => item.clusterIdentification === clusterIdentification);
if (index > -1) {
clusterId = cluster.clusterData[index].clusterId;
}
if (clusterId) {
await cluster.getClusterMetaTopics(clusterId);
this.clusterId = clusterId;
return this.clusterId;
};
return this.clusterId = clusterId as any;
}
public async initFormValue(monitorRule: IRequestParams) {
const strategyFilterList = monitorRule.strategyFilterList;
const clusterFilter = strategyFilterList.filter(item => item.tkey === 'cluster')[0];
const topicFilter = strategyFilterList.filter(item => item.tkey === 'topic')[0];
const consumerFilter = strategyFilterList.filter(item => item.tkey === 'consumerGroup')[0];
const clusterIdentification = clusterFilter ? clusterFilter.tval[0] : null;
const topic = topicFilter ? topicFilter.tval[0] : null;
const consumerGroup = consumerFilter ? consumerFilter.tval[0] : null;
const location: string = null;
const monitorType = monitorRule.strategyExpressionList[0].metric;
alarm.changeMonitorStrategyType(monitorType);
//增加clusterIdentification替代原来的clusterName
this.clusterIdentification = clusterIdentification;
await this.getClusterId(this.clusterIdentification);
//
await this.handleSelectChange(topic, 'topic');
await this.handleSelectChange(consumerGroup, 'consumerGroup');
this.resetFormValue(monitorType, this.clusterIdentification, topic, consumerGroup, location);
}
public clearFormData() {
this.monitorType = null;
this.topicName = null;
this.clusterId = null;
this.consumerGroup = null;
this.location = null;
this.resetFormValue();
}
public async handleClusterChange(e: any) {
this.clusterIdentification = e;
this.topicName = null;
topic.setLoading(true);
const clusterId = await this.getClusterId(e);
await cluster.getClusterMetaTopics(clusterId);
this.resetFormValue(this.monitorType, e, null, this.consumerGroup, this.location);
topic.setLoading(false);
}
public handleSelectChange = (e: string, type: 'topic' | 'consumerGroup' | 'location') => {
switch (type) {
case 'topic':
// if (!this.clusterId) {
// return message.info('请选择集群');
// }
this.topicName = e;
const type = this.dealMonitorType();
if (['kafka-consumer-maxLag', 'kafka-consumer-maxDelayTime', 'kafka-consumer-lag'].indexOf(type) > -1) {
this.getConsumerInfo();
}
break;
case 'consumerGroup':
this.consumerGroup = e;
break;
case 'location':
this.location = e;
break;
}
}
public getConsumerInfo = () => {
if (!this.clusterId || !this.topicName) {
return;
}
topic.setLoading(true);
if (IsNotNaN(this.clusterId)) {
topic.getConsumerGroups(this.clusterId, this.topicName);
}
this.consumerGroup = null;
this.location = null;
this.resetFormValue(this.monitorType, this.clusterIdentification, this.topicName);
topic.setLoading(false);
}
public dealMonitorType() {
const index = alarm.monitorType.indexOf('-');
let type = alarm.monitorType;
if (index > -1) {
type = type.substring(index + 1);
}
return type;
}
public getRenderItem() {
const type = this.dealMonitorType();
const showMore = ['kafka-consumer-maxLag', 'kafka-consumer-maxDelayTime', 'kafka-consumer-lag'].indexOf(type) > -1;
this.monitorType = alarm.monitorType;
const monitorType = {
key: 'monitorType',
label: '监控指标',
type: 'select',
options: alarm.monitorTypeList.map(item => ({
label: item.metricName,
value: item.metricName,
})),
attrs: {
placeholder: '请选择',
className: 'large-size',
disabled: this.isDetailPage,
optionFilterProp: 'children',
showSearch: true,
filterOption: (input: any, option: any) => {
if (typeof option.props.children === 'object') {
const { props } = option.props.children as any;
return (props.children + '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
}
return (option.props.children + '').toLowerCase().indexOf(input.toLowerCase()) >= 0;
},
onChange: (e: string) => this.handleTypeChange(e),
},
rules: [{ required: true, message: '请选择监控指标' }],
} as IVritualScrollSelect;
const clusterData = toJS(cluster.clusterData);
const options = clusterData?.length ? clusterData.map(item => {
return {
label: `${item.clusterName}${item.description ? '(' + item.description + ')' : ''}`,
value: item.clusterIdentification
}
}) : null;
const clusterItem = {
label: '集群',
options,
defaultValue: this.clusterIdentification,
rules: [{ required: true, message: '请选择集群' }],
attrs: {
placeholder: '请选择集群',
className: 'large-size',
disabled: this.isDetailPage,
onChange: (e: any) => this.handleClusterChange(e),
},
key: 'cluster',
} as unknown as IVritualScrollSelect;
const topicItem = {
label: 'Topic',
defaultValue: this.topicName,
rules: [{ required: true, message: '请选择Topic' }],
isDisabled: this.isDetailPage,
options: cluster.clusterMetaTopics.map(item => {
return {
label: item.topicName,
value: item.topicName,
};
}),
attrs: {
placeholder: '请选择Topic',
className: 'large-size',
disabled: this.isDetailPage,
onChange: (e: string) => this.handleSelectChange(e, 'topic'),
},
key: 'topic',
} as IVritualScrollSelect;
const consumerGroupItem = {
label: '消费组',
options: topic.consumerGroups.map(item => {
return {
label: item.consumerGroup,
value: item.consumerGroup,
};
}),
defaultValue: this.consumerGroup,
rules: [{ required: showMore, message: '请选择消费组' }],
attrs: {
placeholder: '请选择消费组',
className: 'large-size',
disabled: this.isDetailPage,
onChange: (e: string) => this.handleSelectChange(e, 'consumerGroup'),
},
key: 'consumerGroup',
} as IVritualScrollSelect;
const locationItem = {
label: 'location',
options: topic.filterGroups.map(item => {
return {
label: item.location,
value: item.location,
};
}),
defaultValue: this.location,
rules: [{ required: showMore, message: '请选择location' }],
attrs: {
placeholder: '请选择location',
optionFilterProp: 'children',
showSearch: true,
className: 'middle-size',
disabled: this.isDetailPage,
onChange: (e: string) => this.handleSelectChange(e, 'location'),
},
key: 'location',
} as IVritualScrollSelect;
const common = (
<>
{this.renderFormItem(clusterItem)}
{this.renderFormItem(topicItem)}
</>
);
const more = showMore ? (
<>
{this.renderFormItem(consumerGroupItem)}
{/* {this.renderFormItem(locationItem)} */}
</>
) : null;
return (
<>
<div className="dynamic-set">
{this.renderFormItem(monitorType)}
<ul>{common}{more}</ul>
</div>
</>
);
}
public handleTypeChange = (e: string) => {
// tslint:disable-next-line:no-unused-expression
this.clearFormData();
alarm.changeMonitorStrategyType(e);
}
public getSelectFormItem(item: IFormItem) {
return (
<Select
key={item.key}
{...item.attrs}
{...searchProps}
>
{(item as IFormSelect).options && (item as IFormSelect).options.map((v, index) => (
<Select.Option
key={v.value || v.key || index}
value={v.value}
>
{v.label?.length > 25 ? <Tooltip placement="bottomLeft" title={v.label}>
{v.label}
</Tooltip> : v.label}
</Select.Option>
))}
</Select>
);
}
public renderFormItem(item: IVritualScrollSelect, virtualScroll: boolean = false) {
const { getFieldDecorator } = this.props.form;
const { formData = {} } = this.props;
const initialValue = formData[item.key] === 0 ? 0 : (formData[item.key] || item.defaultValue || '');
const getFieldValue = {
initialValue,
rules: item.rules || [{ required: true, message: '请填写' }],
};
const formItemLayout = {
labelCol: { span: 6 },
wrapperCol: { span: 10 },
};
return (
<Form.Item
label={item.label}
key={item.key}
{...formItemLayout}
>
{getFieldDecorator(item.key, getFieldValue)(
virtualScroll ?
<VirtualScrollSelect
attrs={item.attrs}
isDisabled={item.isDisabled}
onChange={item.attrs.onChange}
getData={item.getData}
refetchData={item.refetchData}
/>
: this.getSelectFormItem(item),
)}
</Form.Item>
);
}
public componentDidMount() {
cluster.getClusters();
}
public render() {
return (
<Spin spinning={cluster.filterLoading}>
<Form>
<div className="form-list">
{this.getRenderItem()}
</div>
</Form>
</Spin>
);
}
}
export const WrappedDynamicSetFilter = Form.create({ name: 'dynamic_filter_form_item' })(DynamicSetFilter); | the_stack |
namespace ts {
describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileTextToJson", () => {
function createParseConfigHost(additionalFiles?: vfs.FileSet) {
return new fakes.ParseConfigHost(
new vfs.FileSystem(
/*ignoreCase*/ false,
{
cwd: "/",
files: { "/": {}, "/a.ts": "", ...additionalFiles }
}
)
);
}
function getParsedCommandJson(json: object, additionalFiles?: vfs.FileSet, existingWatchOptions?: WatchOptions) {
return parseJsonConfigFileContent(
json,
createParseConfigHost(additionalFiles),
"/",
/*existingOptions*/ undefined,
"tsconfig.json",
/*resolutionStack*/ undefined,
/*extraFileExtensions*/ undefined,
/*extendedConfigCache*/ undefined,
existingWatchOptions,
);
}
function getParsedCommandJsonNode(json: object, additionalFiles?: vfs.FileSet, existingWatchOptions?: WatchOptions) {
const parsed = parseJsonText("tsconfig.json", JSON.stringify(json));
return parseJsonSourceFileConfigFileContent(
parsed,
createParseConfigHost(additionalFiles),
"/",
/*existingOptions*/ undefined,
"tsconfig.json",
/*resolutionStack*/ undefined,
/*extraFileExtensions*/ undefined,
/*extendedConfigCache*/ undefined,
existingWatchOptions,
);
}
interface VerifyWatchOptions {
json: object;
expectedOptions: WatchOptions | undefined;
additionalFiles?: vfs.FileSet;
existingWatchOptions?: WatchOptions | undefined;
expectedErrors?: (sourceFile?: SourceFile) => Diagnostic[];
}
function verifyWatchOptions(scenario: () => VerifyWatchOptions[]) {
it("with json api", () => {
for (const { json, expectedOptions, additionalFiles, existingWatchOptions, expectedErrors } of scenario()) {
const parsed = getParsedCommandJson(json, additionalFiles, existingWatchOptions);
assert.deepEqual(parsed.watchOptions, expectedOptions, `With ${JSON.stringify(json)}`);
if (length(parsed.errors)) {
assert.deepEqual(parsed.errors, expectedErrors?.());
}
else {
assert.equal(0, length(expectedErrors?.()), `Expected no errors`);
}
}
});
it("with json source file api", () => {
for (const { json, expectedOptions, additionalFiles, existingWatchOptions, expectedErrors } of scenario()) {
const parsed = getParsedCommandJsonNode(json, additionalFiles, existingWatchOptions);
assert.deepEqual(parsed.watchOptions, expectedOptions);
if (length(parsed.errors)) {
assert.deepEqual(parsed.errors, expectedErrors?.(parsed.options.configFile));
}
else {
assert.equal(0, length(expectedErrors?.(parsed.options.configFile)), `Expected no errors`);
}
}
});
}
describe("no watchOptions specified option", () => {
verifyWatchOptions(() => [{
json: {},
expectedOptions: undefined
}]);
});
describe("empty watchOptions specified option", () => {
verifyWatchOptions(() => [{
json: { watchOptions: {} },
expectedOptions: undefined
}]);
});
describe("extending config file", () => {
describe("when extending config file without watchOptions", () => {
verifyWatchOptions(() => [
{
json: {
extends: "./base.json",
watchOptions: { watchFile: "UseFsEvents" }
},
expectedOptions: { watchFile: WatchFileKind.UseFsEvents },
additionalFiles: { "/base.json": "{}" }
},
{
json: { extends: "./base.json", },
expectedOptions: undefined,
additionalFiles: { "/base.json": "{}" }
}
]);
});
describe("when extending config file with watchOptions", () => {
verifyWatchOptions(() => [
{
json: {
extends: "./base.json",
watchOptions: {
watchFile: "UseFsEvents",
}
},
expectedOptions: {
watchFile: WatchFileKind.UseFsEvents,
watchDirectory: WatchDirectoryKind.FixedPollingInterval
},
additionalFiles: {
"/base.json": JSON.stringify({
watchOptions: {
watchFile: "UseFsEventsOnParentDirectory",
watchDirectory: "FixedPollingInterval"
}
})
}
},
{
json: {
extends: "./base.json",
},
expectedOptions: {
watchFile: WatchFileKind.UseFsEventsOnParentDirectory,
watchDirectory: WatchDirectoryKind.FixedPollingInterval
},
additionalFiles: {
"/base.json": JSON.stringify({
watchOptions: {
watchFile: "UseFsEventsOnParentDirectory",
watchDirectory: "FixedPollingInterval"
}
})
}
}
]);
});
});
describe("different options", () => {
verifyWatchOptions(() => [
{
json: { watchOptions: { watchFile: "UseFsEvents" } },
expectedOptions: { watchFile: WatchFileKind.UseFsEvents }
},
{
json: { watchOptions: { watchDirectory: "UseFsEvents" } },
expectedOptions: { watchDirectory: WatchDirectoryKind.UseFsEvents }
},
{
json: { watchOptions: { fallbackPolling: "DynamicPriority" } },
expectedOptions: { fallbackPolling: PollingWatchKind.DynamicPriority }
},
{
json: { watchOptions: { synchronousWatchDirectory: true } },
expectedOptions: { synchronousWatchDirectory: true }
},
{
json: { watchOptions: { excludeDirectories: ["**/temp"] } },
expectedOptions: { excludeDirectories: ["/**/temp"] }
},
{
json: { watchOptions: { excludeFiles: ["**/temp/*.ts"] } },
expectedOptions: { excludeFiles: ["/**/temp/*.ts"] }
},
{
json: { watchOptions: { excludeDirectories: ["**/../*"] } },
expectedOptions: { excludeDirectories: [] },
expectedErrors: sourceFile => [
{
messageText: `File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '**/../*'.`,
category: Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0.category,
code: Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0.code,
file: sourceFile,
start: sourceFile && sourceFile.text.indexOf(`"**/../*"`),
length: sourceFile && `"**/../*"`.length,
reportsDeprecated: undefined,
reportsUnnecessary: undefined
}
]
},
{
json: { watchOptions: { excludeFiles: ["**/../*"] } },
expectedOptions: { excludeFiles: [] },
expectedErrors: sourceFile => [
{
messageText: `File specification cannot contain a parent directory ('..') that appears after a recursive directory wildcard ('**'): '**/../*'.`,
category: Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0.category,
code: Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0.code,
file: sourceFile,
start: sourceFile && sourceFile.text.indexOf(`"**/../*"`),
length: sourceFile && `"**/../*"`.length,
reportsDeprecated: undefined,
reportsUnnecessary: undefined
}
]
},
]);
});
describe("watch options extending passed in watch options", () => {
verifyWatchOptions(() => [
{
json: { watchOptions: { watchFile: "UseFsEvents" } },
expectedOptions: { watchFile: WatchFileKind.UseFsEvents, watchDirectory: WatchDirectoryKind.FixedPollingInterval },
existingWatchOptions: { watchDirectory: WatchDirectoryKind.FixedPollingInterval }
},
{
json: {},
expectedOptions: { watchDirectory: WatchDirectoryKind.FixedPollingInterval },
existingWatchOptions: { watchDirectory: WatchDirectoryKind.FixedPollingInterval }
},
]);
});
});
} | the_stack |
module TDev
{
export class SearchTab
extends SideTab
{
constructor() {
super()
}
public icon() { return "svg:search,currentColor"; }
public name() { return "results"; }
public keyShortcut() { return "Ctrl-F"; }
private lastSearchValue = "";
private lastHistoryVersion = 0;
private lastSelectedIdx = -1;
private lastEntryCount = -1;
private wasSelected:any = {};
private locations:CodeLocation[] = [];
private version = 1;
public phoneFullScreen() { return true }
public selectFirst()
{
var entry = this.htmlEntries[0];
if (entry)
KeyboardMgr.triggerClick(entry);
}
public select(ix: number) {
var entry = this.htmlEntries[ix];
if (entry)
KeyboardMgr.triggerClick(entry);
}
public getTick() { return Ticks.sideSearch; }
public navigatedTo()
{
super.navigatedTo();
this.navRefreshPending = true; // we want to always refresh
}
public refreshCore()
{
this.setupList();
this.visualRoot.setChildren([this.scrollRoot]);
}
public init(e:Editor)
{
super.init(e);
}
public searchKey()
{
if (this.lastSearchValue != TheEditor.searchBox.value) {
this.lastSearchValue = TheEditor.searchBox.value;
if (!this.lastSearchValue) {
TheEditor.backToScript();
return;
}
this.setupList();
this.highlightCarret();
}
}
private setupList()
{
var terms:string[] = [];
var refNames:string[] = [];
var refOp = false;
var bangOp = false;
var specialCommand = "";
TheEditor.setupSearchButton()
AST.Lexer.tokenize(this.lastSearchValue).forEach((t:AST.LexToken) => {
var add = (tt) => {
if (!!tt) {
if (refOp)
refNames.push(tt);
else if (bangOp)
specialCommand = tt;
else
terms.push(tt);
}
refOp = false;
bangOp = false;
}
switch (t.category) {
case AST.TokenType.Op:
if (t.data == "?")
refOp = true;
else if (t.data == ":")
bangOp = true;
else if (/^[a-zA-Z]/.test(t.data))
add(t.data);
break;
case AST.TokenType.Id:
case AST.TokenType.String:
case AST.TokenType.Keyword:
add(t.data)
break;
}
});
var origTerms = terms
terms = terms.map(t => t.toLowerCase())
var fullName = terms.join("");
var entries:CodeLocation[] = [];
var stmtFilter = (s:AST.Stmt) => true;
var nameOverride : (s:AST.Stmt) => string = null;
var refs:AST.AstNode[] = refNames.map((t:string) => {
var m = /^(.*)->(.*)$/.exec(t)
var fieldName = null
if (m) {
t = m[1]
fieldName = m[2]
}
var th:AST.AstNode = Script.things.filter((th:AST.Decl) => th.getName() == t)[0]
if (fieldName == null)
return th;
if (th instanceof AST.RecordDef) {
th = (<AST.RecordDef>th).getFields().filter(e => e.getName() == fieldName)[0];
}
return th
});
if (refs.length > 0) {
if (refs.some((t) => !t)) {
this.setChildren(this.htmlEntries = []);
return;
}
// needed to fixup property refs
AST.TypeChecker.tcApp(Script);
}
var maxEntries = 50;
var addResult = (decl:AST.Decl) =>
{
var codeSearch = (stmt:AST.Stmt) =>
{
if (stmt instanceof AST.Block) {
var b = <AST.Block>stmt;
b.stmts.forEach(codeSearch);
} else {
var score = 0
if (stmtFilter(stmt)) {
var fs = stmt.forSearch();
if (stmt.getError()) fs += " " + stmt.getError()
if (stmt.calcNode() && stmt.calcNode().hint) fs += " " + stmt.calcNode().hint
if (stmt.annotations && stmt.annotations.length > 0) fs += " " + stmt.annotations.map(a => a.message).join(" ")
score = IntelliItem.matchString(fs, terms, 0.1, 0.1, 0.01);
if (score > 0 && refs.length > 0) {
refs.forEach((rf:AST.Decl) => {
if (score > 0 && !stmt.matches(rf))
score = 0;
});
}
}
if (score > 0) {
var loc = new CodeLocation(decl);
var currAct = TheEditor.lastDecl == decl;
if (currAct)
loc.isCurrAction = true;
else
score *= 0.01;
loc.score = score;
loc.stmt = stmt;
loc.isSearchResult = true;
if (nameOverride)
loc.nameOverride = nameOverride(stmt);
entries.push(loc);
}
if (stmt instanceof AST.ExprStmt) {
if (stmt instanceof AST.InlineActions)
codeSearch((<AST.InlineActions>stmt).actions)
} else {
var ch = stmt.children();
for (var i = 0; i < ch.length; ++i)
if (ch[i] instanceof AST.Stmt) codeSearch(<AST.Stmt>ch[i]);
}
}
}
{
var prop = decl.propertyForSearch();
var score = 0;
if (!prop) {
var it = new IntelliItem();
it.decl = decl;
score = it.match(terms, fullName);
} else
score = IntelliItem.matchProp(prop, terms, fullName);
if (refs.length > 0) {
refs.forEach((rf:AST.Decl) => {
if (score > 0 && !decl.matches(rf))
score = 0;
});
}
if (!stmtFilter(decl))
score = 0;
if (score > 0) {
var loc = new CodeLocation(decl);
loc.isSearchResult = true;
loc.score = score;
entries.push(loc);
}
}
if (decl instanceof AST.App) return
decl.children().forEach(ch => {
if (ch instanceof AST.Stmt)
codeSearch(<AST.Stmt>ch)
})
}
specialCommand = specialCommand.toLowerCase()
if (!specialCommand && refs.length == 0) {
var stkM = /^StK([a-zA-Z0-9]+)$/.exec(origTerms[0])
if (stkM && stkM[1].length % 8 == 0) {
var frames = AST.decompressStack(stkM[1])
if (frames.length > 0) {
AST.Compiler.annotateWithIds(Script)
TheEditor.overrideStackTrace(frames)
specialCommand = "stack"
terms.shift()
} else {
HTML.showProgressNotification(lf("Stack trace not understood."))
}
}
}
function locMatches(loc:CodeLocation, doScore = false) {
if (terms.length > 0) {
var str = loc.decl.getName() + " ";
if (loc.stmt) str += loc.stmt.forSearch();
var score = IntelliItem.matchString(str, terms, 0.1, 0.1, 0.01);
if (score <= 0) return false;
if (doScore) loc.score = score;
}
return true;
}
if (specialCommand == "stack" || specialCommand == "s") {
var stack = TheEditor.getStackTrace()
stack.forEach((s:IStackFrame, i:number) => {
var lib = s.d ? s.d.libName : null
var loc = CodeLocation.fromNodeId(s.pc, lib)
if (!loc) {
var decl = Script.things.filter((d) => d.getName() == s.name)[0];
if (!decl) return;
loc = new CodeLocation(decl);
loc.isSearchResult = true;
}
if (!locMatches(loc)) return;
loc.score = 1/i; // keep the order
entries.push(loc)
})
} else if (specialCommand == "recent" || specialCommand == "r") {
this.locations.forEach((loc, i) => {
loc.score = 1/i;
if (!locMatches(loc, true)) return;
loc.isSearchResult = true;
entries.push(loc);
})
} else {
if (specialCommand == "e" || specialCommand == "errors")
nameOverride = (s) => s.getError();
else if (specialCommand == "h" || specialCommand == "hints")
nameOverride = (s) => s.calcNode() ? s.calcNode().hint : null;
else if (specialCommand == "p" || specialCommand == "plugin")
nameOverride = (s) => s.annotations && s.annotations[0] ? s.annotations[0].message : null
else if (specialCommand == "m" || specialCommand == "message")
nameOverride = (s) => s.getError()
|| (s.calcNode() ? s.calcNode().hint : null)
|| (s.annotations && s.annotations[0] ? s.annotations[0].message : null);
if (nameOverride)
stmtFilter = (s) => !!nameOverride(s)
addResult(Script);
Script.orderedThings().forEach(addResult)
}
if (this.lastEntryCount != entries.length) {
this.lastSelectedIdx = -1;
this.wasSelected = {};
}
this.lastEntryCount = entries.length;
var cmpScore = (a:CodeLocation, b:CodeLocation) => b.score - a.score;
entries.stableSortObjs(cmpScore);
var hasMore = false;
if (entries.length > maxEntries) {
entries = entries.slice(0, maxEntries);
hasMore = true;
}
var items:HTMLElement[] = [];
var allTerms = terms.concat(refNames);
entries.forEach((e:CodeLocation, idx:number) => {
var b = e.mkBox();
if (allTerms.length > 0)
Util.highlightWords(b, allTerms);
if (this.lastSelectedIdx == idx && this.version == this.lastHistoryVersion) {
b.setFlag("selected", true);
b.setFlag("was-selected", true);
}
else if (this.wasSelected[idx])
b.setFlag("was-selected", true);
b.withClick(() => {
if (e.stmt)
tick(Ticks.sideSearchGoToStmt);
else
tick(Ticks.sideSearchGoToDecl);
this.lastSelectedIdx = -1;
TheEditor.goToLocation(e);
items.forEach((x:HTMLElement) => x.setFlag("selected", false));
b.setFlag("selected", true);
b.setFlag("was-selected", true);
this.wasSelected[idx] = true;
this.lastSelectedIdx = idx;
this.lastHistoryVersion = this.version;
});
items.push(b);
});
if (hasMore) items.push(IntelliItem.thereIsMore());
this.htmlEntries = items;
this.setChildren(items);
}
public rebind()
{
this.locations = this.locations.map((l:CodeLocation) => l.rebind()).filter((l) => !!l);
}
public saveLocation()
{
var curr = TheEditor.currentLocation();
if (!curr) return;
var first = this.locations[0];
if (first && first.similar(curr)) {
this.locations[0] = curr;
} else {
this.version++;
this.locations.unshift(curr);
}
if (this.locations.length > 100)
this.locations = this.locations.slice(0, 50);
//this.queueNavRefresh();
/*
var last = this.locations[this.currentIdx];
if (!!last && last.similar(curr)) {
this.locations[this.currentIdx] = curr;
} else {
this.version++;
this.locations.splice(this.currentIdx + 1);
this.currentIdx = this.locations.length;
this.locations.push(curr);
this.queueNavRefresh();
}
*/
}
public reset()
{
super.reset();
this.locations = [];
}
}
} | the_stack |
import { blockchainTests, constants, describe, expect, verifyEventsFromLogs } from '@0x/contracts-test-utils';
import { OrderStatus, OtcOrder, RevertErrors, SignatureType } from '@0x/protocol-utils';
import { BigNumber } from '@0x/utils';
import { IOwnableFeatureContract, IZeroExContract, IZeroExEvents } from '../../src/wrappers';
import { artifacts } from '../artifacts';
import { abis } from '../utils/abis';
import { fullMigrateAsync } from '../utils/migration';
import {
computeOtcOrderFilledAmounts,
createExpiry,
getRandomOtcOrder,
NativeOrdersTestEnvironment,
} from '../utils/orders';
import {
OtcOrdersFeatureContract,
TestMintableERC20TokenContract,
TestOrderSignerRegistryWithContractWalletContract,
TestWethContract,
} from '../wrappers';
blockchainTests.resets('OtcOrdersFeature', env => {
const { NULL_ADDRESS, MAX_UINT256, ZERO_AMOUNT: ZERO } = constants;
const ETH_TOKEN_ADDRESS = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
let maker: string;
let taker: string;
let notMaker: string;
let notTaker: string;
let contractWalletOwner: string;
let contractWalletSigner: string;
let txOrigin: string;
let notTxOrigin: string;
let zeroEx: IZeroExContract;
let verifyingContract: string;
let makerToken: TestMintableERC20TokenContract;
let takerToken: TestMintableERC20TokenContract;
let wethToken: TestWethContract;
let contractWallet: TestOrderSignerRegistryWithContractWalletContract;
let testUtils: NativeOrdersTestEnvironment;
before(async () => {
// Useful for ETH balance accounting
const txDefaults = { ...env.txDefaults, gasPrice: 0 };
let owner;
[
owner,
maker,
taker,
notMaker,
notTaker,
contractWalletOwner,
contractWalletSigner,
txOrigin,
notTxOrigin,
] = await env.getAccountAddressesAsync();
[makerToken, takerToken] = await Promise.all(
[...new Array(2)].map(async () =>
TestMintableERC20TokenContract.deployFrom0xArtifactAsync(
artifacts.TestMintableERC20Token,
env.provider,
txDefaults,
artifacts,
),
),
);
wethToken = await TestWethContract.deployFrom0xArtifactAsync(
artifacts.TestWeth,
env.provider,
txDefaults,
artifacts,
);
zeroEx = await fullMigrateAsync(owner, env.provider, txDefaults, {}, { wethAddress: wethToken.address });
const otcFeatureImpl = await OtcOrdersFeatureContract.deployFrom0xArtifactAsync(
artifacts.OtcOrdersFeature,
env.provider,
txDefaults,
artifacts,
zeroEx.address,
wethToken.address,
);
await new IOwnableFeatureContract(zeroEx.address, env.provider, txDefaults, abis)
.migrate(otcFeatureImpl.address, otcFeatureImpl.migrate().getABIEncodedTransactionData(), owner)
.awaitTransactionSuccessAsync();
verifyingContract = zeroEx.address;
await Promise.all([
makerToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: maker }),
makerToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: notMaker }),
takerToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: taker }),
takerToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: notTaker }),
wethToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: maker }),
wethToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: notMaker }),
wethToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: taker }),
wethToken.approve(zeroEx.address, MAX_UINT256).awaitTransactionSuccessAsync({ from: notTaker }),
]);
// contract wallet for signer delegation
contractWallet = await TestOrderSignerRegistryWithContractWalletContract.deployFrom0xArtifactAsync(
artifacts.TestOrderSignerRegistryWithContractWallet,
env.provider,
{
from: contractWalletOwner,
},
artifacts,
zeroEx.address,
);
await contractWallet
.approveERC20(makerToken.address, zeroEx.address, MAX_UINT256)
.awaitTransactionSuccessAsync({ from: contractWalletOwner });
await contractWallet
.approveERC20(takerToken.address, zeroEx.address, MAX_UINT256)
.awaitTransactionSuccessAsync({ from: contractWalletOwner });
testUtils = new NativeOrdersTestEnvironment(maker, taker, makerToken, takerToken, zeroEx, ZERO, ZERO, env);
});
function getTestOtcOrder(fields: Partial<OtcOrder> = {}): OtcOrder {
return getRandomOtcOrder({
maker,
verifyingContract,
chainId: 1337,
takerToken: takerToken.address,
makerToken: makerToken.address,
taker: NULL_ADDRESS,
txOrigin: taker,
...fields,
});
}
describe('getOtcOrderHash()', () => {
it('returns the correct hash', async () => {
const order = getTestOtcOrder();
const hash = await zeroEx.getOtcOrderHash(order).callAsync();
expect(hash).to.eq(order.getHash());
});
});
describe('lastOtcTxOriginNonce()', () => {
it('returns 0 if bucket is unused', async () => {
const nonce = await zeroEx.lastOtcTxOriginNonce(taker, ZERO).callAsync();
expect(nonce).to.bignumber.eq(0);
});
it('returns the last nonce used in a bucket', async () => {
const order = getTestOtcOrder();
await testUtils.fillOtcOrderAsync(order);
const nonce = await zeroEx.lastOtcTxOriginNonce(taker, order.nonceBucket).callAsync();
expect(nonce).to.bignumber.eq(order.nonce);
});
});
describe('getOtcOrderInfo()', () => {
it('unfilled order', async () => {
const order = getTestOtcOrder();
const info = await zeroEx.getOtcOrderInfo(order).callAsync();
expect(info).to.deep.equal({
status: OrderStatus.Fillable,
orderHash: order.getHash(),
});
});
it('unfilled expired order', async () => {
const expiry = createExpiry(-60);
const order = getTestOtcOrder({ expiry });
const info = await zeroEx.getOtcOrderInfo(order).callAsync();
expect(info).to.deep.equal({
status: OrderStatus.Expired,
orderHash: order.getHash(),
});
});
it('filled then expired order', async () => {
const expiry = createExpiry(60);
const order = getTestOtcOrder({ expiry });
await testUtils.fillOtcOrderAsync(order);
// Advance time to expire the order.
await env.web3Wrapper.increaseTimeAsync(61);
const info = await zeroEx.getOtcOrderInfo(order).callAsync();
expect(info).to.deep.equal({
status: OrderStatus.Invalid,
orderHash: order.getHash(),
});
});
it('filled order', async () => {
const order = getTestOtcOrder();
// Fill the order first.
await testUtils.fillOtcOrderAsync(order);
const info = await zeroEx.getOtcOrderInfo(order).callAsync();
expect(info).to.deep.equal({
status: OrderStatus.Invalid,
orderHash: order.getHash(),
});
});
});
async function assertExpectedFinalBalancesFromOtcOrderFillAsync(
order: OtcOrder,
takerTokenFillAmount: BigNumber = order.takerAmount,
): Promise<void> {
const { makerTokenFilledAmount, takerTokenFilledAmount } = computeOtcOrderFilledAmounts(
order,
takerTokenFillAmount,
);
const makerBalance = await new TestMintableERC20TokenContract(order.takerToken, env.provider)
.balanceOf(order.maker)
.callAsync();
const takerBalance = await new TestMintableERC20TokenContract(order.makerToken, env.provider)
.balanceOf(order.taker !== NULL_ADDRESS ? order.taker : taker)
.callAsync();
expect(makerBalance, 'maker balance').to.bignumber.eq(takerTokenFilledAmount);
expect(takerBalance, 'taker balance').to.bignumber.eq(makerTokenFilledAmount);
}
describe('fillOtcOrder()', () => {
it('can fully fill an order', async () => {
const order = getTestOtcOrder();
const receipt = await testUtils.fillOtcOrderAsync(order);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order);
});
it('can partially fill an order', async () => {
const order = getTestOtcOrder();
const fillAmount = order.takerAmount.minus(1);
const receipt = await testUtils.fillOtcOrderAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order, fillAmount)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order, fillAmount);
});
it('clamps fill amount to remaining available', async () => {
const order = getTestOtcOrder();
const fillAmount = order.takerAmount.plus(1);
const receipt = await testUtils.fillOtcOrderAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order, fillAmount)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order, fillAmount);
});
it('cannot fill an order with wrong tx.origin', async () => {
const order = getTestOtcOrder();
const tx = testUtils.fillOtcOrderAsync(order, order.takerAmount, notTaker);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), notTaker, taker),
);
});
it('cannot fill an order with wrong taker', async () => {
const order = getTestOtcOrder({ taker: notTaker });
const tx = testUtils.fillOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByTakerError(order.getHash(), taker, notTaker),
);
});
it('can fill an order from a different tx.origin if registered', async () => {
const order = getTestOtcOrder();
await zeroEx.registerAllowedRfqOrigins([notTaker], true).awaitTransactionSuccessAsync({ from: taker });
return testUtils.fillOtcOrderAsync(order, order.takerAmount, notTaker);
});
it('cannot fill an order with registered then unregistered tx.origin', async () => {
const order = getTestOtcOrder();
await zeroEx.registerAllowedRfqOrigins([notTaker], true).awaitTransactionSuccessAsync({ from: taker });
await zeroEx.registerAllowedRfqOrigins([notTaker], false).awaitTransactionSuccessAsync({ from: taker });
const tx = testUtils.fillOtcOrderAsync(order, order.takerAmount, notTaker);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), notTaker, taker),
);
});
it('cannot fill an order with a zero tx.origin', async () => {
const order = getTestOtcOrder({ txOrigin: NULL_ADDRESS });
const tx = testUtils.fillOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), taker, NULL_ADDRESS),
);
});
it('cannot fill an expired order', async () => {
const order = getTestOtcOrder({ expiry: createExpiry(-60) });
const tx = testUtils.fillOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order.getHash(), OrderStatus.Expired),
);
});
it('cannot fill order with bad signature', async () => {
const order = getTestOtcOrder();
// Overwrite chainId to result in a different hash and therefore different
// signature.
const tx = testUtils.fillOtcOrderAsync(order.clone({ chainId: 1234 }));
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotSignedByMakerError(order.getHash(), undefined, order.maker),
);
});
it('fails if ETH is attached', async () => {
const order = getTestOtcOrder();
await testUtils.prepareBalancesForOrdersAsync([order], taker);
const tx = zeroEx
.fillOtcOrder(order, await order.getSignatureWithProviderAsync(env.provider), order.takerAmount)
.awaitTransactionSuccessAsync({ from: taker, value: 1 });
// This will revert at the language level because the fill function is not payable.
return expect(tx).to.be.rejectedWith('revert');
});
it('cannot fill the same order twice', async () => {
const order = getTestOtcOrder();
await testUtils.fillOtcOrderAsync(order);
const tx = testUtils.fillOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order.getHash(), OrderStatus.Invalid),
);
});
it('cannot fill two orders with the same nonceBucket and nonce', async () => {
const order1 = getTestOtcOrder();
await testUtils.fillOtcOrderAsync(order1);
const order2 = getTestOtcOrder({ nonceBucket: order1.nonceBucket, nonce: order1.nonce });
const tx = testUtils.fillOtcOrderAsync(order2);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order2.getHash(), OrderStatus.Invalid),
);
});
it('cannot fill an order whose nonce is less than the nonce last used in that bucket', async () => {
const order1 = getTestOtcOrder();
await testUtils.fillOtcOrderAsync(order1);
const order2 = getTestOtcOrder({ nonceBucket: order1.nonceBucket, nonce: order1.nonce.minus(1) });
const tx = testUtils.fillOtcOrderAsync(order2);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order2.getHash(), OrderStatus.Invalid),
);
});
it('can fill two orders that use the same nonce bucket and increasing nonces', async () => {
const order1 = getTestOtcOrder();
const tx1 = await testUtils.fillOtcOrderAsync(order1);
verifyEventsFromLogs(
tx1.logs,
[testUtils.createOtcOrderFilledEventArgs(order1)],
IZeroExEvents.OtcOrderFilled,
);
const order2 = getTestOtcOrder({ nonceBucket: order1.nonceBucket, nonce: order1.nonce.plus(1) });
const tx2 = await testUtils.fillOtcOrderAsync(order2);
verifyEventsFromLogs(
tx2.logs,
[testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('can fill two orders that use the same nonce but different nonce buckets', async () => {
const order1 = getTestOtcOrder();
const tx1 = await testUtils.fillOtcOrderAsync(order1);
verifyEventsFromLogs(
tx1.logs,
[testUtils.createOtcOrderFilledEventArgs(order1)],
IZeroExEvents.OtcOrderFilled,
);
const order2 = getTestOtcOrder({ nonce: order1.nonce });
const tx2 = await testUtils.fillOtcOrderAsync(order2);
verifyEventsFromLogs(
tx2.logs,
[testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('can fill a WETH buy order and receive ETH', async () => {
const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker);
const order = getTestOtcOrder({ makerToken: wethToken.address, makerAmount: new BigNumber('1e18') });
await wethToken.deposit().awaitTransactionSuccessAsync({ from: maker, value: order.makerAmount });
const receipt = await testUtils.fillOtcOrderAsync(order, order.takerAmount, taker, true);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker);
expect(takerEthBalanceAfter.minus(takerEthBalanceBefore)).to.bignumber.equal(order.makerAmount);
});
it('reverts if `unwrapWeth` is true but maker token is not WETH', async () => {
const order = getTestOtcOrder();
const tx = testUtils.fillOtcOrderAsync(order, order.takerAmount, taker, true);
return expect(tx).to.revertWith('OtcOrdersFeature::fillOtcOrderForEth/MAKER_TOKEN_NOT_WETH');
});
it('allows for fills on orders signed by a approved signer', async () => {
const order = getTestOtcOrder({ maker: contractWallet.address });
const sig = await order.getSignatureWithProviderAsync(
env.provider,
SignatureType.EthSign,
contractWalletSigner,
);
// covers taker
await testUtils.prepareBalancesForOrdersAsync([order]);
// need to provide contract wallet with a balance
await makerToken.mint(contractWallet.address, order.makerAmount).awaitTransactionSuccessAsync();
// allow signer
await contractWallet
.registerAllowedOrderSigner(contractWalletSigner, true)
.awaitTransactionSuccessAsync({ from: contractWalletOwner });
// fill should succeed
const receipt = await zeroEx
.fillOtcOrder(order, sig, order.takerAmount)
.awaitTransactionSuccessAsync({ from: taker });
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order);
});
it('disallows fills if the signer is revoked', async () => {
const order = getTestOtcOrder({ maker: contractWallet.address });
const sig = await order.getSignatureWithProviderAsync(
env.provider,
SignatureType.EthSign,
contractWalletSigner,
);
// covers taker
await testUtils.prepareBalancesForOrdersAsync([order]);
// need to provide contract wallet with a balance
await makerToken.mint(contractWallet.address, order.makerAmount).awaitTransactionSuccessAsync();
// first allow signer
await contractWallet
.registerAllowedOrderSigner(contractWalletSigner, true)
.awaitTransactionSuccessAsync({ from: contractWalletOwner });
// then disallow signer
await contractWallet
.registerAllowedOrderSigner(contractWalletSigner, false)
.awaitTransactionSuccessAsync({ from: contractWalletOwner });
// fill should revert
const tx = zeroEx.fillOtcOrder(order, sig, order.takerAmount).awaitTransactionSuccessAsync({ from: taker });
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotSignedByMakerError(
order.getHash(),
contractWalletSigner,
order.maker,
),
);
});
it(`doesn't allow fills with an unapproved signer`, async () => {
const order = getTestOtcOrder({ maker: contractWallet.address });
const sig = await order.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, maker);
// covers taker
await testUtils.prepareBalancesForOrdersAsync([order]);
// need to provide contract wallet with a balance
await makerToken.mint(contractWallet.address, order.makerAmount).awaitTransactionSuccessAsync();
// fill should revert
const tx = zeroEx.fillOtcOrder(order, sig, order.takerAmount).awaitTransactionSuccessAsync({ from: taker });
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotSignedByMakerError(order.getHash(), maker, order.maker),
);
});
});
describe('fillOtcOrderWithEth()', () => {
it('Can fill an order with ETH (takerToken=WETH)', async () => {
const order = getTestOtcOrder({ takerToken: wethToken.address });
const receipt = await testUtils.fillOtcOrderWithEthAsync(order);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order);
});
it('Can fill an order with ETH (takerToken=ETH)', async () => {
const order = getTestOtcOrder({ takerToken: ETH_TOKEN_ADDRESS });
const makerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(maker);
const receipt = await testUtils.fillOtcOrderWithEthAsync(order);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
const takerBalance = await new TestMintableERC20TokenContract(order.makerToken, env.provider)
.balanceOf(taker)
.callAsync();
expect(takerBalance, 'taker balance').to.bignumber.eq(order.makerAmount);
const makerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(maker);
expect(makerEthBalanceAfter.minus(makerEthBalanceBefore), 'maker balance').to.bignumber.equal(
order.takerAmount,
);
});
it('Can partially fill an order with ETH (takerToken=WETH)', async () => {
const order = getTestOtcOrder({ takerToken: wethToken.address });
const fillAmount = order.takerAmount.minus(1);
const receipt = await testUtils.fillOtcOrderWithEthAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order, fillAmount)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order, fillAmount);
});
it('Can partially fill an order with ETH (takerToken=ETH)', async () => {
const order = getTestOtcOrder({ takerToken: ETH_TOKEN_ADDRESS });
const fillAmount = order.takerAmount.minus(1);
const makerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(maker);
const receipt = await testUtils.fillOtcOrderWithEthAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order, fillAmount)],
IZeroExEvents.OtcOrderFilled,
);
const { makerTokenFilledAmount, takerTokenFilledAmount } = computeOtcOrderFilledAmounts(order, fillAmount);
const takerBalance = await new TestMintableERC20TokenContract(order.makerToken, env.provider)
.balanceOf(taker)
.callAsync();
expect(takerBalance, 'taker balance').to.bignumber.eq(makerTokenFilledAmount);
const makerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(maker);
expect(makerEthBalanceAfter.minus(makerEthBalanceBefore), 'maker balance').to.bignumber.equal(
takerTokenFilledAmount,
);
});
it('Can refund excess ETH is msg.value > order.takerAmount (takerToken=WETH)', async () => {
const order = getTestOtcOrder({ takerToken: wethToken.address });
const fillAmount = order.takerAmount.plus(420);
const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker);
const receipt = await testUtils.fillOtcOrderWithEthAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker);
expect(takerEthBalanceBefore.minus(takerEthBalanceAfter)).to.bignumber.equal(order.takerAmount);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order);
});
it('Can refund excess ETH is msg.value > order.takerAmount (takerToken=ETH)', async () => {
const order = getTestOtcOrder({ takerToken: ETH_TOKEN_ADDRESS });
const fillAmount = order.takerAmount.plus(420);
const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker);
const makerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(maker);
const receipt = await testUtils.fillOtcOrderWithEthAsync(order, fillAmount);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker);
expect(takerEthBalanceBefore.minus(takerEthBalanceAfter), 'taker eth balance').to.bignumber.equal(
order.takerAmount,
);
const takerBalance = await new TestMintableERC20TokenContract(order.makerToken, env.provider)
.balanceOf(taker)
.callAsync();
expect(takerBalance, 'taker balance').to.bignumber.eq(order.makerAmount);
const makerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(maker);
expect(makerEthBalanceAfter.minus(makerEthBalanceBefore), 'maker balance').to.bignumber.equal(
order.takerAmount,
);
});
it('Cannot fill an order if taker token is not ETH or WETH', async () => {
const order = getTestOtcOrder();
const tx = testUtils.fillOtcOrderWithEthAsync(order);
return expect(tx).to.revertWith('OtcOrdersFeature::fillOtcOrderWithEth/INVALID_TAKER_TOKEN');
});
});
describe('fillTakerSignedOtcOrder()', () => {
it('can fully fill an order', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
const receipt = await testUtils.fillTakerSignedOtcOrderAsync(order);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
await assertExpectedFinalBalancesFromOtcOrderFillAsync(order);
});
it('cannot fill an order with wrong tx.origin', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order, notTxOrigin);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), notTxOrigin, txOrigin),
);
});
it('can fill an order from a different tx.origin if registered', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
await zeroEx
.registerAllowedRfqOrigins([notTxOrigin], true)
.awaitTransactionSuccessAsync({ from: txOrigin });
return testUtils.fillTakerSignedOtcOrderAsync(order, notTxOrigin);
});
it('cannot fill an order with registered then unregistered tx.origin', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
await zeroEx
.registerAllowedRfqOrigins([notTxOrigin], true)
.awaitTransactionSuccessAsync({ from: txOrigin });
await zeroEx
.registerAllowedRfqOrigins([notTxOrigin], false)
.awaitTransactionSuccessAsync({ from: txOrigin });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order, notTxOrigin);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), notTxOrigin, txOrigin),
);
});
it('cannot fill an order with a zero tx.origin', async () => {
const order = getTestOtcOrder({ taker, txOrigin: NULL_ADDRESS });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order, txOrigin);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByOriginError(order.getHash(), txOrigin, NULL_ADDRESS),
);
});
it('cannot fill an expired order', async () => {
const order = getTestOtcOrder({ taker, txOrigin, expiry: createExpiry(-60) });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order.getHash(), OrderStatus.Expired),
);
});
it('cannot fill an order with bad taker signature', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order, txOrigin, notTaker);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableByTakerError(order.getHash(), notTaker, taker),
);
});
it('cannot fill order with bad maker signature', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
const anotherOrder = getTestOtcOrder({ taker, txOrigin });
await testUtils.prepareBalancesForOrdersAsync([order], taker);
const tx = zeroEx
.fillTakerSignedOtcOrder(
order,
await anotherOrder.getSignatureWithProviderAsync(env.provider),
await order.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker),
)
.awaitTransactionSuccessAsync({ from: txOrigin });
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotSignedByMakerError(order.getHash(), undefined, order.maker),
);
});
it('fails if ETH is attached', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
await testUtils.prepareBalancesForOrdersAsync([order], taker);
const tx = zeroEx
.fillTakerSignedOtcOrder(
order,
await order.getSignatureWithProviderAsync(env.provider),
await order.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker),
)
.awaitTransactionSuccessAsync({ from: txOrigin, value: 1 });
// This will revert at the language level because the fill function is not payable.
return expect(tx).to.be.rejectedWith('revert');
});
it('cannot fill the same order twice', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
await testUtils.fillTakerSignedOtcOrderAsync(order);
const tx = testUtils.fillTakerSignedOtcOrderAsync(order);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order.getHash(), OrderStatus.Invalid),
);
});
it('cannot fill two orders with the same nonceBucket and nonce', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
await testUtils.fillTakerSignedOtcOrderAsync(order1);
const order2 = getTestOtcOrder({ taker, txOrigin, nonceBucket: order1.nonceBucket, nonce: order1.nonce });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order2);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order2.getHash(), OrderStatus.Invalid),
);
});
it('cannot fill an order whose nonce is less than the nonce last used in that bucket', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
await testUtils.fillTakerSignedOtcOrderAsync(order1);
const order2 = getTestOtcOrder({
taker,
txOrigin,
nonceBucket: order1.nonceBucket,
nonce: order1.nonce.minus(1),
});
const tx = testUtils.fillTakerSignedOtcOrderAsync(order2);
return expect(tx).to.revertWith(
new RevertErrors.NativeOrders.OrderNotFillableError(order2.getHash(), OrderStatus.Invalid),
);
});
it('can fill two orders that use the same nonce bucket and increasing nonces', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
const tx1 = await testUtils.fillTakerSignedOtcOrderAsync(order1);
verifyEventsFromLogs(
tx1.logs,
[testUtils.createOtcOrderFilledEventArgs(order1)],
IZeroExEvents.OtcOrderFilled,
);
const order2 = getTestOtcOrder({
taker,
txOrigin,
nonceBucket: order1.nonceBucket,
nonce: order1.nonce.plus(1),
});
const tx2 = await testUtils.fillTakerSignedOtcOrderAsync(order2);
verifyEventsFromLogs(
tx2.logs,
[testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('can fill two orders that use the same nonce but different nonce buckets', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
const tx1 = await testUtils.fillTakerSignedOtcOrderAsync(order1);
verifyEventsFromLogs(
tx1.logs,
[testUtils.createOtcOrderFilledEventArgs(order1)],
IZeroExEvents.OtcOrderFilled,
);
const order2 = getTestOtcOrder({ taker, txOrigin, nonce: order1.nonce });
const tx2 = await testUtils.fillTakerSignedOtcOrderAsync(order2);
verifyEventsFromLogs(
tx2.logs,
[testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('can fill a WETH buy order and receive ETH', async () => {
const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker);
const order = getTestOtcOrder({
taker,
txOrigin,
makerToken: wethToken.address,
makerAmount: new BigNumber('1e18'),
});
await wethToken.deposit().awaitTransactionSuccessAsync({ from: maker, value: order.makerAmount });
const receipt = await testUtils.fillTakerSignedOtcOrderAsync(order, txOrigin, taker, true);
verifyEventsFromLogs(
receipt.logs,
[testUtils.createOtcOrderFilledEventArgs(order)],
IZeroExEvents.OtcOrderFilled,
);
const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker);
expect(takerEthBalanceAfter.minus(takerEthBalanceBefore)).to.bignumber.equal(order.makerAmount);
});
it('reverts if `unwrapWeth` is true but maker token is not WETH', async () => {
const order = getTestOtcOrder({ taker, txOrigin });
const tx = testUtils.fillTakerSignedOtcOrderAsync(order, txOrigin, taker, true);
return expect(tx).to.revertWith('OtcOrdersFeature::fillTakerSignedOtcOrder/MAKER_TOKEN_NOT_WETH');
});
});
describe('batchFillTakerSignedOtcOrders()', () => {
it('Fills multiple orders', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
const order2 = getTestOtcOrder({
taker: notTaker,
txOrigin,
nonceBucket: order1.nonceBucket,
nonce: order1.nonce.plus(1),
});
await testUtils.prepareBalancesForOrdersAsync([order1], taker);
await testUtils.prepareBalancesForOrdersAsync([order2], notTaker);
const tx = await zeroEx
.batchFillTakerSignedOtcOrders(
[order1, order2],
[
await order1.getSignatureWithProviderAsync(env.provider),
await order2.getSignatureWithProviderAsync(env.provider),
],
[
await order1.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker),
await order2.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, notTaker),
],
[false, false],
)
.awaitTransactionSuccessAsync({ from: txOrigin });
verifyEventsFromLogs(
tx.logs,
[testUtils.createOtcOrderFilledEventArgs(order1), testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('Fills multiple orders and unwraps WETH', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
const order2 = getTestOtcOrder({
taker: notTaker,
txOrigin,
nonceBucket: order1.nonceBucket,
nonce: order1.nonce.plus(1),
makerToken: wethToken.address,
makerAmount: new BigNumber('1e18'),
});
await testUtils.prepareBalancesForOrdersAsync([order1], taker);
await testUtils.prepareBalancesForOrdersAsync([order2], notTaker);
await wethToken.deposit().awaitTransactionSuccessAsync({ from: maker, value: order2.makerAmount });
const tx = await zeroEx
.batchFillTakerSignedOtcOrders(
[order1, order2],
[
await order1.getSignatureWithProviderAsync(env.provider),
await order2.getSignatureWithProviderAsync(env.provider),
],
[
await order1.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker),
await order2.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, notTaker),
],
[false, true],
)
.awaitTransactionSuccessAsync({ from: txOrigin });
verifyEventsFromLogs(
tx.logs,
[testUtils.createOtcOrderFilledEventArgs(order1), testUtils.createOtcOrderFilledEventArgs(order2)],
IZeroExEvents.OtcOrderFilled,
);
});
it('Skips over unfillable orders', async () => {
const order1 = getTestOtcOrder({ taker, txOrigin });
const order2 = getTestOtcOrder({
taker: notTaker,
txOrigin,
nonceBucket: order1.nonceBucket,
nonce: order1.nonce.plus(1),
});
await testUtils.prepareBalancesForOrdersAsync([order1], taker);
await testUtils.prepareBalancesForOrdersAsync([order2], notTaker);
const tx = await zeroEx
.batchFillTakerSignedOtcOrders(
[order1, order2],
[
await order1.getSignatureWithProviderAsync(env.provider),
await order2.getSignatureWithProviderAsync(env.provider),
],
[
await order1.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker),
await order2.getSignatureWithProviderAsync(env.provider, SignatureType.EthSign, taker), // Invalid signature for order2
],
[false, false],
)
.awaitTransactionSuccessAsync({ from: txOrigin });
verifyEventsFromLogs(
tx.logs,
[testUtils.createOtcOrderFilledEventArgs(order1)],
IZeroExEvents.OtcOrderFilled,
);
});
});
}); | the_stack |
import {
include,
extend,
throwError,
getSize,
is,
throwWarn,
belowIOS8,
TGetSizeImage,
forin,
transValue,
getLength,
splitWords,
} from '@Src/utils'
import { Canvas } from '@Src/canvas'
import { crop as cropFn } from '@Src/utils/crop'
export class MCanvas {
private ops: Required<TCanvas.options>
private cvs: HTMLCanvasElement
private ctx: CanvasRenderingContext2D
// 绘制函数队列;
private queue: TCanvas.queue = []
// 回调函数池;
private fn = {
// 最后执行的函数;
success() {},
// 错误回调;
error(err) {},
}
private data: TCanvas.data = {
// 文字id;
textId: 0,
// 文字绘制数据;
text : {},
// 背景图数据;
bgConfig: null,
}
constructor(options: TCanvas.options = { }) {
// 配置canvas初始大小;
// width:画布宽度,Number,选填,默认为 500;
// height: 画布高度,Number,选填,默认与宽度一致;
this.ops = extend({
width: 500,
height: 500,
backgroundColor: '',
}, options)
this._init()
}
private _init() {
const { width, height, backgroundColor } = this.ops;
[this.cvs, this.ctx] = Canvas.create(width, height)
backgroundColor && this._setBgColor(backgroundColor)
}
// --------------------------------------------------------
// 绘制背景部分;
// --------------------------------------------------------
public background(image?: TCommon.image, bg: TCanvas.backgroundOptions = { type : 'origin' }) {
if (!image && !this.data.bgConfig) {
throwError('the init background must has a image.')
return this
}
// 缓存bg options, 用于重置;
if (image) {
bg.image = image
this.data.bgConfig = bg
} else if (this.data.bgConfig) {
bg = this.data.bgConfig
}
this.queue.push(() => {
if (bg.color) this._setBgColor(bg.color)
Canvas.getImage(bg.image)
.then(img => this._background(img, bg))
.catch(this.fn.error)
})
return this
}
// 设置画布颜色;
private _setBgColor(color: string) {
this.ctx.fillStyle = color
this.ctx.fillRect(0, 0, this.cvs.width, this.cvs.height)
}
private _getBgAlign(
left: TCanvas.backgroundOptions['left'],
iw: number,
cw: number,
cropScale: number
) {
let rv
if (is.str(left)) {
if (left === '50%' || left === 'center') {
rv = Math.abs((iw - cw / cropScale) / 2)
} else if (left === '100%') {
rv = Math.abs(iw - cw / cropScale)
} else if (left === '0%') {
rv = 0
}
} else if (is.num(left)) {
rv = left
} else {
rv = 0
}
return rv
}
private _background(img: HTMLImageElement, bg: TCanvas.backgroundOptions) {
const { iw, ih } = getSize(img)
// 图片与canvas的长宽比;
const iRatio = iw / ih
const cRatio = this.cvs.width / this.cvs.height
// 背景绘制参数;
let sx, sy, swidth, sheight, dx, dy, dwidth, dheight
let cropScale
switch (bg.type) {
case 'crop':
// 裁剪模式,固定canvas大小,原图铺满,超出的部分裁剪;
if (iRatio > cRatio) {
swidth = ih * cRatio
sheight = ih
cropScale = this.cvs.height / ih
} else {
swidth = iw
sheight = swidth / cRatio
cropScale = this.cvs.width / iw
}
sx = this._getBgAlign(bg.left, iw, this.cvs.width, cropScale)
sy = this._getBgAlign(bg.top, ih, this.cvs.height, cropScale)
dy = dx = 0
dheight = this.cvs.height
dwidth = this.cvs.width
break
case 'contain':
// 包含模式,固定canvas大小,包含背景图;
sy = sx = 0
swidth = iw
sheight = ih
if (iRatio > cRatio) {
dwidth = this.cvs.width
dheight = dwidth / iRatio
dx = bg.left || 0
dy = (bg.top || bg.top === 0) ? bg.top : (this.cvs.height - dheight) / 2
} else {
dheight = this.cvs.height
dwidth = dheight * iRatio
dy = bg.top || 0
dx = (bg.left || bg.left === 0) ? bg.left : (this.cvs.width - dwidth) / 2
}
break
case 'origin':
// 原图模式:canvas与原图大小一致,忽略初始化 传入的宽高参数;
// 同时,background 传入的 left/top 均被忽略;
this.cvs.width = iw
this.cvs.height = ih
sx = sy = 0
swidth = iw
sheight = ih
dx = dy = 0
dwidth = this.cvs.width
dheight = this.cvs.height
break
default:
throwError('background type error!')
return
}
this.ctx.drawImage(img, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
this._next()
}
// --------------------------------------------------------
// 绘制图层部分;
// --------------------------------------------------------
// 绘制矩形层;
public rect(ops: TCanvas.rectOptions = {}) {
this.queue.push(() => {
const { width: cw, height: ch } = this.cvs
const {
fillColor = '#fff',
strokeColor = fillColor,
strokeWidth = 0,
radius = 0,
} = ops
let { width = 100, height = 100, x = 0, y = 0 } = ops
width = transValue(cw, 0, width, 'pos') - 2 * strokeWidth,
height = transValue(ch, 0, height, 'pos') - 2 * strokeWidth
// 计算尾值时,与边框的关系则为相反
x = transValue(cw, width, x, 'pos') + (include(x, 'right') ? -strokeWidth : strokeWidth)
y = transValue(ch, height, y, 'pos') + (include(y, 'bottom') ? -strokeWidth : strokeWidth)
Canvas.drawRoundRect(
this.ctx,
x, y, width, height, radius,
fillColor, strokeWidth, strokeColor,
)
this._resetCtx()._next()
})
return this
}
// 绘制圆形层;
public circle(ops: TCanvas.circleOptions = {}) {
this.queue.push(() => {
const { fillColor = '#fff', strokeColor = fillColor, strokeWidth = 0 } = ops
const { width: cw, height: ch } = this.cvs
let { x = 0, y = 0, radius = 100 } = ops
const r = transValue(cw, 0, radius, 'pos') - 2 * strokeWidth
x = transValue(cw, 2 * r, x, 'pos') + r + (include(x, 'right') ? -strokeWidth : strokeWidth)
y = transValue(ch, 2 * r, y, 'pos') + r + (include(y, 'bottom') ? -strokeWidth : strokeWidth)
this.ctx.beginPath()
this.ctx.arc(x, y, r, 0, Math.PI * 2, false)
this.ctx.fillStyle = fillColor
this.ctx.fill()
this.ctx.strokeStyle = strokeColor
this.ctx.lineWidth = strokeWidth
this.ctx.stroke()
this.ctx.closePath()
this._resetCtx()._next()
})
return this
}
// 重置ctx属性;
private _resetCtx() {
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
return this
}
// 绘制水印;基于 add 函数封装;
public watermark(
image: TCommon.image,
ops: TCanvas.watermarkOptions = {},
) {
if (!image) {
throwError('there is not image of watermark.')
return this
}
// 参数默认值;
const { width = '40%', pos = 'rightbottom', margin = 20 } = ops
const position: Required<TCanvas.position> = {
x: 0,
y: 0,
scale: 1,
rotate: 0,
}
switch (pos) {
case 'leftTop':
position.x = `left:${margin}`
position.y = `top:${margin}`
break
case 'leftBottom':
position.x = `left:${margin}`
position.y = `bottom:${margin}`
break
case 'rightTop':
position.x = `right:${margin}`
position.y = `top:${margin}`
break
case 'rightBottom':
position.x = `right:${margin}`
position.y = `bottom:${margin}`
break
default:
}
this.add(image, {
width,
pos: position,
})
return this
}
// 通用绘制图层函数;
// 使用方式:
// 多张图: add([{image:'',options:{}},{image:'',options:{}}]);
// 单张图: add(image,options);
public add(
image: TCanvas.addData[] | TCommon.image,
options?: TCanvas.addOptions
) {
// 默认参数;
const def = {
width: '100%',
crop: {
x: 0,
y: 0,
width: '100%',
height: '100%',
radius: 0,
},
pos: {
x: 0,
y: 0,
scale: 1,
rotate: 0,
},
}
const images = is.arr(image) ? image : [{ image, options }]
images.map(({ image, options }) => {
// 将封装好的 add函数 推入队列中待执行;
// 参数经过 _handleOps 加工;
this.queue.push(() => {
Canvas.getImage(image).then(img => {
this._add(
img,
this._handleOps(img, extend(true, def, options))
)
}).catch(this.fn.error)
})
})
return this
}
private _add(img, ops: Required<TCanvas.addOptions>) {
const crop = ops.crop as {
x: number,
y: number,
width: number,
height: number,
radius: number,
}
const pos = ops.pos as {
x: number,
y: number,
scale: number,
rotate: number,
}
const width = ops.width as number
if (width === 0) throwWarn(`the width of mc-element is zero`)
const { iw, ih } = getSize(img)
// 画布canvas参数;
let cdx, cdy, cdw, cdh
// 素材canvas参数;
const { width: lsw, height: lsh, radius } = crop
// 图片需要裁剪
if (lsw !== iw || lsh !== ih || radius > 0) {
// 此时 img 已加载,且直接导出 canvas
// 因此 success 为同步代码
img = cropFn(img, crop).cvs
}
const cratio = lsw / lsh
let ldx, ldy, ldw, ldh
// 由于 canvas 的特性,旋转只是 ctx 的旋转,并不是 canvas,
// 因此如果 canvas 与 ctx 完全相等时,旋转就会出现被裁剪的问题
// 这里通过将 canvas 放大的方式来解决该问题;
// 图片宽高比 * 1.4 是一个最安全的宽度,旋转任意角度都不会被裁剪;
// 没有旋转却长宽比很高大的图,会导致放大倍数太大,因此设置最高倍数为5;
// _ratio 为 较大边 / 较小边 的比例;
const _ratio = iw > ih ? iw / ih : ih / iw
const lctxScale = _ratio * 1.4 > 5 ? 5 : _ratio * 1.4
let spaceX, spaceY
// 素材canvas的绘制;
const [lcvs, lctx] = Canvas.create(
Math.round(lsw * lctxScale),
Math.round(lsh * lctxScale)
)
// 限制canvas的大小,ios8以下为 2096, 其余平台均限制为 4096;
const limitLength = belowIOS8() && (lcvs.width > 2096 || lcvs.height > 2096) ? 2096 : 4096
const shrink = cratio > 1 ? limitLength / lcvs.width : limitLength / lcvs.height
// 从素材canvas的中心点开始绘制;
ldx = - Math.round(lsw / 2)
ldy = - Math.round(lsh / 2)
ldw = lsw
ldh = Math.round(lsw / cratio)
// 当素材缩放后超出限制时,缩放为限制值,避免绘制失败;
// 获取素材最终的宽高;
if ((lcvs.width > limitLength || lcvs.height > limitLength) && shrink) {
[lcvs.width, lcvs.height, ldx, ldy, ldw, ldh] = [lcvs.width, lcvs.height, ldx, ldy, ldw, ldh].map(v => Math.round(v * shrink))
}
lctx.translate(lcvs.width / 2, lcvs.height / 2)
lctx.rotate(pos.rotate)
lctx.drawImage(img, ldx, ldy, ldw, ldh)
cdw = Math.round(width * lctxScale)
cdh = Math.round(cdw / cratio)
spaceX = (lctxScale - 1) * width / 2
spaceY = spaceX / cratio
// 获取素材的位置;
// 配置的位置 - 缩放的影响 - 绘制成正方形的影响;
cdx = Math.round(pos.x + cdw * (1 - pos.scale) / 2 - spaceX)
cdy = Math.round(pos.y + cdh * (1 - pos.scale) / 2 - spaceY)
cdw *= pos.scale
cdh *= pos.scale
this.ctx.drawImage(lcvs, cdx, cdy, cdw, cdh)
this._next()
}
private _getRotate(r?: string | number) {
if (is.str(r)) {
return parseFloat(r) * Math.PI / 180
} else if (is.num(r)) {
return r * Math.PI / 180
} else {
return 0
}
}
// 参数加工函数;
private _handleOps(img: TGetSizeImage, ops: Required<TCanvas.addOptions>) {
const { width: cw, height: ch } = this.cvs
const { iw, ih } = getSize(img)
// 图片宽高比;
const ratio = iw / ih
// 根据参数计算后的绘制宽度;
const width = transValue(cw, iw, ops.width, 'pos')
// 裁剪参数;
const cropw = transValue(cw, iw, ops.crop.width!, 'crop')
const croph = transValue(ch, ih, ops.crop.height!, 'crop')
const crop = {
width: cropw,
height: croph,
x: transValue(iw, cropw, ops.crop.x!, 'crop'),
y: transValue(ih, croph, ops.crop.y!, 'crop'),
radius: getLength(cropw, ops.crop.radius!),
}
// 裁剪的最大宽高;
let maxLsw, maxLsh
// 最大值判定;
if (crop.x > iw) crop.x = iw
if (crop.y > ih) crop.y = ih
maxLsw = iw - crop.x
maxLsh = ih - crop.y
if (crop.width > maxLsw) crop.width = maxLsw
if (crop.height > maxLsh) crop.height = maxLsh
// 位置参数;
const { x: px, y: py, rotate: pr, scale: ps = 1 } = ops.pos
const pos = {
x: transValue(cw, width, px!, 'pos'),
y: transValue(ch, width / ratio, py!, 'pos'),
scale: ps,
rotate: this._getRotate(pr),
}
return { width, crop, pos }
}
// --------------------------------------------------------
// 绘制文字部分;
// --------------------------------------------------------
private _defaultFontFamily = 'helvetica neue,hiragino sans gb,Microsoft YaHei,arial,tahoma,sans-serif'
private _createStyle(fontSize: number, lineHeight: number) {
return {
font: `${fontSize}px ${this._defaultFontFamily}`,
lineHeight,
color: '#000',
type: 'fill',
lineWidth: 1,
wordBreak: true,
shadow: {
color: null,
blur: 0,
offsetX: 0,
offsetY: 0,
},
}
}
public text(context: string, ops: TCanvas.textOptions = {}) {
// 默认的字体大小;
const dfs = this.cvs.width / 20
this.queue.push(() => {
const option = extend(true, {
width: 300,
align: 'left',
smallStyle: this._createStyle(dfs * 0.8, dfs * 0.9),
normalStyle: this._createStyle(dfs, dfs * 1.1),
largeStyle: this._createStyle(dfs * 1.3, dfs * 1.4),
pos: {
x: 0,
y: 0,
rotate: 0,
},
}, ops) as Required<TCanvas.textOptions>
// 解析字符串模板后,调用字体绘制函数;
const parseContext = this._parse(String(context))
let max = 0, maxFont
parseContext.map(v => {
if (v.size > max) {
max = v.size
maxFont = v.type
}
})
// 当设置的宽度小于字体宽度时,强行将设置宽度设为与字体一致;
const maxFontSize = parseInt(option[`${maxFont}Style`].font)
if (maxFontSize && option.width < maxFontSize) option.width = maxFontSize
this._text(parseContext, option)
this._resetCtx()._next()
})
return this
}
// 字符串模板解析函数
// 解析 <s></s> <b></b>
private _parse(context: string) {
const arr = context.split(/<s>|<b>/)
const result: {
type: 'small' | 'normal' | 'large',
text: string,
// 用于字体的大小比较;
size: 0 | 1 | 2,
}[] = []
for (let i = 0; i < arr.length; i++) {
const value = arr[i]
if (/<\/s>|<\/b>/.test(value)) {
const splitTag = /<\/s>/.test(value) ? '</s>' : '</b>',
type = /<\/s>/.test(value) ? 'small' : 'large',
tmp = arr[i].split(splitTag)
result.push({
type,
text: tmp[0],
// 用于字体的大小比较;
size: type === 'small' ? 0 : 2,
})
tmp[1] && result.push({
type: 'normal',
text: tmp[1],
size: 1,
})
continue
}
arr[i] && result.push({
text: arr[i],
type: 'normal',
size: 1,
})
}
return result
}
private _text(
textArr: {
type: "small" | "normal" | "large";
text: string;
size: 0 | 1 | 2;
}[],
option: Required<TCanvas.textOptions>
) {
this.data.textId++
this.data.text[this.data.textId] = {}
// 处理宽度参数;
const opsWidth = option.width = transValue(this.cvs.width, 0, option.width, 'pos')
let style,
line = 1,
lineWidth = 0,
lineHeight = this._getLineHeight(textArr, option),
x = transValue(this.cvs.width, opsWidth, 0, 'pos'),
y = (transValue(this.cvs.height, 0, 0, 'pos')) + lineHeight
// data:字体数据;
// lineWidth:行宽;
this.data.text[this.data.textId][line] = {
data: [],
lineWidth: 0,
}
// 生成字体数据;
textArr.map(v => {
style = option[`${v.type}Style`]
this.ctx.font = style.font
// 先获取整个字体块的宽度
// 用于判断是否会再当前字体块产生换行
let width = this.ctx.measureText(v.text).width
// 处理 <br> 换行,先替换成 '|',便于单字绘图时进行判断;
let context: string | string[] = v.text.replace(/<br>/g, '|')
// 先进行字体块超出判断,超出宽度 或 包含换行符 时采用单字绘制;
if ((lineWidth + width) > opsWidth || include(context, '|')) {
// 重新分词
if (!style.wordBreak) context = splitWords(context)
for (let i = 0, fontLength = context.length; i < fontLength; i++) {
const _context = context[i]
width = this.ctx.measureText(_context).width
// 当字体的计算宽度 > 设置的宽度 || 内容中包含换行时,进入换行逻辑;
if ((lineWidth + width) > opsWidth || _context === '|') {
x = lineWidth = 0
y += lineHeight
line += 1
this.data.text[this.data.textId][line] = {
data: [],
lineWidth: 0,
}
// 不绘制换行符
if (_context === '|') continue
}
// 生成绘制数据
const lineData = this.data.text[this.data.textId][line]
lineData.data.push({ context: _context, x, y, style, width })
x += width
lineData.lineWidth = lineWidth += width
}
} else {
// 当前字体块不会换行,则整块绘制;
const lineData = this.data.text[this.data.textId][line]
lineData.data.push({ context, x, y, style, width })
x += width
lineData.lineWidth = lineWidth += width
}
})
// 创建文字画布;
const [tcvs, tctx] = Canvas.create(opsWidth, this._getTextRectHeight(line))
const tdh = tcvs.height
const tdw = tcvs.width
const tdx = transValue(this.cvs.width, tdw, option.pos.x!, 'pos')
const tdy = transValue(this.cvs.height, tdh, option.pos.y!, 'pos')
// 通过字体数据进行文字的绘制;
forin(this.data.text[this.data.textId], (k, v) => {
// 增加 align 的功能;
let add = 0
if (v.lineWidth < opsWidth) {
if (option.align === 'center') {
add = (opsWidth - v.lineWidth) / 2
}else if (option.align === 'right') {
add = opsWidth - v.lineWidth
}
}
v.data.map(text => {
text.x += add
this._fillText(tctx, text)
})
})
// tcvs.style.width = '300px'
// document.body.appendChild(tcvs)
// 绘制文字画布;
this.ctx.translate(tdx + tdw / 2, tdy + tdh / 2)
this.ctx.rotate(this._getRotate(option.pos.rotate))
this.ctx.drawImage(tcvs, -tdw / 2, -tdh / 2, tdw, tdh)
}
private _getLineHeight(textArr, option) {
let lh = 0, vlh
textArr.map(v => {
vlh = option[`${v.type}Style`].lineHeight
if (vlh > lh) lh = vlh
})
return lh
}
private _fillText(ctx, text) {
const { context, x, y, style } = text
const { align, lineWidth, shadow, font, gradient, lineHeight } = style
const { color, blur, offsetX, offsetY } = shadow
ctx.font = font
ctx.textAlign = align
ctx.textBaseline = 'alphabetic'
ctx.lineWidth = lineWidth
ctx.shadowColor = color
ctx.shadowBlur = blur
ctx.shadowOffsetX = offsetX
ctx.shadowOffsetY = offsetY
if (gradient) {
const { type, colorStop } = gradient
let x1, y1, x2, y2
if (type === 1) {
x1 = x
y1 = y
x2 = x + text.width
y2 = y
} else {
x1 = x
y1 = y - lineHeight
x2 = x
y2 = y
}
const grad = ctx.createLinearGradient(x1, y1, x2, y2)
const colorNum = colorStop.length || 0
forin(colorStop, (i, v) => {
grad.addColorStop(1 / colorNum * (+i + 1), v)
})
ctx[`${style.type}Style`] = grad
}else {
ctx[`${style.type}Style`] = style.color
}
ctx[`${style.type}Text`](context, x, y)
this._resetCtx()
}
private _getTextRectHeight (lastLine) {
const lastLineData = this.data.text[this.data.textId][lastLine].data[0]
return lastLineData.y + lastLineData.style.lineHeight
}
// 绘制函数;
public draw(ops: TCommon.drawOptions | ((b64: string) => void) = {}) {
return new Promise((resolve, reject) => {
let config = {
type: 'jpeg',
quality: .9,
exportType: 'base64',
success(b64) { },
error(err) { },
}
if (is.fn(ops)) {
config.success = ops
}else {
config = extend(true, config, ops)
if (config.type === 'jpg') config.type = 'jpeg'
}
this.fn.error = (err) => {
config.error(err)
reject(err)
}
this.fn.success = () => {
if (config.exportType === 'canvas') {
config.success(this.cvs)
resolve(this.cvs)
} else {
setTimeout(() => {
const b64 = this.cvs.toDataURL(`image/${config.type}`, config.quality)
config.success(b64)
resolve(b64)
}, 0)
}
}
this._next()
})
}
private _next() {
if (this.queue.length > 0) {
this.ctx.save()
const next = this.queue.shift()
next && next()
this.ctx.restore()
}else {
this.fn.success()
}
}
public clear() {
this.ctx.clearRect(0, 0, this.cvs.width, this.cvs.height)
return this
}
} | the_stack |
declare namespace adone.math {
/**
* ES7 (proposed) SIMD numeric type polyfill
*/
namespace simd {
namespace I {
type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray
| Int16Array | Uint16Array
| Int32Array | Uint32Array
| Float32Array | Float64Array;
/**
* 128-bits divided into 4 lanes storing single precision floating point values.
*/
interface Float32x4 {
constructor: Float32x4Constructor;
valueOf(): Float32x4;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Float32x4".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Float32x4;
[Symbol.toPrimitive](hint: string): any;
}
interface Float32x4Constructor {
/**
* SIMD.Float32x4 constructor
* @param s0 A 32bit float specifying the value of the lane.
* @param s1 A 32bit float specifying the value of the lane.
* @param s2 A 32bit float specifying the value of the lane.
* @param s3 A 32bit float specifying the value of the lane.
* @return SIMD.Float32x4 object
*/
(s0?: number, s1?: number, s2?: number, s3?: number): Float32x4;
prototype: Float32x4;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Float32x4, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(a: Float32x4, l1: number, l2: number, l3: number, l4: number): Float32x4;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(a: Float32x4, b: Float32x4, l1: number, l2: number, l3: number, l4: number): Float32x4;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Float32x4. Throws a TypeError otherwise.
*/
check(a: Float32x4): Float32x4;
/**
* Creates a new SIMD.Float32x4 data type with all lanes set to a given value.
*/
splat(n: number): Float32x4;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Float32x4, lane: number, value: number): Float32x4;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool32x4, a: Float32x4, b: Float32x4): Float32x4;
equal(a: Float32x4, b: Float32x4): Bool32x4;
notEqual(a: Float32x4, b: Float32x4): Bool32x4;
lessThan(a: Float32x4, b: Float32x4): Bool32x4;
lessThanOrEqual(a: Float32x4, b: Float32x4): Bool32x4;
greaterThan(a: Float32x4, b: Float32x4): Bool32x4;
greaterThanOrEqual(a: Float32x4, b: Float32x4): Bool32x4;
add(a: Float32x4, b: Float32x4): Float32x4;
sub(a: Float32x4, b: Float32x4): Float32x4;
mul(a: Float32x4, b: Float32x4): Float32x4;
div(a: Float32x4, b: Float32x4): Float32x4;
neg(a: Float32x4): Float32x4;
abs(a: Float32x4): Float32x4;
min(a: Float32x4, b: Float32x4): Float32x4;
max(a: Float32x4, b: Float32x4): Float32x4;
minNum(a: Float32x4, b: Float32x4): Float32x4;
maxNum(a: Float32x4, b: Float32x4): Float32x4;
reciprocalApproximation(a: Float32x4, b: Float32x4): Float32x4;
reciprocalSqrtApproximation(a: Float32x4): Float32x4;
sqrt(a: Float32x4): Float32x4;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Float32x4;
/**
* Returns a new instance with 1 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load1(tarray: TypedArray, index: number): Float32x4;
/**
* Returns a new instance with 2 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load2(tarray: TypedArray, index: number): Float32x4;
/**
* Returns a new instance with 3 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load3(tarray: TypedArray, index: number): Float32x4;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Float32x4): Float32x4;
/**
* Store 1 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store1(tarray: TypedArray, index: number, value: Float32x4): Float32x4;
/**
* Store 2 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store2(tarray: TypedArray, index: number, value: Float32x4): Float32x4;
/**
* Store 3 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store3(tarray: Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, index: number, value: Float32x4): Float32x4;
/**
* Creates a new SIMD data type with a float conversion from a Int32x4.
* @param value An Int32x4 SIMD type to convert from.
*/
fromInt32x4(value: Int32x4): Float32x4;
/**
* Creates a new SIMD data type with a float conversion from a Uint32x4.
* @param value An Uint32x4 SIMD type to convert from.
*/
fromUint32x4(value: Uint32x4): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Float32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Float32x4;
}
/**
* 128-bits divided into 4 lanes storing 32-bit signed integer values.
*/
interface Int32x4 {
constructor: Int32x4Constructor;
valueOf(): Int32x4;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Int32x4".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Int32x4;
[Symbol.toPrimitive](hint: string): any;
}
interface Int32x4Constructor {
/**
* SIMD.Int32x4 constructor
* @param s0 A 32bit int specifying the value of the lane.
* @param s1 A 32bit int specifying the value of the lane.
* @param s2 A 32bit int specifying the value of the lane.
* @param s3 A 32bit int specifying the value of the lane.
* @return SIMD.Int32x4 object
*/
(s0?: number, s1?: number, s2?: number, s3?: number): Int32x4;
prototype: Int32x4;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Int32x4, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(a: Int32x4, l1: number, l2: number, l3: number, l4: number): Int32x4;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(a: Int32x4, b: Int32x4, l1: number, l2: number, l3: number, l4: number): Int32x4;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Int32x4. Throws a TypeError otherwise.
*/
check(a: Int32x4): Int32x4;
/**
* Creates a new SIMD.Int32x4 data type with all lanes set to a given value.
*/
splat(n: number): Int32x4;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Int32x4, lane: number, value: number): Int32x4;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool32x4, a: Int32x4, b: Int32x4): Int32x4;
equal(a: Int32x4, b: Int32x4): Bool32x4;
notEqual(a: Int32x4, b: Int32x4): Bool32x4;
lessThan(a: Int32x4, b: Int32x4): Bool32x4;
lessThanOrEqual(a: Int32x4, b: Int32x4): Bool32x4;
greaterThan(a: Int32x4, b: Int32x4): Bool32x4;
greaterThanOrEqual(a: Int32x4, b: Int32x4): Bool32x4;
and(a: Int32x4, b: Int32x4): Int32x4;
or(a: Int32x4, b: Int32x4): Int32x4;
xor(a: Int32x4, b: Int32x4): Int32x4;
not(a: Int32x4, b: Int32x4): Int32x4;
add(a: Int32x4, b: Int32x4): Int32x4;
sub(a: Int32x4, b: Int32x4): Int32x4;
mul(a: Int32x4, b: Int32x4): Int32x4;
neg(a: Int32x4): Int32x4;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Int32x4, bits: number): Int32x4;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Int32x4, bits: number): Int32x4;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Int32x4;
/**
* Returns a new instance with 1 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load1(tarray: TypedArray, index: number): Int32x4;
/**
* Returns a new instance with 2 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load2(tarray: TypedArray, index: number): Int32x4;
/**
* Returns a new instance with 3 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load3(tarray: TypedArray, index: number): Int32x4;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Int32x4): Int32x4;
/**
* Store 1 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store1(tarray: TypedArray, index: number, value: Int32x4): Int32x4;
/**
* Store 2 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store2(tarray: TypedArray, index: number, value: Int32x4): Int32x4;
/**
* Store 3 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store3(tarray: TypedArray, index: number, value: Int32x4): Int32x4;
/**
* Creates a new SIMD data type with a float conversion from a Float32x4.
* @param value An Float32x4 SIMD type to convert from.
*/
fromFloat32x4(value: Float32x4): Int32x4;
/**
* Creates a new SIMD data type with a float conversion from a Uint32x4.
* @param value An Uint32x4 SIMD type to convert from.
*/
fromUint32x4(value: Uint32x4): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Int32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Int32x4;
}
/**
* 128-bits divided into 8 lanes storing 16-bit signed integer values.
*/
interface Int16x8 {
constructor: Int16x8Constructor;
valueOf(): Int16x8;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Int16x8".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Int16x8;
[Symbol.toPrimitive](hint: string): any;
}
interface Int16x8Constructor {
/**
* SIMD.Int16x8 constructor
* @param s0 A 16bit int specifying the value of the lane.
* @param s1 A 16bit int specifying the value of the lane.
* @param s2 A 16bit int specifying the value of the lane.
* @param s3 A 16bit int specifying the value of the lane.
* @param s4 A 16bit int specifying the value of the lane.
* @param s5 A 16bit int specifying the value of the lane.
* @param s6 A 16bit int specifying the value of the lane.
* @param s7 A 16bit int specifying the value of the lane.
* @return SIMD.Int16x8 object
*/
(s0?: number, s1?: number, s2?: number, s3?: number, s4?: number, s5?: number, s6?: number, s7?: number): Int16x8;
prototype: Int16x8;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Int16x8, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(a: Int16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Int16x8;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(a: Int16x8, b: Int16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Int16x8;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Int16x8. Throws a TypeError otherwise.
*/
check(a: Int16x8): Int16x8;
/**
* Creates a new SIMD.Int16x8 data type with all lanes set to a given value.
*/
splat(n: number): Int16x8;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Int16x8, lane: number, value: number): Int16x8;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool16x8, a: Int16x8, b: Int16x8): Int16x8;
equal(a: Int16x8, b: Int16x8): Bool16x8;
notEqual(a: Int16x8, b: Int16x8): Bool16x8;
lessThan(a: Int16x8, b: Int16x8): Bool16x8;
lessThanOrEqual(a: Int16x8, b: Int16x8): Bool16x8;
greaterThan(a: Int16x8, b: Int16x8): Bool16x8;
greaterThanOrEqual(a: Int16x8, b: Int16x8): Bool16x8;
and(a: Int16x8, b: Int16x8): Int16x8;
or(a: Int16x8, b: Int16x8): Int16x8;
xor(a: Int16x8, b: Int16x8): Int16x8;
not(a: Int16x8, b: Int16x8): Int16x8;
add(a: Int16x8, b: Int16x8): Int16x8;
sub(a: Int16x8, b: Int16x8): Int16x8;
mul(a: Int16x8, b: Int16x8): Int16x8;
neg(a: Int16x8): Int16x8;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Int16x8, bits: number): Int16x8;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Int16x8, bits: number): Int16x8;
addSaturate(a: Int16x8, b: Int16x8): Int16x8;
subSaturate(a: Int16x8, b: Int16x8): Int16x8;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Int16x8;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Int16x8): Int16x8;
/**
* Creates a new SIMD data type with a float conversion from a Uint16x8.
* @param value An Uint16x8 SIMD type to convert from.
*/
fromUint16x8(value: Uint16x8): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Int16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Int16x8;
}
/**
* 128-bits divided into 16 lanes storing 8-bit signed integer values.
*/
interface Int8x16 {
constructor: Int8x16Constructor;
valueOf(): Int8x16;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Int8x16".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Int8x16;
[Symbol.toPrimitive](hint: string): any;
}
interface Int8x16Constructor {
/**
* SIMD.Int8x16 constructor
* @param s0 A 8bit int specifying the value of the lane.
* @param s1 A 8bit int specifying the value of the lane.
* @param s2 A 8bit int specifying the value of the lane.
* @param s3 A 8bit int specifying the value of the lane.
* @param s4 A 8bit int specifying the value of the lane.
* @param s5 A 8bit int specifying the value of the lane.
* @param s6 A 8bit int specifying the value of the lane.
* @param s7 A 8bit int specifying the value of the lane.
* @param s8 A 8bit int specifying the value of the lane.
* @param s9 A 8bit int specifying the value of the lane.
* @param s10 A 8bit int specifying the value of the lane.
* @param s11 A 8bit int specifying the value of the lane.
* @param s12 A 8bit int specifying the value of the lane.
* @param s13 A 8bit int specifying the value of the lane.
* @param s14 A 8bit int specifying the value of the lane.
* @param s15 A 8bit int specifying the value of the lane.
* @return SIMD.Int8x16 object
*/
(
s0?: number,
s1?: number,
s2?: number,
s3?: number,
s4?: number,
s5?: number,
s6?: number,
s7?: number,
s8?: number,
s9?: number,
s10?: number,
s11?: number,
s12?: number,
s13?: number,
s14?: number,
s15?: number
): Int8x16;
prototype: Int8x16;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Int8x16, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(
a: Int8x16,
l1: number,
l2: number,
l3: number,
l4: number,
l5: number,
l6: number,
l7: number,
l8: number,
l9: number,
l10: number,
l11: number,
l12: number,
l13: number,
l14: number,
l15: number,
l16: number
): Int8x16;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(
a: Int8x16,
b: Int8x16,
l1: number,
l2: number,
l3: number,
l4: number,
l5: number,
l6: number,
l7: number,
l8: number,
l9: number,
l10: number,
l11: number,
l12: number,
l13: number,
l14: number,
l15: number,
l16: number
): Int8x16;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Int8x16. Throws a TypeError otherwise.
*/
check(a: Int8x16): Int8x16;
/**
* Creates a new SIMD.Int8x16 data type with all lanes set to a given value.
*/
splat(n: number): Int8x16;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Int8x16, lane: number, value: number): Int8x16;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool8x16, a: Int8x16, b: Int8x16): Int8x16;
equal(a: Int8x16, b: Int8x16): Bool8x16;
notEqual(a: Int8x16, b: Int8x16): Bool8x16;
lessThan(a: Int8x16, b: Int8x16): Bool8x16;
lessThanOrEqual(a: Int8x16, b: Int8x16): Bool8x16;
greaterThan(a: Int8x16, b: Int8x16): Bool8x16;
greaterThanOrEqual(a: Int8x16, b: Int8x16): Bool8x16;
and(a: Int8x16, b: Int8x16): Int8x16;
or(a: Int8x16, b: Int8x16): Int8x16;
xor(a: Int8x16, b: Int8x16): Int8x16;
not(a: Int8x16, b: Int8x16): Int8x16;
add(a: Int8x16, b: Int8x16): Int8x16;
sub(a: Int8x16, b: Int8x16): Int8x16;
mul(a: Int8x16, b: Int8x16): Int8x16;
neg(a: Int8x16): Int8x16;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Int8x16, bits: number): Int8x16;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Int8x16, bits: number): Int8x16;
addSaturate(a: Int8x16, b: Int8x16): Int8x16;
subSaturate(a: Int8x16, b: Int8x16): Int8x16;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Int8x16;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Int8x16): Int8x16;
/**
* Creates a new SIMD data type with a float conversion from a Uint8x16.
* @param value An Uint8x16 SIMD type to convert from.
*/
fromUint8x16(value: Uint8x16): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Int8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Int8x16;
}
/**
* 128-bits divided into 4 lanes storing 32-bit unsigned integer values.
*/
interface Uint32x4 {
constructor: Uint32x4Constructor;
valueOf(): Uint32x4;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Uint32x4".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Uint32x4;
[Symbol.toPrimitive](hint: string): any;
}
interface Uint32x4Constructor {
/**
* SIMD.Uint32x4 constructor
* @param s0 A 32bit uint specifying the value of the lane.
* @param s1 A 32bit uint specifying the value of the lane.
* @param s2 A 32bit uint specifying the value of the lane.
* @param s3 A 32bit uint specifying the value of the lane.
* @return SIMD.Uint32x4 object
*/
(s0?: number, s1?: number, s2?: number, s3?: number): Uint32x4;
prototype: Uint32x4;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Uint32x4, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(a: Uint32x4, l1: number, l2: number, l3: number, l4: number): Uint32x4;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(a: Uint32x4, b: Uint32x4, l1: number, l2: number, l3: number, l4: number): Uint32x4;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Uint32x4. Throws a TypeError otherwise.
*/
check(a: Uint32x4): Uint32x4;
/**
* Creates a new SIMD.Uint32x4 data type with all lanes set to a given value.
*/
splat(n: number): Uint32x4;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Uint32x4, lane: number, value: number): Uint32x4;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool32x4, a: Uint32x4, b: Uint32x4): Uint32x4;
equal(a: Uint32x4, b: Uint32x4): Bool32x4;
notEqual(a: Uint32x4, b: Uint32x4): Bool32x4;
lessThan(a: Uint32x4, b: Uint32x4): Bool32x4;
lessThanOrEqual(a: Uint32x4, b: Uint32x4): Bool32x4;
greaterThan(a: Uint32x4, b: Uint32x4): Bool32x4;
greaterThanOrEqual(a: Uint32x4, b: Uint32x4): Bool32x4;
and(a: Uint32x4, b: Uint32x4): Uint32x4;
or(a: Uint32x4, b: Uint32x4): Uint32x4;
xor(a: Uint32x4, b: Uint32x4): Uint32x4;
not(a: Uint32x4, b: Uint32x4): Uint32x4;
add(a: Uint32x4, b: Uint32x4): Uint32x4;
sub(a: Uint32x4, b: Uint32x4): Uint32x4;
mul(a: Uint32x4, b: Uint32x4): Uint32x4;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Uint32x4, bits: number): Uint32x4;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Uint32x4, bits: number): Uint32x4;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Uint32x4;
/**
* Returns a new instance with 1 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load1(tarray: TypedArray, index: number): Uint32x4;
/**
* Returns a new instance with 2 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load2(tarray: TypedArray, index: number): Uint32x4;
/**
* Returns a new instance with 3 lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load3(tarray: TypedArray, index: number): Uint32x4;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4;
/**
* Store 1 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store1(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4;
/**
* Store 2 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store2(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4;
/**
* Store 3 values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store3(tarray: TypedArray, index: number, value: Uint32x4): Uint32x4;
/**
* Creates a new SIMD data type with a float conversion from a Float32x4.
* @param value An Float32x4 SIMD type to convert from.
*/
fromFloat32x4(value: Float32x4): Uint32x4;
/**
* Creates a new SIMD data type with a float conversion from a Int32x4.
* @param value An Int32x4 SIMD type to convert from.
*/
fromInt32x4(value: Int32x4): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Uint32x4;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Uint32x4;
}
/**
* 128-bits divided into 8 lanes storing 16-bit unsigned integer values.
*/
interface Uint16x8 {
constructor: Uint16x8Constructor;
valueOf(): Uint16x8;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Uint16x8".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Uint16x8;
[Symbol.toPrimitive](hint: string): any;
}
interface Uint16x8Constructor {
/**
* SIMD.Uint16x8 constructor
* @param s0 A 16bit uint specifying the value of the lane.
* @param s1 A 16bit uint specifying the value of the lane.
* @param s2 A 16bit uint specifying the value of the lane.
* @param s3 A 16bit uint specifying the value of the lane.
* @param s4 A 16bit uint specifying the value of the lane.
* @param s5 A 16bit uint specifying the value of the lane.
* @param s6 A 16bit uint specifying the value of the lane.
* @param s7 A 16bit uint specifying the value of the lane.
* @return SIMD.Uint16x8 object
*/
(s0?: number, s1?: number, s2?: number, s3?: number, s4?: number, s5?: number, s6?: number, s7?: number): Uint16x8;
prototype: Uint16x8;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Uint16x8, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(a: Uint16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Uint16x8;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(a: Uint16x8, b: Uint16x8, l1: number, l2: number, l3: number, l4: number, l5: number, l6: number, l7: number, l8: number): Uint16x8;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Uint16x8. Throws a TypeError otherwise.
*/
check(a: Uint16x8): Uint16x8;
/**
* Creates a new SIMD.Uint16x8 data type with all lanes set to a given value.
*/
splat(n: number): Uint16x8;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Uint16x8, lane: number, value: number): Uint16x8;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool16x8, a: Uint16x8, b: Uint16x8): Uint16x8;
equal(a: Uint16x8, b: Uint16x8): Bool16x8;
notEqual(a: Uint16x8, b: Uint16x8): Bool16x8;
lessThan(a: Uint16x8, b: Uint16x8): Bool16x8;
lessThanOrEqual(a: Uint16x8, b: Uint16x8): Bool16x8;
greaterThan(a: Uint16x8, b: Uint16x8): Bool16x8;
greaterThanOrEqual(a: Uint16x8, b: Uint16x8): Bool16x8;
and(a: Uint16x8, b: Uint16x8): Uint16x8;
or(a: Uint16x8, b: Uint16x8): Uint16x8;
xor(a: Uint16x8, b: Uint16x8): Uint16x8;
not(a: Uint16x8, b: Uint16x8): Uint16x8;
add(a: Uint16x8, b: Uint16x8): Uint16x8;
sub(a: Uint16x8, b: Uint16x8): Uint16x8;
mul(a: Uint16x8, b: Uint16x8): Uint16x8;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Uint16x8, bits: number): Uint16x8;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Uint16x8, bits: number): Uint16x8;
addSaturate(a: Uint16x8, b: Uint16x8): Uint16x8;
subSaturate(a: Uint16x8, b: Uint16x8): Uint16x8;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Uint16x8;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Uint16x8): Uint16x8;
/**
* Creates a new SIMD data type with a float conversion from a Int16x8.
* @param value An Int16x8 SIMD type to convert from.
*/
fromInt16x8(value: Int16x8): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Uint16x8;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint8x16.
* @param value A Uint8x16 SIMD type to convert from (bitwise).
*/
fromUint8x16Bits(value: Uint8x16): Uint16x8;
}
/**
* 128-bits divided into 16 lanes storing 8-bit unsigned integer values.
*/
interface Uint8x16 {
constructor: Uint8x16Constructor;
valueOf(): Uint8x16;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Uint8x16".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Uint8x16;
[Symbol.toPrimitive](hint: string): any;
}
interface Uint8x16Constructor {
/**
* SIMD.Uint8x16 constructor
* @param s0 A 8bit uint specifying the value of the lane.
* @param s1 A 8bit uint specifying the value of the lane.
* @param s2 A 8bit uint specifying the value of the lane.
* @param s3 A 8bit uint specifying the value of the lane.
* @param s4 A 8bit uint specifying the value of the lane.
* @param s5 A 8bit uint specifying the value of the lane.
* @param s6 A 8bit uint specifying the value of the lane.
* @param s7 A 8bit uint specifying the value of the lane.
* @param s8 A 8bit uint specifying the value of the lane.
* @param s9 A 8bit uint specifying the value of the lane.
* @param s10 A 8bit uint specifying the value of the lane.
* @param s11 A 8bit uint specifying the value of the lane.
* @param s12 A 8bit uint specifying the value of the lane.
* @param s13 A 8bit uint specifying the value of the lane.
* @param s14 A 8bit uint specifying the value of the lane.
* @param s15 A 8bit uint specifying the value of the lane.
* @return SIMD.Uint8x16 object
*/
(
s0?: number,
s1?: number,
s2?: number,
s3?: number,
s4?: number,
s5?: number,
s6?: number,
s7?: number,
s8?: number,
s9?: number,
s10?: number,
s11?: number,
s12?: number,
s13?: number,
s14?: number,
s15?: number
): Uint8x16;
prototype: Uint8x16;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Uint8x16, lane: number): number;
/**
* Returns a new instance with the lane values swizzled.
*/
swizzle(
a: Uint8x16,
l1: number,
l2: number,
l3: number,
l4: number,
l5: number,
l6: number,
l7: number,
l8: number,
l9: number,
l10: number,
l11: number,
l12: number,
l13: number,
l14: number,
l15: number,
l16: number
): Uint8x16;
/**
* Returns a new instance with the lane values shuffled.
*/
shuffle(
a: Uint8x16,
b: Uint8x16,
l1: number,
l2: number,
l3: number,
l4: number,
l5: number,
l6: number,
l7: number,
l8: number,
l9: number,
l10: number,
l11: number,
l12: number,
l13: number,
l14: number,
l15: number,
l16: number
): Uint8x16;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Uint8x16. Throws a TypeError otherwise.
*/
check(a: Uint8x16): Uint8x16;
/**
* Creates a new SIMD.Uint8x16 data type with all lanes set to a given value.
*/
splat(n: number): Uint8x16;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Uint8x16, lane: number, value: number): Uint8x16;
/**
* Returns a new instance with the lane values being a mix of the lanes depending on the selector mask.
* @param selector the selector mask.
* @param a If the selector mask lane is `true`, pick the corresponding lane value from here.
* @param b If the selector mask lane is `false`, pick the corresponding lane value from here.
*/
select(selector: Bool8x16, a: Uint8x16, b: Uint8x16): Uint8x16;
equal(a: Uint8x16, b: Uint8x16): Bool8x16;
notEqual(a: Uint8x16, b: Uint8x16): Bool8x16;
lessThan(a: Uint8x16, b: Uint8x16): Bool8x16;
lessThanOrEqual(a: Uint8x16, b: Uint8x16): Bool8x16;
greaterThan(a: Uint8x16, b: Uint8x16): Bool8x16;
greaterThanOrEqual(a: Uint8x16, b: Uint8x16): Bool8x16;
and(a: Uint8x16, b: Uint8x16): Uint8x16;
or(a: Uint8x16, b: Uint8x16): Uint8x16;
xor(a: Uint8x16, b: Uint8x16): Uint8x16;
not(a: Uint8x16, b: Uint8x16): Uint8x16;
add(a: Uint8x16, b: Uint8x16): Uint8x16;
sub(a: Uint8x16, b: Uint8x16): Uint8x16;
mul(a: Uint8x16, b: Uint8x16): Uint8x16;
/**
* Returns a new instance with the lane values shifted left by a given bit count (`a << bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted left by a given bit count (`a << bits`).
*/
shiftLeftByScalar(a: Uint8x16, bits: number): Uint8x16;
/**
* Returns a new instance with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
* @param a An instance of a SIMD type.
* @param bits Bit count to shift by.
* @return A new corresponding SIMD data type with the lane values shifted right by a given bit count (`a >> bits` or `a >>> bits`).
*/
shiftRightByScalar(a: Uint8x16, bits: number): Uint8x16;
addSaturate(a: Uint8x16, b: Uint8x16): Uint8x16;
subSaturate(a: Uint8x16, b: Uint8x16): Uint8x16;
/**
* Returns a new instance with all lane values loaded from a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start loading in the typed array.
*/
load(tarray: TypedArray, index: number): Uint8x16;
/**
* Store all values of a SIMD data type into a typed array.
* @param tarray An instance of a typed array.
* @param index A number for the index from where to start storing in the typed array.
* @param value An instance of a SIMD data type to store into the typed array.
* @return The value that has been stored (a SIMD data type).
*/
store(tarray: TypedArray, index: number, value: Uint8x16): Uint8x16;
/**
* Creates a new SIMD data type with a float conversion from a Int8x16.
* @param value An Int8x16 SIMD type to convert from.
*/
fromInt8x16(value: Int8x16): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Float32x4.
* @param value A Float32x4 SIMD type to convert from (bitwise).
*/
fromFloat32x4Bits(value: Float32x4): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int32x4.
* @param value A Int32x4 SIMD type to convert from (bitwise).
*/
fromInt32x4Bits(value: Int32x4): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int16x8.
* @param value A Int16x8 SIMD type to convert from (bitwise).
*/
fromInt16x8Bits(value: Int16x8): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Int8x16.
* @param value A Int8x16 SIMD type to convert from (bitwise).
*/
fromInt8x16Bits(value: Int8x16): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint32x4.
* @param value A Uint32x4 SIMD type to convert from (bitwise).
*/
fromUint32x4Bits(value: Uint32x4): Uint8x16;
/**
* Creates a new SIMD data type with a bit-wise copy from a Uint16x8.
* @param value A Uint16x8 SIMD type to convert from (bitwise).
*/
fromUint16x8Bits(value: Uint16x8): Uint8x16;
}
/**
* A SIMD type representing 4 boolean values, as an intermediate value in manipulating 128-bit vectors.
*/
interface Bool32x4 {
constructor: Bool32x4Constructor;
valueOf(): Bool32x4;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Bool32x4".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Bool32x4;
[Symbol.toPrimitive](hint: string): any;
}
interface Bool32x4Constructor {
/**
* SIMD.Bool32x4 constructor
* @param s0 A 32bit bool specifying the value of the lane.
* @param s1 A 32bit bool specifying the value of the lane.
* @param s2 A 32bit bool specifying the value of the lane.
* @param s3 A 32bit bool specifying the value of the lane.
* @return SIMD.Bool32x4 object
*/
(s0?: boolean, s1?: boolean, s2?: boolean, s3?: boolean): Bool32x4;
prototype: Bool32x4;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Bool32x4, lane: number): boolean;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Bool32x4. Throws a TypeError otherwise.
*/
check(a: Bool32x4): Bool32x4;
/**
* Creates a new SIMD.Bool32x4 data type with all lanes set to a given value.
*/
splat(n: boolean): Bool32x4;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Bool32x4, lane: number, value: boolean): Bool32x4;
/**
* If all lane values are `true`, return `true`.
*/
allTrue(a: Bool32x4): boolean;
/**
* If any lane values are `true`, return `true`.
*/
anyTrue(a: Bool32x4): boolean;
and(a: Bool32x4, b: Bool32x4): Bool32x4;
or(a: Bool32x4, b: Bool32x4): Bool32x4;
xor(a: Bool32x4, b: Bool32x4): Bool32x4;
not(a: Bool32x4, b: Bool32x4): Bool32x4;
}
/**
* A SIMD type representing 16 boolean values, as an intermediate value in manipulating 128-bit vectors
*/
interface Bool16x8 {
constructor: Bool16x8Constructor;
valueOf(): Bool16x8;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Bool16x8".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Bool16x8;
[Symbol.toPrimitive](hint: string): any;
}
interface Bool16x8Constructor {
/**
* SIMD.Bool16x8 constructor
* @param s0 A 16bit bool specifying the value of the lane.
* @param s1 A 16bit bool specifying the value of the lane.
* @param s2 A 16bit bool specifying the value of the lane.
* @param s3 A 16bit bool specifying the value of the lane.
* @param s4 A 16bit bool specifying the value of the lane.
* @param s5 A 16bit bool specifying the value of the lane.
* @param s6 A 16bit bool specifying the value of the lane.
* @param s7 A 16bit bool specifying the value of the lane.
* @return SIMD.Bool16x8 object
*/
(s0?: boolean, s1?: boolean, s2?: boolean, s3?: boolean, s4?: boolean, s5?: boolean, s6?: boolean, s7?: boolean): Bool16x8;
prototype: Bool16x8;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Bool16x8, lane: number): boolean;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Bool16x8. Throws a TypeError otherwise.
*/
check(a: Bool16x8): Bool16x8;
/**
* Creates a new SIMD.Bool16x8 data type with all lanes set to a given value.
*/
splat(n: boolean): Bool16x8;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Bool16x8, lane: number, value: boolean): Bool16x8;
/**
* If all lane values are `true`, return `true`.
*/
allTrue(a: Bool16x8): boolean;
/**
* If any lane values are `true`, return `true`.
*/
anyTrue(a: Bool16x8): boolean;
and(a: Bool16x8, b: Bool16x8): Bool16x8;
or(a: Bool16x8, b: Bool16x8): Bool16x8;
xor(a: Bool16x8, b: Bool16x8): Bool16x8;
not(a: Bool16x8, b: Bool16x8): Bool16x8;
}
/**
* A SIMD type representing 8 boolean values, as an intermediate value in manipulating 128-bit vectors
*/
interface Bool8x16 {
constructor: Bool8x16Constructor;
valueOf(): Bool8x16;
toLocaleString(): string;
toString(): string;
/**
* The initial value of the @@toStringTag property is the String value "SIMD.Bool8x16".
*/
[Symbol.toStringTag]: string;
[Symbol.toPrimitive](hint: "string"): string;
[Symbol.toPrimitive](hint: "number"): number;
[Symbol.toPrimitive](hint: "default"): Bool8x16;
[Symbol.toPrimitive](hint: string): any;
}
interface Bool8x16Constructor {
/**
* SIMD.Bool8x16 constructor
* @param s0 A 8bit bool specifying the value of the lane.
* @param s1 A 8bit bool specifying the value of the lane.
* @param s2 A 8bit bool specifying the value of the lane.
* @param s3 A 8bit bool specifying the value of the lane.
* @param s4 A 8bit bool specifying the value of the lane.
* @param s5 A 8bit bool specifying the value of the lane.
* @param s6 A 8bit bool specifying the value of the lane.
* @param s7 A 8bit bool specifying the value of the lane.
* @param s8 A 8bit bool specifying the value of the lane.
* @param s9 A 8bit bool specifying the value of the lane.
* @param s10 A 8bit bool specifying the value of the lane.
* @param s11 A 8bit bool specifying the value of the lane.
* @param s12 A 8bit bool specifying the value of the lane.
* @param s13 A 8bit bool specifying the value of the lane.
* @param s14 A 8bit bool specifying the value of the lane.
* @param s15 A 8bit bool specifying the value of the lane.
* @return SIMD.Bool8x16 object
*/
(
s0?: boolean, s1?: boolean,
s2?: boolean,
s3?: boolean,
s4?: boolean,
s5?: boolean,
s6?: boolean,
s7?: boolean,
s8?: boolean,
s9?: boolean,
s10?: boolean,
s11?: boolean,
s12?: boolean,
s13?: boolean,
s14?: boolean,
s15?: boolean
): Bool8x16;
prototype: Bool8x16;
/**
* Returns the value of the given lane.
* @param simd An instance of a corresponding SIMD type.
* @param lane An index number for which lane to extract.
* @return The value of the extracted lane.
*/
extractLane(simd: Bool8x16, lane: number): boolean;
/**
* Returns a new instance if the parameter is a valid SIMD data type and the same as Bool8x16. Throws a TypeError otherwise.
*/
check(a: Bool8x16): Bool8x16;
/**
* Creates a new SIMD.Bool8x16 data type with all lanes set to a given value.
*/
splat(n: boolean): Bool8x16;
/**
* Returns a new instance with the given lane value replaced.
* @param simd An instance of a corresponding SIMD type.
* @param value A new value to be used for the lane.
* @return A new SIMD data type with the given lane value replaced.
*/
replaceLane(simd: Bool8x16, lane: number, value: boolean): Bool8x16;
/**
* If all lane values are `true`, return `true`.
*/
allTrue(a: Bool8x16): boolean;
/**
* If any lane values are `true`, return `true`.
*/
anyTrue(a: Bool8x16): boolean;
and(a: Bool8x16, b: Bool8x16): Bool8x16;
or(a: Bool8x16, b: Bool8x16): Bool8x16;
xor(a: Bool8x16, b: Bool8x16): Bool8x16;
not(a: Bool8x16, b: Bool8x16): Bool8x16;
}
}
const Float32x4: I.Float32x4Constructor;
const Int32x4: I.Int32x4Constructor;
const Int16x8: I.Int16x8Constructor;
const Int8x16: I.Int8x16Constructor;
const Uint32x4: I.Uint32x4Constructor;
const Uint16x8: I.Uint16x8Constructor;
const Uint8x16: I.Uint8x16Constructor;
const Bool32x4: I.Bool32x4Constructor;
const Bool16x8: I.Bool16x8Constructor;
const Bool8x16: I.Bool8x16Constructor;
}
} | the_stack |
import RemoteStorage from './remotestorage';
import Authorize from './authorize';
import EventHandling from './eventhandling';
import UnauthorizedError from './unauthorized-error';
import config from './config';
import log from './log';
import {
applyMixins,
cleanPath,
getJSONFromLocalStorage,
getTextFromArrayBuffer,
isFolder,
localStorageAvailable,
shouldBeTreatedAsBinary
} from './util';
let hasLocalStorage;
const SETTINGS_KEY = 'remotestorage:wireclient';
const API_2012 = 1;
const API_00 = 2;
const API_01 = 3;
const API_02 = 4;
const API_HEAD = 5;
const STORAGE_APIS = {
'draft-dejong-remotestorage-00': API_00,
'draft-dejong-remotestorage-01': API_01,
'draft-dejong-remotestorage-02': API_02,
'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012
};
function readSettings () {
const settings = getJSONFromLocalStorage(SETTINGS_KEY) || {};
const { userAddress, href, storageApi, token, properties } = settings;
return { userAddress, href, storageApi, token, properties };
};
let isArrayBufferView;
if (typeof ((global || window as any).ArrayBufferView) === 'function') {
isArrayBufferView = function (object) {
return object && (object instanceof (global || window as any).ArrayBufferView);
};
} else {
const arrayBufferViews = [
Int8Array, Uint8Array, Int16Array, Uint16Array,
Int32Array, Uint32Array, Float32Array, Float64Array
];
isArrayBufferView = function (object): boolean {
for (let i = 0; i < 8; i++) {
if (object instanceof arrayBufferViews[i]) {
return true;
}
}
return false;
};
}
// TODO double check
interface WireClientSettings {
userAddress: string;
href: string;
storageApi: string;
token: string;
properties: unknown;
}
interface WireRequestResponse {
statusCode: number;
revision: string | undefined;
body?: any;
}
function addQuotes (str: string): string {
if (typeof (str) !== 'string') {
return str;
}
if (str === '*') {
return '*';
}
return '"' + str + '"';
}
function stripQuotes (str: string): string {
if (typeof (str) !== 'string') {
return str;
}
return str.replace(/^["']|["']$/g, '');
}
function determineCharset (mimeType: string): string {
let charset = 'UTF-8';
let charsetMatch;
if (mimeType) {
charsetMatch = mimeType.match(/charset=(.+)$/);
if (charsetMatch) {
charset = charsetMatch[1];
}
}
return charset;
}
function isFolderDescription (body: object): boolean {
return ((body['@context'] === 'http://remotestorage.io/spec/folder-description')
&& (typeof (body['items']) === 'object'));
}
function isSuccessStatus (status: number): boolean {
return [201, 204, 304].indexOf(status) >= 0;
}
function isErrorStatus (status: number): boolean {
return [401, 403, 404, 412].indexOf(status) >= 0;
}
function isForbiddenRequestMethod(method: string, uri: string): boolean {
if (method === 'PUT' || method === 'DELETE') {
return isFolder(uri);
} else {
return false;
}
}
class WireClient {
rs: RemoteStorage;
connected: boolean;
online: boolean;
userAddress: string;
/**
* Holds the bearer token of this WireClient, as obtained in the OAuth dance
*
* Example:
* (start code)
*
* remoteStorage.remote.token
* // -> 'DEADBEEF01=='
*/
token: string;
/**
* Holds the server's base URL, as obtained in the Webfinger discovery
*
* Example:
* (start code)
*
* remoteStorage.remote.href
* // -> 'https://storage.example.com/users/jblogg/'
*/
href: string;
/**
* Holds the spec version the server claims to be compatible with
*
* Example:
* (start code)
*
* remoteStorage.remote.storageApi
* // -> 'draft-dejong-remotestorage-01'
*/
storageApi: string;
// TODO implement TS validation for incoming type
supportsRevs: boolean;
_revisionCache: { [key: string]: any } = {};
properties: any;
constructor (rs: RemoteStorage) {
hasLocalStorage = localStorageAvailable();
this.rs = rs;
this.connected = false;
/**
* Event: connected
* Fired when the wireclient connect method realizes that it is in
* possession of a token and href
**/
this.addEvents(['connected', 'not-connected']);
if (hasLocalStorage) {
const settings = readSettings();
if (settings) {
setTimeout(() => {
this.configure(settings);
}, 0);
}
}
if (this.connected) {
setTimeout(this._emit.bind(this), 0, 'connected');
}
}
get storageType () {
if (this.storageApi) {
const spec = this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);
return spec ? spec[1] : '2012.04';
} else {
return undefined;
}
}
async _request (method: string, uri: string, token: string | false, headers: object, body: unknown, getEtag: boolean, fakeRevision?: string): Promise<WireRequestResponse> {
if (isForbiddenRequestMethod(method, uri)) {
return Promise.reject(`Don't use ${method} on directories!`);
}
let revision: string | undefined;
if (token !== Authorize.IMPLIED_FAKE_TOKEN) {
headers['Authorization'] = 'Bearer ' + token;
}
this.rs._emit('wire-busy', {
method: method,
isFolder: isFolder(uri)
});
return WireClient.request(method, uri, {
body: body,
headers: headers,
responseType: 'arraybuffer'
}).then((response: XMLHttpRequest): Promise<WireRequestResponse> => {
if (!this.online) {
this.online = true;
this.rs._emit('network-online');
}
this.rs._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: true
});
if (isErrorStatus(response.status)) {
log('[WireClient] Error response status', response.status);
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = undefined;
}
if (response.status === 401) {
this.rs._emit('error', new UnauthorizedError());
}
return Promise.resolve({statusCode: response.status, revision: revision});
} else if (isSuccessStatus(response.status) ||
(response.status === 200 && method !== 'GET')) {
revision = stripQuotes(response.getResponseHeader('ETag'));
log('[WireClient] Successful request', revision);
return Promise.resolve({statusCode: response.status, revision: revision});
} else {
const mimeType = response.getResponseHeader('Content-Type');
if (getEtag) {
revision = stripQuotes(response.getResponseHeader('ETag'));
} else {
revision = (response.status === 200) ? fakeRevision : undefined;
}
const charset = determineCharset(mimeType);
if (shouldBeTreatedAsBinary(response.response, mimeType)) {
log('[WireClient] Successful request with unknown or binary mime-type', revision);
return Promise.resolve({
statusCode: response.status,
body: response.response,
contentType: mimeType,
revision: revision
});
} else {
return getTextFromArrayBuffer(response.response, charset)
.then((textContent) => {
log('[WireClient] Successful request', revision);
return Promise.resolve({
statusCode: response.status,
body: textContent,
contentType: mimeType,
revision: revision
});
});
}
}
}, error => {
if (this.online) {
this.online = false;
this.rs._emit('network-offline');
}
this.rs._emit('wire-done', {
method: method,
isFolder: isFolder(uri),
success: false
});
return Promise.reject(error);
});
}
/**
* Sets the userAddress, href, storageApi, token, and properties of a
* remote store. Also sets connected and online to true and emits the
* 'connected' event, if both token and href are present.
*
* Parameters:
* settings - An object that may contain userAddress (string or null),
* href (string or null), storageApi (string or null), token (string
* or null), and/or properties (the JSON-parsed properties object
* from the user's WebFinger record, see section 10 of
* http://tools.ietf.org/html/draft-dejong-remotestorage-03
* or null).
* Fields that are not included (i.e. `undefined`), stay at
* their current value. To set a field, include that field
* with a `string` value. To reset a field, for instance when
* the user disconnected their storage, or you found that the
* token you have has expired, simply set that field to `null`.
*/
configure (settings: WireClientSettings): void {
if (typeof settings !== 'object') {
throw new Error('WireClient configure settings parameter should be an object');
}
if (typeof settings.userAddress !== 'undefined') {
this.userAddress = settings.userAddress;
}
if (typeof settings.href !== 'undefined') {
this.href = settings.href;
}
if (typeof settings.storageApi !== 'undefined') {
this.storageApi = settings.storageApi;
}
if (typeof settings.token !== 'undefined') {
this.token = settings.token;
}
if (typeof settings.properties !== 'undefined') {
this.properties = settings.properties;
}
if (typeof this.storageApi === 'string') {
const _storageApi = STORAGE_APIS[this.storageApi] || API_HEAD;
this.supportsRevs = _storageApi >= API_00;
}
if (this.href && this.token) {
this.connected = true;
this.online = true;
this._emit('connected');
} else {
this.connected = false;
}
if (hasLocalStorage) {
localStorage[SETTINGS_KEY] = JSON.stringify({
userAddress: this.userAddress,
href: this.href,
storageApi: this.storageApi,
token: this.token,
properties: this.properties
});
}
}
stopWaitingForToken (): void {
if (!this.connected) {
this._emit('not-connected');
}
}
get (path: string, options: { ifNoneMatch?: string } = {}): Promise<unknown> {
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
const headers = {};
if (this.supportsRevs) {
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
}
// commenting it out as this is doing nothing and jshint is complaining -les
// else if (options.ifNoneMatch) {
// let oldRev = this._revisionCache[path];
// }
return this._request('GET', this.href + cleanPath(path), this.token, headers,
undefined, this.supportsRevs, this._revisionCache[path])
.then((r) => {
if (!isFolder(path)) {
return Promise.resolve(r);
}
let itemsMap = {};
if (typeof (r.body) !== 'undefined') {
try {
r.body = JSON.parse(r.body);
} catch (e) {
return Promise.reject('Folder description at ' + this.href + cleanPath(path) + ' is not JSON');
}
}
if (r.statusCode === 200 && typeof (r.body) === 'object') {
// New folder listing received
if (Object.keys(r.body).length === 0) {
// Empty folder listing of any spec
r.statusCode = 404;
} else if (isFolderDescription(r.body)) {
// >= 02 spec
for (const item in r.body.items) {
this._revisionCache[path + item] = r.body.items[item].ETag;
}
itemsMap = r.body.items;
} else {
// < 02 spec
Object.keys(r.body).forEach((key) => {
this._revisionCache[path + key] = r.body[key];
itemsMap[key] = {'ETag': r.body[key]};
});
}
r.body = itemsMap;
return Promise.resolve(r);
} else {
return Promise.resolve(r);
}
});
}
put (path: string, body: unknown, contentType: string, options: { ifMatch?: string; ifNoneMatch?: string } = {}) {
if (!this.connected) {
return Promise.reject('not connected (path: ' + path + ')');
}
if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) {
contentType += '; charset=binary';
}
const headers = {'Content-Type': contentType};
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
if (options.ifNoneMatch) {
headers['If-None-Match'] = addQuotes(options.ifNoneMatch);
}
}
return this._request('PUT', this.href + cleanPath(path), this.token,
headers, body, this.supportsRevs);
}
delete (path: string, options: { ifMatch?: string } = {}) {
if (!this.connected) {
throw new Error('not connected (path: ' + path + ')');
}
if (!options) {
options = {};
}
const headers = {};
if (this.supportsRevs) {
if (options.ifMatch) {
headers['If-Match'] = addQuotes(options.ifMatch);
}
}
return this._request('DELETE', this.href + cleanPath(path), this.token,
headers,
undefined, this.supportsRevs);
}
// Shared isArrayBufferView used by WireClient and Dropbox
static isArrayBufferView = isArrayBufferView;
// TODO add proper definition for options
// Shared request function used by WireClient, GoogleDrive and Dropbox.
static async request (method: string, url: string, options: unknown): Promise<XMLHttpRequest | Response> {
if (typeof fetch === 'function') {
return WireClient._fetchRequest(method, url, options);
} else if (typeof XMLHttpRequest === 'function') {
return WireClient._xhrRequest(method, url, options);
} else {
log('[WireClient] You need to add a polyfill for fetch or XMLHttpRequest');
return Promise.reject('[WireClient] You need to add a polyfill for fetch or XMLHttpRequest');
}
}
/** options includes body, headers and responseType */
static _fetchRequest (method: string, url: string, options): Promise<Response> {
let syntheticXhr;
const responseHeaders = {};
let abortController;
if (typeof AbortController === 'function') {
abortController = new AbortController();
}
const networkPromise: Promise<Response> = fetch(url, {
method: method,
headers: options.headers,
body: options.body,
signal: abortController ? abortController.signal : undefined
}).then((response) => {
log('[WireClient fetch]', response);
response.headers.forEach((value: string, headerName: string) => {
responseHeaders[headerName.toUpperCase()] = value;
});
syntheticXhr = {
readyState: 4,
status: response.status,
statusText: response.statusText,
response: undefined,
getResponseHeader: (headerName: string): unknown => {
return responseHeaders[headerName.toUpperCase()] || null;
},
// responseText: 'foo',
responseType: options.responseType,
responseURL: url,
};
switch (options.responseType) {
case 'arraybuffer':
return response.arrayBuffer();
case 'blob':
return response.blob();
case 'json':
return response.json();
case undefined:
case '':
case 'text':
return response.text();
default: // document
throw new Error("responseType 'document' is not currently supported using fetch");
}
}).then((processedBody) => {
syntheticXhr.response = processedBody;
if (!options.responseType || options.responseType === 'text') {
syntheticXhr.responseText = processedBody;
}
return syntheticXhr;
});
const timeoutPromise: Promise<Response> = new Promise((resolve, reject) => {
setTimeout(() => {
reject('timeout');
if (abortController) {
abortController.abort();
}
}, config.requestTimeout);
});
return Promise.race([networkPromise, timeoutPromise]);
}
static _xhrRequest (method, url, options): Promise<XMLHttpRequest> {
return new Promise((resolve, reject) => {
log('[WireClient]', method, url);
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
reject('timeout');
}, config.requestTimeout);
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (options.responseType) {
xhr.responseType = options.responseType;
}
if (options.headers) {
for (const key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
}
xhr.onload = (): void => {
if (timedOut) {
return;
}
clearTimeout(timer);
resolve(xhr);
};
xhr.onerror = (error): void => {
if (timedOut) {
return;
}
clearTimeout(timer);
reject(error);
};
let body = options.body;
if (typeof (body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) {
body = new Uint8Array(body);
}
xhr.send(body);
});
}
static _rs_init (remoteStorage): void {
remoteStorage.remote = new WireClient(remoteStorage);
remoteStorage.remote.online = true;
}
static _rs_supported (): boolean {
return typeof fetch === 'function' || typeof XMLHttpRequest === 'function';
}
static _rs_cleanup (): void {
if (hasLocalStorage) {
delete localStorage[SETTINGS_KEY];
}
}
}
interface WireClient extends EventHandling {};
applyMixins(WireClient, [EventHandling]);
export = WireClient; | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import { IMapProviderContext, IViewerComponent, useViewerSideEffects } from '../components/map-providers/base';
import { CURSOR_DIGITIZE_POINT, CURSOR_DIGITIZE_LINE, CURSOR_DIGITIZE_LINESTRING, CURSOR_DIGITIZE_RECT, CURSOR_DIGITIZE_POLYGON, CURSOR_DIGITIZE_CIRCLE, CURSOR_GRABBING, CURSOR_GRAB, CURSOR_ZOOM_IN } from '../constants/assets';
import { MapLoadIndicator } from '../components/map-load-indicator';
import { ActiveMapTool, MapLoadIndicatorPositioning, GenericEvent, ReduxDispatch, ClientKind } from '../api/common';
import { useMapProviderContext, useReduxDispatch } from '../components/map-providers/context';
import { Toaster, Position } from '@blueprintjs/core';
import { isMapGuideProviderState } from '../components/map-providers/mapguide';
import { tr } from '../api/i18n';
import "ol/ol.css";
import { QueryMapFeaturesResponse } from '../api/contracts/query';
import { ISubscriberProps, Subscriber } from './subscriber';
import { useActiveMapClientSelectionSet, useConfiguredLoadIndicatorColor, useConfiguredLoadIndicatorPositioning, useCustomAppSettings, useViewerFlyouts, useViewerSelectCanDragPan } from "./hooks";
import { closeContextMenu, openContextMenu } from "../actions/flyout";
import { WEBLAYOUT_CONTEXTMENU } from "../constants";
interface ICoreMapViewerProps {
context: IMapProviderContext;
loadIndicatorPosition: MapLoadIndicatorPositioning;
loadIndicatorColor: string;
onContextMenu: (pos: [number, number]) => void;
onHideContextMenu: () => void;
onDispatch: ReduxDispatch;
backgroundColor?: string;
children?: React.ReactNode;
isContextMenuOpen: boolean;
selectCanDragPan: boolean;
}
interface ICoreMapViewerState {
shiftKey: boolean;
isMouseDown: boolean;
digitizingType: string | undefined;
loading: number;
loaded: number;
subscribers: ISubscriberProps[];
}
class CoreMapViewer extends React.Component<ICoreMapViewerProps, ICoreMapViewerState> implements IViewerComponent {
private mounted: boolean;
constructor(props: ICoreMapViewerProps) {
super(props);
this.mounted = false;
this.state = {
shiftKey: false,
isMouseDown: false,
digitizingType: undefined,
loaded: 0,
loading: 0,
subscribers: []
}
}
//#region IViewerComponent
selectCanDragPan = () => this.props.selectCanDragPan;
isContextMenuOpen = () => this.props.isContextMenuOpen;
setDigitizingType = (digitizingType: string | undefined) => this.setState({ digitizingType });
onBeginDigitization = (callback: (cancelled: boolean) => void) => { };
onHideContextMenu = () => this.props.onHideContextMenu?.();
onOpenTooltipLink = (url: string) => { };
onDispatch = (action: any) => this.props.onDispatch(action);
addImageLoading(): void {
const { loading } = this.state;
const newLoading = (loading || 0) + 1;
this.setState({ loading: newLoading });
this.props.context.incrementBusyWorker();
}
addSubscribers = (props: ISubscriberProps[]) => {
const subscribers = [...this.state.subscribers, ...props];
this.setState({ subscribers });
return props.map(p => p.name);
}
removeSubscribers = (names: string[]) => {
const { subscribers } = this.state;
const ol = subscribers.length;
const ns = subscribers.filter(s => names.indexOf(s.name) < 0);
this.setState({ subscribers });
return ns.length < ol;
}
getSubscribers(): string[] {
return this.state.subscribers.map(s => s.name);
}
addImageLoaded(): void {
const { loaded, loading } = this.state;
const newLoadedCount = (loaded || 0) + 1;
if (loading === newLoadedCount) {
this.setState({ loaded: 0, loading: 0 });
} else {
this.setState({ loaded: newLoadedCount });
}
this.props.context.decrementBusyWorker();
}
//#endregion
private onContextMenu = (e: React.MouseEvent<HTMLDivElement>) => {
if (!this.mounted)
return;
if (this.props.context.isMouseOverTooltip()) {
return;
}
e.preventDefault();
//console.log(`Open context menu at (${e.clientX}, ${e.clientY})`);
this.props.onContextMenu?.([e.clientX, e.clientY]);
}
private onKeyDown = (e: GenericEvent) => {
if (!this.mounted)
return;
this.props.context.onKeyDown(e);
this.setState({ shiftKey: e.shiftKey });
}
private onKeyUp = (e: GenericEvent) => {
if (!this.mounted)
return;
this.setState({ shiftKey: e.shiftKey });
}
private onMouseDown = (e: GenericEvent) => {
if (!this.mounted)
return;
if (!this.state.isMouseDown) {
this.setState({
isMouseDown: true
});
}
}
private onMouseUp = (e: GenericEvent) => {
if (!this.mounted)
return;
if (this.state.isMouseDown) {
this.setState({
isMouseDown: false
});
}
}
componentDidMount() {
document.addEventListener("keydown", this.onKeyDown);
document.addEventListener("keyup", this.onKeyUp);
const mapNode: any = ReactDOM.findDOMNode(this);
this.props.context.attachToComponent(mapNode, this);
this.mounted = true;
}
componentWillUnmount() {
this.props.context.detachFromComponent();
this.mounted = false;
}
render(): JSX.Element {
const { context, backgroundColor } = this.props;
const { isMouseDown } = this.state;
const tool = context.getActiveTool();
const style: React.CSSProperties = {
width: "100%",
height: "100%"
};
if (context.isDigitizing()) {
const dtype = this.state.digitizingType;
switch (dtype) {
case "Point":
style.cursor = `url(${CURSOR_DIGITIZE_POINT}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
case "Line":
style.cursor = `url(${CURSOR_DIGITIZE_LINE}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
case "LineString":
style.cursor = `url(${CURSOR_DIGITIZE_LINESTRING}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
case "Rectangle":
style.cursor = `url(${CURSOR_DIGITIZE_RECT}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
case "Polygon":
style.cursor = `url(${CURSOR_DIGITIZE_POLYGON}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
case "Circle":
style.cursor = `url(${CURSOR_DIGITIZE_CIRCLE}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
}
} else {
switch (tool) {
case ActiveMapTool.Pan:
if (isMouseDown) {
style.cursor = `url(${CURSOR_GRABBING}), auto`;
//console.log(`cursor: ${style.cursor}`);
} else {
style.cursor = `url(${CURSOR_GRAB}), auto`;
//console.log(`cursor: ${style.cursor}`);
}
break;
case ActiveMapTool.Zoom:
style.cursor = `url(${CURSOR_ZOOM_IN}), auto`;
//console.log(`cursor: ${style.cursor}`);
break;
}
}
if (backgroundColor) {
style.backgroundColor = backgroundColor;
//style.backgroundColor = `#${map.BackgroundColor.substring(2)}`;
}
const { loading, loaded, subscribers } = this.state;
return <div className="map-viewer-component" style={style} onContextMenu={this.onContextMenu} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp}>
<MapLoadIndicator loaded={loaded || 0} loading={loading || 0} position={this.props.loadIndicatorPosition} color={this.props.loadIndicatorColor} />
{subscribers.map((s, i) => <Subscriber key={`subscriber-${i}-${s.name}`} {...s} />)}
{this.props.children}
</div>;
}
}
export const MapViewer = ({ children }: { children?: React.ReactNode }) => {
const context = useMapProviderContext();
const toasterRef = React.useRef<Toaster>(null);
const loadIndicatorPositioning = useConfiguredLoadIndicatorPositioning();
const loadIndicatorColor = useConfiguredLoadIndicatorColor();
const dispatch = useReduxDispatch();
const hookFunc = context.getHookFunction();
const clientSelection = useActiveMapClientSelectionSet();
const appSettings = useCustomAppSettings();
const nextState = hookFunc();
const {
mapName,
layers,
initialExternalLayers,
bgColor,
locale
} = nextState;
const flyouts = useViewerFlyouts();
React.useEffect(() => {
if (!clientSelection) {
context.getSelectedFeatures()?.clear();
}
}, [clientSelection]);
const bContextMenuOpen = (flyouts[WEBLAYOUT_CONTEXTMENU]?.open == true);
const bSelectCanDragPan = useViewerSelectCanDragPan();
const showContextMenuAction = (pos: [number, number]) => dispatch(openContextMenu({ x: pos[0], y: pos[1] }));
const hideContextMenuAction = () => dispatch(closeContextMenu());
const onContextMenu = (pos: [number, number]) => showContextMenuAction?.(pos);
//HACK: Still have some MG-specific state we're needing to check for here. Minor abstraction leakage.
let agentUri: string | undefined;
let agentKind: ClientKind | undefined;
let selection: QueryMapFeaturesResponse | null = null;
if (isMapGuideProviderState(nextState)) {
agentUri = nextState.agentUri;
agentKind = nextState.agentKind;
selection = nextState.selection;
}
context.setToasterRef(toasterRef);
context.setProviderState(nextState);
useViewerSideEffects(context, appSettings ?? {}, nextState.isReady, mapName, layers, initialExternalLayers, agentUri, agentKind, selection);
if (nextState.isReady) {
return <>
{/* HACK: usePortal=false to workaround what I think is: https://github.com/palantir/blueprint/issues/3248 */}
<Toaster usePortal={false} position={Position.TOP} ref={toasterRef} />
<CoreMapViewer context={context}
onDispatch={dispatch}
backgroundColor={bgColor}
onContextMenu={onContextMenu}
onHideContextMenu={hideContextMenuAction}
isContextMenuOpen={bContextMenuOpen}
selectCanDragPan={bSelectCanDragPan}
loadIndicatorPosition={loadIndicatorPositioning}
loadIndicatorColor={loadIndicatorColor}>
{children}
</CoreMapViewer>
</>;
} else {
return <div>{tr("LOADING_MSG", locale)}</div>;
}
} | the_stack |
import * as React from "react";
import Combokeys from "combokeys";
import { BaseContainer } from "../../../BaseContainer";
import { SubscriptionListState } from "../../Subscription/SubscriptionList/SubscriptionListStore";
import { createShowSubscriptionContentsUseCase } from "../../../../../use-case/subscription/ShowSubscriptionContentsUseCase";
import debounce from "lodash.debounce";
import { SubscriptionContentsState } from "../../Subscription/SubscriptionContents/SubscriptionContentsStore";
import { ScrollToNextContentUseCase } from "../../Subscription/SubscriptionContents/use-case/ScrollToNextContentUseCase";
import { ScrollToPrevContentUseCase } from "../../Subscription/SubscriptionContents/use-case/ScrollToPrevContentUseCase";
import { createMarkAsReadToServerUseCase } from "../../../../../use-case/subscription/MarkAsReadToServerUseCase";
import { createOpenSubscriptionContentInNewTabUseCase } from "../../../../../use-case/subscription/OpenSubscriptionContentInNewTabUseCase";
import { createUpdateHeaderMessageUseCase } from "../../../../../use-case/app/UpdateHeaderMessageUseCase";
import { SubscriptionIdentifier } from "../../../../../domain/Subscriptions/Subscription";
import {
TurnOffContentsFilterUseCase,
TurnOnContentsFilterUseCase
} from "../../Subscription/SubscriptionContents/use-case/ToggleFilterContents";
import { createFetchMoreSubscriptContentsUseCase } from "../../../../../use-case/subscription/FetchMoreSubscriptContentsUseCase";
import { ToggleAllListGroupUseCase } from "../../Subscription/SubscriptionList/use-case/ToggleAllListGroupUseCase";
import { createReleaseFocusSubscriptionUseCase } from "../../../../../use-case/subscription/ReleaseFocusSubscriptionUseCase";
const MapSigns = require("react-icons/lib/fa/map-signs");
const DEBOUNCE_TIME = 32;
const IGNORE_NODE_NAME_PATTERN = /webview/i;
const isIgnoreNode = (event: Event): boolean => {
const target = event.target as HTMLElement;
if (!target) {
return false;
}
if (!target.nodeName) {
return false;
}
return IGNORE_NODE_NAME_PATTERN.test(target.nodeName);
};
/**
* Scroll by screen size ratio
* @param {HTMLElement} target
* @param {number} ratio
* @param {"up" | "down"} direction
*/
const scrollByScrollSize = (target: HTMLElement, ratio: number, direction: "up" | "down") => {
const directionOperator = direction === "down" ? 1 : -1;
ratio = ratio || 1;
target.scrollBy(0, (window.innerHeight / 2) * directionOperator * ratio);
};
export interface ShortcutKeyContainerProps {
subscriptionContents: SubscriptionContentsState;
subscriptionList: SubscriptionListState;
}
export class ShortcutKeyContainer extends BaseContainer<ShortcutKeyContainerProps, {}> {
combokeys: any;
triggerKey(keys: string, action?: string): void {
if (this.combokeys) {
this.combokeys.trigger(keys, action);
}
}
registerKey(key: string, handler: (event?: Event) => void): void {
if (this.combokeys) {
this.combokeys.bind(key, handler);
}
}
/**
* Default keyMap Object by
*/
defaultActions = (() => {
const loadNext = async (currentSubscriptionId?: SubscriptionIdentifier) => {
if (!currentSubscriptionId) {
const firstItem = this.props.subscriptionList.getFirstItem();
if (!firstItem) {
return console.info("Not found first item");
}
await this.useCase(createShowSubscriptionContentsUseCase()).execute(firstItem.props.id);
return;
}
const nextItem = this.props.subscriptionList.getNextItem(currentSubscriptionId);
if (!nextItem) {
return console.info("Not found next item");
}
this.useCase(createShowSubscriptionContentsUseCase())
.execute(nextItem.props.id)
.catch((error) => {
return this.useCase(createUpdateHeaderMessageUseCase())
.execute(`Can't load... Skip ${nextItem.title}.`)
.then(() => {
return loadNext(nextItem.props.id);
});
});
};
let actionMap = {
"move-next-subscription-feed": debounce(async (_event: Event) => {
const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
await loadNext(currentSubscriptionId);
}, DEBOUNCE_TIME),
"move-prev-subscription-feed": debounce(async (_event: Event) => {
const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
if (!currentSubscriptionId) {
return;
}
const nextItem = this.props.subscriptionList.getPrevItem(currentSubscriptionId);
if (!nextItem) {
return console.info("Not found next item");
}
await this.useCase(createShowSubscriptionContentsUseCase()).execute(nextItem.props.id);
}, DEBOUNCE_TIME),
"move-next-content-item": (_event: Event) => {
const body = document.querySelector(".SubscriptionContentsContainer");
if (!body) {
return;
}
if (body.scrollTop === 0) {
const firstContent = this.props.subscriptionContents.getFirstContent();
if (firstContent) {
return this.useCase(new ScrollToNextContentUseCase()).execute(firstContent.id);
}
}
const currentContent = this.props.subscriptionContents.focusContentId;
const nextContent = this.props.subscriptionContents.getNextContent();
if (currentContent && !nextContent) {
// last item and next
return this.useCase(createUpdateHeaderMessageUseCase()).execute(
<span>
<MapSigns /> End of contents
</span>
);
}
if (!nextContent) {
return;
}
return this.useCase(new ScrollToNextContentUseCase()).execute(nextContent.id);
},
"move-prev-content-item": (_event: Event) => {
const prevContent = this.props.subscriptionContents.getPrevContent();
if (!prevContent) {
return;
}
this.useCase(new ScrollToPrevContentUseCase()).execute(prevContent.id);
},
"scroll-down-content": (event: Event) => {
event.preventDefault();
// TODO: make explicitly
const contentContainer = document.querySelector(".SubscriptionContentsContainer") as HTMLElement;
if (contentContainer) {
scrollByScrollSize(contentContainer, 0.3, "down");
}
},
"scroll-up-content": (event: Event) => {
event.preventDefault();
// TODO: make explicitly
const contentContainer = document.querySelector(".SubscriptionContentsContainer") as HTMLElement;
if (contentContainer) {
scrollByScrollSize(contentContainer, 0.3, "up");
}
},
"make-subscription-read": (event: Event) => {
event.preventDefault();
const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
if (currentSubscriptionId) {
this.useCase(createMarkAsReadToServerUseCase()).execute(currentSubscriptionId);
}
},
"open-current-content-url": (event: Event) => {
event.preventDefault();
const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
const focusContentId = this.props.subscriptionContents.focusContentId;
if (!currentSubscriptionId || !focusContentId) {
return;
}
this.useCase(createOpenSubscriptionContentInNewTabUseCase()).execute(
currentSubscriptionId,
focusContentId
);
},
"toggle-content-filter": (_event: Event) => {
if (this.props.subscriptionContents.enableContentFilter) {
this.useCase(new TurnOffContentsFilterUseCase()).execute();
} else {
this.useCase(new TurnOnContentsFilterUseCase()).execute();
}
},
"toggle-subscription-feed-list": (_event: Event) => {
this.useCase(new ToggleAllListGroupUseCase()).execute();
},
"load-more-past-contents": async (_event: Event) => {
const subscription = this.props.subscriptionContents.subscription;
if (!subscription) {
return;
}
const beforeFocusContendId = this.props.subscriptionContents.focusContentId;
// disable content filter
this.useCase(new TurnOffContentsFilterUseCase()).execute();
this.useCase(createUpdateHeaderMessageUseCase()).execute("Load more past contents");
// fetch more contents
await this.useCase(createFetchMoreSubscriptContentsUseCase()).execute(subscription.props.id);
// move next content if the user was not moved
if (
beforeFocusContendId &&
beforeFocusContendId.equals(this.props.subscriptionContents.focusContentId)
) {
actionMap["move-next-content-item"](_event);
}
},
"skip-and-move-next-subscription-feed": async (_event: Event) => {
const currentSubscriptionId = this.props.subscriptionList.currentSubscriptionId;
if (!currentSubscriptionId) {
return;
}
await this.useCase(createUpdateHeaderMessageUseCase()).execute("Skip current subscription");
await this.useCase(createReleaseFocusSubscriptionUseCase()).execute();
await loadNext(currentSubscriptionId);
}
};
return actionMap;
})();
componentDidMount() {
this.combokeys = new Combokeys(document.documentElement || document.body);
const actionMap = this.defaultActions;
const keyMap: { [index: string]: keyof typeof actionMap } = {
j: "move-next-content-item",
"shift+j": "load-more-past-contents",
t: "toggle-content-filter",
k: "move-prev-content-item",
a: "move-prev-subscription-feed",
s: "move-next-subscription-feed",
m: "make-subscription-read",
v: "open-current-content-url",
z: "toggle-subscription-feed-list",
space: "scroll-down-content",
"shift+space": "scroll-up-content",
"shift+s": "skip-and-move-next-subscription-feed"
};
Object.keys(keyMap).forEach((key) => {
this.combokeys.bind(key, (event: Event) => {
if (isIgnoreNode(event)) {
return;
}
actionMap[keyMap[key]](event);
});
});
}
componentWillUnmount() {
this.combokeys.detach();
}
render() {
return null;
}
} | the_stack |
import { TransformedVolume } from './../volume_intersection';
import { translateMat, nodeTransformToMat4, EndpointAddr, EndpointType, endpointAddrsMatch, endpointAddrToString, InterfaceLockResult, InitialInterfaceLock, EVolumeContext } from '@aardvarkxr/aardvark-shared';
import { mat4, vec3, vec4 } from '@tlaukkan/tsm';
import { CInterfaceProcessor, InterfaceProcessorCallbacks, InterfaceEntity } from './../interface_processor';
import { makeSphere, makeInfinite, makeEmpty } from '../volume_test_utils';
import 'common/testutils';
beforeEach( async() =>
{
} );
afterEach( () =>
{
} );
enum CallType
{
Start,
End,
TransformUpdated,
Event,
}
interface TestCall
{
type: CallType;
transmitter: EndpointAddr;
receiver: EndpointAddr;
iface: string;
destinationFromPeer?: mat4;
intersectionPoint?: vec3;
event?: object;
}
class TestCallbacks implements InterfaceProcessorCallbacks
{
public calls: TestCall[] = [];
interfaceStarted( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string )
{
this.calls.push(
{
type: CallType.Start,
transmitter,
receiver,
iface
} );
}
interfaceEnded( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string ):void
{
this.calls.push(
{
type: CallType.End,
transmitter,
receiver,
iface
} );
}
interfaceTransformUpdated( destination: EndpointAddr, peer: EndpointAddr, iface: string,
destFromPeer: [ mat4, null | vec3 ] ): void
{
const [ destinationFromPeer, intersectionPoint ] = destFromPeer;
this.calls.push(
{
type: CallType.TransformUpdated,
transmitter: destination,
receiver: peer,
iface,
destinationFromPeer,
intersectionPoint,
} );
}
interfaceEvent( destination: EndpointAddr, peer: EndpointAddr, iface: string, event: object ): void
{
this.calls.push(
{
type: CallType.Event,
transmitter: destination,
receiver: peer,
iface,
event,
} );
}
}
let nextId = 1;
class CTestEntity implements InterfaceEntity
{
public epa: EndpointAddr = { type: EndpointType.Node, endpointId: nextId++, nodeId: nextId++ };
public transmits: string[] = [];
public receives: string[] = [];
public originPath: string = "/user/hand/right";
private _universeFromEntity: mat4 = mat4.identity;
public wantsTransforms = false;
public priority = 0;
public volumes: TransformedVolume[] = [];
public initialLocks: InitialInterfaceLock[] = [];
public addSphere( radius: number, position?: vec3, context?: EVolumeContext )
{
this.volumes.push( makeSphere( radius, position, undefined, context ) );
}
public addInfinite( )
{
this.volumes.push( makeInfinite() );
}
public addEmpty( )
{
this.volumes.push( makeEmpty() );
}
public set universeFromEntity( universeFromEntity: mat4 )
{
this._universeFromEntity = universeFromEntity;
for( let volume of this.volumes )
{
volume.universeFromVolume = mat4.product( universeFromEntity, nodeTransformToMat4( volume.nodeFromVolume ), new mat4() );
}
}
public get universeFromEntity()
{
return this._universeFromEntity;
}
}
describe( "interface processor", () =>
{
it( "empty list", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
ip.processFrame([]);
expect( cb.calls.length ).toBe(0);
ip.processFrame([]);
expect( cb.calls.length ).toBe(0);
} );
it( "self intersect", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let e1 = new CTestEntity();
e1.addSphere( 100 );
e1.transmits.push( "test@1" );
e1.receives.push( "test@1" );
// we still don't expect any intersections
// because an entity can't interface with
// itself
ip.processFrame([e1]);
expect( cb.calls.length ).toBe(0);
ip.processFrame([e1]);
expect( cb.calls.length ).toBe(0);
} );
it( "same hand intersect", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let e1 = new CTestEntity();
e1.addSphere( 100 );
e1.transmits.push( "test@1" );
let e2 = new CTestEntity();
e2.addSphere( 100 );
e2.receives.push( "test@1" );
// we still don't expect any intersections
// because an entity can't interface with
// anything else on the same hand
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(0);
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(0);
} );
it( "simple intersect", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let e1 = new CTestEntity();
e1.addSphere( 1 );
e1.transmits.push( "test@1" );
let e2 = new CTestEntity();
e2.addSphere( 1 );
e2.originPath = "/space/stage";
e2.receives.push( "test@1" );
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
// no repeated start
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
// e2 went away, so end
ip.processFrame([ e1 ]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
// e2 came back so start again
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
// e2 lost interface, so go away again
e2.receives = [];
ip.processFrame([ e1, e2 ]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
// e2's interface came back so start again
e2.receives.push("test@1");
ip.processFrame([e1, e2]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
// e1 lost interface, so go away again
e1.transmits = [];
ip.processFrame([ e1, e2 ]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: e1.epa,
receiver: e2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "two transmits one receive", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let t2 = new CTestEntity();
t2.addSphere( 1 );
t2.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// t2 arrived so start again
ip.processFrame([t1, r1, t2]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t2.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// r1 went away, so lose both
ip.processFrame([ t1, t2 ]);
expect( cb.calls ).toHaveLength( 2 );
expect( cb.calls ).toContainEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
expect( cb.calls ).toContainEqual(
{
type: CallType.End,
transmitter: t2.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "no intersect", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1, new vec3([ 10, 0, 0 ]) );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(0);
} );
it( "highest priority", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
ip.processFrame([r1, r2, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
} );
it( "love the one you're with", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// t1 should not switch interfaces to
// r2 because it's the same priority.
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
} );
it( "new shiny", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// t1 should switch interfaces to
// r2 because it's higher priority.
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "updating transforms", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 10 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
cb.calls = [];
t1.wantsTransforms = true;
t1.universeFromEntity = translateMat( new vec3( [ 0, 1, 0 ] ) );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toMatchObject(
{
type: CallType.TransformUpdated,
transmitter: t1.epa,// really destination
receiver: r1.epa, // really peer
iface: "test@1",
});
expect( cb.calls[0].destinationFromPeer ).toHavePosition( new vec3( [ 0, -1, 0 ]));
expect( cb.calls[0].intersectionPoint ).toBeVec3( new vec3( [ 0, 0, 0 ]));
cb.calls = [];
t1.universeFromEntity = translateMat( new vec3( [ 0, 2, 0 ] ) );
r1.wantsTransforms = true;
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toMatchObject(
{
type: CallType.TransformUpdated,
transmitter: t1.epa,// really destination
receiver: r1.epa, // really peer
iface: "test@1",
});
expect( cb.calls[0].destinationFromPeer ).toHavePosition( new vec3( [ 0, -2, 0 ]));
expect( cb.calls[0].intersectionPoint ).toBeVec3( new vec3( [ 0, -1, 0 ]));
expect( cb.calls[1] ).toMatchObject(
{
type: CallType.TransformUpdated,
transmitter: r1.epa,// really destination
receiver: t1.epa, // really peer
iface: "test@1",
});
expect( cb.calls[1].destinationFromPeer ).toHavePosition( new vec3( [ 0, 2, 0 ]));
expect( cb.calls[1].intersectionPoint ).toBeVec3( new vec3( [ 0, 0, 0 ]));
cb.calls = [];
r1.universeFromEntity = translateMat( new vec3( [ 0, 1, 0 ] ) );
t1.wantsTransforms = false;
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toMatchObject(
{
type: CallType.TransformUpdated,
transmitter: r1.epa,// really destination
receiver: t1.epa, // really peer
iface: "test@1",
});
expect( cb.calls[0].destinationFromPeer ).toHavePosition( new vec3( [ 0, 1, 0 ]));
cb.calls = [];
} );
it( "hysteresis", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 0.001 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 0.1, undefined, EVolumeContext.StartOnly );
r1.addSphere( 1, undefined, EVolumeContext.ContinueOnly );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
// start out beyond the range of the receiver's sphere
t1.universeFromEntity = translateMat( new vec3( [ 0, 1, 0 ] ) );
ip.processFrame( [ r1, t1 ] );
expect( cb.calls.length ).toBe( 0 );
cb.calls = [];
// move into range
t1.universeFromEntity = translateMat( new vec3( [ 0, 0, 0 ] ) );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// Move back out a bit so we're outside the "start" sphere but inside the
// "continue" sphere
t1.universeFromEntity = translateMat( new vec3( [ 0, 0.8, 0 ] ) );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe( 0 );
cb.calls = [];
// now move out of the continue sphere
t1.universeFromEntity = translateMat( new vec3( [ 0, 1.5, 0 ] ) );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toMatchObject(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
// Just for fun, move back into the continue sphere to make sure
// the interface doesn't start again
t1.universeFromEntity = translateMat( new vec3( [ 0, 0.8, 0 ] ) );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe( 0 );
cb.calls = [];
} );
it( "new shiny but locked", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.lockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.lockInterface(t1.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.lockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
expect( ip.lockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.AlreadyLocked );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
expect( ip.unlockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.unlockInterface(t1.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.NotLocked );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "lost receiver but locked", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.receives.push( "test@1" );
ip.processFrame([r1, r2, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.lockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
// End will be sent, but the transmitter won't match with r2 because it's still locked
ip.processFrame([r2, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
// End will be sent, but the transmitter won't match with r2 because it's still locked
ip.processFrame([r2, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "new shiny but initially locked", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let r1 = new CTestEntity();
r1.addEmpty(); // nothing will pick this without an initial lock
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
t1.initialLocks.push(
{
receiver: r1.epa,
iface: "test@1",
}
)
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.lockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.lockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.AlreadyLocked );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
expect( ip.unlockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.unlockInterface(t1.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.NotLocked );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "initial lock but no matching interface", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let r1 = new CTestEntity();
r1.addEmpty(); // nothing will pick this without an initial lock
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
let r3 = new CTestEntity();
r3.addSphere( 1 );
r3.originPath = "/space/stage";
r3.priority = 100;
r3.receives.push( "fred@1" );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "fred@1" );
t1.transmits.push( "test@1" );
t1.initialLocks.push(
{
receiver: r1.epa,
iface: "fred@1",
}
)
ip.processFrame([r1, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "fred@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "fred@1",
});
cb.calls = [];
expect( ip.lockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.lockInterface(t1.epa, r1.epa, "fred@1") ).toBe( InterfaceLockResult.InterfaceNotFound );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r3, t1]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
expect( ip.unlockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.unlockInterface(t1.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.unlockInterface(t1.epa, r1.epa, "fred@1") ).toBe( InterfaceLockResult.Success );
expect( ip.unlockInterface(t1.epa, r1.epa, "fred@1") ).toBe( InterfaceLockResult.InterfaceNotFound );
// t1 should switch interfaces to
// r2 because it's no longer locked
// There's no end with r1 here because we already sent it
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "initial lock with missing receiver", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let r1 = new CTestEntity();
r1.addEmpty(); // nothing will pick this without an initial lock
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
t1.initialLocks.push(
{
receiver: r1.epa,
iface: "test@1",
}
)
ip.processFrame([r2, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.lockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.lockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.InterfaceNotFound );
// t1 should not switch interfaces to
// r2 because it's locked
ip.processFrame([r2, t1]);
expect( cb.calls.length ).toBe(0);
cb.calls = [];
expect( ip.unlockInterface(r2.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.unlockInterface(t1.epa, r1.epa, "blargh@34") ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.InterfaceNotFound );
// t1 should not switch interfaces to
// r2 because it's no longer locked
// There's no end with r1 here because we already sent it
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
} );
it( "events", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.receives.push( "test@1" );
ip.processFrame([r1, r2, t1]);
expect( cb.calls.length ).toBe(1);
cb.calls = [];
ip.interfaceEvent(t1.epa, r1.epa, "test@1", {msg: "Hello"} );
ip.interfaceEvent(t1.epa, r1.epa, "bargle@5", {msg: "failed"} );
ip.interfaceEvent(t1.epa, r2.epa, "test@1", {msg: "failed"} );
// End will be sent, but the transmitter won't match with r2 because it's still locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Event,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
event: { msg: "Hello" },
});
cb.calls = [];
ip.interfaceEvent(r1.epa, t1.epa, "test@1", {msg: "Goodbye"} );
ip.interfaceEvent(r1.epa, t1.epa, "bargle@5", {msg: "failed"} );
ip.interfaceEvent(r2.epa, t1.epa, "test@1", {msg: "failed"} );
// End will be sent, but the transmitter won't match with r2 because it's still locked
ip.processFrame([r2, r1, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Event,
transmitter: r1.epa,
receiver: t1.epa,
iface: "test@1",
event: { msg: "Goodbye" },
});
cb.calls = [];
} );
it( "relocking", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "test@1" );
let t2 = new CTestEntity();
t2.addSphere( 1 );
t2.transmits.push( "test@1" );
let r1 = new CTestEntity();
r1.addSphere( 1 );
r1.originPath = "/space/stage";
r1.receives.push( "test@1" );
let r2 = new CTestEntity();
r2.addSphere( 1 );
r2.originPath = "/space/stage";
r2.priority = 100;
r2.receives.push( "test@1" );
let r3 = new CTestEntity();
r3.addSphere( 1 );
r3.originPath = "/space/stage";
r3.priority = 100;
r3.receives.push( "test@1" );
ip.processFrame([r1, r2, t1]);
expect( cb.calls.length ).toBe(1);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.relockInterface(t1.epa, r2.epa, r1.epa, "test@1" ) ).toBe( InterfaceLockResult.NotLocked );
expect( ip.lockInterface( t1.epa, r2.epa, "test@1" ) ).toBe( InterfaceLockResult.Success );
expect( ip.relockInterface(t1.epa, r2.epa, r1.epa, "test@1" ) ).toBe( InterfaceLockResult.Success );
expect( ip.relockInterface(t2.epa, r2.epa, r1.epa, "test@1" ) ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.relockInterface(t1.epa, r1.epa, r2.epa, "fred@1" ) ).toBe( InterfaceLockResult.InterfaceNameMismatch );
expect( ip.relockInterface(t1.epa, r1.epa, r3.epa, "test@1" ) ).toBe( InterfaceLockResult.NewReceiverNotFound );
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.End,
transmitter: t1.epa,
receiver: r2.epa,
iface: "test@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: r1.epa,
iface: "test@1",
});
cb.calls = [];
expect( ip.unlockInterface(t1.epa, r2.epa, "test@1") ).toBe( InterfaceLockResult.InterfaceNotFound );
expect( ip.unlockInterface(t1.epa, r1.epa, "test@1") ).toBe( InterfaceLockResult.Success );
} );
it( "two_receivers_for_transmitter", async () =>
{
let cb = new TestCallbacks();
let ip = new CInterfaceProcessor( cb );
let t1 = new CTestEntity();
t1.addSphere( 1 );
t1.transmits.push( "testA@1" );
t1.transmits.push( "testB@1" );
let rA = new CTestEntity();
rA.addSphere( 1 );
rA.originPath = "/space/stage";
rA.receives.push( "testA@1" );
let rB = new CTestEntity();
rB.addSphere( 1 );
rB.originPath = "/space/stage";
rB.priority = 100;
rB.receives.push( "testB@1" );
ip.processFrame([rA, rB, t1]);
expect( cb.calls.length ).toBe(2);
expect( cb.calls[0] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: rA.epa,
iface: "testA@1",
});
expect( cb.calls[1] ).toEqual(
{
type: CallType.Start,
transmitter: t1.epa,
receiver: rB.epa,
iface: "testB@1",
});
cb.calls = [];
let lockRes = ip.lockInterface( t1.epa, rB.epa, "testB@1" );
expect( lockRes ).toBe( InterfaceLockResult.Success );
} );} ); | the_stack |
import React from 'react'
import { registerComponent, Components } from '../../../lib/vulcan-lib';
import { useUpdate } from '../../../lib/crud/withUpdate';
import { useNamedMutation } from '../../../lib/crud/withMutation';
import { userCanDo } from '../../../lib/vulcan-users/permissions';
import { userGetDisplayName, userCanCollaborate } from '../../../lib/collections/users/helpers'
import { userCanMakeAlignmentPost } from '../../../lib/alignment-forum/users/helpers'
import { useCurrentUser } from '../../common/withUser'
import { postCanEdit } from '../../../lib/collections/posts/helpers';
import { useSetAlignmentPost } from "../../alignment-forum/withSetAlignmentPost";
import { useItemsRead } from '../../common/withRecordPostView';
import MenuItem from '@material-ui/core/MenuItem';
import { Link } from '../../../lib/reactRouterWrapper';
import Tooltip from '@material-ui/core/Tooltip';
import ListItemIcon from '@material-ui/core/ListItemIcon'
import EditIcon from '@material-ui/icons/Edit'
import GraphIcon from '@material-ui/icons/ShowChart'
import LocalOfferOutlinedIcon from '@material-ui/icons/LocalOfferOutlined'
import WarningIcon from '@material-ui/icons/Warning'
import qs from 'qs'
import { subscriptionTypes } from '../../../lib/collections/subscriptions/schema'
import { useDialog } from '../../common/withDialog';
import { forumTypeSetting, taggingNamePluralCapitalSetting } from '../../../lib/instanceSettings';
import { forumSelect } from '../../../lib/forumTypeUtils';
const NotFPSubmittedWarning = ({className}: {className?: string}) => <div className={className}>
{' '}<WarningIcon fontSize='inherit' />
</div>
const styles = (theme: ThemeType): JssStyles => ({
root: {
margin: 0,
...theme.typography.display3,
...theme.typography.postStyle,
...theme.typography.headerStyle,
color: theme.palette.text.primary,
[theme.breakpoints.down('sm')]: {
fontSize: '2.5rem',
marginBottom: 10,
maxWidth: '80%'
}
},
promoteWarning: {
fontSize: 20,
marginLeft: 4,
}
})
const PostActions = ({post, closeMenu, classes}: {
post: PostsList,
closeMenu: ()=>void
classes: ClassesType
}) => {
const currentUser = useCurrentUser();
const {postsRead, setPostRead} = useItemsRead();
const {openDialog} = useDialog();
const {mutate: updatePost} = useUpdate({
collectionName: "Posts",
fragmentName: 'PostsList',
});
const { mutate: updateUser } = useUpdate({
collectionName: "Users",
fragmentName: 'UsersCurrent',
});
const {setAlignmentPostMutation} = useSetAlignmentPost({fragmentName: "PostsList"});
const {mutate: markAsReadOrUnread} = useNamedMutation<{
postId: string, isRead: boolean,
}>({
name: 'markAsReadOrUnread',
graphqlArgs: {postId: 'String', isRead: 'Boolean'},
});
const handleMarkAsRead = () => {
void markAsReadOrUnread({
postId: post._id,
isRead: true,
});
setPostRead(post._id, true);
}
const handleMarkAsUnread = () => {
void markAsReadOrUnread({
postId: post._id,
isRead: false,
});
setPostRead(post._id, false);
}
const handleMoveToMeta = () => {
if (!currentUser) throw new Error("Cannot move to meta anonymously")
void updatePost({
selector: { _id: post._id},
data: {
meta: true,
draft: false,
metaDate: new Date(),
frontpageDate: null,
curatedDate: null,
reviewedByUserId: currentUser._id,
},
})
}
const handleMoveToFrontpage = () => {
if (!currentUser) throw new Error("Cannot move to frontpage anonymously")
void updatePost({
selector: { _id: post._id},
data: {
frontpageDate: new Date(),
meta: false,
draft: false,
reviewedByUserId: currentUser._id,
},
})
}
const handleMoveToPersonalBlog = () => {
if (!currentUser) throw new Error("Cannot move to personal blog anonymously")
void updatePost({
selector: { _id: post._id},
data: {
draft: false,
meta: false,
frontpageDate: null,
reviewedByUserId: currentUser._id,
},
})
}
const handleMakeShortform = () => {
void updateUser({
selector: { _id: post.userId },
data: {
shortformFeedId: post._id
},
});
}
const handleMoveToAlignmentForum = () => {
void setAlignmentPostMutation({
postId: post._id,
af: true,
})
}
const handleRemoveFromAlignmentForum = () => {
void setAlignmentPostMutation({
postId: post._id,
af: false,
})
}
const handleApproveUser = async () => {
await updateUser({
selector: {_id: post.userId},
data: {reviewedByUserId: currentUser?._id}
})
}
const handleOpenTagDialog = async () => {
openDialog({
componentName: "EditTagsDialog",
componentProps: {
post
}
});
closeMenu();
}
const { MoveToDraft, BookmarkButton, SuggestCurated, SuggestAlignment, ReportPostMenuItem, DeleteDraft, NotifyMeButton } = Components
if (!post) return null;
const postAuthor = post.user;
const isRead = (post._id in postsRead) ? postsRead[post._id] : post.isRead;
const defaultLabel = forumSelect({
EAForum:'This post may appear on the Frontpage',
default: 'Moderators may promote to Frontpage'
})
// WARNING: Clickable items in this menu must be full-width, and
// ideally should use the <MenuItem> component. In particular,
// do NOT wrap a <MenuItem> around something that has its own
// onClick handler; the onClick handler should either be on the
// MenuItem, or on something outside of it. Putting an onClick
// on an element inside of a MenuItem can create a dead-space
// click area to the right of the item which looks like you've
// selected the thing, and closes the menu, but doesn't do the
// thing.
return (
<div className={classes.actions}>
{ postCanEdit(currentUser,post) && <Link to={{pathname:'/editPost', search:`?${qs.stringify({postId: post._id, eventForm: post.isEvent})}`}}>
<MenuItem>
<ListItemIcon>
<EditIcon />
</ListItemIcon>
Edit
</MenuItem>
</Link>}
{ forumTypeSetting.get() === 'EAForum' && postCanEdit(currentUser, post) && <Link
to={{pathname: '/postAnalytics', search: `?${qs.stringify({postId: post._id})}`}}
>
<MenuItem>
<ListItemIcon>
<GraphIcon />
</ListItemIcon>
Analytics
</MenuItem>
</Link>}
{ userCanCollaborate(currentUser, post) &&
<Link to={{pathname:'/collaborateOnPost', search:`?${qs.stringify({postId: post._id})}`}}>
<MenuItem>
<ListItemIcon>
<EditIcon />
</ListItemIcon>
Collaborative Editing
</MenuItem>
</Link>
}
{currentUser && post.group &&
<NotifyMeButton asMenuItem
document={post.group} showIcon
subscribeMessage={"Subscribe to "+post.group.name}
unsubscribeMessage={"Unsubscribe from "+post.group.name}
/>
}
{currentUser && post.shortform && (post.userId !== currentUser._id) &&
<NotifyMeButton asMenuItem document={post} showIcon
subscriptionType={subscriptionTypes.newShortform}
subscribeMessage={`Subscribe to ${post.title}`}
unsubscribeMessage={`Unsubscribe from ${post.title}`}
/>
}
{currentUser && postAuthor && postAuthor._id !== currentUser._id &&
<NotifyMeButton asMenuItem document={postAuthor} showIcon
subscribeMessage={"Subscribe to posts by "+userGetDisplayName(postAuthor)}
unsubscribeMessage={"Unsubscribe from posts by "+userGetDisplayName(postAuthor)}
/>
}
{currentUser && <NotifyMeButton asMenuItem
document={post} showIcon
subscribeMessage="Subscribe to comments"
unsubscribeMessage="Unsubscribe from comments"
/>}
<BookmarkButton post={post} menuItem/>
<ReportPostMenuItem post={post}/>
<div onClick={handleOpenTagDialog}>
<MenuItem>
<ListItemIcon>
<LocalOfferOutlinedIcon />
</ListItemIcon>
Edit {taggingNamePluralCapitalSetting.get()}
</MenuItem>
</div>
{ isRead
? <div onClick={handleMarkAsUnread}>
<MenuItem>
Mark as Unread
</MenuItem>
</div>
: <div onClick={handleMarkAsRead}>
<MenuItem>
Mark as Read
</MenuItem>
</div>
}
<SuggestCurated post={post}/>
<MoveToDraft post={post}/>
<DeleteDraft post={post}/>
{ userCanDo(currentUser, "posts.edit.all") &&
<span>
{ !post.frontpageDate &&
<div onClick={handleMoveToFrontpage}>
<Tooltip placement="left" title={
post.submitToFrontpage ?
'' :
`user did not select ${defaultLabel} option`
}>
<MenuItem>
Move to Frontpage
{!post.submitToFrontpage && <NotFPSubmittedWarning className={classes.promoteWarning} />}
</MenuItem>
</Tooltip>
</div>
}
{ (post.frontpageDate || post.meta || post.curatedDate) &&
<div onClick={handleMoveToPersonalBlog}>
<MenuItem>
Move to Personal Blog
</MenuItem>
</div>
}
{ !post.shortform &&
<div onClick={handleMakeShortform}>
<MenuItem>
Set as user's Shortform Post
</MenuItem>
</div>
}
{ post.authorIsUnreviewed &&
<div onClick={handleApproveUser}>
<MenuItem>
Approve New User
</MenuItem>
</div>
}
</span>
}
{forumTypeSetting.get() !== "EAForum" && <>
<SuggestAlignment post={post}/>
{ userCanMakeAlignmentPost(currentUser, post) && !post.af &&
<div onClick={handleMoveToAlignmentForum }>
<MenuItem>
Ω Move to Alignment
</MenuItem>
</div>
}
{ userCanMakeAlignmentPost(currentUser, post) && post.af &&
<div onClick={handleRemoveFromAlignmentForum}>
<MenuItem>
Ω Remove Alignment
</MenuItem>
</div>
}
</>}
</div>
)
}
const PostActionsComponent = registerComponent('PostActions', PostActions, {styles});
declare global {
interface ComponentTypes {
PostActions: typeof PostActionsComponent
}
} | the_stack |
import {
BehaviorSubject,
combineLatest,
debounceTime,
map,
Subject,
tap,
} from "rxjs";
import { singleton } from "tsyringe";
import { AuthService } from "../../auth/service";
import { WebSocketService } from "../../common/websocket";
import { chatApi } from "../api";
import {
ChatData,
ChatMessage,
FriendChat,
FriendChatStatus,
IsTypingMessage,
PrivateChat,
} from "../model";
import { ChatService } from "../service";
/**
* Store that manages all chat-related data.
*
* @export
* @class ChatStore
*/
@singleton()
export class ChatStore {
private _footerChats$ = new BehaviorSubject<PrivateChat[]>([]);
private _privateChats$ = new BehaviorSubject<PrivateChat[]>([]);
private _onlineFriendsIds$ = new BehaviorSubject<string[]>([]);
private _friendsChats$ = new BehaviorSubject<FriendChat[]>([]);
private _unreadConversationsIds$ = new BehaviorSubject<string[]>([]);
private _lastReadMessages: Map<string, string | null> = new Map();
public static messagesQueryLimit: number = 20;
public static isTypingDebounceTime: number = 4000;
public readonly footerChats$ = this._footerChats$.asObservable();
public readonly privateChats$ = this._privateChats$.asObservable();
public readonly onlineFriendsIds$ = this._onlineFriendsIds$.asObservable();
public readonly friendsChats$ = this._friendsChats$.asObservable();
public readonly unreadConversationsIds$ =
this._unreadConversationsIds$.asObservable();
public chatBoxesData: Map<string, BehaviorSubject<ChatData>> = new Map();
constructor(
private _ws: WebSocketService,
private _chatService: ChatService,
private _authService: AuthService
) {
// update private chat list
this._ws
.listenTo("private_chats")
.subscribe((privateChats) => this._privateChats$.next(privateChats));
// handle friend addition, refreshing
this._ws.listenTo("add_friend").subscribe((privateChat: PrivateChat) => {
// TODO: Socket.IO session refresh should be performed by backend: this is a hacky way to refresh cached friends
this._ws.reconnect(localStorage.getItem("jwtToken")!);
});
// handler friend deletion, removing chat from footer
this._ws.listenTo("remove_friend").subscribe((friendId: string) => {
this._footerChats$.next(
this._footerChats$.value.filter(
(footerChat) => footerChat.profileId !== friendId
)
);
this._ws.reconnect(localStorage.getItem("jwtToken")!);
});
// show which user is typing on a specific chat
this._ws
.listenTo("is_typing")
.pipe(
tap((data: IsTypingMessage) => {
const chatData$ = this._getOrCreateChat(data.chatGroupId);
chatData$.next({
...chatData$.value,
usernameIsTyping: data.username,
});
}),
debounceTime(ChatStore.isTypingDebounceTime)
)
.subscribe((data: IsTypingMessage) => {
const chatData$ = this._getOrCreateChat(data.chatGroupId);
chatData$.next({ ...chatData$.value, usernameIsTyping: null });
});
// update online friends statuses
this._ws
.listenTo("online_friends")
.subscribe((friendsIds: string[]) =>
this._onlineFriendsIds$.next(friendsIds)
);
// update unread conversations count
this._ws
.listenTo("unread_conversations_ids")
.subscribe((conversationsIds: string[]) => {
for (const id of this._unreadConversationsIds$.value) {
if (!conversationsIds.includes(id)) {
conversationsIds.push(id);
}
}
this._unreadConversationsIds$.next(conversationsIds);
});
/*
Handle new chat message.
Expected behavior:
- "is typing" indicator of the chat instantly disappears
- if chat box is not included in the footer section: add it to footer and open it, load latest messages (only if
no message has already been loaded into that chat) and scroll to bottom
- if chat box is already included in the footer section:
- if chat box is open, just add the new message and scroll to bottom
- if chat box is closed, add the new message (keeping chat box closed) and add +1 to unread messages counter
*/
this._ws.listenTo("chat_message").subscribe((message: ChatMessage) => {
const chatData$ = this._getOrCreateChat(message.chatGroupId);
if (message.fromProfileId !== this._authService.user.id) {
chatData$.next({ ...chatData$.value, usernameIsTyping: null });
}
// if chat is not in footer
if (
!this._footerChats$.value
.map((f) => f.chatGroupId)
.includes(message.chatGroupId)
) {
this.setChatIsOpen(message.chatGroupId, true, false);
// if chat message history is empty
if (
!chatData$.value.messages.length &&
!chatData$.value.noMoreMessages
) {
this.loadMoreMessages(message.chatGroupId).then(() => {
if (
!chatData$.value.messages
.map((msg) => msg.id)
.includes(message.id)
) {
chatData$.next({
...chatData$.value,
messages: [...chatData$.value.messages, message],
});
}
chatData$.value.scrollTo.next("bottom");
this.markChatAsRead(message);
this._unreadConversationsIds$.next(
this._unreadConversationsIds$.value.filter(
(id) => id !== message.chatGroupId
)
);
});
// if chat has already stored some messages
} else {
chatData$.next({
...chatData$.value,
messages: [...chatData$.value.messages, message],
});
chatData$.value.scrollTo.next("bottom");
}
return;
}
// if chat is in footer
chatData$.next({
...chatData$.value,
messages: [...chatData$.value.messages, message],
});
// if its not open
if (!chatData$.value.isOpen) {
chatData$.next({
...chatData$.value,
unreadMessages: chatData$.value.unreadMessages + 1,
});
if (
!this._unreadConversationsIds$.value.includes(message.chatGroupId)
) {
this._unreadConversationsIds$.next([
...this._unreadConversationsIds$.value,
message.chatGroupId,
]);
}
// if its open
} else {
this.markChatAsRead(message);
chatData$.value.scrollTo.next("bottom");
}
});
// combine private chat list and online friends statuses to get a sorted list of online/offline friends
combineLatest([this._privateChats$, this._onlineFriendsIds$])
.pipe(
map(([privateChats, onlineIds]: [PrivateChat[], string[]]) =>
privateChats
.map((privateChat: PrivateChat) => ({
...privateChat,
status: onlineIds.includes(privateChat.profileId)
? FriendChatStatus.Online
: FriendChatStatus.Offline,
}))
.sort((a, b) =>
a.status !== b.status
? a.status === FriendChatStatus.Online
? -1
: 1
: a.username < b.username
? -1
: 1
)
)
)
.subscribe((friends) => this._friendsChats$.next(friends));
}
public sendMessage(message: string, to: string): void {
this._chatService.sendMessage(message, to);
}
public isTyping(chatGroupId: string): void {
this._chatService.isTyping(chatGroupId);
}
public markChatAsRead(message: ChatMessage): void {
if (this._lastReadMessages.get(message.chatGroupId) !== message.id) {
this._chatService.markChatAsRead(message.chatGroupId, message.id);
this._lastReadMessages.set(message.chatGroupId, message.id);
}
}
public addChatToFooter(friend: FriendChat): void {
if (
!this._footerChats$.value
.map((f) => f.chatGroupId)
.includes(friend.chatGroupId)
) {
this._getOrCreateChat(friend.chatGroupId);
this._footerChats$.next([...this._footerChats$.value, friend]);
}
}
public async loadMoreMessages(chatGroupId: string): Promise<void> {
const chatData$ = this._getOrCreateChat(chatGroupId);
if (chatData$.value.isLoadingMessages || chatData$.value.noMoreMessages) {
return;
}
chatData$.next({ ...chatData$.value, isLoadingMessages: true });
const olderThan =
chatData$.value.messages[0] && chatData$.value.messages[0]?.createdAt;
try {
const messages = await chatApi.getChatMessages(chatGroupId, olderThan);
chatData$.next({
...chatData$.value,
messages: [...messages.reverse(), ...chatData$.value.messages],
});
if (messages.length < ChatStore.messagesQueryLimit) {
chatData$.next({ ...chatData$.value, noMoreMessages: true });
}
} finally {
chatData$.next({ ...chatData$.value, isLoadingMessages: false });
}
}
public setChatIsOpen(
chatGroupId: string,
isOpen: boolean,
loadMessages: boolean = false
): void {
const chatData$ = this._getOrCreateChat(chatGroupId);
if (isOpen) {
this.addChatToFooter(
this._friendsChats$.value.filter(
(friendChat) => friendChat.chatGroupId === chatGroupId
)[0]
);
if (
chatData$.value.messages.length &&
this._unreadConversationsIds$.value.includes(chatGroupId)
) {
this.markChatAsRead(
chatData$.value.messages[chatData$.value.messages.length - 1]
);
this._unreadConversationsIds$.next(
this._unreadConversationsIds$.value.filter((id) => id !== chatGroupId)
);
}
chatData$.value.scrollTo.next("bottom");
}
chatData$.next({
...chatData$.value,
isOpen: isOpen,
unreadMessages: isOpen ? 0 : chatData$.value.unreadMessages,
});
if (
!chatData$.value.messages.length &&
!chatData$.value.noMoreMessages &&
loadMessages
) {
this.loadMoreMessages(chatGroupId).then(() => {
if (chatData$.value.messages.length === 0) {
return;
}
chatData$.value.scrollTo.next("bottom");
if (
chatData$.value.messages.length &&
this._unreadConversationsIds$.value.includes(chatGroupId)
) {
this.markChatAsRead(
chatData$.value.messages[chatData$.value.messages.length - 1]
);
this._unreadConversationsIds$.next(
this._unreadConversationsIds$.value.filter(
(id) => id !== chatGroupId
)
);
}
});
}
}
public removeChatFromFooter(privateChat: PrivateChat): void {
this._footerChats$.next(
this._footerChats$.value.filter(
(f) => f.chatGroupId !== privateChat.chatGroupId
)
);
this.chatBoxesData.delete(privateChat.chatGroupId);
}
private _getOrCreateChat(chatGroupId: string): BehaviorSubject<ChatData> {
const chatData$ = this.chatBoxesData.get(chatGroupId);
if (chatData$) {
return chatData$;
}
const chatData = new BehaviorSubject<ChatData>({
messages: [],
isLoadingMessages: false,
noMoreMessages: false,
isOpen: false,
unreadMessages: 0,
usernameIsTyping: null,
scrollTo: new Subject<"top" | "bottom">(),
});
this.chatBoxesData.set(chatGroupId, chatData);
return chatData;
}
} | the_stack |
import { printError } from "./debug";
import { SvgNamespace, VNodeFlags, VNodeDebugFlags, ComponentDescriptorFlags, setAttr } from "./misc";
import { Component, ComponentDescriptor, updateComponent } from "./component";
import { ElementDescriptor } from "./element_descriptor";
/**
* Virtual DOM Node.
*
* VNode object is the core object in kivi Virtual DOM, it can represent any node type.
*
* The easiest way to create VNode instances is to use factory functions:
*
* // HTMLElement
* const htmlElement = createVElement("div");
* // SVGElement
* const svgElement = createVSvgElement("a");
* // Text node
* const textNode = createVText("text content");
* // Component's root node
* const root = createVRoot();
*
* VNode instances can't be reused to represent multiple DOM nodes.
*
* @final
*/
export class VNode {
/**
* Flags, see `VNodeFlags` for details.
*/
_flags: VNodeFlags;
/**
* Tag name of the element, reference to an ElementDescriptor, or ComponentDescriptor if this node represents a
* component.
*/
_tag: string | ElementDescriptor<any> | ComponentDescriptor<any, any> | null;
/**
* Children reconciliation algorithm is using key property to find the same node in the previous children array. Key
* should be unique among its siblings.
*/
_key: any;
/**
* Properties.
*
* When virtual node represents an element, props property is used to set properties directly on DOM node:
*
* e: HTMLElement;
* e.propertyName = propertyValue;
*
* When virtual node is mounted on top of existing HTML, all properties will be assigned during mounting phase.
*/
_props: any;
/**
* Attributes.
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*/
_attrs: { [key: string]: any } | null;
/**
* Style in css string format.
*
* Style is assigned to DOM nodes with `style.cssText` property, if virtual node represents an element from svg
* namespace, style will be assigned with `setAttribute("style", "cssText")` method.
*/
_style: string | null;
/**
* Class name.
*
* Class name is assigned to DOM nodes with `className` property, if virtual node represents an element from svg
* namespace, class name will be assigned with `setAttribute("class", "className")` method.
*/
_className: string | null;
/**
* Children property can contain flat array of children virtual nodes, or text if it contains a single text node
* child. If virtual node represents an input field, children property will contain input value.
*/
_children: VNode[] | VNode | string | boolean | null;
/**
* Reference to HTML Node. It will be available after virtual node is created or synced. Each time VNode is synced,
* reference to the HTML Node is transferred from old virtual node to the new one.
*/
ref: Node | null;
/**
* Reference to a Component. If virtual node is a Component, then cref will be available after virtual node is
* created or synced. Each time virtual node is synced, reference to a Component is transferred from old virtual
* node to the new one.
*/
cref: Component<any, any> | null;
/**
* Flags used in DEBUG mode.
*
* See `VNodeDebugFlags` for details.
*/
_debugFlags: number;
constructor(flags: number, tag: string | ElementDescriptor<any> | ComponentDescriptor<any, any> | null, props: any) {
this._flags = flags;
this._tag = tag;
this._key = null;
this._props = props;
this._attrs = null;
this._style = null;
this._className = null;
this._children = null;
this.ref = null;
this.cref = null;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
this._debugFlags = 0;
}
}
/**
* Set key.
*
* Children reconciliation algorithm is using key property to find the same node in the previous children array. Key
* should be unique among its siblings.
*
* This method is available in all virtual node types.
*/
key(key: any): VNode {
this._key = key;
return this;
}
/**
* Set properties with static shape.
*
* Each time virtual node representing the same DOM node is created, it should have properties with exactly the same
* shape. Values can be different, but all keys should be the same. For example:
*
* const a = createVElement("div").props({"id": "Main", "title": "Title"});
* const b = createVElement("div").props({"id": "Main", "title": "New Title"});
*
* Props property is used to set properties directly on DOM node:
*
* e: HTMLElement;
* e.propertyName = propertyValue;
*
* When virtual node is mounted on top of existing HTML, all properties will be assigned during mounting phase.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
props(props: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set props on VNode: props method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set props on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._props !== null) {
const keys = Object.keys(props);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._props.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set props on VNode: VNode is using ElementDescriptor that uses the same` +
` property "${keys[i]}".`);
}
}
}
}
}
this._props = props;
return this;
}
/**
* Set attributes with static shape.
*
* Each time virtual node representing the same DOM node is created, it should have attributes with exactly the same
* shape. Values can be different, but all keys should be the same. For example:
*
* const a = createVElement("div").attrs({"id": "Main", "title": "Title"});
* const b = createVElement("div").attrs({"id": "Main", "title": "New Title"});
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
attrs(attrs: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set attrs on VNode: attrs method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set attrs on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._attrs !== null) {
const keys = Object.keys(attrs);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._attrs.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set attrs on VNode: VNode is using ElementDescriptor that uses the same` +
` attribute "${keys[i]}".`);
}
}
}
}
}
this._attrs = attrs;
return this;
}
/**
* Set attributes with dynamic shape.
*
* Attributes can have different set of keys, when reconciliation algorithm updates attribute values, it will remove
* attributes with `removeAttribute` method for all missing keys.
*
* const a = createVElement("div").props({"id": "Main", "title": "Title"});
* const b = createVElement("div").props({"id": "Main"});
*
* All attributes are assigned to DOM nodes with `setAttribute` method:
*
* e: HTMLElement;
* e.setAttribute(key, value);
*
* If attribute is prefixed with "xlink:", or "xml:" namespace, it will assign attributes with `setAttributeNS`
* method and use appropriate namespaces.
*
* If virtual node is using `ElementDescriptor` instance with custom update handler, update data should be assigned
* with `data` method.
*
* This method is available on element and component's root virtual node types.
*/
dynamicShapeAttrs(attrs?: { [key: string]: any }): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set attrs on VNode: attrs method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set attrs on VNode: VNode is using ElementDescriptor with custom update handler.");
}
const eDescriptor = this._tag as ElementDescriptor<any>;
if (eDescriptor._attrs !== null) {
const keys = Object.keys(attrs);
for (let i = 0; i < keys.length; i++) {
if (eDescriptor._attrs.hasOwnProperty(keys[i])) {
throw new Error(`Failed to set attrs on VNode: VNode is using ElementDescriptor that uses the same` +
` attribute "${keys[i]}".`);
}
}
}
}
}
this._flags |= VNodeFlags.DynamicShapeAttrs;
this._attrs = attrs === undefined ? null : attrs;
return this;
}
/**
* Set data for ElementDescriptor update handler.
*
* This method is available on element and component's root virtual node types.
*/
data(data: any): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root | VNodeFlags.ElementDescriptor)) === 0) {
throw new Error("Failed to set data on VNode: data method should be called on element or component" +
" root nodes represented by ElementDescriptors only.");
}
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {
throw new Error("Failed to set data on VNode: VNode should be using ElementDescriptor with update handler.");
}
}
this._props = data;
return this;
}
/**
* Set style in css string format.
*
* Style is assigned to DOM nodes with `style.cssText` property, if virtual node represents an element from svg
* namespace, style will be assigned with `setAttribute("style", "cssText")` method.
*
* This method is available on element and component's root virtual node types.
*/
style(style: string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set style on VNode: style method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with custom update handler.");
}
if (((this._tag as ElementDescriptor<any>)._style) !== null) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with assigned style.");
}
}
}
this._style = style;
return this;
}
/**
* Set className.
*
* Class name is assigned to DOM nodes with `className` property, if virtual node represents an element from svg
* namespace, class name will be assigned with `setAttribute("class", "className")` method.
*
* This method is available on element and component's root virtual node types.
*/
className(className: string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set className on VNode: className method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.ElementDescriptor) !== 0) {
if ((this._flags & VNodeFlags.ElementDescriptorUpdateHandler) !== 0) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with update handler.");
}
if (((this._tag as ElementDescriptor<any>)._className) !== null) {
throw new Error("Failed to set style on VNode: VNode is using ElementDescriptor with assigned className.");
}
}
}
this._className = className;
return this;
}
/**
* Set single child.
*
* This method is available on element and component's root virtual node types.
*/
child(child: VNode | string | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set child on VNode: child method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set child on VNode: input elements can't have children.");
}
}
this._children = child;
return this;
}
/**
* Set children.
*
* This method is available on element and component's root virtual node types.
*/
children(children: VNode[] | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set children on VNode: children method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set children on VNode: input elements can't have children.");
}
}
this._flags |= VNodeFlags.ArrayChildren;
this._children = children;
return this;
}
/**
* Set children as an innerHTML string. It is potentially vulnerable to XSS attacks.
*
* This method is available on element and component's root virtual node types.
*/
unsafeHTML(html: string): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set unsafeHTML on VNode: unsafeHTML method should be called on element or" +
" component root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set unsafeHTML on VNode: input elements can't have children.");
}
}
this._flags |= VNodeFlags.UnsafeHTML;
this._children = html;
return this;
}
/**
* Set children and enable track by key reconciliation algorithm. Children parameter should be a flat array of
* virtual nodes with assigned key properties.
*
* This method is available on element and component's root virtual node types.
*/
trackByKeyChildren(children: VNode[] | null): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to set children on VNode: children method should be called on element or component" +
" root nodes only.");
}
if ((this._flags & VNodeFlags.InputElement) !== 0) {
throw new Error("Failed to set children on VNode: input elements can't have children.");
}
if (children !== null) {
for (let i = 0; i < children.length; i++) {
if (children[i]._key === null) {
throw new Error("Failed to set children on VNode: trackByKeyChildren method expects all children to" +
" have a key.");
}
}
}
}
this._flags |= VNodeFlags.ArrayChildren | VNodeFlags.TrackByKeyChildren;
this._children = children;
return this;
}
/**
* Set text value for Input Elements.
*
* This method is available on text input element node type.
*/
value(value: string): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (this._children !== null) {
throw new Error("Failed to set value on VNode: VNode is already have either children or checked property.");
}
}
this._flags |= VNodeFlags.TextInputElement;
this._children = value;
return this;
}
/**
* Set checked value for Input Elements.
*
* This method is available on checked input element node type.
*/
checked(value: boolean): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (this._children !== null) {
throw new Error("Failed to set checked on VNode: VNode is already have either children or value property.");
}
}
this._flags |= VNodeFlags.CheckedInputElement;
this._children = value;
return this;
}
/**
* Prevents component node from syncing.
*
* This method is available on component node type.
*/
bindOnce(): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & VNodeFlags.Component) === 0) {
throw new Error("Failed to set bindOnce on VNode: bindOnce method should be called on component nodes only.");
}
}
this._flags |= VNodeFlags.BindOnce;
return this;
}
/**
* Keep alive node when removing from the document. Keep alive nodes will be detached instead of disposed when they
* are removed from virtual dom tree.
*
* Keep alive nodes should be manually disposed by owning component.
*/
keepAlive(component: Component<any, any>): VNode {
this._flags |= VNodeFlags.KeepAlive;
this.ref = component.element as Node;
this.cref = component;
return this;
}
/**
* Disable children shape errors in DEBUG mode.
*/
disableChildrenShapeError(): VNode {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((this._flags & (VNodeFlags.Element | VNodeFlags.Root)) === 0) {
throw new Error("Failed to disable children shape error on VNode: disableChildrenShapeError method should" +
" be called on element or component root nodes only.");
}
this._debugFlags |= VNodeDebugFlags.DisabledChildrenShapeError;
}
return this;
}
}
/**
* Recursively attach all nodes.
*/
export function vNodeAttach(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Attached) !== 0) {
throw new Error("Failed to attach VNode: VNode is already attached.");
}
vnode._debugFlags |= VNodeDebugFlags.Attached;
vnode._debugFlags &= ~VNodeDebugFlags.Detached;
}
if ((vnode._flags & VNodeFlags.Component) === 0) {
const children = vnode._children;
if (children !== null && typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeAttach((children as VNode[])[i]);
}
}
} else {
(vnode.cref as Component<any, any>).attach();
}
}
/**
* This method should be invoked when node is attached, we don't use recursive implementation because we appending
* nodes to the document as soon as they created and children nodes aren"t attached at this time.
*/
export function vNodeAttached(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Attached) !== 0) {
throw new Error("Failed to attach VNode: VNode is already attached.");
}
vnode._debugFlags |= VNodeDebugFlags.Attached;
vnode._debugFlags &= ~VNodeDebugFlags.Detached;
}
if ((vnode._flags & VNodeFlags.Component) !== 0) {
(vnode.cref as Component<any, any>).attach();
}
}
/**
* Recursively detach all nodes.
*/
export function vNodeDetach(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Detached) !== 0) {
throw new Error("Failed to detach VNode: VNode is already detached.");
}
vnode._debugFlags |= VNodeDebugFlags.Detached;
vnode._debugFlags &= ~VNodeDebugFlags.Attached;
}
if ((vnode._flags & VNodeFlags.Component) === 0) {
const children = vnode._children;
if (children !== null && typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeDetach((children as VNode[])[i]);
}
}
} else {
(vnode.cref as Component<any, any>).detach();
}
}
/**
* Recursively dispose all nodes.
*/
export function vNodeDispose(vnode: VNode): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._debugFlags & VNodeDebugFlags.Disposed) !== 0) {
throw new Error("Failed to dispose VNode: VNode is already disposed.");
}
if ((vnode._debugFlags & (VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted)) === 0) {
throw new Error("Failed to dispose VNode: VNode should be rendered or mounted before disposing.");
}
vnode._debugFlags |= VNodeDebugFlags.Disposed;
}
if ((vnode._flags & VNodeFlags.KeepAlive) === 0) {
if ((vnode._flags & VNodeFlags.Component) !== 0) {
(vnode.cref as Component<any, any>).dispose();
} else if (vnode._children !== null) {
const children = vnode._children;
if (typeof children !== "string") {
for (let i = 0; i < (children as VNode[]).length; i++) {
vNodeDispose((children as VNode[])[i]);
}
}
}
} else {
vNodeDetach(vnode);
}
}
/**
* Instantiate a DOM Node or Component from the Virtual DOM Node.
*
* This method doesn't set any attributes, or create children, to render internal representation of the virtual node,
* use `vNodeRender` method.
*/
export function vNodeInstantiate(vnode: VNode, owner: Component<any, any> | undefined): void {
const flags = vnode._flags;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref !== null) {
throw new Error("Failed to create VNode: VNode already has a reference to the DOM node.");
}
}
if ((flags & VNodeFlags.Text) !== 0) {
vnode.ref = document.createTextNode(vnode._props);
} else if ((flags & VNodeFlags.Element) !== 0) {
if ((flags & VNodeFlags.ElementDescriptor) === 0) {
if ((flags & VNodeFlags.Svg) === 0) {
vnode.ref = document.createElement(vnode._tag as string) as Node;
} else {
vnode.ref = document.createElementNS(SvgNamespace, vnode._tag as string) as Node;
}
} else {
vnode.ref = (vnode._tag as ElementDescriptor<any>).createElement() as Node;
}
} else if ((flags & VNodeFlags.KeepAlive) === 0) {
const c = (vnode._tag as ComponentDescriptor<any, any>).createComponent(owner, vnode._props);
vnode.ref = c.element as Node;
vnode.cref = c;
}
}
/**
* Render internal representation of the Virtual DOM Node.
*/
export function vNodeRender(vnode: VNode, owner: Component<any, any> | undefined): void {
let i: number;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref === null) {
throw new Error("Failed to render VNode: VNode should be created before render.");
}
if ((vnode._flags & VNodeFlags.Root) !== 0 && owner === undefined) {
throw new Error("Failed to render VNode: VNode component root should have an owner.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Rendered) !== 0) {
throw new Error("Failed to render VNode: VNode cannot be rendered twice.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Mounted) !== 0) {
throw new Error("Failed to render VNode: VNode cannot be rendered after mount.");
}
vnode._debugFlags |= VNodeDebugFlags.Mounted;
}
let il: number;
let key: any;
let keys: any[];
const flags = vnode._flags;
let ref: Element;
if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
ref = vnode.ref as Element;
if ((flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {
const props = vnode._props;
if (props !== null) {
keys = Object.keys(props);
for (i = 0, il = keys.length; i < il; i++) {
key = keys[i];
(ref as any)[key] = props[key];
}
}
if (vnode._attrs !== null) {
keys = Object.keys(vnode._attrs);
for (i = 0, il = keys.length; i < il; i++) {
key = keys[i];
setAttr(ref, key, (vnode._attrs as any)[key]);
}
}
if (vnode._style !== null) {
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).style.cssText = vnode._style;
} else {
ref.setAttribute("style", vnode._style);
}
}
if (vnode._className !== null) {
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).className = vnode._className;
} else {
ref.setAttribute("class", vnode._className);
}
}
} else {
if ((flags & VNodeFlags.Root) === 0) {
(vnode._tag as ElementDescriptor<any>)._update!(ref, undefined, vnode._props);
} else {
(owner!.descriptor._tag as ElementDescriptor<any>)._update!(ref, undefined, vnode._props);
}
}
const children = vnode._children;
if (children !== null) {
if ((flags & VNodeFlags.UnsafeHTML) === 0) {
if ((flags & VNodeFlags.InputElement) === 0) {
if ((flags & VNodeFlags.ArrayChildren) === 0) {
if (typeof children === "string") {
ref.textContent = children;
} else {
vNodeInsertChild(vnode, children as VNode, null, owner);
}
} else {
for (i = 0, il = (children as VNode[]).length; i < il; i++) {
vNodeInsertChild(vnode, (children as VNode[])[i], null, owner);
}
}
} else {
if ((vnode._flags & VNodeFlags.TextInputElement) !== 0) {
(vnode.ref as HTMLInputElement).value = vnode._children as string;
} else { // ((vnode.flags & VNodeFlags.CheckedInputElement) !== 0)
(vnode.ref as HTMLInputElement).checked = vnode._children as boolean;
}
}
} else {
ref.innerHTML = children as string;
}
}
} else if ((flags & VNodeFlags.Component) !== 0) {
updateComponent(vnode.cref as Component<any, any>);
}
}
/**
* Mount VNode on top of existing html document.
*/
export function vNodeMount(vnode: VNode, node: Node, owner: Component<any, any> | undefined): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (vnode.ref !== null) {
throw new Error("Failed to mount VNode: VNode cannot be mounted if it already has a reference to DOM Node.");
}
if ((vnode._flags & VNodeFlags.Root) !== 0 && owner === undefined) {
throw new Error("Failed to render VNode: VNode component root should have an owner.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Rendered) !== 0) {
throw new Error("Failed to mount VNode: VNode cannot be mounted after render.");
}
if ((vnode._debugFlags & VNodeDebugFlags.Mounted) !== 0) {
throw new Error("Failed to mount VNode: VNode cannot be mounted twice.");
}
vnode._debugFlags |= VNodeDebugFlags.Mounted;
}
const flags = vnode._flags;
const children = vnode._children;
let keys: string[];
let key: string;
let i: number;
vnode.ref = node;
if ((flags & VNodeFlags.Component) !== 0) {
const cref = vnode.cref = (vnode._tag as ComponentDescriptor<any, any>)
.mountComponent(node as Element, owner, vnode._props);
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
const dflags = cref.descriptor._flags;
if (node.nodeType !== 1) {
throw new Error("Failed to mount VNode: invalid node type, components can be mounted on element nodes only.");
}
const eTagName = ((node as Element).tagName).toLowerCase();
let cTagName: string;
if ((dflags & ComponentDescriptorFlags.ElementDescriptor) !== 0) {
cTagName = (cref.descriptor._tag as ElementDescriptor<any>)._tagName.toLowerCase();
if (cTagName !== eTagName) {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "${cTagName}", but` +
` found "${eTagName}".`);
}
} else if ((dflags & ComponentDescriptorFlags.Canvas2D) !== 0) {
if (eTagName !== "canvas") {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "canvas", but` +
` found "${eTagName}".`);
}
} else {
cTagName = (cref.descriptor._tag as string).toLowerCase();
if (cTagName !== eTagName) {
throw new Error(`Failed to mount VNode: invalid tagName, component expects tagName "${cTagName}", but` +
` found "${eTagName}".`);
}
}
}
updateComponent(cref);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((vnode._flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
if (node.nodeType !== 1) {
throw new Error("Failed to mount VNode: invalid node type, VNode expects Element node.");
}
if (vnode._className !== null) {
const eClassName = (node as Element).getAttribute("class");
if (vnode._className !== eClassName) {
throw new Error(`Failed to mount VNode: invalid className, VNode expects className` +
` "${vnode._className}", but found "${eClassName}".`);
}
}
if (vnode._style !== null) {
const eStyle = (node as Element).getAttribute("style");
if (vnode._style !== eStyle) {
throw new Error(`Failed to mount VNode: invalid style, VNode expects style` +
` "${vnode._style}", but found "${eStyle}".`);
}
}
} else {
if (node.nodeType !== 3) {
throw new Error("Failed to mount VNode: invalid node type, VNode expects Text node.");
}
const text = node.nodeValue;
if (vnode._props !== text) {
throw new Error(`Failed to mount VNode: invalid text, VNode expects text "${vnode._props}", but found` +
` "${text}".`);
}
}
}
if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
// Assign properties on mount, because they don't exist in html markup.
if ((flags & VNodeFlags.ElementDescriptor) !== 0) {
const eDescriptor = vnode._tag as ElementDescriptor<any>;
if (eDescriptor._props !== null) {
keys = Object.keys(eDescriptor._props);
for (i = 0; i < keys.length; i++) {
key = keys[i];
(node as any)[key] = eDescriptor._props[key];
}
}
}
if (vnode._props !== null) {
keys = Object.keys(vnode._props);
for (i = 0; i < keys.length; i++) {
key = keys[i];
(node as any)[key] = vnode._props[key];
}
}
if (children !== null) {
if ((flags & VNodeFlags.ArrayChildren) === 0) {
if (typeof children !== "string") {
let child = node.firstChild;
// Adjacent text nodes should be separated by Comment node "<!---->", so we can properly mount them.
let commentNode: Node;
while (child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
vNodeMount(children as VNode, child, owner);
}
} else if ((children as VNode[]).length > 0) {
let child = node.firstChild;
// Adjacent text nodes should be separated by Comment node "<!---->", so we can properly mount them.
let commentNode: Node;
while (child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
for (i = 0; i < (children as VNode[]).length; i++) {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (!child) {
throw new Error("Failed to mount VNode: cannot find matching node.");
}
}
vNodeMount((children as VNode[])[i], child, owner);
child = child.nextSibling;
while (child !== null && child.nodeType === 8) {
commentNode = child;
child = child.nextSibling;
node.removeChild(commentNode);
}
}
}
}
}
}
}
function vNodeInsertChild(parent: VNode, node: VNode, nextRef: Node | null, owner?: Component<any, any>): void {
const container = parent.ref as Element;
if (node.ref === null) {
vNodeInstantiate(node, owner);
vNodeAttached(node);
vNodeRender(node, owner);
container.insertBefore(node.ref!, nextRef!);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((node._flags & VNodeFlags.KeepAlive) === 0) {
throw new Error("Failed to replace node: VNode instance already has been used to create DOM node.");
}
}
container.insertBefore(node.ref, nextRef!);
vNodeAttach(node);
updateComponent(node.cref as Component<any, any>,
(node._flags & VNodeFlags.BindOnce) === 0 ? node._props : null);
}
}
function vNodeReplaceChild(parent: VNode, newNode: VNode, refNode: VNode, owner?: Component<any, any>): void {
const container = parent.ref as Element;
if (newNode.ref === null) {
vNodeInstantiate(newNode, owner);
vNodeAttached(newNode);
vNodeRender(newNode, owner);
container.replaceChild(newNode.ref!, refNode.ref!);
} else {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((newNode._flags & VNodeFlags.KeepAlive) === 0) {
throw new Error("Failed to replace node: VNode instance already has been used to create DOM node.");
}
}
container.replaceChild(newNode.ref, refNode.ref!);
vNodeAttach(newNode);
updateComponent(newNode.cref as Component<any, any>,
(newNode._flags & VNodeFlags.BindOnce) === 0 ? newNode._props : null);
}
vNodeDispose(refNode);
}
function vNodeMoveChild(parent: VNode, node: VNode, nextRef: Node | null): void {
(parent.ref as Element).insertBefore(node.ref!, nextRef!);
}
function vNodeRemoveChild(parent: VNode, node: VNode): void {
(parent.ref as Element).removeChild(node.ref!);
vNodeDispose(node);
}
function vNodeRemoveAllChildren(parent: VNode, nodes: VNode[]): void {
parent.ref!.textContent = "";
for (let i = 0; i < nodes.length; i++) {
vNodeDispose(nodes[i]);
}
}
/**
* Sync two VNodes
*
* When node `a` is synced with node `b`, `a` node should be considered as destroyed, and any access to it after sync
* is an undefined behavior.
*/
export function syncVNodes(a: VNode, b: VNode, owner?: Component<any, any>): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((a._debugFlags & (VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted)) === 0) {
throw new Error("Failed to sync VNode: VNode should be rendered or mounted before sync.");
}
b._debugFlags |= a._debugFlags &
(VNodeDebugFlags.Rendered | VNodeDebugFlags.Mounted |
VNodeDebugFlags.Attached | VNodeDebugFlags.Detached);
}
const ref = a.ref as Element;
const flags = a._flags;
let component: Component<any, any>;
let className: string;
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (a._flags !== b._flags) {
throw new Error(`Failed to sync VNode: flags does not match (old: ${a._flags}, new: ${b._flags}).`);
}
if (a._tag !== b._tag) {
throw new Error(`Failed to sync VNode: tags does not match (old: ${a._tag}, new: ${b._tag}).`);
}
if (a._key !== b._key) {
throw new Error(`Failed to sync VNode: keys does not match (old: ${a._key}, new: ${b._key}).`);
}
if (b.ref !== null && a.ref !== b.ref) {
throw new Error("Failed to sync VNode: reusing VNodes isn't allowed unless it has the same ref.");
}
}
b.ref = a.ref;
if ((flags & VNodeFlags.Text) !== 0) {
if (a._props !== b._props) {
a.ref!.nodeValue = b._props as string;
}
} else if ((flags & (VNodeFlags.Element | VNodeFlags.Root)) !== 0) {
if ((flags & VNodeFlags.ElementDescriptorUpdateHandler) === 0) {
if (a._props !== b._props) {
syncStaticShapeProps(ref, a._props, b._props);
}
if (a._attrs !== b._attrs) {
if ((a._flags & VNodeFlags.DynamicShapeAttrs) === 0) {
syncStaticShapeAttrs(ref, a._attrs, b._attrs);
} else {
syncDynamicShapeAttrs(ref, a._attrs, b._attrs);
}
}
if (a._style !== b._style) {
const style = (b._style === null) ? "" : b._style;
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).style.cssText = style;
} else {
ref.setAttribute("style", style);
}
}
if (a._className !== b._className) {
className = (b._className === null) ? "" : b._className;
if ((flags & VNodeFlags.Svg) === 0) {
(ref as HTMLElement).className = className;
} else {
ref.setAttribute("class", className);
}
}
} else if (a._props !== b._props) {
if ((flags & VNodeFlags.Root) === 0) {
(a._tag as ElementDescriptor<any>)._update!(ref, a._props, b._props);
} else {
(owner!.descriptor._tag as ElementDescriptor<any>)._update!(ref, a._props, b._props);
}
}
if ((a._flags & VNodeFlags.InputElement) === 0) {
if (a._children !== b._children) {
if ((a._flags & VNodeFlags.UnsafeHTML) === 0) {
_syncChildren(
a,
a._children as VNode[] | string,
b._children as VNode[] | string,
owner);
} else {
ref.innerHTML = b._children as string;
}
}
} else {
if ((flags & VNodeFlags.TextInputElement) !== 0) {
if ((ref as HTMLInputElement).value !== b._children) {
(ref as HTMLInputElement).value = b._children as string;
}
} else { // ((flags & VNodeFlags.CheckedInputElement) !== 0)
if ((ref as HTMLInputElement).checked !== b._children) {
(ref as HTMLInputElement).checked = b._children as boolean;
}
}
}
} else { // if ((flags & VNodeFlags.Component) !== 0)
component = b.cref = a.cref as Component<any, any>;
if (((flags & VNodeFlags.ImmutableProps) === 0) || a._props !== b._props) {
updateComponent(component, (flags & VNodeFlags.BindOnce) === 0 ? b._props : undefined);
}
}
}
/**
* Check if two nodes can be synced.
*
* Two nodes can be synced when their flags and tags are identical.
*/
function _canSyncVNodes(a: VNode, b: VNode): boolean {
return (a._flags === b._flags &&
a._tag === b._tag);
}
/**
* Sync old children list with the new one.
*/
function _syncChildren(parent: VNode, a: VNode[] | VNode | string, b: VNode[] | VNode | string,
owner: Component<any, any> | undefined): void {
let i = 0;
if ((parent._flags & VNodeFlags.ArrayChildren) === 0) {
if (a === null) {
if (typeof b === "string") {
parent.ref!.textContent = b as string;
} else {
vNodeInsertChild(parent, b as VNode, null, owner);
}
} else if (b === null) {
if (typeof a === "string") {
parent.ref!.textContent = "";
} else {
vNodeRemoveChild(parent, a as VNode);
}
} else {
if (typeof a === "string") {
if (typeof b === "string") {
const c = parent.ref!.firstChild;
if (c) {
c.nodeValue = b as string;
} else {
parent.ref!.textContent = b as string;
}
} else {
parent.ref!.textContent = "";
vNodeInsertChild(parent, b as VNode, null, owner);
}
} else {
if (typeof b === "string") {
parent.ref!.textContent = b;
vNodeDispose(a as VNode);
} else {
a = a as VNode;
b = b as VNode;
if (_canSyncVNodes(a, b) && a._key === b._key) {
syncVNodes(a, b, owner);
} else {
vNodeReplaceChild(parent, b, a, owner);
}
}
}
}
} else {
a = a as VNode[];
b = b as VNode[];
if (a !== null && a.length !== 0) {
if (b === null || b.length === 0) {
// b is empty, remove all children from a.
vNodeRemoveAllChildren(parent, a as VNode[]);
} else {
if (a.length === 1 && b.length === 1) {
// Fast path when a and b have only one child.
const aNode = a[0] as VNode;
const bNode = b[0] as VNode;
if (_canSyncVNodes(aNode, bNode) && aNode._key === bNode._key) {
syncVNodes(aNode, bNode, owner);
} else {
vNodeReplaceChild(parent, bNode, aNode, owner);
}
} else {
// a and b have more than 1 child.
if ((parent._flags & VNodeFlags.TrackByKeyChildren) === 0) {
_syncChildrenNaive(parent, a as VNode[], b as VNode[], owner);
} else {
_syncChildrenTrackByKeys(parent, a as VNode[], b as VNode[], owner);
}
}
}
} else if (b !== null) {
// a is empty, insert all children from b.
for (i = 0; i < b.length; i++) {
vNodeInsertChild(parent, b[i] as VNode, null, owner);
}
}
}
}
/**
* Sync children naive way.
*
* Any heuristics that is used in this algorithm is an undefined behaviour, and external dependencies should not rely on
* any knowledge about this algorithm, because it can be changed in any time.
*
* This naive algorithm is quite simple:
*
* A: -> [a a c d e g g] <-
* B: -> [a a f d c g] <-
*
* It starts by iterating over old children list `A` and new children list `B` from both ends.
*
* A: -> [a b c d e g g] <-
* B: -> [a b f d c g] <-
*
* When it find nodes that have the same key, tag and flags, it will sync them. Node "a" and "b" on the right side, and
* node "g" on the right side will be synced.
*
* A: -> [c d e g]
* B: -> [f d c]
*
* Then it start iterating over old and new children lists from the left side and check if nodes can be synced. Nodes
* "c" and "f" can't be synced, remove node "c" and insert new node "f".
*
* A: -> [d e g]
* B: -> [d c]
*
* Node "d" is synced.
*
* A: -> [e g]
* B: -> [c]
*
* Node "e" removed, node "c" inserted.
*
* A: -> [g]
* B: []
*
* Length of the old list is larger than length of the new list, remove remaining nodes from the old list.
*
*/
function _syncChildrenNaive(parent: VNode, a: VNode[], b: VNode[], owner: Component<any, any> | undefined): void {
let aStart = 0;
let bStart = 0;
let aEnd = a.length - 1;
let bEnd = b.length - 1;
let aNode: VNode;
let bNode: VNode;
let nextPos: number;
let next: Node | null;
// Sync similar nodes at the beginning.
while (aStart <= aEnd && bStart <= bEnd) {
aNode = a[aStart];
bNode = b[bStart];
if (!_canSyncVNodes(aNode, bNode) || aNode._key !== bNode._key) {
break;
}
aStart++;
bStart++;
syncVNodes(aNode, bNode, owner);
}
// Sync similar nodes at the end.
while (aStart <= aEnd && bStart <= bEnd) {
aNode = a[aEnd];
bNode = b[bEnd];
if (!_canSyncVNodes(aNode, bNode) || aNode._key !== bNode._key) {
break;
}
aEnd--;
bEnd--;
syncVNodes(aNode, bNode, owner);
}
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if ((aStart <= aEnd || bStart <= bEnd) &&
((parent._debugFlags & VNodeDebugFlags.DisabledChildrenShapeError) === 0)) {
printError(
"VNode sync children: children shape is changing, you should enable tracking by key with " +
"VNode method trackByKeyChildren(children).\n" +
"If you certain that children shape changes won't cause any problems with losing " +
"state, you can remove this error message with VNode method disableChildrenShapeError().");
}
}
// Iterate over the remaining nodes and if they have the same type, then sync, otherwise just
// remove the old node and insert the new one.
while (aStart <= aEnd && bStart <= bEnd) {
aNode = a[aStart++];
bNode = b[bStart++];
if (_canSyncVNodes(aNode, bNode) && aNode._key === bNode._key) {
syncVNodes(aNode, bNode, owner);
} else {
vNodeReplaceChild(parent, bNode, aNode, owner);
}
}
if (aStart <= aEnd) {
// All nodes from a are synced, remove the rest.
do {
vNodeRemoveChild(parent, a[aStart++]);
} while (aStart <= aEnd);
} else if (bStart <= bEnd) {
// All nodes from b are synced, insert the rest.
nextPos = bEnd + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
do {
vNodeInsertChild(parent, b[bStart++], next, owner);
} while (bStart <= bEnd);
}
}
/**
* Sync children with track by keys algorithm.
*
* This algorithm finds a minimum[1] number of DOM operations. It works in several steps:
*
* 1. Find common suffix and prefix, and perform simple moves on the edges.
*
* This optimization technique is searching for nodes with identical keys by simultaneously iterating over nodes in the
* old children list `A` and new children list `B` from both sides:
*
* A: -> [a b c d e f g] <-
* B: -> [a b f d c g] <-
*
* Here we can skip nodes "a" and "b" at the begininng, and node "g" at the end.
*
* A: -> [c d e f] <-
* B: -> [f d c] <-
*
* At this position it will try to look at the opposite edge, and if there is a node with the same key at the opposite
* edge, it will perform simple move operation. Node "c" is moved to the right edge, and node "f" is moved to the left
* edge.
*
* A: -> [d e] <-
* B: -> [d] <-
*
* Now it will try again to find common prefix and suffix, node "d" is the same, so we can skip it.
*
* A: [e]
* B: []
*
* Here it will check if the size of one of the list is equal to zero, and if length of the old children list is zero,
* it will insert all remaining nodes from the new list, or if length of the new children list is zero, it will remove
* all remaining nodes from the old list.
*
* This simple optimization technique will cover most of the real world use cases, even reversing the children list,
* except for sorting.
*
* When algorithm couldn't find a solution with this simple optimization technique, it will go to the next step of the
* algorithm. For example:
*
* A: -> [a b c d e f g] <-
* B: -> [a c b h f e g] <-
*
* Nodes "a" and "g" at the edges are the same, skipping them.
*
* A: -> [b c d e f] <-
* B: -> [c b h f e] <-
*
* Here we are stuck, so we need to switch to the next step.
*
* 2. Look for removed and inserted nodes, and simultaneously check if one of the nodes is moved.
*
* First we create an array `P` with the length of the new children list and assign to each position value `-1`, it has
* a meaning of a new node that should be inserted. Later we will assign node positions in the old children list to this
* array.
*
* A: [b c d e f]
* B: [c b h f e]
* P: [. . . . .] // . == -1
*
* Then we need to build an index `I` that maps keys with node positions of the remaining nodes from the new children
* list.
*
* A: [b c d e f]
* B: [c b h f e]
* P: [. . . . .] // . == -1
* I: {
* c: 0,
* b: 1,
* h: 2,
* f: 3,
* e: 4,
* }
* last = 0
*
* With this index, we start to iterate over the remaining nodes from the old children list and check if we can find a
* node with the same key in the index. If we can't find any node, it means that it should be removed, otherwise we
* assign position of the node in the old children list to the positions array.
*
* A: [b c d e f]
* ^
* B: [c b h f e]
* P: [. 0 . . .] // . == -1
* I: {
* c: 0,
* b: 1, <-
* h: 2,
* f: 3,
* e: 4,
* }
* last = 1
*
* When we assigning positions to the positions array, we also keep a position of the last seen node in the new children
* list, if the last seen position is larger than current position of the node at the new list, then we are switching
* `moved` flag to `true`.
*
* A: [b c d e f]
* ^
* B: [c b h f e]
* P: [1 0 . . .] // . == -1
* I: {
* c: 0, <-
* b: 1,
* h: 2,
* f: 3,
* e: 4,
* }
* last = 1 // last > 0; moved = true
*
* The last position `1` is larger than current position of the node at the new list `0`, switching `moved` flag to
* `true`.
*
* A: [b c d e f]
* ^
* B: [c b h f e]
* P: [1 0 . . .] // . == -1
* I: {
* c: 0,
* b: 1,
* h: 2,
* f: 3,
* e: 4,
* }
* moved = true
*
* Node with key "d" doesn't exist in the index, removing node.
*
* A: [b c d e f]
* ^
* B: [c b h f e]
* P: [1 0 . . 3] // . == -1
* I: {
* c: 0,
* b: 1,
* h: 2,
* f: 3,
* e: 4, <-
* }
* moved = true
*
* Assign position for `e`.
*
* A: [b c d e f]
* ^
* B: [c b h f e]
* P: [1 0 . 4 3] // . == -1
* I: {
* c: 0,
* b: 1,
* h: 2,
* f: 3, <-
* e: 4,
* }
* moved = true
*
* Assign position for 'f'.
*
* At this point we are checking if `moved` flag is on, or if the length of the old children list minus the number of
* removed nodes isn't equal to the length of the new children list. If any of this conditions is true, then we are
* going to the next step.
*
* 3. Find minimum number of moves if `moved` flag is on, or insert new nodes if the length is changed.
*
* When `moved` flag is on, we need to find the
* [longest increasing subsequence](http://en.wikipedia.org/wiki/Longest_increasing_subsequence) in the positions array,
* and move all nodes that doesn't belong to this subsequence.
*
* A: [b c d e f]
* B: [c b h f e]
* P: [1 0 . 4 3] // . == -1
* LIS: [1 4]
* moved = true
*
* Now we just need to simultaneously iterate over the new children list and LIS from the end and check if the current
* position is equal to a value from LIS.
*
* A: [b c d e f]
* B: [c b h f e]
* ^ // new_pos == 4
* P: [1 0 . 4 3] // . == -1
* LIS: [1 4]
* ^ // new_pos == 4
* moved = true
*
* Node "e" stays at the same place.
*
* A: [b c d e f]
* B: [c b h f e]
* ^ // new_pos == 3
* P: [1 0 . 4 3] // . == -1
* LIS: [1 4]
* ^ // new_pos != 1
* moved = true
*
* Node "f" is moved, move it before the next node "e".
*
* A: [b c d e f]
* B: [c b h f e]
* ^ // new_pos == 2
* P: [1 0 . 4 3] // . == -1
* ^ // old_pos == -1
* LIS: [1 4]
* ^
* moved = true
*
* Node "h" has a `-1` value in the positions array, insert new node "h".
*
* A: [b c d e f]
* B: [c b h f e]
* ^ // new_pos == 1
* P: [1 0 . 4 3] // . == -1
* LIS: [1 4]
* ^ // new_pos == 1
* moved = true
*
* Node "b" stays at the same place.
*
* A: [b c d e f]
* B: [c b h f e]
* ^ // new_pos == 0
* P: [1 0 . 4 3] // . == -1
* LIS: [1 4]
* ^ // new_pos != undefined
* moved = true
*
* Node "c" is moved, move it before the next node "b".
*
* When moved flag is off, we don't need to find LIS, and we just iterate over the new children list and check its
* current position in the positions array, if it is `-1`, then we insert new node.
*
* That is how children reconciliation algorithm is working in one of the fastest virtual dom libraries :)
*
* [1] Actually it is almost minimum number of dom ops, when node is removed and another one is inserted at the same
* place, instead of insert and remove dom ops, we can use one replace op. It will make everything even more
* complicated, and other use cases will be slower, so I don't think that it is worth to use replace here. Naive algo
* and simple 1/N, N/1 cases are using replace op.
*/
function _syncChildrenTrackByKeys(parent: VNode, a: VNode[], b: VNode[], owner: Component<any, any> | undefined): void {
let aStart = 0;
let bStart = 0;
let aEnd = a.length - 1;
let bEnd = b.length - 1;
let aStartNode = a[aStart];
let bStartNode = b[bStart];
let aEndNode = a[aEnd];
let bEndNode = b[bEnd];
let i: number;
let j: number | undefined;
let nextPos: number;
let next: Node | null;
let aNode: VNode | null;
let bNode: VNode;
let node: VNode;
// Step 1
outer: while (true) {
// Sync nodes with the same key at the beginning.
while (aStartNode._key === bStartNode._key) {
if (_canSyncVNodes(aStartNode, bStartNode)) {
syncVNodes(aStartNode, bStartNode, owner);
} else {
vNodeReplaceChild(parent, bStartNode, aStartNode, owner);
}
aStart++;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aStartNode = a[aStart];
bStartNode = b[bStart];
}
// Sync nodes with the same key at the end.
while (aEndNode._key === bEndNode._key) {
if (_canSyncVNodes(aEndNode, bEndNode)) {
syncVNodes(aEndNode, bEndNode, owner);
} else {
vNodeReplaceChild(parent, bEndNode, aEndNode, owner);
}
aEnd--;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break outer;
}
aEndNode = a[aEnd];
bEndNode = b[bEnd];
}
// Move and sync nodes from right to left.
if (aEndNode._key === bStartNode._key) {
if (_canSyncVNodes(aEndNode, bStartNode)) {
syncVNodes(aEndNode, bStartNode, owner);
} else {
vNodeReplaceChild(parent, bStartNode, aEndNode, owner);
}
vNodeMoveChild(parent, bStartNode, aStartNode.ref);
aEnd--;
bStart++;
if (aStart > aEnd || bStart > bEnd) {
break;
}
aEndNode = a[aEnd];
bStartNode = b[bStart];
// In a real-world scenarios there is a higher chance that next node after the move will be the same, so we
// immediately jump to the start of this prefix/suffix algo.
continue;
}
// Move and sync nodes from left to right.
if (aStartNode._key === bEndNode._key) {
if (_canSyncVNodes(aStartNode, bEndNode)) {
syncVNodes(aStartNode, bEndNode, owner);
} else {
vNodeReplaceChild(parent, bEndNode, aStartNode, owner);
}
nextPos = bEnd + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
vNodeMoveChild(parent, bEndNode, next);
aStart++;
bEnd--;
if (aStart > aEnd || bStart > bEnd) {
break;
}
aStartNode = a[aStart];
bEndNode = b[bEnd];
continue;
}
break;
}
if (aStart > aEnd) {
// All nodes from a are synced, insert the rest from b.
nextPos = bEnd + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
while (bStart <= bEnd) {
vNodeInsertChild(parent, b[bStart++], next, owner);
}
} else if (bStart > bEnd) {
// All nodes from b are synced, remove the rest from a.
while (aStart <= aEnd) {
vNodeRemoveChild(parent, a[aStart++]);
}
// Step 2
} else {
let aLength = aEnd - aStart + 1;
let bLength = bEnd - bStart + 1;
const aNullable = a as Array<VNode | null>; // will be removed by js optimizing compilers.
// Mark all nodes as inserted.
const sources = new Array<number>(bLength).fill(-1);
let moved = false;
let pos = 0;
let synced = 0;
// When children lists are small, we are using naive O(N) algorithm to find if child is removed.
if ((bLength <= 4) || ((aLength * bLength) <= 16)) {
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (synced < bLength) {
for (j = bStart; j <= bEnd; j++) {
bNode = b[j];
if (aNode._key === bNode._key) {
sources[j - bStart] = i;
if (pos > j) {
moved = true;
} else {
pos = j;
}
if (_canSyncVNodes(aNode, bNode)) {
syncVNodes(aNode, bNode, owner);
} else {
vNodeReplaceChild(parent, bNode, aNode, owner);
}
synced++;
aNullable[i] = null;
break;
}
}
}
}
} else {
const keyIndex = new Map<any, number>();
for (i = bStart; i <= bEnd; i++) {
node = b[i];
keyIndex.set(node._key, i);
}
for (i = aStart; i <= aEnd; i++) {
aNode = a[i];
if (synced < bLength) {
j = keyIndex.get(aNode._key);
if (j !== undefined) {
bNode = b[j];
sources[j - bStart] = i;
if (pos > j) {
moved = true;
} else {
pos = j;
}
if (_canSyncVNodes(aNode, bNode)) {
syncVNodes(aNode, bNode, owner);
} else {
vNodeReplaceChild(parent, bNode, aNode, owner);
}
synced++;
aNullable[i] = null;
}
}
}
}
if (aLength === a.length && synced === 0) {
// Noone is synced, remove all children with one dom op.
vNodeRemoveAllChildren(parent, a);
while (bStart < bLength) {
vNodeInsertChild(parent, b[bStart++], null, owner);
}
} else {
i = aLength - synced;
while (i > 0) {
aNode = aNullable[aStart++];
if (aNode !== null) {
vNodeRemoveChild(parent, aNode);
i--;
}
}
// Step 3
if (moved) {
const seq = _lis(sources);
j = seq.length - 1;
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
vNodeInsertChild(parent, node, next, owner);
} else {
if (j < 0 || i !== seq[j]) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
vNodeMoveChild(parent, node, next);
} else {
j--;
}
}
}
} else if (synced !== bLength) {
for (i = bLength - 1; i >= 0; i--) {
if (sources[i] === -1) {
pos = i + bStart;
node = b[pos];
nextPos = pos + 1;
next = nextPos < b.length ? b[nextPos].ref : null;
vNodeInsertChild(parent, node, next, owner);
}
}
}
}
}
}
/**
* Slightly modified Longest Increased Subsequence algorithm, it ignores items that have -1 value, they're representing
* new items.
*
* http://en.wikipedia.org/wiki/Longest_increasing_subsequence
*/
function _lis(a: number[]): number[] {
const p = a.slice(0);
const result: number[] = [];
result.push(0);
let u: number;
let v: number;
for (let i = 0, il = a.length; i < il; i++) {
if (a[i] === -1) {
continue;
}
let j = result[result.length - 1];
if (a[j] < a[i]) {
p[i] = j;
result.push(i);
continue;
}
u = 0;
v = result.length - 1;
while (u < v) {
let c = ((u + v) / 2) | 0;
if (a[result[c]] < a[i]) {
u = c + 1;
} else {
v = c;
}
}
if (a[i] < a[result[u]]) {
if (u > 0) {
p[i] = result[u - 1];
}
result[u] = i;
}
}
u = result.length;
v = result[u - 1];
while (u-- > 0) {
result[u] = v;
v = p[v];
}
return result;
}
/**
* Sync HTML attributes with static shape.
*
* Attributes with static shape should have the same keys.
*
* Valid:
*
* a: { title: "Google", href: "https://www.google.com" }
* b: { title: "Facebook", href: "https://www.facebook.com" }
*
* Invalid:
*
* a: { title: "Google", href: "https://www.google.com" }
* b: { title: "Facebook" }
*/
function syncStaticShapeAttrs(node: Element, a: { [key: string]: any } | null, b: { [key: string]: any } | null): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (a === null || b === null) {
throw new Error("Failed to update attrs with static shape: attrs object have dynamic shape.");
}
}
let keys = Object.keys(a);
let key: string;
let i: number;
for (i = 0; i < keys.length; i++) {
key = keys[i];
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (!b!.hasOwnProperty(key)) {
throw new Error("Failed to update attrs with static shape: attrs object have dynamic shape.");
}
}
const bValue = b![key];
if (a![key] !== bValue) {
setAttr(node, key, bValue);
}
}
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
keys = Object.keys(b);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (!a!.hasOwnProperty(key)) {
throw new Error("Failed to update attrs with static shape: attrs object have dynamic shape.");
}
}
}
}
/**
* Sync HTML attributes with dynamic shape.
*
* Attributes with dynamic shape can have any keys, missing keys will be removed with `node.removeAttribute` method.
*
* a: { title: "Google", href: "https://www.google.com" }
* b: { title: "Google" }
*
* In this example `href` attribute will be removed.
*/
function syncDynamicShapeAttrs(node: Element, a: { [key: string]: any } | null, b: { [key: string]: any } | null): void {
let i: number;
let keys: string[];
let key: string;
if (a !== null) {
if (b === null) {
// b is empty, remove all attributes from a.
keys = Object.keys(a);
for (i = 0; i < keys.length; i++) {
node.removeAttribute(keys[i]);
}
} else {
// Remove and update attributes.
keys = Object.keys(a);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (b.hasOwnProperty(key)) {
const bValue = b[key];
if (a[key] !== bValue) {
setAttr(node, key, bValue);
}
} else {
node.removeAttribute(key);
}
}
// Insert new attributes.
keys = Object.keys(b);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (!a.hasOwnProperty(key)) {
setAttr(node, key, b[key]);
}
}
}
} else if (b !== null) {
// a is empty, insert all attributes from b.
keys = Object.keys(b);
for (i = 0; i < keys.length; i++) {
key = keys[i];
setAttr(node, key, b[key]);
}
}
}
/**
* Sync HTML properties with static shape.
*
* Properties with static shape should have the same keys.
*
* Valid:
*
* a: { title: "Google", href: "https://www.google.com" }
* b: { title: "Facebook", href: "https://www.facebook.com" }
*
* Invalid:
*
* a: { title: "Google", href: "https://www.google.com" }
* b: { title: "Facebook" }
*/
function syncStaticShapeProps(node: Element, a: { [key: string]: any }, b: { [key: string]: any }): void {
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (a === null || b === null) {
throw new Error("Failed to update props with static shape: props object have dynamic shape.");
}
}
let keys = Object.keys(a);
let key: string;
let i: number;
for (i = 0; i < keys.length; i++) {
key = keys[i];
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
if (!b.hasOwnProperty(key)) {
throw new Error("Failed to update props with static shape: props object have dynamic shape.");
}
}
const bValue = b[key];
if (a[key] !== bValue) {
(node as { [key: string]: any })[key] = bValue;
}
}
if ("<@KIVI_DEBUG@>" as string !== "DEBUG_DISABLED") {
keys = Object.keys(b);
for (i = 0; i < keys.length; i++) {
key = keys[i];
if (!a.hasOwnProperty(key)) {
throw new Error("Failed to update attrs with static shape: attrs object have dynamic shape.");
}
}
}
}
/**
* Create a VNode representing a [Text] node.
*/
export function createVText(content: string): VNode {
return new VNode(VNodeFlags.Text, null, content);
}
/**
* Create a VNode representing an [Element] node.
*/
export function createVElement(tagName: string): VNode {
return new VNode(VNodeFlags.Element, tagName, null);
}
/**
* Create a VNode representing a [SVGElement] node.
*/
export function createVSvgElement(tagName: string): VNode {
return new VNode(VNodeFlags.Element | VNodeFlags.Svg, tagName, null);
} | the_stack |
import * as crypto from 'crypto';
import {
IGitWorkingCopy,
IGitRemote,
IGitBranch,
IGitHistory,
IGitHistoryDetails,
IGitRemoteSuccessResponse
} from '@materia/interfaces';
import * as fs from 'fs';
import { join } from 'path';
import * as git from 'simple-git/promise';
import { App } from '../../lib';
export class Git {
client: any;
workingCopy: IGitWorkingCopy;
history: IGitHistory[];
constructor(private app: App) {
try {
this.client = git(this.app.path);
this.client.silent(true);
} catch (e) { }
}
clone(params: {repoPath: string, destinationFolder?: string, localPath?: string, options?: any}) {
const args = [];
if (params.options) {
args.push(params.options);
}
return git(params.destinationFolder ? params.destinationFolder : this.app.path)
.clone(params.repoPath, params.localPath, params.options);
}
init() {
return this.client.init();
}
load(): Promise<any> {
return Promise.all([
this.refreshWorkingCopy(),
this.refreshHistory(),
this.refreshRemotes(),
this.refreshBranches()
]).then(data => {
return {
history: data[1],
workingCopy: data[0],
remotes: data[2],
branches: data[3]
};
});
}
refreshHistory(): Promise<IGitHistory[]> {
return this.getLogs().then(logs => {
const history = logs.all.map(log => {
if (log.refs) {
log.refs = log.refs
.split(', ')
.filter(ref => {
return !ref.match(/\/HEAD$/);
})
.map(ref => {
const refobj = { name: ref } as any;
const head = ref.match(/^HEAD -> (.*)/);
if (head) {
refobj.name = head[1];
refobj.head = true;
}
return refobj;
});
} else {
log.refs = [];
}
log.date = new Date(log.date);
log.full_date = `${log.date.getUTCMonth() +
1}/${log.date.getUTCDate()}/${log.date.getUTCFullYear()} at ${log.date.getUTCHours()}:${
log.date.getUTCMinutes()}:${log.date.getUTCSeconds()}`;
log.date = `${log.date.getMonth() +
1}/${log.date.getDate()}/${log.date.getFullYear()}`;
log.author_email_md5 = crypto
.createHash('md5')
.update(log.author_email)
.digest('hex');
return log;
});
this.history = history;
return history;
});
}
refreshWorkingCopy(): Promise<IGitWorkingCopy> {
return this.client.status().then(data => {
this.workingCopy = data;
return data;
});
}
refreshBranches(): Promise<IGitBranch[]> {
return this.client.raw(['branch', '-avv']).then(branchesRaw => {
const branches = this._parseBranch(branchesRaw);
// When 0 commit
let firstCommit = false;
if (branches.length == 0) {
branches.push({
name: 'master',
current: true
});
firstCommit = true;
}
return {
branches,
firstCommit
};
});
}
private _parseBranch(raw) {
if ( ! raw) {
return [];
}
const lines = raw.split('\n');
const regexp = /^([* ]) ([^ ]+)[ \t]+([a-f0-9]{7}) (\[([^ :\]]*)(: (ahead|behind) ([0-9]+))?] )?(.*)$/;
const regexpLink = /^([* ]) ([^ ]+)[ \t]+(-> ([^ ]+))$/;
const results = [];
lines.forEach(line => {
const parsed = line.match(regexp);
if (parsed) {
const res = {
current: parsed[1] == '*',
name: parsed[2],
commit: {
hash: parsed[3],
subject: parsed[9]
},
tracking: parsed[5],
ahead: parsed[7] == 'ahead' ? parsed[8] : 0,
behind: parsed[7] == 'behind' ? parsed[8] : 0
};
results.push(res);
} else {
const parsed2 = line.match(regexpLink);
if (parsed2) {
// ?
}
}
});
return results;
}
refreshRemotes(): Promise<IGitRemote[]> {
return this.client
.getRemotes(true)
.then(remotes => remotes.filter(remote => remote.name != ''));
}
getStatusDiff(
statusPath: string
): Promise<{ before: string; after: string }> {
if ( ! statusPath ) {
return Promise.resolve({
before: '',
after: ''
});
}
const status = this.workingCopy.files.find(p => p.path == statusPath);
let content = null;
statusPath = this._fixGitPath(statusPath);
try {
const size = fs.statSync(join(this.app.path, statusPath)).size;
if (size > 1000000.0) {
content = '// The content is too long to display...';
} else {
content = fs.readFileSync(
join(this.app.path, statusPath),
'utf8'
);
}
} catch (e) { }
if (['A', '?'].indexOf(status.index) != -1) {
return Promise.resolve({
before: null,
after: content
});
} else {
return this.client
.raw(['show', `HEAD:${statusPath}`])
.then(oldVersion => {
if (oldVersion.length > 1000000) {
oldVersion = '// The content is too long to display...';
}
return {
before: oldVersion,
after: content
};
});
}
}
getHistoryDetail(
hash: string
): Promise<IGitHistoryDetails> {
const log = this.history.find(h => h.hash == hash);
return this.getCommit(log.hash).then(details => {
const t = details.message.split('\n');
details.summary = t[0];
t.shift();
if (t[0] == '') {
t.shift();
}
details.description = t.join('\n');
details.changes = details.changes.map((change, i) => {
return {
index: change[0],
path: change.slice(1).join(' ')
};
});
return details;
});
}
getHistoryFileDetail(hash, filepath) {
const log = this.history.find(h => h.hash == hash);
const tmp = log.parents.split(' ');
const parentCommit = tmp[tmp.length - 1];
return this.getCommit(hash).then(details => {
const promises = [];
let p: Promise<any> = Promise.resolve();
details.changes.forEach(change => {
if (change.slice(1).join(' ') === filepath) {
const errCallback = e => {
return null;
};
if ('A' == change[0]) {
promises.push(
this.client
.raw(['show', `${hash}:${filepath}`])
.catch(errCallback)
);
promises.push(Promise.resolve(''));
} else if ('D' == change[0]) {
promises.push(Promise.resolve(''));
promises.push(
this.client
.raw(['show', `${parentCommit}:${filepath}`])
.catch(errCallback)
);
} else {
promises.push(
this.client
.raw(['show', `${hash}:${filepath}`])
.catch(errCallback)
);
promises.push(
this.client
.raw(['show', `${parentCommit}:${filepath}`])
.catch(errCallback)
);
}
}
});
p = Promise.all(promises);
return p.then(data => {
let change = { original: '', modified: '' };
if (data) {
change = {
original: data[1],
modified: data[0]
};
}
return change;
});
});
}
private getCommit(hash): Promise<any> {
return this.client
.show(['--pretty=%w(0)%B%n<~diffs~>', '--name-status', hash])
.then(data => {
const result = data.split('<~diffs~>');
const changes = result[1]
.trim()
.split(/[\r\n]/)
.map(line => line.split(/[ \t]/));
return {
message: result[0].trim(),
changes: changes
};
});
}
stage(statusPath: string): Promise<IGitWorkingCopy> {
const status = this.workingCopy.files.find(s => s.path == statusPath);
let res;
status.path = this._fixGitPath(status.path);
if (status.index == 'D') {
res = this.client.rmKeepLocal([status.path]);
}
res = this.client.add([status.path]);
return res.then(() => this.refreshWorkingCopy());
}
unstage(statusPath: string): Promise<IGitWorkingCopy> {
const status = this.workingCopy.files.find(s => s.path == statusPath);
status.path = this._fixGitPath(status.path);
return this.client
.reset(['HEAD', status.path])
.catch(e => {
if (
e &&
e.message &&
e.message.match(
/ambiguous argument 'HEAD': unknown revision/
)
) {
return this.client.reset([status.path]); // no HEAD yet
}
return Promise.reject(e);
})
.then(() => this.refreshWorkingCopy());
}
stageAll(): Promise<IGitWorkingCopy> {
return this.client.add(['-A']).then(() => this.refreshWorkingCopy());
}
unstageAll(): Promise<IGitWorkingCopy> {
return this.client.reset(['.']).then(() => this.refreshWorkingCopy());
}
private refreshRemoteData(): Promise<IGitRemoteSuccessResponse> {
return Promise.all([
this.refreshWorkingCopy(),
this.refreshHistory()
]).then(res => {
return {
workingCopy: res[0],
history: res[1]
};
});
}
fetch(
force?: boolean,
gitState?: any
): Promise<IGitRemoteSuccessResponse> {
// if ( ! force && gitState.lastFetch && new Date().getTime() - gitState.lastFetch.getTime() < 10000) {
// return Observable.of(null);
// }
// if (gitState && gitState.noRemote) {
// throw Observable.throw(new Error("No remote"));
// }
return this.client
.raw(['fetch'])
.then(this.refreshRemoteData.bind(this));
}
commit(
summary: string,
description?: string
): Promise<IGitRemoteSuccessResponse> {
let message = summary;
if (description) {
message += '\n\n' + description;
}
return this.client
.commit(message)
.then(data =>
Promise.all([
this.refreshWorkingCopy(),
this.refreshHistory()
])
)
.then(res => {
return {
workingCopy: res[0],
history: res[1]
};
});
}
pull(
remote?: string,
branch?: string
): Promise<IGitRemoteSuccessResponse> {
return this.client
.pull(remote, branch)
.then(this.refreshRemoteData.bind(this));
}
push(): Promise<IGitRemoteSuccessResponse> {
return this.client.push().then(this.refreshRemoteData.bind(this));
}
publish(
remote: string,
branch: string
): Promise<IGitRemoteSuccessResponse> {
return this.client
.push(['-u', remote, branch])
.then(this.refreshRemoteData.bind(this));
}
copyCheckout() { }
setupRemote(config: IGitRemote): Promise<IGitRemote[]> {
return this.client
.addRemote(config.name, config.url)
.then(() => this.refreshRemotes());
}
private getLogs() {
const args = {
format: {
hash: '%H',
parents: '%P',
date: '%ai',
message: '%s',
refs: '%D',
author_name: '%aN',
author_email: '%ae'
},
splitter: '<~spt~>',
'--branches': null,
'--remotes': null,
'--tags': null
};
return this.client.log(args).catch(e => {
if (
e &&
e.message &&
e.message.match(
/your current branch '.*?' does not have any commits yet/
)
) {
return Promise.resolve({ all: [] });
}
throw e;
});
}
createLocalBranch(branchName) {
return this.client.checkoutLocalBranch(branchName);
}
checkout(arg) {
if (arg.split('remotes/origin/').length - 1) {
arg = arg.split('remotes/origin/')[1];
}
return this.client.checkout(arg);
}
stash() {
return this.client.stash();
}
stashPop() {
return this.client.stash(['pop']);
}
private _fixGitPath(filePath): string {
if (filePath.substr(0, 1) == '"') {
filePath = filePath.substr(1);
}
if (filePath.substr(filePath.length - 1, 1) == '"') {
filePath = filePath.substr(0, filePath.length - 1);
}
return filePath;
}
} | the_stack |
'use strict';
declare var define;
interface ICopyFunc {
<T>(value: T, propName: string): T;
}
interface IIassignOption {
freeze?: boolean; // Deep freeze both input and output
freezeInput?: boolean; // Deep freeze input
freezeOutput?: boolean; // Deep freeze output
useConstructor?: boolean; // Uses the constructor to create new instances
copyFunc?: ICopyFunc; // Custom copy function, can be used to handle special types, e.g., Map, Set
disableAllCheck?: boolean;
disableHasReturnCheck?: boolean;
// Disable validation for extra statements in the getProp() function,
// which is needed when running the coverage, e.g., istanbul.js does add
// instrument statements in our getProp() function, which can be safely ignored.
disableExtraStatementCheck?: boolean;
// Default: 100
maxGetPropCacheSize?: number;
// Return the same object if setProp() returns its parameter (i.e., reference pointer not changed).
ignoreIfNoChange?: boolean;
}
type getPropFunc<TObj, TProp, TContext> = (
obj: TObj,
context: TContext
) => TProp;
type setPropFunc<TProp> = (prop: TProp) => TProp;
interface IIassign extends IIassignOption {
// Intellisense for the TObj parameter in getProp will only work if we remove the auto added closing bracket of iassign,
// and manually add the closing bracket at last. i.e.,
//
// 1. Type iassign( in the editor
// 2. Most editor will auto complete with closing bracket, e.g., iassign()
// 3. If we continue to type without removing the closing bracket, e.g., iassign(nested, (n) => n.),
// editor such as VS Code will not show any intellisense for "n"
// 4. We must remove the closing bracket of iassign(), and intellisense will be shown for "n"
<TObj>(obj: TObj, setProp: setPropFunc<TObj>, option?: IIassignOption): TObj;
<TObj, TProp, TContext>(
obj: TObj,
getProp: getPropFunc<TObj, TProp, TContext>,
setProp: setPropFunc<TProp>,
context?: TContext,
option?: IIassignOption
): TObj;
<TObj, TProp, TContext>(
obj: TObj,
propPaths: (string | number)[],
setProp: setPropFunc<TProp>,
context?: TContext,
option?: IIassignOption
): TObj;
// functional programming friendly style, moved obj to the last parameter and supports currying
fp<TObj, TProp, TContext>(
option: IIassignOption,
getPropOrPropPath: getPropFunc<TObj, TProp, TContext> | (string | number)[],
setProp: setPropFunc<TProp>,
context?: TContext,
obj?: TObj
): TObj;
// In ES6, you cannot set property on imported module directly, because they are default
// to readonly, in this case you need to use this method.
setOption(option: IIassignOption);
deepFreeze<T>(obj: T): T;
// ES6 default export
default: IIassign;
}
(function(root: any, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
try {
var deepFreeze: DeepFreeze.DeepFreezeInterface = require('deep-freeze-strict');
} catch (ex) {
console.warn(
'Cannot load deep-freeze-strict module, however you can still use iassign() function.'
);
}
const v = factory(deepFreeze, exports);
if (v !== undefined) module.exports = v;
} else if (typeof define === 'function' && define.amd) {
define(['deep-freeze-strict', 'exports'], factory);
} else {
// Browser globals (root is window)
root.iassign = factory(root.deepFreeze, {});
}
})(this, function(deepFreeze, exports) {
const autoCurry = (function() {
const toArray = function toArray(arr, from?) {
return Array.prototype.slice.call(arr, from || 0);
};
const curry = function curry(fn /* variadic number of args */) {
const args = toArray(arguments, 1);
return function curried() {
return fn.apply(undefined, args.concat(toArray(arguments)));
};
};
return function autoCurry(fn, numArgs?) {
numArgs = numArgs || fn.length;
return function autoCurried() {
if (arguments.length < numArgs) {
return numArgs - arguments.length > 0
? autoCurry(
curry.apply(undefined, [fn].concat(toArray(arguments))),
numArgs - arguments.length
)
: curry.apply(undefined, [fn].concat(toArray(arguments)));
} else {
return fn.apply(undefined, arguments);
}
};
};
})();
const iassign: IIassign = <any>_iassign;
iassign.fp = autoCurry(_iassignFp);
iassign.maxGetPropCacheSize = 100;
iassign.freeze =
typeof process !== 'undefined' && process.env.NODE_ENV !== 'production';
iassign.setOption = function(option) {
copyOption(iassign, option);
};
// Immutable Assign
function _iassign<TObj, TProp, TContext>(
obj: TObj, // Object to set property, it will not be modified.
getPropOrSetPropOrPaths:
| getPropFunc<TObj, TProp, TContext>
| setPropFunc<TProp>
| (string | number)[], // Function to get property to be updated. Must be pure function.
setPropOrOption: setPropFunc<TProp> | IIassignOption, // Function to set property.
contextOrUndefined?: TContext, // (Optional) Context to be used in getProp().
optionOrUndefined?: IIassignOption
): TObj {
let getProp = <getPropFunc<TObj, TProp, TContext>>getPropOrSetPropOrPaths;
let propPaths = undefined;
let setProp = <setPropFunc<TProp>>setPropOrOption;
let context = contextOrUndefined;
let option = optionOrUndefined;
if (typeof setPropOrOption !== 'function') {
getProp = undefined;
setProp = <setPropFunc<TProp>>getPropOrSetPropOrPaths;
context = undefined;
option = <IIassignOption>setPropOrOption;
} else {
if (getProp instanceof Array) {
propPaths = getProp;
}
}
option = copyOption(undefined, option, iassign);
if (deepFreeze && (option.freeze || option.freezeInput)) {
deepFreeze(obj);
}
if (!getProp) {
let newValue = undefined;
if (option.ignoreIfNoChange) {
newValue = setProp(<any>obj);
if (<any>newValue === <any>obj) {
return obj;
}
}
obj = quickCopy(obj, undefined, option.useConstructor, option.copyFunc);
obj = option.ignoreIfNoChange ? newValue : <any>setProp(<any>obj);
} else {
let newValue = undefined;
if (!propPaths) {
if (option.ignoreIfNoChange) {
// Check if getProp() is valid
let value = getProp(obj, context);
newValue = setProp(value);
if (newValue === value) {
return obj;
}
}
let funcText = getProp.toString();
let arrowIndex = funcText.indexOf('=>');
if (arrowIndex <= -1) {
let returnIndex = funcText.indexOf('return ');
if (returnIndex <= -1) {
throw new Error('getProp() function does not return a part of obj');
}
}
propPaths = getPropPath(getProp, obj, context, option);
} else {
if (option.ignoreIfNoChange) {
// Check if getProp() is valid
let value = getPropByPaths(obj, propPaths);
newValue = setProp(value);
if (newValue === value) {
return obj;
}
}
}
if (!propPaths) {
throw new Error('getProp() function does not return a part of obj');
}
obj = updateProperty(obj, setProp, newValue, context, propPaths, option);
}
if (deepFreeze && (option.freeze || option.freezeOutput)) {
deepFreeze(obj);
}
return obj;
}
function _iassignFp<
TObj,
TProp,
TContext
>(option: IIassignOption, getProp: getPropFunc<TObj, TProp, TContext>, setProp: setPropFunc<TProp>, context?: TContext, obj?: TObj): TObj {
return _iassign<
TObj,
TProp,
TContext
>(obj, getProp, setProp, context, option);
}
function getPropPath<
TObj,
TProp,
TContext
>(getProp: getPropFunc<TObj, TProp, TContext>, obj: TObj, context: TContext, option: IIassignOption): string[] {
let paths = [];
let objCopy;
let propValue;
if (typeof Proxy === 'undefined') {
propValue = getProp(obj, context);
objCopy = _getPropPathViaProperty(obj, paths);
} else {
objCopy = _getPropPathViaProxy(obj, paths);
}
getProp(objCopy, context);
// Check propValue === undefined for performance
if (typeof Proxy === 'undefined' && propValue === undefined) {
const functionInfo = parseGetPropFuncInfo(getProp, option);
if (paths.length != functionInfo.funcTokens.length - 1) {
const remainingFunctionTokens = functionInfo.funcTokens.slice(
paths.length + 1
);
for (const token of remainingFunctionTokens) {
if (
token.propNameSource == ePropNameSource.inBracket &&
isNaN(<any>token.propName)
) {
throw new Error(
`Cannot handle ${
token.propName
} when the property it point to is undefined.`
);
}
}
paths = [...paths, ...remainingFunctionTokens.map((s) => s.propName)];
}
}
return paths;
}
function _getPropPathViaProperty(obj, paths: string[], level = 0): any {
let objCopy = quickCopy(obj, paths[level - 1]);
const propertyNames = getOwnPropertyNames(obj);
propertyNames.forEach(function(propKey) {
const descriptor = Object.getOwnPropertyDescriptor(obj, propKey);
if (descriptor && (!(obj instanceof Array) || propKey != 'length')) {
const copyDescriptor = {
enumerable: descriptor.enumerable,
configurable: false,
get: function() {
if (level == paths.length) {
paths.push(propKey);
let propValue = obj[propKey];
if (propValue != undefined) {
return _getPropPathViaProperty(propValue, paths, level + 1);
}
}
return obj[propKey];
}
};
Object.defineProperty(objCopy, propKey, copyDescriptor);
}
});
return objCopy;
}
function _getPropPathViaProxy(obj, paths: string[], level = 0): any {
const handlers = {
get: (target: any, propKey: string) => {
let propValue = obj[propKey];
if (level == paths.length) {
paths.push(propKey);
if (typeof propValue === 'object' && propValue != null) {
return _getPropPathViaProxy(propValue, paths, level + 1);
}
}
return propValue;
}
};
return new Proxy(quickCopy(obj, paths[level - 1]), handlers);
}
// For performance
function copyOption(
target: IIassignOption = {},
option: IIassignOption,
defaultOption?: IIassignOption
) {
if (defaultOption) {
target.freeze = defaultOption.freeze;
target.freezeInput = defaultOption.freezeInput;
target.freezeOutput = defaultOption.freezeOutput;
target.useConstructor = defaultOption.useConstructor;
target.copyFunc = defaultOption.copyFunc;
target.disableAllCheck = defaultOption.disableAllCheck;
target.disableHasReturnCheck = defaultOption.disableHasReturnCheck;
target.disableExtraStatementCheck =
defaultOption.disableExtraStatementCheck;
target.maxGetPropCacheSize = defaultOption.maxGetPropCacheSize;
target.ignoreIfNoChange = defaultOption.ignoreIfNoChange;
}
if (option) {
if (option.freeze != undefined) {
target.freeze = option.freeze;
}
if (option.freezeInput != undefined) {
target.freezeInput = option.freezeInput;
}
if (option.freezeOutput != undefined) {
target.freezeOutput = option.freezeOutput;
}
if (option.useConstructor != undefined) {
target.useConstructor = option.useConstructor;
}
if (option.copyFunc != undefined) {
target.copyFunc = option.copyFunc;
}
if (option.disableAllCheck != undefined) {
target.disableAllCheck = option.disableAllCheck;
}
if (option.disableHasReturnCheck != undefined) {
target.disableHasReturnCheck = option.disableHasReturnCheck;
}
if (option.disableExtraStatementCheck != undefined) {
target.disableExtraStatementCheck = option.disableExtraStatementCheck;
}
if (option.maxGetPropCacheSize != undefined) {
target.maxGetPropCacheSize = option.maxGetPropCacheSize;
}
if (option.ignoreIfNoChange != undefined) {
target.ignoreIfNoChange = option.ignoreIfNoChange;
}
}
return target;
}
function updateProperty<
TObj,
TProp,
TContext
>(obj: TObj, setProp: setPropFunc<TProp>, newValue: TProp, context: TContext, propPaths: string[], option: IIassignOption): TObj {
let propValue: any = quickCopy(
obj,
undefined,
option.useConstructor,
option.copyFunc
);
obj = propValue;
if (!propPaths.length) {
return option.ignoreIfNoChange ? newValue : (setProp(propValue) as any);
}
for (let propIndex = 0; propIndex < propPaths.length; ++propIndex) {
const propName = propPaths[propIndex];
const isLast = propIndex + 1 === propPaths.length;
const prevPropValue = propValue;
propValue = propValue[propName];
propValue = quickCopy(
propValue,
propName,
option.useConstructor,
option.copyFunc
);
if (isLast) {
propValue = option.ignoreIfNoChange ? newValue : setProp(propValue);
}
prevPropValue[propName] = propValue;
}
return obj;
}
function quickCopy<
T
>(value: T, propName?: string, useConstructor?: boolean, copyFunc?: ICopyFunc): T {
if (value != undefined && !(value instanceof Date)) {
if (value instanceof Array) {
return (<any>value).slice();
} else if (typeof value === 'object') {
if (useConstructor) {
const target = new (value as any).constructor();
return extend(target, value);
} else if (copyFunc) {
let newValue = copyFunc(value, propName);
if (newValue != undefined) return newValue;
}
return extend({}, value);
}
}
return value;
}
function extend(destination: any, source) {
for (let key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key)) {
continue;
}
let value = source[key];
destination[key] = value;
}
return destination;
}
interface IGetPropFuncToken {
propName: string;
propNameSource: ePropNameSource;
subAccessorText: string;
getPropName?: (obj, context) => string;
}
enum ePropNameSource {
none,
beforeDot,
beforeBracket,
inBracket,
last
}
interface IGetPropFuncInfo extends IParsedTextInQuotes {
objParameterName: string;
cxtParameterName: string;
bodyText: string;
funcTokens: IGetPropFuncToken[];
}
interface IParsedTextInQuotes {
accessorText: string;
quotedTextInfos: { [key: string]: string };
}
let getPropCaches: { [key: string]: IGetPropFuncInfo } = {};
let getPropCacheKeys: string[] = [];
function parseGetPropFuncInfo(
func: Function,
option: IIassignOption
): IGetPropFuncInfo {
let funcText = func.toString();
let cacheKey = funcText + JSON.stringify(option);
let info = getPropCaches[cacheKey];
if (getPropCaches[cacheKey]) {
return info;
}
let matches = /\(([^\)]*)\)/.exec(funcText);
let objParameterName = undefined;
let cxtParameterName = undefined;
if (matches) {
let parametersText = matches[1];
let parameters = parametersText.split(',');
objParameterName = parameters[0];
cxtParameterName = parameters[1];
}
if (objParameterName) {
objParameterName = objParameterName.trim();
}
if (cxtParameterName) {
cxtParameterName = cxtParameterName.trim();
}
let bodyStartIndex = funcText.indexOf('{');
let bodyEndIndex = funcText.lastIndexOf('}');
let bodyText = '';
if (bodyStartIndex > -1 && bodyEndIndex > -1) {
bodyText = funcText.substring(bodyStartIndex + 1, bodyEndIndex);
} else {
let arrowIndex = funcText.indexOf('=>');
if (arrowIndex > -1) {
//console.log("Handle arrow function.");
bodyText = 'return ' + funcText.substring(arrowIndex + 3);
} else {
throw new Error(`Cannot parse function: ${funcText}`);
}
}
let accessorTextInfo = getAccessorTextInfo(bodyText, option);
info = {
objParameterName: objParameterName,
cxtParameterName: cxtParameterName,
bodyText: bodyText,
accessorText: accessorTextInfo.accessorText,
quotedTextInfos: accessorTextInfo.quotedTextInfos,
funcTokens: parseGetPropFuncTokens(accessorTextInfo.accessorText)
};
if (option.maxGetPropCacheSize > 0) {
getPropCaches[cacheKey] = info;
getPropCacheKeys.push(cacheKey);
if (getPropCacheKeys.length > option.maxGetPropCacheSize) {
let cacheKeyToRemove = getPropCacheKeys.shift();
delete getPropCaches[cacheKeyToRemove];
}
}
return info;
}
function parseGetPropFuncTokens(accessorText: string): IGetPropFuncToken[] {
let tokens: IGetPropFuncToken[] = [];
while (accessorText) {
let openBracketIndex = accessorText.indexOf('[');
let closeBracketIndex = accessorText.indexOf(']');
let dotIndex = accessorText.indexOf('.');
let propName = '';
let propNameSource = ePropNameSource.none;
// if (dotIndex == 0) {
// accessorText = accessorText.substr(dotIndex + 1);
// continue;
// }
if (openBracketIndex > -1 && closeBracketIndex <= -1) {
throw new Error('Found open bracket but not close bracket.');
}
if (openBracketIndex <= -1 && closeBracketIndex > -1) {
throw new Error('Found close bracket but not open bracket.');
}
if (
dotIndex > -1 &&
(dotIndex < openBracketIndex || openBracketIndex <= -1)
) {
propName = accessorText.substr(0, dotIndex);
accessorText = accessorText.substr(dotIndex + 1);
propNameSource = ePropNameSource.beforeDot;
} else if (
openBracketIndex > -1 &&
(openBracketIndex < dotIndex || dotIndex <= -1)
) {
if (openBracketIndex > 0) {
propName = accessorText.substr(0, openBracketIndex);
accessorText = accessorText.substr(openBracketIndex);
propNameSource = ePropNameSource.beforeBracket;
} else {
propName = accessorText.substr(
openBracketIndex + 1,
closeBracketIndex - 1
);
accessorText = accessorText.substr(closeBracketIndex + 1);
propNameSource = ePropNameSource.inBracket;
}
} else {
propName = accessorText;
accessorText = '';
propNameSource = ePropNameSource.last;
}
propName = propName.trim();
if (propName == '') {
continue;
}
//console.log(propName);
tokens.push({
propName,
propNameSource,
subAccessorText: accessorText
});
}
return tokens;
}
function getAccessorTextInfo(bodyText: string, option: IIassignOption) {
let returnIndex = bodyText.indexOf('return ');
if (!option.disableAllCheck && !option.disableHasReturnCheck) {
if (returnIndex <= -1) {
throw new Error("getProp() function has no 'return' keyword.");
}
}
if (!option.disableAllCheck && !option.disableExtraStatementCheck) {
let otherBodyText = bodyText.substr(0, returnIndex);
otherBodyText = otherBodyText.replace(/['"]use strict['"];*/g, '');
otherBodyText = otherBodyText.trim();
if (otherBodyText != '') {
throw new Error(
"getProp() function has statements other than 'return': " +
otherBodyText
);
}
}
let accessorText = bodyText.substr(returnIndex + 7).trim();
if (accessorText[accessorText.length - 1] == ';') {
accessorText = accessorText.substring(0, accessorText.length - 1);
}
accessorText = accessorText.trim();
return parseTextInQuotes(accessorText, option);
}
function parseTextInQuotes(
accessorText,
option: IIassignOption
): IParsedTextInQuotes {
let quotedTextInfos: { [key: string]: string } = {};
let index = 0;
while (true) {
let singleQuoteIndex = accessorText.indexOf("'");
let doubleQuoteIndex = accessorText.indexOf('"');
let varName = '#' + index++;
if (singleQuoteIndex <= -1 && doubleQuoteIndex <= -1) break;
let matches: RegExpExecArray = undefined;
let quoteIndex: number;
if (
doubleQuoteIndex > -1 &&
(doubleQuoteIndex < singleQuoteIndex || singleQuoteIndex <= -1)
) {
matches = /("[^"\\]*(?:\\.[^"\\]*)*")/.exec(accessorText);
quoteIndex = doubleQuoteIndex;
} else if (
singleQuoteIndex > -1 &&
(singleQuoteIndex < doubleQuoteIndex || doubleQuoteIndex <= -1)
) {
matches = /('[^'\\]*(?:\\.[^'\\]*)*')/.exec(accessorText);
quoteIndex = singleQuoteIndex;
}
if (matches) {
quotedTextInfos[varName] = matches[1];
accessorText =
accessorText.substr(0, quoteIndex) +
varName +
accessorText.substr(matches.index + matches[1].length);
} else {
throw new Error('Invalid text in quotes: ' + accessorText);
}
}
return {
accessorText,
quotedTextInfos
};
}
iassign.default = iassign;
iassign.deepFreeze = (obj) => (iassign.freeze ? deepFreeze(obj) : obj);
return iassign;
});
function getPropByPaths(obj, paths: (string | number)[]) {
paths = paths.slice();
let value = obj;
while (paths.length > 0) {
let path = paths.shift();
value = value[path];
}
return value;
}
// Android 5: Object.getOwnPropertyNames does not support primitive values gracefully.
function getOwnPropertyNames(obj: any) {
if (typeof obj !== 'object') {
return [];
}
return Object.getOwnPropertyNames(obj);
} | the_stack |
declare module "epsilon" {
const _exports: number;
export = _exports;
}
declare module "create" {
export = create;
/**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/
function create(): any;
}
declare module "clone" {
export = clone;
/**
* Creates a new vec3 initialized with values from an existing vector
*
* @param {vec3} a vector to clone
* @returns {vec3} a new 3D vector
*/
function clone(a: any): any;
}
declare module "fromValues" {
export = fromValues;
/**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/
function fromValues(x: number, y: number, z: number): any;
}
declare module "normalize" {
export = normalize;
/**
* Normalize a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to normalize
* @returns {vec3} out
*/
function normalize(out: any, a: any): any;
}
declare module "dot" {
export = dot;
/**
* Calculates the dot product of two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a: any, b: any): number;
}
declare module "angle" {
export = angle;
/**
* Get the angle between two 3D vectors
* @param {vec3} a The first operand
* @param {vec3} b The second operand
* @returns {Number} The angle in radians
*/
function angle(a: any, b: any): number;
}
declare module "copy" {
export = copy;
/**
* Copy the values from one vec3 to another
*
* @param {vec3} out the receiving vector
* @param {vec3} a the source vector
* @returns {vec3} out
*/
function copy(out: any, a: any): any;
}
declare module "set" {
export = set;
/**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} out
*/
function set(out: any, x: number, y: number, z: number): any;
}
declare module "equals" {
export = equals;
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function equals(a: any, b: any): boolean;
}
declare module "exactEquals" {
export = exactEquals;
/**
* Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function exactEquals(a: any, b: any): boolean;
}
declare module "add" {
export = add;
/**
* Adds two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function add(out: any, a: any, b: any): any;
}
declare module "subtract" {
export = subtract;
/**
* Subtracts vector b from vector a
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function subtract(out: any, a: any, b: any): any;
}
declare module "sub" {
const _exports: typeof import("subtract");
export = _exports;
}
declare module "multiply" {
export = multiply;
/**
* Multiplies two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function multiply(out: any, a: any, b: any): any;
}
declare module "mul" {
const _exports: typeof import("multiply");
export = _exports;
}
declare module "divide" {
export = divide;
/**
* Divides two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function divide(out: any, a: any, b: any): any;
}
declare module "div" {
const _exports: typeof import("divide");
export = _exports;
}
declare module "min" {
export = min;
/**
* Returns the minimum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function min(out: any, a: any, b: any): any;
}
declare module "max" {
export = max;
/**
* Returns the maximum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function max(out: any, a: any, b: any): any;
}
declare module "floor" {
export = floor;
/**
* Math.floor the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to floor
* @returns {vec3} out
*/
function floor(out: any, a: any): any;
}
declare module "ceil" {
export = ceil;
/**
* Math.ceil the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to ceil
* @returns {vec3} out
*/
function ceil(out: any, a: any): any;
}
declare module "round" {
export = round;
/**
* Math.round the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to round
* @returns {vec3} out
*/
function round(out: any, a: any): any;
}
declare module "scale" {
export = scale;
/**
* Scales a vec3 by a scalar number
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec3} out
*/
function scale(out: any, a: any, b: number): any;
}
declare module "scaleAndAdd" {
export = scaleAndAdd;
/**
* Adds two vec3's after scaling the second operand by a scalar value
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec3} out
*/
function scaleAndAdd(out: any, a: any, b: any, scale: number): any;
}
declare module "distance" {
export = distance;
/**
* Calculates the euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} distance between a and b
*/
function distance(a: any, b: any): number;
}
declare module "dist" {
const _exports: typeof import("distance");
export = _exports;
}
declare module "squaredDistance" {
export = squaredDistance;
/**
* Calculates the squared euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} squared distance between a and b
*/
function squaredDistance(a: any, b: any): number;
}
declare module "sqrDist" {
const _exports: typeof import("squaredDistance");
export = _exports;
}
declare module "length" {
export = length;
/**
* Calculates the length of a vec3
*
* @param {vec3} a vector to calculate length of
* @returns {Number} length of a
*/
function length(a: any): number;
}
declare module "len" {
const _exports: typeof import("length");
export = _exports;
}
declare module "squaredLength" {
export = squaredLength;
/**
* Calculates the squared length of a vec3
*
* @param {vec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
function squaredLength(a: any): number;
}
declare module "sqrLen" {
const _exports: typeof import("squaredLength");
export = _exports;
}
declare module "negate" {
export = negate;
/**
* Negates the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to negate
* @returns {vec3} out
*/
function negate(out: any, a: any): any;
}
declare module "inverse" {
export = inverse;
/**
* Returns the inverse of the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to invert
* @returns {vec3} out
*/
function inverse(out: any, a: any): any;
}
declare module "cross" {
export = cross;
/**
* Computes the cross product of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function cross(out: any, a: any, b: any): any;
}
declare module "lerp" {
export = lerp;
/**
* Performs a linear interpolation between two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
function lerp(out: any, a: any, b: any, t: number): any;
}
declare module "random" {
export = random;
/**
* Generates a random vector with the given scale
*
* @param {vec3} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec3} out
*/
function random(out: any, scale?: number): any;
}
declare module "transformMat4" {
export = transformMat4;
/**
* Transforms the vec3 with a mat4.
* 4th vector component is implicitly '1'
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec3} out
*/
function transformMat4(out: any, a: any, m: any): any;
}
declare module "transformMat3" {
export = transformMat3;
/**
* Transforms the vec3 with a mat3.
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m the 3x3 matrix to transform with
* @returns {vec3} out
*/
function transformMat3(out: any, a: any, m: any): any;
}
declare module "transformQuat" {
export = transformQuat;
/**
* Transforms the vec3 with a quat
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec3} out
*/
function transformQuat(out: any, a: any, q: any): any;
}
declare module "rotateX" {
export = rotateX;
/**
* Rotate a 3D vector around the x-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateX(out: any, a: any, b: any, c: number): any;
}
declare module "rotateY" {
export = rotateY;
/**
* Rotate a 3D vector around the y-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateY(out: any, a: any, b: any, c: number): any;
}
declare module "rotateZ" {
export = rotateZ;
/**
* Rotate a 3D vector around the z-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateZ(out: any, a: any, b: any, c: number): any;
}
declare module "forEach" {
export = forEach;
/**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
function forEach(a: any[], stride: number, offset: number, count: number, fn: Function, arg?: any): any[];
}
declare module "gl-vec3" {
export const EPSILON: number;
export const create: typeof import("create");
export const clone: typeof import("clone");
export const angle: typeof import("angle");
export const fromValues: typeof import("fromValues");
export const copy: typeof import("copy");
export const set: typeof import("set");
export const equals: typeof import("equals");
export const exactEquals: typeof import("exactEquals");
export const add: typeof import("add");
export const subtract: typeof import("subtract");
export const sub: typeof import("subtract");
export const multiply: typeof import("multiply");
export const mul: typeof import("multiply");
export const divide: typeof import("divide");
export const div: typeof import("divide");
export const min: typeof import("min");
export const max: typeof import("max");
export const floor: typeof import("floor");
export const ceil: typeof import("ceil");
export const round: typeof import("round");
export const scale: typeof import("scale");
export const scaleAndAdd: typeof import("scaleAndAdd");
export const distance: typeof import("distance");
export const dist: typeof import("distance");
export const squaredDistance: typeof import("squaredDistance");
export const sqrDist: typeof import("squaredDistance");
export const length: typeof import("length");
export const len: typeof import("length");
export const squaredLength: typeof import("squaredLength");
export const sqrLen: typeof import("squaredLength");
export const negate: typeof import("negate");
export const inverse: typeof import("inverse");
export const normalize: typeof import("normalize");
export const dot: typeof import("dot");
export const cross: typeof import("cross");
export const lerp: typeof import("lerp");
export const random: typeof import("random");
export const transformMat4: typeof import("transformMat4");
export const transformMat3: typeof import("transformMat3");
export const transformQuat: typeof import("transformQuat");
export const rotateX: typeof import("rotateX");
export const rotateY: typeof import("rotateY");
export const rotateZ: typeof import("rotateZ");
export const forEach: typeof import("forEach");
} | the_stack |
module Tests {
"use strict";
var List = WinJS.Binding.List;
var join = WinJS.Promise.join;
function post(v) {
return WinJS.Promise.timeout().
then(function () { return v; });
}
function errorHandler(msg) {
try {
LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg);
} catch (ex) { }
}
function range(l, h) {
var res = [];
for (; l < h; l++) {
res.push(l);
}
return res;
}
function asyncSequence(workFunctions) {
return workFunctions.reduce(function (p, work) {
return WinJS.Promise.as(p).then(function () {
return WinJS.Promise.as(work()).then(function () { return WinJS.Promise.timeout(); });
});
}, WinJS.Promise.wrap());
}
var seed = 0;
function rand(nMax) {
seed = (seed + 0.81282849124) * 2375.238208308;
seed -= Math.floor(seed);
return Math.floor(seed * nMax);
}
function moveRandom(list) {
var target = rand(list.length);
var source = rand(list.length);
list.move(source, target);
}
function spliceRandom(list) {
var target = rand(list.length);
var element = { title: target, detail: "New Item spliced at " + target };
list.splice(target, 0, element);
}
function setAtRandom(list) {
var target = rand(list.length);
var oldElement = list.getAt(target);
var newElement = {
title: oldElement.title,
detail: oldElement.title + " additional(" + target + ")"
};
list.setAt(target, newElement);
}
function unshiftAndShiftRandom(list, order, iteration) {
iteration = iteration;
var shift = true;
if (order && order.length) {
shift = order.pop() ? false : true;
} else {
shift = rand(2) ? false : true;
}
if (shift && list.length) {
var element = list.shift();
} else {
var newElement = {
title: iteration,
detail: "New element unshifted on, iteration: " + iteration
};
list.unshift(newElement);
}
}
function pushAndPopRandom(list, order, iteration) {
iteration = iteration || 0;
var pop = true;
if (order && order.length) {
pop = order.pop() ? false : true;
} else {
pop = rand(2) ? false : true;
}
if (pop && list.length) {
list.pop();
} else {
var newElement = {
title: iteration,
detail: "New element pushed on, iteration: " + iteration.toString()
};
list.push(newElement);
}
}
function setAtRandomSpecial(list) {
var target = rand(list.length);
var oldElement = list.getAt(target);
var newElement = {
title: list.getAt(target).title + 2,
detail: oldElement.title + " additional(" + target + ")"
};
list.setAt(target, newElement);
list.notifyMutated(target);
}
function resetSeed() {
seed = 0;
}
function verifyFlipView(flipView, list, obj?) {
flipView = flipView.winControl;
//var length = flipView.count()._value // for length
var length = flipView._dataSource.getCount()._value;
for (var i = 0; i < length; i++) {
var fvElement = flipView.itemDataSource.itemFromIndex(i)._value.data;
var listElement = list.getAt(i);
var objectShape = obj || listElement;
for (var j in objectShape) {
LiveUnit.Assert.areEqual(listElement[j], fvElement[j], "checking the correctness of the flipView element");
if (listElement[j] !== fvElement[j]) {
return false;
}
}
}
return list.length === length;
}
function parent(element) {
document.body.appendChild(element);
element.cleanup = function () {
WinJS.Utilities.disposeSubTree(element);
document.body.removeChild(element);
};
return element;
}
function createDataSource(dataSource) {
var holder: any = document.createElement("div");
holder.msParentSelectorScope = true;
holder.className = "dataSource";
holder.dataSource = dataSource;
return holder;
}
function createTemplate() {
var holder: any = document.createElement("div");
holder.msParentSelectorScope = true;
holder.id = "testTemplateWithFlipView";
holder.innerHTML = '<div class="sampleTemplate" data-win-control="WinJS.Binding.Template" style="display: none">' +
'<div>' +
'<div data-win-bind="textContent: title" ></div>' +
'<div data-win-bind="textContent: detail"></div>' +
'</div>' +
'</div>';
return holder;
}
function createTemplateWithViewBox() {
var holder: any = document.createElement("div");
holder.msParentSelectorScope = true;
holder.id = "testTemplateWithFlipView";
holder.innerHTML = '<div class="sampleTemplate" data-win-control="WinJS.Binding.Template" style="display: none">' +
'<div data-win-control="WinJS.UI.ViewBox">' +
'<div style="width:25px;height:25px" class="viewBoxInstance">' +
'<div data-win-bind="textContent: title" ></div>' +
'<div data-win-bind="textContent: detail"></div>' +
'</div>' +
'</div>' +
'</div>';
return holder;
}
function createFlipView() {
var holder: any = document.createElement("div");
holder.msParentSelectorScope = true;
holder.cssText = "height:50%;width:50%;overflow:scroll";
var flipView = document.createElement("div");
flipView.className = "flipViewExample";
flipView.setAttribute("data-win-control", "WinJS.UI.FlipView ");
flipView.setAttribute("data-win-options", "{itemDataSource : select('.dataSource').dataSource , layout:{type:WinJS.UI.ListLayout}, itemTemplate: select('.sampleTemplate') } ");
flipView.style.height = "200px";
flipView.style.width = "100px";
holder.appendChild(flipView);
return holder;
}
function createTestElements(dataSource, templateFactory?) {
templateFactory = templateFactory || createTemplate;
var holder = document.createElement("div");
holder.appendChild(createDataSource(dataSource));
holder.appendChild(templateFactory());
holder.appendChild(createFlipView());
return holder;
}
export class FlipViewIntegrationTestingWithBindingList {
testFlipWithViewBox = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Javascript Toolkit_" + i }; });
var list = new WinJS.Binding.List(sampleDataSource);
var elements = parent(createTestElements(list.dataSource, createTemplateWithViewBox));
var flipView = elements.querySelector(".flipViewExample");
WinJS.UI.processAll().
then(function () {
return waitForFlipViewReady(flipView);
}).
then(function () {
// pagecompleted only guarantees the first page will be rendered
var view = elements.querySelector(".viewBoxInstance");
LiveUnit.Assert.areEqual("25px", view.style.height);
LiveUnit.Assert.areEqual("25px", view.style.width);
LiveUnit.Assert.areEqual("translate(0px, 50px) scale(4)", view.style[WinJS.Utilities._browserStyleEquivalents["transform"].scriptName]);
LiveUnit.Assert.areEqual("0px 0px", getComputedStyle(view)[WinJS.Utilities._browserStyleEquivalents["transform-origin"].scriptName]);
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testReversingAndSortingFlipView = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Javascript Toolkit_" + i }; });
var list = new WinJS.Binding.List(sampleDataSource);
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
WinJS.UI.processAll().
then(post).
then(function () {
list.reverse();
// listView.winControl.forceLayout();
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of reverse");
list.sort(function (l, r) { return l.title - r.title; });
//listView.winControl.forceLayout();
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "check the correctness of sort");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithEmptyFiltered = function (complete) {
var sampleDataSource = [];
var sorted = new WinJS.Binding.List(sampleDataSource);
var list = sorted.createFiltered(function (num) { return num.title % 2 === 0 });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
WinJS.UI.processAll().
then(post).
then(function () {
list.push({ title: 1, detail: "first element" });
flipView.winControl.forceLayout();
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "verfying the flipView filter empty insertion");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithOneElementAndThenDeletedAndThenAdded = function (complete) {
var sampleDataSource = [{ title: 3, detail: "hello world" }];
var sorted = new WinJS.Binding.List(sampleDataSource);
var list = sorted.createFiltered(function (num) { return num.title % 2 === 0 });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
WinJS.UI.processAll().
then(post).
then(function () {
list.pop();
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of popping the last element");
list.push({ title: 2, detail: "hello world2" });
flipView.winControl.forceLayout();
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of pushing the first element");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithBindingEnabledInSortedList = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var list = new WinJS.Binding.List(sampleDataSource, { binding: true });
var objToCompare = { title: 1, detail: "temp" };
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
function assertFlipView(i) {
return function () {
list.getAt(i).detail = list.getAt(i).detail + '_' + i;
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(10, list.length).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list, objToCompare), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithBindingAndFiltered = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var objToCompare = { title: 1, detail: 1 };
var sort = new WinJS.Binding.List(sampleDataSource, { binding: true });
var list = sort.createFiltered(function (num) { return (num.title % 2 === 0); });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
function assertFlipView(i) {
return function () {
if (list.getAt(i)) {
list.getAt(i).title = list.getAt(i).title + i + (i % 3);
list.notifyMutated(i);
}
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(0, list.length).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list, objToCompare), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithBindingAndSorted = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var objToCompare = { title: 1, detail: 1 };
var sort = new WinJS.Binding.List(sampleDataSource, { binding: true });
var list = sort.createSorted(function (l, r) { return l.title - r.title; });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
function assertFlipView(i) {
return function () {
list.getAt(i).title = list.getAt(i).title + i * 10;
list.notifyMutated(i);
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(0, list.length).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list, objToCompare), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewReplaceCurrentItem = function (complete) {
var sampleDataSource = range(0, 3).map(function (i) { return { title: i, detail: "hello world " + i }; });
var list = new WinJS.Binding.List(sampleDataSource);
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
WinJS.UI.processAll().
then(function () {
return WinJS.Promise.timeout(100).then(function () {
list.pop();
});
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithSortedProjectionSpecialCases = function (complete) {
var sampleDataSource = range(0, 10).map(function (i) { return { title: i, detail: "hello world " + i }; });
var sorted = new WinJS.Binding.List(sampleDataSource);
var list = sorted.createFiltered(function (num) { return num.title % 2 === 0 });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
function assertFlipView(i) {
return function () {
if (i <= 11) {
sorted.push({ title: i, detail: "hello world " + i });
}
else if (i < 14) {
list.push({ title: i, detail: "hello world " + i });
}
else if (i == 14) {
sorted.length = 6;
}
else {
list.length = 2;
}
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(10, 16).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithListMutations = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: "Corsica_" + i, detail: "Javascript Toolkit_" + i }; });
var list = new WinJS.Binding.List(sampleDataSource);
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
var order = [0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0];
function assertFlipView(i) {
return function () {
switch (rand(4)) {
case 0: spliceRandom(list); break;
case 1: moveRandom(list); break;
case 2: setAtRandom(list); break;
case 3: pushAndPopRandom(list, order, i); break;
default: throw "NYI";
}
};
}
WinJS.UI.processAll().
then(post).
then(function () {
return asyncSequence(range(0, 20).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithSortedListMutations = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var sorted = new WinJS.Binding.List(sampleDataSource);
var list = sorted.createSorted(function (l, r) { return l.title - r.title; });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
var order = [0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0];
function assertFlipView(i) {
return function () {
switch (rand(4)) {
case 0: spliceRandom(list); break;
case 1: moveRandom(list); break;
case 2: setAtRandom(list); break;
case 3: pushAndPopRandom(list, order, i); break;
default: throw "NYI";
}
};
}
WinJS.UI.processAll().
then(post).
then(function () {
return asyncSequence(range(0, 20).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewWithFilteredListMutation = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var sorted = new WinJS.Binding.List(sampleDataSource);
var list = sorted.createFiltered(function (num) { return num.title % 2 === 0 });
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
var order = [0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0];
function assertFlipView(i) {
return function () {
switch (rand(4)) {
case 0: spliceRandom(list); break;
case 1: moveRandom(list); break;
case 2: setAtRandomSpecial(list); break;
case 3: pushAndPopRandom(list, order, i); break;
default: throw "NYI";
}
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(0, 20).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
testFlipViewUsingGroupSortedWithMutations = function (complete) {
var sampleDataSource = range(0, 20).map(function (i) { return { title: i, detail: "Corsica_" + i }; });
var sorted = new WinJS.Binding.List(sampleDataSource);
var compare = function (num) { return (num.title % 2 === 0) ? "even" : "odd"; };
var list = sorted.createGrouped(compare, compare);
var elements = parent(createTestElements(list.dataSource));
var flipView = elements.querySelector(".flipViewExample");
var order = [0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0];
function assertFlipView(i) {
return function () {
switch (rand(4)) {
case 0: spliceRandom(list); break;
case 1: moveRandom(list); break;
case 2: setAtRandom(list); break;
case 3: pushAndPopRandom(list, order, i); break;
default: throw "NYI";
}
};
}
WinJS.UI.processAll().
then(function () {
return asyncSequence(range(0, 20).map(assertFlipView));
}).
then(post).
then(function () {
LiveUnit.Assert.isTrue(verifyFlipView(flipView, list), "checking the correctness of the flipView after all Mutations are over");
}).
then(null, errorHandler).
then(elements.cleanup).
then(resetSeed).
then(complete);
}
}
}
LiveUnit.registerTestClass("Tests.FlipViewIntegrationTestingWithBindingList"); | the_stack |
import { put, takeEvery, select, call } from 'redux-saga/effects';
import { v4 as uuid } from 'uuid';
import { fromImage } from 'imtool';
import { RSA } from 'matcrypt';
import {
ActionModel,
TransferModel,
TransferMessageModel,
NameMessageModel,
ActionMessageModel,
PingMessageModel,
Message,
ClientModel,
EncryptedMessageModel,
ChatMessageModel,
} from '../types/Models';
import { ActionType } from '../types/ActionType';
import { StateType } from '../reducers';
import transferSendFile from './transferSendFile';
import transferReceiveFile from './transferReceiveFile';
import { TransferState } from '../types/TransferState';
import {
setRemoteDescriptionAction,
removeTransferAction,
updateTransferAction,
addTransferAction,
addIceCandidateAction,
} from '../actions/transfers';
import {
connectAction,
messageAction,
sendMessageAction,
} from '../actions/websocket';
import {
setNetworkAction,
setRtcConfigurationAction,
setSuggestedNameAction,
setClientIdAction,
setClientColorAction,
setConnectedAction,
setMaxSizeAction,
setNoticeAction,
setKeyPairAction,
setNetworkNameAction,
addChatItemAction,
} from '../actions/state';
import { MessageType, ActionMessageActionType } from '../types/MessageType';
import { title } from '../config';
function* message(action: ActionModel, dispatch: (action: any) => void) {
const msg: Message = action.value as Message;
switch (msg.type) {
case MessageType.WELCOME:
yield put(setRtcConfigurationAction(msg.rtcConfiguration));
yield put(setSuggestedNameAction(msg.suggestedName));
yield put(setClientIdAction(msg.clientId));
yield put(setClientColorAction(msg.clientColor));
yield put(setMaxSizeAction(msg.maxSize));
yield put(setNoticeAction(msg.noticeText, msg.noticeUrl));
const networkName = yield select((state: StateType) => state.networkName);
if (networkName && networkName !== '') {
yield put(setNetworkNameAction(networkName));
}
break;
case MessageType.TRANSFER:
const transfer: TransferModel = {
fileName: msg.fileName,
fileType: msg.fileType,
fileSize: msg.fileSize,
transferId: msg.transferId,
clientId: msg.clientId,
state: TransferState.INCOMING,
preview: msg.preview?.startsWith('data:') ? msg.preview : undefined,
receiving: true,
};
yield put(addTransferAction(transfer));
break;
case MessageType.ACTION:
switch (msg.action) {
case ActionMessageActionType.CANCEL:
case ActionMessageActionType.REJECT:
yield put(removeTransferAction(msg.transferId));
break;
case ActionMessageActionType.ACCEPT:
yield call(() => transferSendFile(msg, dispatch));
break;
}
break;
case MessageType.NETWORK:
yield put(setNetworkAction(msg.clients));
break;
case MessageType.PING:
const pongMessage: PingMessageModel = {
type: MessageType.PING,
timestamp: new Date().getTime(),
};
yield put(sendMessageAction(pongMessage));
break;
case MessageType.RTC_DESCRIPTION:
if (msg.data.type === 'answer') {
yield put(setRemoteDescriptionAction(msg.transferId, msg.data));
} else {
yield call(() => transferReceiveFile(msg, dispatch));
}
break;
case MessageType.RTC_CANDIDATE:
yield put(addIceCandidateAction(msg.transferId, msg.data));
break;
case MessageType.CHAT:
const network: ClientModel[] = yield select(
(state: StateType) => state.network
);
const client = network.find(client => client.clientId === msg.clientId);
if (client) {
yield put(
addChatItemAction({
id: uuid(),
date: new Date(),
clientColor: client.clientColor,
clientId: client.clientId,
message: msg.message,
})
);
}
break;
case MessageType.ENCRYPTED:
const privateKey = yield select((state: StateType) => state.privateKey);
if (privateKey) {
try {
const json = JSON.parse(
yield call(
async () => await RSA.decryptString(privateKey, msg.payload)
)
);
if (json && json.type) {
if (msg.clientId) {
json.clientId = msg.clientId;
}
yield put(messageAction(json));
}
} catch {}
}
break;
}
}
function* prepareMessage(action: ActionModel) {
const msg = action.value as Message;
const secure = !!msg.secure;
delete msg['secure'];
if ('targetId' in msg) {
const network: ClientModel[] = yield select(
(state: StateType) => state.network
);
const target = network?.find(client => client.clientId === msg.targetId);
if (target && target.publicKey) {
try {
const payload: string = yield call(
async () =>
await RSA.encryptString(target.publicKey, JSON.stringify(msg))
);
const message: EncryptedMessageModel = {
type: MessageType.ENCRYPTED,
targetId: msg.targetId,
payload,
};
yield put({
type: ActionType.WS_SEND_MESSAGE,
value: message,
});
return;
} catch {}
}
}
if (secure) {
return;
}
yield put({
type: ActionType.WS_SEND_MESSAGE,
value: msg,
});
}
function* connected() {
yield put(setConnectedAction(true));
}
function* setName(action: ActionModel) {
const publicKey = yield select((state: StateType) => state.publicKey);
const message: NameMessageModel = {
type: MessageType.NAME,
networkName: action.value,
publicKey,
};
yield put(sendMessageAction(message));
}
function* disconnected() {
yield put(setConnectedAction(false));
}
function* createTransfer(action: ActionModel) {
const file: File = action.value.file;
let preview: string | undefined = undefined;
if (file.type.startsWith('image/')) {
const maxSize = yield select((state: StateType) => state.maxSize);
preview = yield call(async () => {
try {
const imtool = await fromImage(file);
imtool.thumbnail(100, true);
const url = await imtool.toDataURL();
// Ensure the URL isn't too long.
if (url.length < maxSize * 0.75) {
return url;
}
} catch {}
return undefined;
});
}
const transfer: TransferModel = {
file: file,
fileName: file.name,
fileSize: file.size,
fileType: file.type || 'application/octet-stream', // fileType is required by the server.
transferId: uuid(),
clientId: action.value.clientId,
state: TransferState.OUTGOING,
receiving: false,
preview,
};
yield put(addTransferAction(transfer));
const model: TransferMessageModel = {
type: MessageType.TRANSFER,
transferId: transfer.transferId,
fileName: transfer.fileName,
fileSize: transfer.fileSize,
fileType: transfer.fileType,
targetId: transfer.clientId,
preview,
};
yield put(sendMessageAction(model));
}
function* cancelTransfer(action: ActionModel) {
const transfers: TransferModel[] = yield select(
(state: StateType) => state.transfers
);
const filteredTransfers: TransferModel[] = transfers.filter(
transfer => transfer.transferId === action.value
);
if (filteredTransfers.length === 0) return;
const transfer = filteredTransfers[0];
if (!transfer) return;
if (transfer.peerConnection) {
try {
transfer.peerConnection.close();
} catch {}
}
const model: ActionMessageModel = {
type: MessageType.ACTION,
transferId: transfer.transferId,
targetId: transfer.clientId,
action: ActionMessageActionType.CANCEL,
};
yield put(sendMessageAction(model));
yield put(removeTransferAction(action.value));
}
function* acceptTransfer(action: ActionModel) {
const transfers: TransferModel[] = yield select(
(state: StateType) => state.transfers
);
const filteredTransfers: TransferModel[] = transfers.filter(
transfer =>
transfer.state === TransferState.INCOMING &&
transfer.transferId === action.value
);
if (filteredTransfers.length === 0) return;
const transfer = filteredTransfers[0];
if (!transfer) return;
const model: ActionMessageModel = {
type: MessageType.ACTION,
transferId: transfer.transferId,
targetId: transfer.clientId,
action: ActionMessageActionType.ACCEPT,
};
yield put(sendMessageAction(model));
yield put(
updateTransferAction({
transferId: action.value,
state: TransferState.CONNECTING,
})
);
}
function* rejectTransfer(action: ActionModel) {
const transfers: TransferModel[] = yield select(
(state: StateType) => state.transfers
);
const filteredTransfers: TransferModel[] = transfers.filter(
transfer =>
transfer.state === TransferState.INCOMING &&
transfer.transferId === action.value
);
if (filteredTransfers.length === 0) return;
const transfer = filteredTransfers[0];
if (!transfer) return;
const model: ActionMessageModel = {
type: MessageType.ACTION,
transferId: transfer.transferId,
targetId: transfer.clientId,
action: ActionMessageActionType.REJECT,
};
yield put(sendMessageAction(model));
yield put(removeTransferAction(action.value));
}
function* sendChatMessage(action: ActionModel) {
const message = action.value as string;
const clientId: string = yield select((state: StateType) => state.clientId);
const clientColor: string = yield select(
(state: StateType) => state.clientColor
);
const network: ClientModel[] = yield select(
(state: StateType) => state.network
);
for (const client of network) {
const model: ChatMessageModel = {
type: MessageType.CHAT,
targetId: client.clientId,
message,
secure: true,
};
yield put(sendMessageAction(model));
}
yield put(
addChatItemAction({
id: uuid(),
date: new Date(),
clientId,
clientColor,
message,
})
);
}
/**
* Called after the welcome screen is dismissed.
*/
function* welcomed() {
yield call(() => localStorage.setItem('welcomed', '1'));
}
function* updateNotificationCount() {
const transfers: TransferModel[] = yield select(
(state: StateType) => state.transfers
);
const incomingTransfers: TransferModel[] = transfers.filter(
transfer => transfer.state === TransferState.INCOMING
);
if (incomingTransfers.length > 0) {
document.title = '(' + incomingTransfers.length + ') ' + title;
} else {
document.title = title;
}
}
function* createKeys() {
// Generate keys.
const keyPair: RSA.KeyPair | undefined = yield call(async () => {
try {
return await RSA.randomKeyPair();
} catch {
// In case of failure we default to plaintext communication.
return undefined;
}
});
if (keyPair) {
yield put(setKeyPairAction(keyPair.publicKey, keyPair.privateKey));
}
yield put(connectAction());
}
export default function* root(dispatch: (action: any) => void) {
yield call(() => createKeys());
yield takeEvery(ActionType.DISMISS_WELCOME, welcomed);
yield takeEvery(ActionType.WS_MESSAGE, function* (action: ActionModel) {
// TODO: rewrite this to avoid passing dispatch
yield call(() => message(action, dispatch));
});
yield takeEvery(ActionType.PREPARE_MESSAGE, prepareMessage);
yield takeEvery(ActionType.WS_CONNECTED, connected);
yield takeEvery(ActionType.WS_DISCONNECTED, disconnected);
yield takeEvery(ActionType.SET_NETWORK_NAME, setName);
yield takeEvery(ActionType.CREATE_TRANSFER, createTransfer);
yield takeEvery(ActionType.CANCEL_TRANSFER, cancelTransfer);
yield takeEvery(ActionType.ACCEPT_TRANSFER, acceptTransfer);
yield takeEvery(ActionType.REJECT_TRANSFER, rejectTransfer);
yield takeEvery(ActionType.SEND_CHAT_MESSAGE, sendChatMessage);
yield takeEvery(
[
ActionType.ADD_TRANSFER,
ActionType.UPDATE_TRANSFER,
ActionType.REMOVE_TRANSFER,
ActionType.SET_NETWORK,
],
updateNotificationCount
);
} | the_stack |
import assert from 'assert';
import { r } from '../src';
import config from './config';
import { uuid } from './util/common';
describe('pool legacy', () => {
after(async () => {
await r.getPoolMaster().drain();
});
const options = {
max: 10,
buffer: 2,
servers: [
{
host: config.host,
port: config.port
}
],
user: config.user,
password: config.password,
discovery: false,
silent: true
};
it('`createPool` should create a PoolMaster and `getPoolMaster` should return it', async () => {
await r.connectPool(options);
assert.ok(r.getPoolMaster(), 'expected an instance of pool master');
assert.equal(
r.getPoolMaster().getPools().length,
1,
'expected number of pools is 1'
);
});
it('The pool should create a buffer', async () => {
const result = await new Promise((resolve, reject) => {
setTimeout(() => {
const numConnections = r.getPoolMaster().getAvailableLength();
numConnections >= options.buffer
? resolve(numConnections)
: reject(
new Error(
'expected number of connections to equal option.buffer within 250 msecs'
)
);
}, 50);
});
assert.equal(
options.buffer,
result,
'expected buffer option to result in number of created connections'
);
});
it('`run` should work without a connection if a pool exists and the pool should keep a buffer', async () => {
const numExpr = 5;
const result1 = await Promise.all(
Array(numExpr)
.fill(r.expr(1))
.map(expr => expr.run())
);
assert.deepEqual(result1, Array(numExpr).fill(1));
await new Promise(resolve => setTimeout(resolve, 200));
const numConnections = r.getPoolMaster().getAvailableLength();
assert.ok(
numConnections >= options.buffer + numExpr,
'expected number of connections to be at least buffer size plus number of run expressions'
);
});
it('A noreply query should release the connection', async () => {
const numConnections = r.getPoolMaster().getLength();
await r.expr(1).run({ noreply: true });
assert.equal(
numConnections,
r.getPoolMaster().getLength(),
'expected number of connections be equal before and after a noreply query'
);
});
it('The pool should not have more than `options.max` connections', async () => {
let result = [];
for (let i = 0; i <= options.max; i++) {
result.push(r.expr(1).run());
await new Promise(resolve => setTimeout(resolve, 100));
}
result = await Promise.all(result);
assert.deepEqual(result, Array(options.max + 1).fill(1));
assert.equal(r.getPoolMaster().getLength(), options.max);
assert.ok(
r.getPoolMaster().getAvailableLength() <= options.max,
'available connections more than max'
);
assert.equal(
r.getPoolMaster().getAvailableLength(),
r.getPoolMaster().getLength(),
'expected available connections to equal pool size'
);
});
it('The pool should shrink if a connection is not used for some time', async () => {
r.getPoolMaster().setOptions({ timeoutGb: 100 });
const result = await Promise.all(
Array(9)
.fill(r.expr(1))
.map(expr => expr.run())
);
assert.deepEqual(result, Array(9).fill(1));
const { availableLength, length } = await new Promise<{
availableLength: number;
length: number;
}>(resolve => {
setTimeout(
() =>
resolve({
availableLength: r.getPoolMaster().getAvailableLength(),
length: r.getPoolMaster().getLength()
}),
1000
);
});
assert.equal(
availableLength,
options.buffer,
'expected available connections to equal buffer size'
);
assert.equal(
length,
options.buffer,
'expected pool size to equal buffer size'
);
});
it('`poolMaster.drain` should eventually remove all the connections', async () => {
await r.getPoolMaster().drain();
assert.equal(r.getPoolMaster().getAvailableLength(), 0);
assert.equal(r.getPoolMaster().getLength(), 0);
});
it('If the pool cannot create a connection, it should reject queries', async () => {
await r
.connectPool({
servers: [{ host: 'notarealhost' }],
buffer: 1,
max: 2,
silent: true
})
.catch(() => undefined);
try {
await r.expr(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'None of the pools have an opened connection and failed to open a new one.'
);
}
await r.getPoolMaster().drain();
});
it('If the driver cannot create a connection, it should reject queries - timeout', async () => {
await r
.connectPool({
servers: [{ host: 'notarealhost' }],
buffer: 1,
max: 2,
silent: true
})
.catch(() => undefined);
try {
await r.expr(1).run();
assert.fail('should throw');
} catch (e) {
assert.equal(
e.message,
'None of the pools have an opened connection and failed to open a new one.'
);
} finally {
await r.getPoolMaster().drain();
}
});
it('If the pool is drained, it should reject queries', async () => {
await r
.connectPool({
buffer: 1,
max: 2,
port: config.port,
host: config.host
})
.catch(() => undefined);
await r.getPoolMaster().drain();
try {
await r.expr(1).run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.startsWith(
'`run` was called without a connection and no pool has been created after:'
)
);
} finally {
await r.getPoolMaster().drain();
}
});
it('If the pool is draining, it should reject queries', async () => {
await r.connectPool({
buffer: 1,
max: 2,
silent: true,
port: config.port,
host: config.host
});
r.getPoolMaster().drain();
try {
await r.expr(1).run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.startsWith(
'`run` was called without a connection and no pool has been created after:'
)
);
} finally {
await r.getPoolMaster().drain();
}
});
// it('`drain` should work in case of failures', async function () {
// await r.connectPool({ buffer: 1, max: 2, silent: true });
// r.createPools({
// port: 80, // non valid port
// silent: true,
// timeoutError: 100
// });
// const pool = r.getPoolMaster();
// await new Promise(function (resolve, reject) {
// setTimeout(resolve, 150);
// });
// pool.drain();
// // timeoutReconnect should have been canceled
// assert.equal(pool.timeoutReconnect, null);
// pool.options.silent = false;
// });
it('The pool should remove a connection if it errored', async () => {
await r.connectPool({
buffer: 1,
max: 2,
silent: true,
port: config.port,
host: config.host
});
r.getPoolMaster().setOptions({ timeoutGb: 60 * 60 * 1000 });
try {
const result1 = await Promise.all(
Array(options.max)
.fill(r.expr(1))
.map(expr => expr.run())
);
assert.deepEqual(result1, Array(options.max).fill(1));
} catch (e) {
assert.ifError(e); // This should not error anymore because since the JSON protocol was introduced.
assert.equal(
e.message,
'Client is buggy (failed to deserialize protobuf)'
);
// We expect the connection that errored to get closed in the next second
await new Promise((resolve, reject) => {
setTimeout(() => {
assert.equal(r.getPoolMaster().getAvailableLength(), options.max - 1);
assert.equal(r.getPoolMaster().getLength(), options.max - 1);
resolve();
}, 1000);
});
} finally {
await r.getPoolMaster().drain();
}
});
describe('cursor', () => {
let dbName: string;
let tableName: string;
before(async () => {
await r.connectPool(options);
dbName = uuid();
tableName = uuid();
const result1 = await r.dbCreate(dbName).run();
assert.equal(result1.dbs_created, 1);
const result2 = await r
.db(dbName)
.tableCreate(tableName)
.run();
assert.equal(result2.tables_created, 1);
const result3 = await r
.db(dbName)
.table(tableName)
.insert(Array(10000).fill({}))
.run();
assert.equal(result3.inserted, 10000);
// Making bigger documents to retrieve multiple batches
const result4 = await r
.db(dbName)
.table(tableName)
.update({
foo: uuid(),
fooo: uuid(),
foooo: uuid(),
fooooo: uuid(),
foooooo: uuid(),
fooooooo: uuid(),
foooooooo: uuid(),
fooooooooo: uuid(),
foooooooooo: uuid(),
date: r.now()
})
.run();
assert.equal(result4.replaced, 10000);
});
after(async () => {
const result1 = await r.dbDrop(dbName).run();
assert.equal(result1.dbs_dropped, 1);
await r.getPoolMaster().drain();
});
it('The pool should release a connection only when the cursor has fetch everything or get closed', async () => {
const result = [];
for (let i = 0; i < options.max; i++) {
result.push(
await r
.db(dbName)
.table(tableName)
.getCursor()
);
await new Promise(resolve => setTimeout(resolve, 100));
}
assert.equal(
result.length,
options.max,
'expected to get the same number of results as number of expressions'
);
assert.equal(
r.getPoolMaster().getAvailableLength(),
0,
'expected no available connections'
);
await result[0].toArray();
assert.equal(
r.getPoolMaster().getAvailableLength(),
1,
'expected available connections'
);
await result[1].toArray();
assert.equal(
r.getPoolMaster().getAvailableLength(),
2,
'expected available connections'
);
await result[2].close();
assert.equal(
r.getPoolMaster().getAvailableLength(),
3,
'expected available connections'
);
// close the 7 next seven cursors
await Promise.all(
[...Array(7).keys()].map(key => {
return result[key + 3].close();
})
);
assert.equal(
r.getPoolMaster().getAvailableLength(),
options.max,
'expected available connections to equal option.max'
);
});
});
}); | the_stack |
import * as React from "react";
import { useState } from "react";
import { getThemeService } from "@core/service-registry";
import { Cz88KeyView } from "../machines/cambridge-z88/cz88-keys";
import { Z88ButtonClickArgs } from "./ui-core-types";
const NORMAL_WIDTH = 100;
const NORMAL_HEIGHT = 100;
/**
* Component properties
*/
interface Props {
zoom: number;
code: number;
layoutInfo?: Cz88KeyView;
iconCount?: number;
top?: string;
bottom?: string;
xwidth?: number;
xheight?: number;
vshift?: number;
fontSize?: number;
isEnter?: boolean;
keyAction?: (e: Z88ButtonClickArgs, down: boolean) => void;
}
/**
* Represents a key of the Cambridge Z88 keyboard
*/
export default function Cz88Key(props: Props) {
// --- Component states
const [mouseOverKey, setMouseOverKey] = useState(false);
const [mouseOverSymbol, setMouseOverSymbol] = useState(false);
const [mouseOverSecondSymbol, setMouseOverSecondSymbol] = useState(false);
// --- Number of icons on the key
let iconCount = 0;
// --- Invariant display properties
const themeService = getThemeService();
const keyBackground = themeService.getProperty("--key-cz88-background-color");
const mainKeyColor = themeService.getProperty("--key-cz88-main-color");
const keyStrokeColor = themeService.getProperty("--key-cz88-stroke-color");
const symbolKeyColor = themeService.getProperty("--key-cz88-main-color");
const highlightKeyColor = themeService.getProperty(
"--key-cz88-highlight-color"
);
// --- Prepare rendering
let main = "";
let keyword = "";
let symbol = "";
let secondSymbol;
if (props.layoutInfo) {
keyword = props.layoutInfo.keyword;
main = props.layoutInfo.key;
symbol = props.layoutInfo.symbol;
secondSymbol = props.layoutInfo.secondSymbol;
}
iconCount = 0;
if (main) iconCount++;
if (symbol) iconCount++;
if (secondSymbol) iconCount++;
const currentWidth = props.zoom * (props.xwidth || NORMAL_WIDTH);
const currentHeight = props.zoom * (props.xheight || NORMAL_HEIGHT);
const mainFillColor = mouseOverKey ? highlightKeyColor : mainKeyColor;
const mainStrokeColor = mouseOverKey ? highlightKeyColor : "transparent";
const symbolFillColor = mouseOverSymbol ? highlightKeyColor : symbolKeyColor;
const symbolStrokeColor = mouseOverSymbol ? highlightKeyColor : "transparent";
const secondSymbolFillColor = mouseOverSecondSymbol
? highlightKeyColor
: symbolKeyColor;
const secondSymbolStrokeColor = mouseOverSecondSymbol
? highlightKeyColor
: "transparent";
const cursor = mouseOverKey || mouseOverSymbol ? "pointer" : "default";
// --- Render
return (
<svg
width={currentWidth}
height={currentHeight}
viewBox={`0 0 ${(props.xwidth || NORMAL_WIDTH) + 20} ${
(props.xheight || NORMAL_HEIGHT) + 20
}`}
style={{ margin: 0 }}
preserveAspectRatio="none"
xmlns="http://www.w3.org/2000/svg"
>
<rect
x="2"
y="2"
rx="12"
ry="12"
width={props.xwidth || NORMAL_WIDTH}
height={props.xheight || NORMAL_HEIGHT}
fill={keyBackground}
stroke={keyStrokeColor}
strokeWidth="4"
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
/>
{main && (
<text
x="14"
y="88"
fontSize="36"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
{main}
</text>
)}
{symbol && (
<rect
x="48"
y="16"
width={54}
height={40}
fill="transparent"
cursor={cursor}
onMouseEnter={() => setMouseOverSymbol(true)}
onMouseLeave={() => setMouseOverSymbol(false)}
onMouseDown={(e) => raiseKeyAction(e, "symbol", true)}
onMouseUp={(e) => raiseKeyAction(e, "symbol", false)}
>
{symbol}
</rect>
)}
{symbol && (
<text
x="68"
y="36"
fontSize={32}
textAnchor="middle"
fill={symbolFillColor}
stroke={symbolStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverSymbol(true)}
onMouseLeave={() => setMouseOverSymbol(false)}
onMouseDown={(e) => raiseKeyAction(e, "symbol", true)}
onMouseUp={(e) => raiseKeyAction(e, "symbol", false)}
>
{symbol}
</text>
)}
{secondSymbol && (
<rect
x="48"
y="68"
width={54}
height={40}
fill="transparent"
cursor={cursor}
onMouseEnter={() => setMouseOverSecondSymbol(true)}
onMouseLeave={() => setMouseOverSecondSymbol(true)}
onMouseDown={(e) => raiseKeyAction(e, "secondsymbol", true)}
onMouseUp={(e) => raiseKeyAction(e, "secondsymbol", false)}
></rect>
)}
{secondSymbol && (
<text
x="68"
y="88"
fontSize={32}
textAnchor="middle"
fill={secondSymbolFillColor}
stroke={secondSymbolStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverSecondSymbol(true)}
onMouseLeave={() => setMouseOverSecondSymbol(true)}
onMouseDown={(e) => raiseKeyAction(e, "secondsymbol", true)}
onMouseUp={(e) => raiseKeyAction(e, "secondsymbol", false)}
>
{secondSymbol}
</text>
)}
{keyword && (
<text
x={(props.xwidth || 100) / 2}
y={62 + (props.vshift || 0)}
fontSize={props.fontSize ?? 28}
textAnchor="middle"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
{keyword}
</text>
)}
{props.top && (
<text
x={(props.xwidth || 100) / 2}
y={48}
fontSize="28"
textAnchor="middle"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
{props.top}
</text>
)}
{props.bottom && (
<text
x={(props.xwidth || 100) / 2}
y={76}
fontSize="28"
textAnchor="middle"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
{props.bottom}
</text>
)}
{props.isEnter && (
<text
x={(props.xwidth || 100) / 2 - 6}
y={54}
fontSize="28"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
E
</text>
)}
{props.isEnter && (
<text
x={(props.xwidth || 100) / 2 - 6}
y={84}
fontSize="28"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
N
</text>
)}
{props.isEnter && (
<text
x={(props.xwidth || 100) / 2 - 6}
y={114}
fontSize="28"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
T
</text>
)}
{props.isEnter && (
<text
x={(props.xwidth || 100) / 2 - 6}
y={144}
fontSize="28"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
E
</text>
)}
{props.isEnter && (
<text
x={(props.xwidth || 100) / 2 - 6}
y={174}
fontSize="28"
textAnchor="left"
fill={mainFillColor}
stroke={mainStrokeColor}
cursor={cursor}
onMouseEnter={() => setMouseOverKey(true)}
onMouseLeave={() => setMouseOverKey(false)}
onMouseDown={(e) => raiseKeyAction(e, "main", true)}
onMouseUp={(e) => raiseKeyAction(e, "main", false)}
>
R
</text>
)}
</svg>
);
function raiseKeyAction(
e: React.MouseEvent,
keyCategory: string,
down: boolean
) {
props.keyAction?.(
{
code: props.code,
keyCategory,
down,
isLeft: e.button === 0,
iconCount: iconCount,
special: props.layoutInfo ? props.layoutInfo.special : undefined,
},
down
);
}
} | the_stack |
import * as path from 'path';
import rimraf = require('rimraf');
import events = require('events');
import mkdirp = require('mkdirp');
import { JspmUserError, bold, highlight, underline, JSPM_CACHE_DIR, PATH } from './utils/common';
import { logErr, log, confirm, input, LogType, startSpinner, stopSpinner, logLevel } from './utils/ui';
import Config from './config';
import RegistryManager, { Registry } from './install/registry-manager';
import Cache from './utils/cache';
import globalConfig from './config/global-config-file';
import FetchClass from './install/fetch';
import { dispose as cjsConvertDispose, init as cjsConvertInit } from './compile/cjs-convert';
// import { ExactPackage, PackageName, clearPackageCache } from './utils/package';
import { Install, InstallOptions, Installer } from './install';
import { runCmd } from './utils/run-cmd';
import { JSPM_GLOBAL_PATH } from './api';
export type Hook = 'preinstall' | 'postinstall';
export interface Logger {
newline: () => void;
msg: (msg: string) => void;
errMsg: (err: string | Error | JspmUserError) => void;
err: (err: string | Error | JspmUserError) => void;
debug: (msg: string) => void;
info: (msg: string) => void;
warn: (msg: string) => void;
ok: (msg: string) => void;
taskStart: (name: string) => () => void;
taskEnd: (name: string) => void;
}
export type input = typeof input;
export type confirm = typeof confirm;
// git is required for jspm to work
let hasGit = true;
try {
require('which').sync('git');
}
catch (e) {
hasGit = false;
}
export interface ProjectConfiguration {
userInput?: boolean;
cacheDir?: string;
timeouts?: {
resolve?: number;
download?: number
};
defaultRegistry?: string;
offline?: boolean;
preferOffline?: boolean;
strictSSL?: boolean;
registries?: {[name: string]: Registry};
cli?: boolean;
multiProject?: boolean;
}
function applyDefaultConfiguration (userConfig: ProjectConfiguration) {
const config: ProjectConfiguration = Object.assign({}, userConfig);
if (!config.registries) {
const registriesGlobalConfig = globalConfig.get('registries') || {};
const registries: { [name: string]: Registry } = {};
Object.keys(registriesGlobalConfig).forEach((registryName) => {
const registry = registriesGlobalConfig[registryName];
if (registry.handler === 'jspm-npm' || registry.handler === 'jspm-github')
registry.handler = undefined;
registries[registryName] = {
handler: registry.handler || `@jspm/${registryName}`,
config: registry
};
});
config.registries = registries
}
if (!config.defaultRegistry) {
let defaultRegistry = globalConfig.get('defaultRegistry');
if (!defaultRegistry || defaultRegistry === 'jspm')
defaultRegistry = 'npm';
config.defaultRegistry = defaultRegistry;
}
if ('offline' in config === false)
config.offline = false;
if ('preferOffline' in config === false)
config.preferOffline = globalConfig.get('preferOffline') || false;
if ('cli' in config === false)
config.cli = true;
if ('timeouts' in config === false)
config.timeouts = {
resolve: globalConfig.get('timeouts.resolve') || 30000,
download: globalConfig.get('timeouts.download') || 300000
};
if ('userInput' in config === false)
config.userInput = true;
if ('cacheDir' in config === false)
config.cacheDir = JSPM_CACHE_DIR;
if ('strictSSL' in config === false)
config.strictSSL = globalConfig.get('strictSSL');
return config;
}
export class Project {
projectPath: string;
config: Config;
globalConfig: typeof globalConfig;
cli: boolean;
defaultRegistry: string;
log: Logger;
confirm: typeof confirm;
input: typeof input;
userInput: boolean;
offline: boolean;
preferOffline: boolean;
registryManager: RegistryManager;
installer: Installer;
fetch: FetchClass;
cacheDir: string;
checkedGlobalBin: boolean;
constructor (projectPath: string, options: ProjectConfiguration) {
this.projectPath = projectPath;
if (!hasGit)
throw new JspmUserError(`${bold('git')} is not installed in path. You can install git from http://git-scm.com/downloads.`);
const config = applyDefaultConfiguration(options);
// is this running as a CLI or API?
this.cli = config.cli;
this.log = this.cli ? new CLILogger(options.multiProject ? projectPath : null) : new APILogger();
if (projectPath === JSPM_GLOBAL_PATH)
this.checkGlobalBin();
// if (process.env.globalJspm === 'true')
// this.log.warn(`Running jspm globally, it is advisable to locally install jspm via ${bold(`npm install jspm --save-dev`)}.`);
this.defaultRegistry = config.defaultRegistry;
// hardcoded for now (pending jspm 3...)
this.defaultRegistry = 'npm';
mkdirp.sync(projectPath);
this.config = new Config(projectPath, this);
this.globalConfig = globalConfig;
this.confirm = this.cli ? confirm : (_msg, def) => Promise.resolve(typeof def === 'boolean' ? def : undefined);
this.input = this.cli ? input : (_msg, def) => Promise.resolve(typeof def === 'string' ? def : undefined);
this.userInput = config.userInput;
this.offline = config.offline;
this.preferOffline = config.preferOffline;
this.cacheDir = config.cacheDir;
this.fetch = new FetchClass(this);
this.registryManager = new RegistryManager({
cacheDir: this.cacheDir,
defaultRegistry: this.defaultRegistry,
Cache,
timeouts: {
resolve: config.timeouts.resolve,
download: config.timeouts.download
},
offline: this.offline,
preferOffline: this.preferOffline,
userInput: this.userInput,
strictSSL: config.strictSSL,
log: this.log,
confirm: this.confirm,
input: this.input,
fetch: this.fetch,
registries: config.registries
});
// load registries upfront
// (strictly we should save registry configuration when a new registry appears)
this.registryManager.loadEndpoints();
cjsConvertInit();
this.installer = new Installer(this);
}
checkGlobalBin () {
if (this.checkedGlobalBin)
return;
const globalBin = path.join(JSPM_GLOBAL_PATH, 'jspm_packages', '.bin');
if (process.env[PATH].indexOf(globalBin) === -1)
this.log.warn(`The global jspm bin folder ${highlight(globalBin)} is not currently in your PATH, add this for native jspm bin support.`);
this.checkedGlobalBin = true;
}
dispose () {
return Promise.all([
this.config.dispose(),
this.registryManager.dispose(),
cjsConvertDispose()
]);
}
async save () {
return await this.config.save();
}
/*
* Main API methods
*/
async update (selectors: string[], opts: InstallOptions) {
const taskEnd = this.log.taskStart('Updating...');
try {
var changed = await this.installer.update(selectors, opts);
}
finally {
taskEnd();
}
// NB install state change logging!
if (changed)
this.log.ok('Update complete.');
else
this.log.ok('Already up to date.');
}
async install (installs: Install[], opts: InstallOptions = {}) {
const taskEnd = this.log.taskStart('Installing...');
try {
await runHook(this, 'preinstall');
if (installs.length === 0) {
opts.lock = true;
if (opts.latest) {
opts.latest = false;
this.log.warn(`${bold('--latest')} flag does not apply to package lock install.`);
}
}
var changed = await this.installer.install(installs, opts);
await runHook(this, 'postinstall');
}
finally {
taskEnd();
}
// NB install state change logging!
if (changed)
this.log.ok(`Install complete.`);
else
this.log.ok(`Already installed.`);
}
async uninstall (names: string[]) {
const taskEnd = this.log.taskStart('Uninstalling...');
try {
await this.installer.uninstall(names);
}
finally {
taskEnd();
}
this.log.ok('Uninstalled successfully.');
}
async checkout (names: string[]) {
const taskEnd = this.log.taskStart('Checking out...');
try {
await this.installer.checkout(names);
}
finally {
taskEnd();
}
}
async link (pkg: string, source: string, opts: InstallOptions) {
const taskEnd = this.log.taskStart('Linking...');
try {
await runHook(this, 'preinstall');
var changed = await this.installer.link(pkg, source, opts);
await runHook(this, 'postinstall');
}
finally {
taskEnd();
}
if (changed)
this.log.ok('Linked Successfully.');
else
this.log.ok('Already linked.');
}
async clean () {
const taskEnd = this.log.taskStart('Cleaning...');
try {
await this.installer.clean(true);
}
finally {
taskEnd();
}
this.log.ok('Project cleaned successfully.');
}
/*
async resolve (name: string, parentName: string) {
let loader = getLoader(this);
if (parentName)
parentName = await loader.resolve(parentName);
let resolved = await loader.resolve(name, parentName);
return toCleanPath(resolved);
}
resolveSync (name: string, parentName: string) {
let loader = getLoader(this);
if (parentName)
parentName = loader.resolveSync(parentName);
let resolved = loader.resolveSync(name, parentName);
return toCleanPath(resolved);
}
*/
async init (basePath: string) {
if (basePath)
process.env.jspmConfigPath = path.resolve(basePath, 'package.json');
let relBase = path.relative(process.cwd(), path.dirname(process.env.jspmConfigPath || ''));
if (relBase !== '')
this.log.msg(`Initializing package at ${highlight(relBase)}\nUse ${bold(`jspm init .`)} to intialize into the current folder.`);
/* await this.config.load(true);
await this.config.save();
this.log('');
this.ok(`package.json at %${path.relative(process.cwd(), config.pjsonPath)}\n` +
`Config at %${path.relative(process.cwd(), config.pjson.configFile)}%` +
(config.loader.devFile ? ', %' + path.relative(process.cwd(), config.pjson.configFileDev) + '%' : '') +
(config.loader.browserFile ? ', %' + path.relative(process.cwd(), config.pjson.configFileBrowser) + '%' : '') +
(config.loader.nodeFile ? ', %' + path.relative(process.cwd(), config.pjson.configFileNode) + '%' : ''));*/
}
async registryConfig (name: string) {
return this.registryManager.configure(name);
}
async clearCache () {
await new Promise((resolve, reject) => rimraf(this.cacheDir, err => err ? reject(err) : resolve()));
this.log.warn(`Global cache cleared. ${underline(`All jspm projects for this system user will now have broken symlinks due to the shared global package cache.`)}`);
this.log.info(`${bold(`jspm install <packageName> -f`)} is equivalent to running a cache clear for that specific install tree.`);
this.log.info(`Please post an issue if you suspect the cache isn't invalidating properly.`);
}
async run (name: string, args: string[]): Promise<number> {
const scripts = this.config.pjson.scripts;
const script = scripts[name];
if (!script)
throw new JspmUserError(`No package.json ${highlight('"scripts"')} entry for command ${bold(name)}`);
const doPrePost = !name.startsWith('pre') && !name.startsWith('post');
const cmds = [];
if (doPrePost) {
const pre = scripts[`pre${name}`];
if (pre)
cmds.push(pre);
cmds.push(script);
const post = scripts[`post${name}`];
if (post)
cmds.push(post);
}
else {
cmds.push(script);
}
// before running commands dispose the configuration
this.config.dispose();
this.config = undefined;
let exitCode = 0;
await Promise.all(cmds.map(async cmd => {
if (args.length)
cmd += joinArgs(args);
cmd = cmd.replace('npm ', 'jspm ');
const cmdCode = await runCmd(cmd, this.projectPath);
if (cmdCode !== 0)
exitCode = cmdCode;
}));
return exitCode;
}
}
const dblQuoteRegEx = /"/g;
function joinArgs (args: string[]) {
return args.reduce((str, arg) => `${str} "${arg.replace(dblQuoteRegEx, '\\"')}"`, '');
}
export async function runHook (project: Project, name: Hook) {
var hooks = project.config.pjson.hooks;
if (!hooks || !hooks[name])
return;
try {
let m = require(hooks[name]);
if (!m.default || typeof m.default !== 'function')
throw new Error(`Hook ${bold(name)} doesn't contain a default export hook function.`);
await m.default();
}
catch (e) {
project.log.err(`Error running ${bold(name)} hook.`);
project.log.err(e.stack || e);
}
}
class APILogger extends events.EventEmitter implements Logger {
newline () {}
msg (msg: string) {
this.emit('msg', msg);
}
errMsg (msg: string | Error | JspmUserError) {
this.emit('errMsg', msg);
}
err (msg: string | Error | JspmUserError) {
this.emit('err', msg);
}
debug (msg: string) {
this.emit('debug', msg);
}
info (msg: string) {
this.emit('info', msg);
}
warn (msg: string) {
this.emit('warn', msg);
}
ok (msg: string) {
this.emit('ok', msg);
}
taskStart (name: string) {
this.emit('taskStart', name);
return () => this.taskEnd(name);
}
taskEnd (name: string) {
this.emit('taskEnd', name);
}
};
class CLILogger implements Logger {
tasks: string[];
lastTask: string;
label: string;
constructor (label?: string) {
this.label = label ? `[${label}] ` : '';
this.tasks = [];
this.lastTask = undefined;
}
newline () {
log('');
}
msg (msg: string) {
log(this.label + msg);
}
errMsg (msg: string | Error | JspmUserError) {
if (msg instanceof Error) {
if ((<JspmUserError>msg).hideStack)
msg = msg.message;
else
msg = msg.stack || msg && msg.toString();
}
logErr(this.label + msg);
}
err (msg: string | Error | JspmUserError) {
if (msg instanceof Error) {
if ((<JspmUserError>msg).hideStack)
msg = msg.message;
else
msg = msg.stack || msg && msg.toString();
}
log(this.label + msg, LogType.err);
}
debug (msg: string) {
log(this.label + msg, LogType.debug);
}
info (msg: string) {
log(this.label + msg, LogType.info);
}
warn (msg: string) {
log(this.label + msg, LogType.warn);
}
ok (msg: string) {
log(this.label + msg, LogType.ok);
}
taskStart (name: string) {
this.tasks.push(name);
log(this.label + this.tasks[this.tasks.length - 1], LogType.status);
if (this.tasks.length === 1)
startSpinner();
// allow debug log state to expand status
if (logLevel === LogType.debug && this.lastTask)
log(this.label + this.lastTask, LogType.debug);
this.lastTask = name;
return this.taskEnd.bind(this, name);
}
taskEnd (name: string) {
const taskIndex = this.tasks.indexOf(name);
if (taskIndex === -1)
return;
this.tasks.splice(taskIndex, 1);
if (this.tasks.length)
log(this.label + this.tasks[this.tasks.length - 1], LogType.status);
else
stopSpinner();
if (logLevel === LogType.debug && this.lastTask && this.lastTask !== this.tasks[this.tasks.length - 1]) {
log(this.label + this.lastTask, LogType.debug);
this.lastTask = undefined;
}
}
}; | the_stack |
import assert from 'assert'
import Ajv from 'ajv'
import * as React from 'react'
import { Formik } from 'formik'
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
import { reportEvent } from '../analytics'
import { reportErrors } from './analyticsUtils'
import { AlertModal } from '@opentrons/components'
import labwareSchema from '@opentrons/shared-data/labware/schemas/2.json'
import {
aluminumBlockAutofills,
aluminumBlockChildTypeOptions,
aluminumBlockTypeOptions,
FormStatus,
getDefaultFormState,
getInitialStatus,
tubeRackAutofills,
tubeRackInsertOptions,
} from './fields'
import { makeAutofillOnChange } from './utils/makeAutofillOnChange'
import { labwareDefToFields } from './labwareDefToFields'
import { labwareFormSchema } from './labwareFormSchema'
import {
formLevelValidation,
LabwareCreatorErrors,
} from './formLevelValidation'
import { labwareTestProtocol } from './testProtocols/labwareTestProtocol'
import { tipRackTestProtocol } from './testProtocols/tipRackTestProtocol'
import { fieldsToLabware } from './fieldsToLabware'
import { LabwareCreator as LabwareCreatorComponent } from './components/LabwareCreator'
import { Dropdown } from './components/Dropdown'
import { IntroCopy } from './components/IntroCopy'
import { ImportErrorModal } from './components/ImportErrorModal'
import { CreateNewDefinition } from './components/sections/CreateNewDefinition'
import { UploadExisting } from './components/sections/UploadExisting'
import { CustomTiprackWarning } from './components/sections/CustomTiprackWarning'
import { Description } from './components/sections/Description'
import { Export } from './components/sections/Export'
import { File } from './components/sections/File'
import { Footprint } from './components/sections/Footprint'
import { Grid } from './components/sections/Grid'
import { GridOffset } from './components/sections/GridOffset'
import { HandPlacedTipFit } from './components/sections/HandPlacedTipFit'
import { Height } from './components/sections/Height'
import { Preview } from './components/sections/Preview'
import { Regularity } from './components/sections/Regularity'
import { Volume } from './components/sections/Volume'
import { WellBottomAndDepth } from './components/sections/WellBottomAndDepth'
import { WellShapeAndSides } from './components/sections/WellShapeAndSides'
import { WellSpacing } from './components/sections/WellSpacing'
import styles from './styles.css'
import type { LabwareDefinition2 } from '@opentrons/shared-data'
import type {
ImportError,
LabwareFields,
ProcessedLabwareFields,
} from './fields'
import { getDefaultedDef } from './getDefaultedDef'
import { getIsXYGeometryChanged } from './utils/getIsXYGeometryChanged'
const ajv = new Ajv()
const validateLabwareSchema = ajv.compile(labwareSchema)
export const LabwareCreator = (): JSX.Element => {
const [
showExportErrorModal,
_setShowExportErrorModal,
] = React.useState<boolean>(false)
const setShowExportErrorModal = React.useMemo(
() => (v: boolean, fieldValues?: LabwareFields) => {
// NOTE: values that take a default will remain null in this event
// eslint-disable-next-line @typescript-eslint/no-unnecessary-boolean-literal-compare
if (v === true) {
assert(
fieldValues,
'expected `fieldValues` when setting showExportErrorModal to true'
)
reportEvent({
name: 'labwareCreatorFileExport',
properties: {
labwareType: fieldValues?.labwareType,
labwareDisplayName: fieldValues?.displayName,
labwareAPIName: fieldValues?.loadName,
labwareBrand: fieldValues?.brand,
labwareManufacturerID: fieldValues?.brandId,
exportSuccess: false,
exportError: true,
},
})
}
_setShowExportErrorModal(v)
},
[_setShowExportErrorModal]
)
const [showCreatorForm, setShowCreatorForm] = React.useState<boolean>(false)
const [importError, _setImportError] = React.useState<ImportError | null>(
null
)
const setImportError = React.useMemo(
() => (v: ImportError | null, def?: LabwareDefinition2) => {
if (v != null) {
reportEvent({
name: 'labwareCreatorFileImport',
properties: {
labwareDisplayName: def?.metadata.displayName,
labwareAPIName: def?.parameters.loadName,
labwareBrand: def?.brand.brand,
importSuccess: false,
importError: v.key,
},
})
}
_setImportError(v)
},
[_setImportError]
)
const [lastUploaded, _setLastUploaded] = React.useState<LabwareFields | null>(
null
)
const setLastUploaded = React.useMemo(
() => (v: LabwareFields | null, def?: LabwareDefinition2) => {
if (v != null) {
assert(def, "setLastUploaded expected `def` if `v` isn't null")
reportEvent({
name: 'labwareCreatorFileImport',
properties: {
labwareType: v.labwareType,
labwareDisplayName: def?.metadata.displayName,
labwareAPIName: def?.parameters.loadName,
labwareBrand: def?.brand.brand,
labwareManufacturerID: v.brandId,
importSuccess: true,
importError: null,
},
})
}
_setLastUploaded(v)
},
[_setLastUploaded]
)
const scrollRef = React.useRef<HTMLDivElement | null>(null)
const scrollToForm = React.useCallback(() => {
setShowCreatorForm(true)
window.scrollTo({
left: 0,
// @ts-expect-error(IL, 2021-03-24): needs code change to ensure no null to `top`
top: scrollRef.current && scrollRef.current.offsetTop - 200,
behavior: 'smooth',
})
}, [scrollRef])
// if showCreatorForm has changed and is a truthy value, it must have been false -> true. Scroll to it
React.useEffect(() => {
if (showCreatorForm) {
scrollToForm()
}
}, [showCreatorForm, scrollToForm])
const onUpload = React.useCallback(
(
event:
| React.DragEvent<HTMLLabelElement>
| React.ChangeEvent<HTMLInputElement>
) => {
let files: FileList | never[] = []
if ('dataTransfer' in event && event.dataTransfer.files !== null) {
files = event.dataTransfer.files
} else if ('files' in event.target && event.target.files !== null) {
files = event.target.files
}
const file = files[0]
const reader = new FileReader()
// reset the state of the input to allow file re-uploads
if ('value' in event.currentTarget) {
event.currentTarget.value = ''
}
if (!file.name.endsWith('.json')) {
setImportError({ key: 'INVALID_FILE_TYPE' })
} else {
reader.onload = readEvent => {
const result = (readEvent.currentTarget as FileReader).result
let parsedLabwareDef: LabwareDefinition2
try {
parsedLabwareDef = JSON.parse(result as string)
} catch (error) {
console.error(error)
setImportError({
key: 'INVALID_JSON_FILE',
messages: [error.message],
})
return
}
if (!validateLabwareSchema(parsedLabwareDef)) {
console.warn(validateLabwareSchema.errors)
setImportError({
key: 'INVALID_LABWARE_DEF',
// @ts-expect-error(IL, 2021-03-24): ajv def mixup
messages: validateLabwareSchema.errors.map(
ajvError =>
`${ajvError.schemaPath}: ${
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
ajvError.message
}. (${JSON.stringify(ajvError.params)})`
),
})
return
}
const fields = labwareDefToFields(parsedLabwareDef)
if (!fields) {
setImportError(
{ key: 'UNSUPPORTED_LABWARE_PROPERTIES' },
parsedLabwareDef
)
return
}
setLastUploaded(fields, parsedLabwareDef)
if (
fields.labwareType === 'wellPlate' ||
fields.labwareType === 'reservoir' ||
fields.labwareType === 'tipRack'
) {
// no additional required labware type child fields, we can scroll right away
scrollToForm()
}
}
reader.readAsText(file)
}
},
[scrollToForm, setLastUploaded, setImportError]
)
React.useEffect(() => {
if (process.env.NODE_ENV === 'production') {
// NOTE: the contents of this message will be overridden by modern browsers
window.onbeforeunload = () =>
'Are you sure you want to leave? You may have unsaved changes.'
return () => {
window.onbeforeunload = null
}
}
})
return (
<LabwareCreatorComponent>
{importError && (
<ImportErrorModal
onClose={() => setImportError(null)}
importError={importError}
/>
)}
{showExportErrorModal && (
<AlertModal
className={styles.error_modal}
heading="Cannot export file"
onCloseClick={() => setShowExportErrorModal(false)}
buttons={[
{
onClick: () => setShowExportErrorModal(false),
children: 'close',
},
]}
>
Please resolve all invalid fields in order to export the labware
definition
</AlertModal>
)}
<Formik
initialValues={lastUploaded || getDefaultFormState()}
enableReinitialize
validationSchema={labwareFormSchema}
validate={formLevelValidation}
initialStatus={getInitialStatus}
onSubmit={(values: LabwareFields) => {
const castValues: ProcessedLabwareFields = labwareFormSchema.cast(
values
)
const { pipetteName } = castValues
const def = fieldsToLabware(castValues)
const { displayName } = def.metadata
const { loadName } = def.parameters
const testProtocol =
values.labwareType === 'tipRack'
? tipRackTestProtocol({ pipetteName, definition: def })
: labwareTestProtocol({ pipetteName, definition: def })
const zip = new JSZip()
zip.file(`${loadName}.json`, JSON.stringify(def, null, 4))
zip.file(`test_${loadName}.py`, testProtocol)
// TODO(IL, 2021-03-31): add `catch`
// eslint-disable-next-line @typescript-eslint/no-floating-promises
zip.generateAsync({ type: 'blob' }).then(blob => {
saveAs(blob, `${loadName}.zip`)
})
reportEvent({
name: 'labwareCreatorFileExport',
properties: {
labwareType: castValues.labwareType,
labwareDisplayName: displayName,
labwareAPIName: castValues.loadName,
labwareBrand: castValues.brand,
labwareManufacturerID: castValues.brandId,
exportSuccess: true,
exportError: null,
},
})
}}
>
{bag => {
const {
values,
touched,
setTouched,
setValues,
isValid,
handleSubmit,
} = bag
const status: FormStatus = bag.status
const setStatus: (status: FormStatus) => void = bag.setStatus
const errors: LabwareCreatorErrors = bag.errors
if (
(status.prevValues !== values && status.prevValues == null) ||
getIsXYGeometryChanged(status.prevValues, values)
) {
// since geometry has changed, clear the pipette field (to avoid multi-channel selection
// for labware not that is not multi-channel compatible)
setValues({
...values,
pipetteName: getDefaultFormState().pipetteName,
})
// update defaultedDef with new values
setStatus({
defaultedDef: getDefaultedDef(values),
prevValues: values,
})
}
const onExportClick = (): void => {
if (!isValid && !showExportErrorModal) {
setShowExportErrorModal(true, values)
}
handleSubmit()
}
// @ts-expect-error(IL, 2021-03-24): values/errors/touched not typed for reportErrors to be happy
reportErrors({ values, errors, touched })
// TODO (ka 2019-8-27): factor out this as sub-schema from Yup schema and use it to validate instead of repeating the logic
const canProceedToForm = Boolean(
values.labwareType === 'wellPlate' ||
values.labwareType === 'reservoir' ||
values.labwareType === 'tipRack' ||
(values.labwareType === 'tubeRack' &&
values.tubeRackInsertLoadName) ||
(values.labwareType === 'aluminumBlock' &&
values.aluminumBlockType === '24well') ||
(values.labwareType === 'aluminumBlock' &&
values.aluminumBlockType === '96well' &&
values.aluminumBlockChildType)
)
const labwareTypeChildFields = (
<>
{values.labwareType === 'tubeRack' && (
<Dropdown
name="tubeRackInsertLoadName"
options={tubeRackInsertOptions}
onValueChange={makeAutofillOnChange({
name: 'tubeRackInsertLoadName',
autofills: tubeRackAutofills,
values,
touched,
setTouched,
setValues,
})}
/>
)}
{values.labwareType === 'aluminumBlock' && (
<Dropdown
name="aluminumBlockType"
options={aluminumBlockTypeOptions}
onValueChange={makeAutofillOnChange({
name: 'aluminumBlockType',
autofills: aluminumBlockAutofills,
values,
touched,
setTouched,
setValues,
})}
/>
)}
{values.labwareType === 'aluminumBlock' &&
values.aluminumBlockType === '96well' && (
// Only show for '96well' aluminum block type
<Dropdown
name="aluminumBlockChildType"
options={aluminumBlockChildTypeOptions}
/>
)}
</>
)
return (
<div className={styles.labware_creator}>
<h2>Custom Labware Creator BETA</h2>
<IntroCopy />
<div className={styles.flex_row}>
<CreateNewDefinition
showDropDownOptions={lastUploaded === null}
disabled={!canProceedToForm || lastUploaded !== null}
labwareTypeChildFields={labwareTypeChildFields}
onClick={scrollToForm}
/>
<UploadExisting
disabled={!canProceedToForm}
labwareTypeChildFields={labwareTypeChildFields}
lastUploaded={lastUploaded}
onClick={scrollToForm}
onUpload={onUpload}
/>
</div>
<div ref={scrollRef} />
{showCreatorForm && (
<>
<CustomTiprackWarning />
<HandPlacedTipFit />
<Regularity />
<Footprint />
<Height />
<Grid />
<Volume />
<WellShapeAndSides />
<WellBottomAndDepth />
<WellSpacing />
<GridOffset />
<Preview />
<Description />
<File />
<Export onExportClick={onExportClick} />
</>
)}
</div>
)
}}
</Formik>
</LabwareCreatorComponent>
)
} | the_stack |
import { EventEmitter } from 'events';
import * as Http from 'http';
import * as Https from 'https';
import * as Stream from 'stream';
import * as Url from 'url';
import { Boom } from '@hapi/boom';
/**
* An HTTP request client.
*/
declare class Client {
/**
* An object containing the node agents used for pooling connections for `http` and `https`.
*/
agents: Client.Agents;
/**
* An event emitter used to deliver events when the `events` option is set.
*/
events?: Client.Events;
/**
* Creates a new client.
*
* @param options - the client default options.
*/
constructor(options?: Client.Options);
/**
* Creates a new client using the current client options as defaults and the provided options as override.
*
* @param options - the client override options.
*
* @returns a new client.
*/
defaults(options: Client.Options): Client;
/**
* Request an HTTP resource.
*
* @param method - a string specifying the HTTP request method. Defaults to 'GET'.
* @param url - the URI of the requested resource.
* @param options - default options override.
*
* @returns a promise resolving into an HTTP response object with a 'req' property holding a reference to the HTTP request object.
*/
request(method: string, url: string, options?: Client.request.Options): Promise<Http.IncomingMessage> & { req: Http.ClientRequest };
/**
* Reads a readable stream and returns the parsed payload.
*
* @param res - the readable stream.
* @param options - default options override.
*
* @returns the parsed payload based on the provided options.
*/
read<T = Buffer>(res: Stream.Readable | Http.IncomingMessage, options?: Client.read.Options): Promise<T>;
/**
* Converts a buffer, string, or an array of them into a readable stream.
*
* @param payload - a string, buffer, or an array of them.
* @param encoding - the payload encoding.
*
* @returns a readable stream.
*/
toReadableStream(payload: Client.toReadableStream.Payload, encoding?: string): Stream.Readable;
/**
* Parses the HTTP Cache-Control header.
*
* @param field - the header content.
*
* @returns an object with the header parameters or null if invalid.
*/
parseCacheControl(field: string): Client.parseCacheControl.Parameters | null;
/**
* Performs an HTTP GET request.
*
* @param uri - the resource URI.
* @param options - default options override.
*
* @returns the received payload Buffer or parsed payload based on the options.
*/
get<T>(uri: string, options?: Client.request.Options & Client.read.Options): Promise<Client.request.Response<T>>;
/**
* Performs an HTTP POST request.
*
* @param uri - the resource URI.
* @param options - default options override.
*
* @returns the received payload Buffer or parsed payload based on the options.
*/
post<T>(uri: string, options?: Client.request.Options & Client.read.Options): Promise<Client.request.Response<T>>;
/**
* Performs an HTTP PATCH request.
*
* @param uri - the resource URI.
* @param options - default options override.
*
* @returns the received payload Buffer or parsed payload based on the options.
*/
patch<T>(uri: string, options?: Client.request.Options & Client.read.Options): Promise<Client.request.Response<T>>;
/**
* Performs an HTTP PUT request.
*
* @param uri - the resource URI.
* @param options - default options override.
*
* @returns the received payload Buffer or parsed payload based on the options.
*/
put<T>(uri: string, options?: Client.request.Options & Client.read.Options): Promise<Client.request.Response<T>>;
/**
* Performs an HTTP DELETE request.
*
* @param uri - the resource URI.
* @param options - default options override.
*
* @returns the received payload Buffer or parsed payload based on the options.
*/
delete<T>(uri: string, options?: Client.request.Options & Client.read.Options): Promise<Client.request.Response<T>>;
}
declare namespace Client {
interface Options extends request.Options, read.Options {
/**
* An object containing the node agents used for pooling connections for `http` and `https`.
*/
readonly agents?: Agents;
/**
* Enables events.
*
* @default false
*/
readonly events?: boolean;
}
interface Agents {
/**
* The agent used for HTTP requests.
*/
readonly http: Http.Agent;
/**
* The agent used for HTTPS requests.
*/
readonly https: Https.Agent;
/**
* The agent used for HTTPS requests which ignores unauthorized requests.
*/
readonly httpsAllowUnauthorized: Https.Agent;
}
class Events extends EventEmitter {
on(event: 'preRequest', litener: Events.preRequest): this;
once(event: 'preRequest', litener: Events.preRequest): this;
addListener(event: 'preRequest', litener: Events.preRequest): this;
on(event: 'request', listener: Events.request): this;
once(event: 'request', listener: Events.request): this;
addListener(event: 'request', listener: Events.request): this;
on(event: 'response', listener: Events.response): this;
once(event: 'response', listener: Events.response): this;
addListener(event: 'response', listener: Events.response): this;
}
namespace Events {
type preRequest = (uri: string, options: Client.Options) => void;
type request = (req: Http.ClientRequest) => void;
type response = (err: Boom | undefined, details: { req: Http.ClientRequest, res: Http.IncomingMessage | undefined, start: number, url: Url.URL }) => void;
}
namespace request {
interface Options {
/**
* Node HTTP or HTTPS Agent object (false disables agent pooling).
*/
readonly agent?: Http.Agent | Https.Agent | false;
/**
* Fully qualified URL string used as the base URL.
*/
readonly baseUrl?: string;
/**
* A function to call before a redirect is triggered.
*
* @param redirectMethod - a string specifying the redirect method.
* @param statusCode - HTTP status code of the response that triggered the redirect.
* @param location - The redirect location string.
* @param resHeaders - An object with the headers received as part of the redirection response.
* @param redirectOptions - Options that will be applied to the redirect request. Changes to this object are applied to the redirection request.
* @param next - the callback function called to perform the redirection.
*/
readonly beforeRedirect?: (redirectMethod: string, statusCode: number, location: string, resHeaders: Record<string, string>, redirectOptions: Client.request.Options, next: () => void) => void;
/**
* TLS list of TLS ciphers to override node's default.
*/
readonly ciphers?: string;
/**
* An object containing the request headers.
*/
readonly headers?: Record<string, string>;
/**
* Determines how to handle gzipped payloads.
*
* @default false
*/
readonly gunzip?: boolean | 'force';
/**
* The request body as a string, Buffer, readable stream, or an object that can be serialized using `JSON.stringify()`.
*/
readonly payload?: Payload;
/**
* Enables redirects on 303 responses (using GET).
*
* @default false
*/
readonly redirect303?: boolean;
/**
* Overrides the HTTP method used when following 301 and 302 redirections. Defaults to the original method.
*/
readonly redirectMethod?: string;
/**
* The maximum number of redirects to follow.
*
* @default false
*/
readonly redirects?: number | false;
/**
* A function to call when a redirect was triggered.
*
* @param statusCode - HTTP status code of the response that triggered the redirect.
* @param location - the redirected location string.
* @param req - the new ClientRequest object which replaces the one initially returned.
*/
readonly redirected?: (statusCode: number, location: string, req: Http.ClientRequest) => void;
/**
* TLS flag indicating whether the client should reject a response from a server with invalid certificates.
*/
readonly rejectUnauthorized?: boolean;
/**
* TLS flag indicating the SSL method to use, e.g. `SSLv3_method` to force SSL version 3.
*/
readonly secureProtocol?: string;
/**
* A UNIX socket path string for direct server connection.
*/
readonly socketPath?: string;
/**
* Number of milliseconds to wait without receiving a response before aborting the request.
*
* @default 0
*/
readonly timeout?: number;
}
type Payload = string | Buffer | Stream.Readable | object;
interface Response<T = Buffer> {
res: Http.IncomingMessage;
payload: T;
}
}
namespace read {
interface Options {
/**
* Determines how to handle gzipped payloads.
*
* @default false
*/
readonly gunzip?: boolean | 'force';
/**
* Determines how to parse the payload as JSON.
*/
readonly json?: boolean | 'strict' | 'force';
/**
* The maximum allowed response payload size.
*
* @default 0
*/
readonly maxBytes?: number;
/**
* The number of milliseconds to wait while reading data before aborting handling of the response.
*
* @default 0
*/
readonly timeout?: number;
}
}
namespace toReadableStream {
type Item = string | Buffer;
type Payload = Item | Item[];
}
namespace parseCacheControl {
interface Parameters {
'max-age'?: number;
[key: string]: string | number | undefined;
}
}
}
declare const client: Client;
export = client; | the_stack |
import * as React from 'react';
import { DataGridStore } from './providers';
import {
DataGridEvents,
DataGridHeader,
DataGridBody,
DataGridScroll,
DataGridPage,
DataGridLoader,
} from './components';
import {
makeHeaderTable,
makeBodyRowTable,
makeBodyRowMap,
makeFootSumTable,
divideTableByFrozenColumnIndex,
isNumber,
} from './utils';
import { IDataGrid } from './common/@types';
// import DataGridAutofitHelper from './components/DataGridAutofitHelper';
interface IProps extends IDataGrid.IRootProps {}
interface IState extends IDataGrid.IRootState {}
class DataGrid extends React.Component<IProps, IState> {
static defaultHeight: number = 400;
static defaultColumnKeys: IDataGrid.IColumnKeys = {
selected: '_selected_',
modified: '_modified_',
deleted: '_deleted_',
disableSelection: '_disable_selection_',
};
static defaultHeader: IDataGrid.IOptionHeader = {
display: true,
align: 'left',
columnHeight: 24,
columnPadding: 3,
columnBorderWidth: 1,
selector: true,
clickAction: 'sort',
};
static defaultBody: IDataGrid.IOptionBody = {
align: 'left',
columnHeight: 24,
columnPadding: 3,
columnBorderWidth: 1,
grouping: false,
mergeCells: false,
};
static defaultPage: IDataGrid.IOptionPage = {
height: 20,
};
static defaultScroller: IDataGrid.IOptionScroller = {
theme: 'default',
width: 14,
height: 14,
arrowSize: 14,
barMinSize: 12,
padding: 3,
horizontalScrollerWidth: 30, // 30%
};
static defaultOptions: IDataGrid.IOptions = {
frozenColumnIndex: 0,
frozenRowIndex: 0,
showLineNumber: true,
multipleSelect: true,
columnMinWidth: 100,
lineNumberColumnWidth: 60,
lineNumberStartAt: 1,
rowSelectorColumnWidth: 28,
rowSelectorSize: 16,
header: DataGrid.defaultHeader,
body: DataGrid.defaultBody,
page: DataGrid.defaultPage,
scroller: DataGrid.defaultScroller,
columnKeys: DataGrid.defaultColumnKeys,
bodyLoaderHeight: 100,
autofitColumnWidthMin: 50,
autofitColumnWidthMax: 300,
disableClipboard: false,
};
static defaultStyles: IDataGrid.IStyles = {
asidePanelWidth: 0,
frozenPanelWidth: 0,
bodyTrHeight: 0,
elWidth: 0,
elHeight: 0,
rightPanelWidth: 0,
headerHeight: 0,
bodyHeight: 0,
frozenPanelHeight: 0,
footSumHeight: 0,
pageHeight: 0,
verticalScrollerWidth: 0,
horizontalScrollerHeight: 0,
scrollContentContainerHeight: 0,
scrollContentHeight: 0,
scrollContentContainerWidth: 0,
scrollContentWidth: 0,
verticalScrollerHeight: 0,
verticalScrollBarHeight: 0,
horizontalScrollerWidth: 0,
horizontalScrollBarWidth: 0,
scrollerPadding: 0,
scrollerArrowSize: 0,
};
static defaultThrottleWait = 100;
rootObject: any = {};
rootNode: React.RefObject<HTMLDivElement>;
clipBoardNode: React.RefObject<HTMLTextAreaElement>;
state: IState = {
mounted: false,
autofitAsideWidth: undefined,
autofitColGroup: [],
headerTable: { rows: [] },
bodyRowTable: { rows: [] },
bodyRowMap: {},
asideHeaderData: { rows: [] },
leftHeaderData: { rows: [] },
headerData: { rows: [] },
asideBodyRowData: { rows: [] },
leftBodyRowData: { rows: [] },
bodyRowData: { rows: [] },
colGroupMap: {},
asideColGroup: [],
colGroup: [],
footSumColumns: [],
footSumTable: { rows: [] },
leftFootSumData: { rows: [] },
footSumData: { rows: [] },
};
constructor(props: IProps) {
super(props);
this.rootNode = React.createRef();
this.clipBoardNode = React.createRef();
}
getOptions = (options: IDataGrid.IOptions): IDataGrid.IOptions => {
const _options = {
...DataGrid.defaultOptions,
...options,
header: { ...DataGrid.defaultOptions.header, ...options.header },
body: { ...DataGrid.defaultOptions.body, ...options.body },
page: { ...DataGrid.defaultOptions.page, ...options.page },
scroller: { ...DataGrid.defaultOptions.scroller, ...options.scroller },
columnKeys: {
...DataGrid.defaultOptions.columnKeys,
...options.columnKeys,
},
};
if (this.state.autofitAsideWidth !== undefined) {
_options.lineNumberColumnWidth = this.state.autofitAsideWidth;
}
return _options;
};
applyAutofit = (params: IDataGrid.IapplyAutofitParam) => {
const newState: IState = {};
const { columns, footSum, onChangeColumns } = this.props;
const { options } = this.state;
newState.options = this.getOptions(options || {});
newState.options.lineNumberColumnWidth = params.asideWidth;
const columnData = this.getColumnData(
columns,
footSum || [],
newState.options,
params.colGroup,
);
this.setState({
autofitAsideWidth: params.asideWidth,
autofitColGroup: params.colGroup,
options: newState.options,
...columnData,
});
if (onChangeColumns) {
// console.log('Run DataGrid :: applyAutofit');
onChangeColumns({
colGroup: columnData.colGroup,
});
}
// render가 다시되고 > getProviderProps이 다시 실행됨 (getProviderProps에서 doneAutofit인지 판단하여 autofitColGroup의 width값을 colGroup에 넣어주면 됨.)
};
getColumnData = (
columns: IDataGrid.IColumn[],
footSum: IDataGrid.IColumn[][],
options: IDataGrid.IOptions,
autofitColGroup?: IDataGrid.IColumn[],
): IState => {
const { frozenColumnIndex = 0 } = options;
const data: IState = {};
data.headerTable = makeHeaderTable(columns, options);
data.bodyRowTable = makeBodyRowTable(columns, options);
data.bodyRowMap = makeBodyRowMap(
data.bodyRowTable || { rows: [] },
options,
);
// header를 위한 divide
const headerDividedObj = divideTableByFrozenColumnIndex(
data.headerTable || { rows: [] },
frozenColumnIndex,
options,
);
// body를 위한 divide
const bodyDividedObj = divideTableByFrozenColumnIndex(
data.bodyRowTable || { rows: [] },
frozenColumnIndex,
options,
);
data.asideHeaderData = headerDividedObj.asideData;
data.leftHeaderData = headerDividedObj.leftData;
data.headerData = headerDividedObj.rightData;
data.asideBodyRowData = bodyDividedObj.asideData;
data.leftBodyRowData = bodyDividedObj.leftData;
data.bodyRowData = bodyDividedObj.rightData;
// colGroupMap, colGroup을 만들고 틀고정 값을 기준으로 나누어 left와 나머지에 저장
data.colGroupMap = {};
if (data.headerTable) {
data.headerTable.rows.forEach((row, ridx) => {
row.cols.forEach((col, cidx) => {
if (data.colGroupMap) {
let colWidth = col.width; // columns로부터 전달받은 너비값.
if (autofitColGroup) {
if (
isNumber(col.colIndex) &&
autofitColGroup[Number(col.colIndex)]
) {
colWidth = autofitColGroup[Number(col.colIndex)].width;
}
}
const currentCol: IDataGrid.ICol = {
key: col.key,
label: col.label,
width: colWidth,
align: col.align,
colSpan: col.colSpan,
rowSpan: col.rowSpan,
colIndex: col.colIndex,
rowIndex: col.rowIndex,
formatter: col.formatter,
editor: col.editor,
};
data.colGroupMap[col.colIndex || 0] = currentCol;
}
});
});
}
data.asideColGroup = headerDividedObj.asideColGroup;
data.colGroup = Object.values(data.colGroupMap);
// colGroup이 정의되면 footSum
data.footSumColumns = [...footSum];
data.footSumTable = makeFootSumTable(footSum, data.colGroup, options);
const footSumDividedObj = divideTableByFrozenColumnIndex(
data.footSumTable || { rows: [] },
frozenColumnIndex,
options,
);
data.leftFootSumData = footSumDividedObj.leftData;
data.footSumData = footSumDividedObj.rightData;
return data;
};
componentDidMount() {
const { columns, footSum = [], options = {}, sortInfos } = this.props;
const sortInfo = {};
sortInfos &&
sortInfos.forEach((si, idx) => {
if (si.key) {
sortInfo[si.key] = { seq: idx, orderBy: si.orderBy };
}
});
const newOptions = this.getOptions(options);
const columnData = this.getColumnData(columns, footSum, newOptions);
// console.log('componentDidMount, autofitColumns:', !!autofitColumns);
this.setState({
mounted: true,
...columnData,
options: newOptions,
sortInfo,
});
}
componentDidUpdate(prevProps: IProps, prevState: IState) {
const {
columns: _columns,
footSum: _footSum,
options: _options,
sortInfos: _sortInfos,
// data: _data,
} = prevProps;
const {
columns,
footSum,
options,
sortInfos,
// data,
} = this.props;
const newState: any = {};
let changeState = false;
//console.log(`
// _sortInfos !== sortInfos : ${_sortInfos !== sortInfos},
// _autofitColumns !== autofitColumns : ${_autofitColumns !== autofitColumns},
// _columns !== columns : ${_columns !== columns},
// _footSum !== footSum : ${_footSum !== footSum},
// _options !== options : ${_options !== options},
//`);
const sortInfo = {};
if (_sortInfos !== sortInfos) {
sortInfos &&
sortInfos.forEach((si, idx) => {
if (si.key) {
sortInfo[si.key] = { seq: idx, orderBy: si.orderBy };
}
});
changeState = true;
}
if (_columns !== columns || _footSum !== footSum || _options !== options) {
newState.newOptions = this.getOptions(options || {});
newState.columnData = this.getColumnData(
columns,
footSum || [],
newState.newOptions,
// this.state.autofitColGroup,
);
changeState = true;
}
if (changeState) {
this.setState({
...newState.columnData,
options: newState.newOptions,
sortInfo,
});
}
}
public render() {
const {
mounted,
autofitColGroup,
headerTable,
bodyRowTable,
bodyRowMap,
asideHeaderData,
leftHeaderData,
headerData,
asideBodyRowData,
leftBodyRowData,
bodyRowData,
colGroupMap,
asideColGroup,
colGroup,
footSumColumns,
footSumTable,
leftFootSumData,
footSumData,
options,
sortInfo,
} = this.state;
const {
loading = false,
loadingData = false,
data = {},
dataLength = 0,
width,
height = DataGrid.defaultHeight,
selection,
status,
scrollLeft,
scrollTop,
onBeforeEvent,
onScroll,
onScrollEnd,
onChangeScrollSize,
onChangeSelection,
onChangeColumns,
onSelect,
onRightClick,
onClick,
onError,
onSort,
onEdit,
style = {},
} = this.props;
const gridRootStyle = {
...{
height: height,
width: width,
},
...style,
};
const providerProps = {
loading,
loadingData,
data,
dataLength,
width,
height,
selection,
status,
scrollLeft,
scrollTop,
autofitColGroup,
headerTable,
bodyRowTable,
bodyRowMap,
asideHeaderData,
leftHeaderData,
headerData,
asideBodyRowData,
leftBodyRowData,
bodyRowData,
colGroupMap,
asideColGroup,
colGroup,
footSumColumns,
footSumTable,
leftFootSumData,
footSumData,
rootNode: this.rootNode,
clipBoardNode: this.clipBoardNode,
rootObject: this.rootObject,
onBeforeEvent,
onScroll,
onScrollEnd,
onChangeScrollSize,
onChangeSelection,
onChangeColumns,
onSelect,
onRightClick,
onClick,
onError,
onSort,
onEdit,
options,
sortInfo,
};
return (
<DataGridStore.Provider {...providerProps}>
<div
tabIndex={-1}
ref={this.rootNode}
className="axui-datagrid"
style={gridRootStyle}
>
<div className="axui-datagrid-clip-board">
<textarea ref={this.clipBoardNode} />
</div>
{mounted && (
<DataGridEvents>
<DataGridHeader />
<DataGridBody />
<DataGridPage />
<DataGridScroll />
<DataGridLoader loading={loading} />
</DataGridEvents>
)}
</div>
</DataGridStore.Provider>
);
}
}
export default DataGrid; | the_stack |
var Validation = require('../../src/validation/Validation.js');
var Validators = require('../../src/validation/BasicValidators.js');
var FormSchema = require('../../src/validation/FormSchema.js');
var expect = require('expect.js');
var _:UnderscoreStatic = require('underscore');
import Q = require('q');
interface IPerson{
Checked:boolean;
FirstName:string;
LastName:string;
Contacts:Array<IContact>;
}
interface IContact{
Email:string;
Mobile:IPhone;
FixedLine:IPhone;
}
interface IPhone{
CountryCode:string
Number:string
}
describe('JsonSchemaRuleFactory', function () {
//JSOM form schema
var formSchema = {
FirstName: {
type: "string",
title: "First name",
required: "true",
maxLength: 15
},
LastName: {
type: "string",
"title": "Last name",
required: true,
maxLength: 15
},
Contacts: {
type: "array",
maxItems: 4,
minItems: 2,
items: {
type: "object",
properties: {
Email: {
type: "string",
title: "Email",
default: '',
required: true,
maxLength: 100,
email: true },
Mobile: {
type: "object",
properties: {
CountryCode: {
type: "string",
title: "Country code",
required: true,
maxLength: 3,
enum: ["FRA", "CZE", "USA", "GER"]
},
Number: {
type: "string",
title: "Phone number",
required: true,
maxLength: 9
}
}
},
FixedLine: {
type: "object",
properties: {
CountryCode: {
type: "string",
title: "Country code",
required: true,
maxLength: 3,
enum: ["FRA", "CZE", "USA", "GER"]
},
Number: {
type: "string",
title: "Phone number",
required: true,
maxLength: 9
}
}
}
}
}
}
}
//
var getItemDataTemplate = function () {
var item = FormSchema.Util.InitValues(formSchema.Contacts.items.properties);
item.Email = 'mail@gmail.com';
item.Mobile.CountryCode = 'CZE';
item.Mobile.Number = '736483690';
item.FixedLine.CountryCode = 'USA';
item.FixedLine.Number = '736483690';
return item;
}
beforeEach(function () {
this.FormSchema = formSchema;
this.Data = FormSchema.Util.InitValues(this.FormSchema);
this.Data.FirstName = "John";
this.Data.LastName = "Smith";
this.MainValidator = new FormSchema.JsonSchemaRuleFactory(this.FormSchema).CreateRule("Main");
});
describe('email', function () {
it('fill no email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0] = {};
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(true);
});
it('fill wrong email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0].Email = 'jsmith.com';
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(true);
});
it('fill some email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0].Email = 'jsmith@gmail.com';
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(false);
});
});
// it('form values - parsing', function () {
//
// var personData = FormSchema.Util.GetFormValues(this.FormSchema);
// console.log(JSON.stringify(personData));
//
// var contactRow = FormSchema.Util.GetFormValues(this.FormSchema.Contacts.items.properties);
// console.log(JSON.stringify(contactRow));
// });
//
// it('form rules', function () {
//
// var personData = FormSchema.Util.GetAbstractRule(this.FormSchema);
// console.log(JSON.stringify(personData));
//
//
//// var contactRow = FormSchema.Util.GetFormValues(this.FormSchema.Person.properties.Contacts.items.properties);
//// console.log(JSON.stringify(contactRow));
// });
it('fill undefined - some errors', function () {
//when
this.Data.Contacts = undefined;
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
});
it('fill 1 item - minItems errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].ValidationFailures["minItems"].HasError).to.equal(true);
});
it('fill 5 items - maxItems errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].ValidationFailures["maxItems"].HasError).to.equal(true);
});
it('fill correct data - no errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(false);
});
it('fill incorrect data - some errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//simulate error at second item in list
this.Data.Contacts[1].Email = "";
//simulate async error at third item in list
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
expect(result.Errors["Contacts"].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[2].HasErrors).to.equal(true);
});
it('delete error item, leave correct item - no errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//item list property error
this.Data.Contacts[2].Email = "";
//item list async property error
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//delete last error item
this.Data.Contacts.splice(2, 1);
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(false);
expect(result.Errors["Contacts"].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(false);
});
it('delete correct item, leave error item - some errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//item list property error
this.Data.Contacts[2].Email = "";
//item list async property error
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//delete correct item
this.Data.Contacts.splice(1, 1);
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
expect(result.Errors["Contacts"].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(true);
});
});
describe('JQueryValidationRuleFactory', function () {
// define data structure + validation rules meta data
var metaData = {
FirstName: {
rules: {required: true, maxlength: 15},
label:"Email"
},
LastName: {
rules: {required: true, maxlength: 15}},
NickName:{
label:'Nick name'
},
Contacts: [
{
Email: {
label:"Email",
rules: {
required: true,
maxlength: 100,
email: true
}
},
Mobile: {
CountryCode: {
rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
},
Number: {
rules: {required: true, maxlength: 9 }
}
},
FixedLine: {
CountryCode: {
rules: {required: true, maxlength: 3, enum: ["FRA", "CZE", "USA", "GER"] }
},
Number: {
rules: {required: true, maxlength: 9 }
}
}
},{maxItems: 4, minItems: 2}
]
};
//setup
var getData = function () {
return {
Checked: true,
FirstName: "John",
LastName: "Smith",
Contacts: []
}
};
//
var getItemDataTemplate = function() {
return {
Email: 'mail@gmail.com',
Mobile: {
CountryCode: 'CZE',
Number: '736483690'
},
FixedLine: {
CountryCode: 'USA',
Number: '736483690'
}
}
};
beforeEach(function () {
this.Data = getData();
this.Data.FirstName = "John";
this.Data.LastName = "Smith";
this.MainValidator = new FormSchema.JQueryValidationRuleFactory(metaData).CreateRule("Main");
});
describe('email', function () {
it('fill no email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0] = {};
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(true);
});
it('fill wrong email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0].Email = 'jsmith.com';
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(true);
});
it('fill some email', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts[0].Email = 'jsmith@gmail.com';
//exec
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].Children[0].Errors["Email"].HasErrors).to.equal(false);
});
});
// it('form values - parsing', function () {
//
// var personData = FormSchema.Util.GetFormValues(this.FormSchema);
// console.log(JSON.stringify(personData));
//
// var contactRow = FormSchema.Util.GetFormValues(this.FormSchema.Contacts.items.properties);
// console.log(JSON.stringify(contactRow));
// });
//
// it('form rules', function () {
//
// var personData = FormSchema.Util.GetAbstractRule(this.FormSchema);
// console.log(JSON.stringify(personData));
//
//
//// var contactRow = FormSchema.Util.GetFormValues(this.FormSchema.Person.properties.Contacts.items.properties);
//// console.log(JSON.stringify(contactRow));
// });
it('fill undefined - some errors', function () {
//when
this.Data.Contacts = undefined;
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
});
it('fill 1 item - minItems errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].ValidationFailures["minItems"].HasError).to.equal(true);
});
it('fill 5 items - maxItems errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.Errors["Contacts"].ValidationFailures["maxItems"].HasError).to.equal(true);
});
it('fill correct data - no errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(false);
});
it('fill incorrect data - some errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//simulate error at second item in list
this.Data.Contacts[1].Email = "";
//simulate async error at third item in list
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
expect(result.Errors["Contacts"].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[2].HasErrors).to.equal(true);
});
it('delete error item, leave correct item - no errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//item list property error
this.Data.Contacts[2].Email = "";
//item list async property error
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//delete last error item
this.Data.Contacts.splice(2, 1);
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(false);
expect(result.Errors["Contacts"].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(false);
});
it('delete correct item, leave error item - some errors', function () {
//when
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
this.Data.Contacts.push(getItemDataTemplate());
//item list property error
this.Data.Contacts[2].Email = "";
//item list async property error
this.Data.Contacts[2].Mobile.CountryCode = "BLA";
//delete correct item
this.Data.Contacts.splice(1, 1);
//excercise
var result = this.MainValidator.Validate(this.Data);
//verify
expect(result.HasErrors).to.equal(true);
expect(result.Errors["Contacts"].HasErrors).to.equal(true);
expect(result.Errors["Contacts"].Children[0].HasErrors).to.equal(false);
expect(result.Errors["Contacts"].Children[1].HasErrors).to.equal(true);
});
}); | the_stack |
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { getSkylinkUrlForPortal } from "./download";
import { MAX_REVISION } from "./utils/number";
import { stringToUint8ArrayUtf8, toHexString } from "./utils/string";
import { DEFAULT_SKYNET_PORTAL_URL, URI_SKYNET_PREFIX } from "./utils/url";
import { SkynetClient } from "./index";
import { getEntryUrlForPortal } from "./registry";
import { checkCachedDataLink, DELETION_ENTRY_DATA, JSONResponse } from "./skydb";
import { MAX_ENTRY_LENGTH } from "./mysky";
import { decodeSkylink } from "./skylink/sia";
import { getSettledValues } from "../utils/testing";
import { JsonData } from "./utils/types";
// Generated with genKeyPairFromSeed("insecure test seed")
const [publicKey, privateKey] = [
"658b900df55e983ce85f3f9fb2a088d568ab514e7bbda51cfbfb16ea945378d9",
"7caffac49ac914a541b28723f11776d36ce81e7b9b0c96ccacd1302db429c79c658b900df55e983ce85f3f9fb2a088d568ab514e7bbda51cfbfb16ea945378d9",
];
const dataKey = "app";
const skylink = "CABAB_1Dt0FJsxqsu_J4TodNCbCGvtFf1Uys_3EgzOlTcg";
const sialink = `${URI_SKYNET_PREFIX}${skylink}`;
const jsonData = { data: "thisistext" };
const fullJsonData = { _data: jsonData, _v: 2 };
const legacyJsonData = jsonData;
const merkleroot = "QAf9Q7dBSbMarLvyeE6HTQmwhr7RX9VMrP9xIMzpU3I";
const bitfield = 2048;
const portalUrl = DEFAULT_SKYNET_PORTAL_URL;
const client = new SkynetClient(portalUrl);
const registryPostUrl = `${portalUrl}/skynet/registry`;
const registryGetUrl = getEntryUrlForPortal(portalUrl, publicKey, dataKey);
const uploadUrl = `${portalUrl}/skynet/skyfile`;
const skylinkUrl = getSkylinkUrlForPortal(portalUrl, skylink);
// Hex-encoded skylink.
const data = "43414241425f31447430464a73787173755f4a34546f644e4362434776744666315579735f3345677a4f6c546367";
const revision = 11;
// Entry data for the data and revision.
const entryData = {
data,
revision,
signature:
"33d14d2889cb292142614da0e0ff13a205c4867961276001471d13b779fc9032568ddd292d9e0dff69d7b1f28be07972cc9d86da3cecf3adecb6f9b7311af809",
};
const headers = {
"skynet-portal-api": portalUrl,
"skynet-skylink": skylink,
"content-type": "application/json",
};
describe("getJSON", () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onHead(portalUrl).replyOnce(200, {}, { "skynet-portal-api": portalUrl });
mock.resetHistory();
});
it("should perform a lookup and skylink GET", async () => {
// Mock a successful registry lookup.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
// Mock a successful data download.
mock.onGet(skylinkUrl).replyOnce(200, fullJsonData, headers);
const { data, dataLink } = await client.db.getJSON(publicKey, dataKey);
expect(data).toEqual(jsonData);
expect(dataLink).toEqual(sialink);
expect(mock.history.get.length).toBe(2);
});
it("should fail properly with a too low error", async () => {
// Use a custom data key for this test to get a fresh cache.
const dataKey = "testTooLowError";
const registryGetUrl = getEntryUrlForPortal(portalUrl, publicKey, dataKey);
const skylinkData = toHexString(decodeSkylink(skylink));
const entryData = {
data: skylinkData,
revision: 1,
signature:
"18d2b5f64042db39c4c591c21bd93015f7839eefab487ef8e27086cdb95b190732211b9a23d38c33f4f9a4e5219de55a80f75ff7e437713732ecdb4ccddb0804",
};
const entryDataTooLow = {
data: skylinkData,
revision: 0,
signature:
"4d7b26923f4211794eaf5c13230e62618ea3bebcb3fa6511ec8772b1f1e1a675b5244e7c33f89daf31999aeabe46c3a1e324a04d2f35c6ba902c75d35ceba00d",
};
// Cache the revision.
// Mock a successful registry lookup.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
// Mock a successful data download.
mock.onGet(skylinkUrl).replyOnce(200, fullJsonData, headers);
const { data } = await client.db.getJSON(publicKey, dataKey);
expect(data).toEqual(jsonData);
// The cache should contain revision 1.
const cachedRevisionEntry = await client.db.revisionNumberCache.getRevisionAndMutexForEntry(publicKey, dataKey);
expect(cachedRevisionEntry.revision.toString()).toEqual("1");
// Return a revision that's too low.
// Mock a successful registry lookup.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataTooLow));
// Mock a successful data download.
mock.onGet(skylinkUrl).replyOnce(200, fullJsonData, headers);
await expect(client.db.getJSON(publicKey, dataKey)).rejects.toThrowError(
"Returned revision number too low. A higher revision number for this userID and path is already cached"
);
// The cache should still contain revision 1.
expect(cachedRevisionEntry.revision.toString()).toEqual("1");
});
it("should perform a lookup but not a skylink GET if the cachedDataLink is a hit", async () => {
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
const { data, dataLink } = await client.db.getJSON(publicKey, dataKey, { cachedDataLink: skylink });
expect(data).toBeNull();
expect(dataLink).toEqual(sialink);
expect(mock.history.get.length).toBe(1);
});
it("should perform a lookup and a skylink GET if the cachedDataLink is not a hit", async () => {
const skylinkNoHit = "XABvi7JtJbQSMAcDwnUnmp2FKDPjg8_tTTFP4BwMSxVdEg";
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
mock.onGet(skylinkUrl).replyOnce(200, fullJsonData, headers);
const { data, dataLink } = await client.db.getJSON(publicKey, dataKey, { cachedDataLink: skylinkNoHit });
expect(data).toEqual(jsonData);
expect(dataLink).toEqual(sialink);
expect(mock.history.get.length).toBe(2);
});
it("should throw if the cachedDataLink is not a valid skylink", async () => {
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
mock.onGet(skylinkUrl).replyOnce(200, fullJsonData, {});
await expect(client.db.getJSON(publicKey, dataKey, { cachedDataLink: "asdf" })).rejects.toThrowError(
"Expected optional parameter 'cachedDataLink' to be valid skylink of type 'string', was type 'string', value 'asdf'"
);
});
it("should perform a lookup and skylink GET on legacy pre-v4 data", async () => {
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
mock.onGet(skylinkUrl).replyOnce(200, legacyJsonData, headers);
const jsonReturned = await client.db.getJSON(publicKey, dataKey);
expect(jsonReturned.data).toEqual(jsonData);
expect(mock.history.get.length).toBe(2);
});
it("should return null if no entry is found", async () => {
mock.onGet(registryGetUrl).replyOnce(404);
const { data, dataLink } = await client.db.getJSON(publicKey, dataKey);
expect(data).toBeNull();
expect(dataLink).toBeNull();
});
it("should throw if the returned file data is not JSON", async () => {
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
mock.onGet(skylinkUrl).replyOnce(200, "thisistext", { ...headers, "content-type": "text/plain" });
await expect(client.db.getJSON(publicKey, dataKey)).rejects.toThrowError(
`File data for the entry at data key '${dataKey}' is not JSON.`
);
});
it("should throw if the returned _data field in the file data is not JSON", async () => {
// mock a successful registry lookup
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryData));
mock.onGet(skylinkUrl).replyOnce(200, { _data: "thisistext", _v: 1 }, headers);
await expect(client.db.getJSON(publicKey, dataKey)).rejects.toThrowError(
"File data '_data' for the entry at data key 'app' is not JSON."
);
});
it("should throw if invalid entry data is returned", async () => {
const client = new SkynetClient(portalUrl);
const mockedFn = jest.fn();
mockedFn.mockReturnValueOnce({ entry: { data: new Uint8Array() } });
client.registry.getEntry = mockedFn;
await expect(client.db.getJSON(publicKey, dataKey)).rejects.toThrowError(
"Expected returned entry data 'entry.data' to be length 34 bytes, was type 'object', value ''"
);
});
});
describe("setJSON", () => {
let mock: MockAdapter;
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onHead(portalUrl).replyOnce(200, {}, { "skynet-portal-api": portalUrl });
mock.resetHistory();
// mock a successful upload
mock.onPost(uploadUrl).reply(200, { skylink, merkleroot, bitfield });
});
it("should perform an upload, lookup and registry update", async () => {
// mock a successful registry update
mock.onPost(registryPostUrl).replyOnce(204);
// set data
const { data: returnedData, dataLink: returnedSkylink } = await client.db.setJSON(privateKey, dataKey, jsonData);
expect(returnedData).toEqual(jsonData);
expect(returnedSkylink).toEqual(sialink);
// assert our request history contains the expected amount of requests
expect(mock.history.get.length).toBe(0);
expect(mock.history.post.length).toBe(2);
const data = JSON.parse(mock.history.post[1].data);
expect(data).toBeDefined();
expect(data.revision).toBeGreaterThanOrEqual(revision + 1);
});
it("should use a revision number of 0 if the entry is not cached", async () => {
// mock a successful registry update
mock.onPost(registryPostUrl).replyOnce(204);
// call `setJSON` on the client
await client.db.setJSON(privateKey, "inexistent entry", jsonData);
// assert our request history contains the expected amount of requests
expect(mock.history.get.length).toBe(0);
expect(mock.history.post.length).toBe(2);
const data = JSON.parse(mock.history.post[1].data);
expect(data).toBeDefined();
expect(data.revision).toEqual(0);
});
it("should fail if the entry has the maximum allowed revision", async () => {
const dataKey = "maximum revision";
const cachedRevisionEntry = await client.db.revisionNumberCache.getRevisionAndMutexForEntry(publicKey, dataKey);
cachedRevisionEntry.revision = MAX_REVISION;
// mock a successful registry update
mock.onPost(registryPostUrl).replyOnce(204);
// Try to set data, should fail.
await expect(client.db.setJSON(privateKey, dataKey, entryData)).rejects.toThrowError(
"Current entry already has maximum allowed revision, could not update the entry"
);
});
it("Should throw an error if the private key is not hex-encoded", async () => {
await expect(client.db.setJSON("foo", dataKey, {})).rejects.toThrowError(
"Expected parameter 'privateKey' to be a hex-encoded string, was type 'string', value 'foo'"
);
});
it("Should throw an error if the data key is not provided", async () => {
// @ts-expect-error We do not pass the data key on purpose.
await expect(client.db.setJSON(privateKey)).rejects.toThrowError(
"Expected parameter 'dataKey' to be type 'string', was type 'undefined'"
);
});
it("Should throw an error if the json is not provided", async () => {
// @ts-expect-error We do not pass the json on purpose.
await expect(client.db.setJSON(privateKey, dataKey)).rejects.toThrowError(
"Expected parameter 'json' to be type 'object', was type 'undefined'"
);
});
it("Should not update the cached revision if the registry update fails.", async () => {
const dataKey = "registry failure";
const json = { foo: "bar" };
// mock a successful registry update
mock.onPost(registryPostUrl).replyOnce(204);
await client.db.setJSON(privateKey, dataKey, json);
const cachedRevisionEntry = await client.db.revisionNumberCache.getRevisionAndMutexForEntry(publicKey, dataKey);
const revision1 = cachedRevisionEntry.revision;
// mock a failed registry update
mock.onPost(registryPostUrl).replyOnce(400, JSON.stringify({ message: "foo" }));
await expect(client.db.setJSON(privateKey, dataKey, json)).rejects.toEqual(
new Error("Request failed with status code 400: foo")
);
const revision2 = cachedRevisionEntry.revision;
expect(revision1.toString()).toEqual(revision2.toString());
});
});
describe("setEntryData", () => {
it("should throw if trying to set entry data > 70 bytes", async () => {
await expect(
client.db.setEntryData(privateKey, dataKey, new Uint8Array(MAX_ENTRY_LENGTH + 1))
).rejects.toThrowError(
"Expected parameter 'data' to be 'Uint8Array' of length <= 70, was length 71, was type 'object', value '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'"
);
});
it("should throw if trying to set the deletion entry data", async () => {
await expect(client.db.setEntryData(privateKey, dataKey, DELETION_ENTRY_DATA)).rejects.toThrowError(
"Tried to set 'Uint8Array' entry data that is the deletion sentinel ('Uint8Array(RAW_SKYLINK_SIZE)'), please use the 'deleteEntryData' method instead`"
);
});
});
describe("checkCachedDataLink", () => {
const differentSkylink = "XABvi7JtJbQSMAcDwnUnmp2FKDPjg8_tTTFP4BwMSxVdEg";
const inputs: Array<[string, string | undefined, boolean]> = [
[skylink, undefined, false],
[skylink, skylink, true],
[skylink, differentSkylink, false],
[differentSkylink, skylink, false],
];
it.each(inputs)("checkCachedDataLink(%s, %s) should return %s", (rawDataLink, cachedDataLink, output) => {
expect(checkCachedDataLink(rawDataLink, cachedDataLink)).toEqual(output);
});
it("Should throw on invalid cachedDataLink", () => {
expect(() => checkCachedDataLink(skylink, "asdf")).toThrowError(
"Expected optional parameter 'cachedDataLink' to be valid skylink of type 'string', was type 'string', value 'asdf'"
);
});
});
// REGRESSION TESTS: By creating a gap between setJSON and getJSON, a user
// could call getJSON, get outdated data, then call setJSON, and overwrite
// more up to date data with outdated data, but still use a high enough
// revision number.
//
// The fix is that you cannot retrieve the revision number while calling
// setJSON. You have to use the same revision number that you had when you
// called getJSON.
describe("getJSON/setJSON data race regression unit tests", () => {
let mock: MockAdapter;
beforeEach(() => {
// Add a delay to responses to simulate actual calls that use the network.
mock = new MockAdapter(axios, { delayResponse: 100 });
mock.reset();
mock.onHead(portalUrl).replyOnce(200, {}, { "skynet-portal-api": portalUrl });
});
const skylinkOld = "XABvi7JtJbQSMAcDwnUnmp2FKDPjg8_tTTFP4BwMSxVdEg";
const skylinkOldUrl = getSkylinkUrlForPortal(portalUrl, skylinkOld);
const dataOld = toHexString(stringToUint8ArrayUtf8(skylinkOld)); // hex-encoded skylink
const revisionOld = 0;
const entryDataOld = {
data: dataOld,
revision: revisionOld,
signature:
"921d30e860d51f13d1065ea221b29fc8d11cfe7fa0e32b5d5b8e13bee6f91cfa86fe6b12ca4cef7a90ba52d2c50efb62b241f383e9d7bb264558280e564faa0f",
};
const headersOld = { ...headers, "skynet-skylink": skylinkOld };
const skylinkNew = skylink;
const skylinkNewUrl = skylinkUrl;
const dataNew = data; // hex-encoded skylink
const revisionNew = 1;
const entryDataNew = {
data: dataNew,
revision: revisionNew,
signature:
"2a9889915f06d414e8cde51eb17db565410d20b2b50214e8297f7f4a0cb5c77e0edc62a319607dfaa042e0cc16ed0d7e549cca2abd11c2f86a335009936f150d",
};
const headersNew = { ...headers, "skynet-skylink": skylinkNew };
const jsonOld = { message: 1 };
const jsonNew = { message: 2 };
const skynetJsonOld = { _data: jsonOld, _v: 2 };
const skynetJsonNew = { _data: jsonNew, _v: 2 };
const concurrentAccessError = "Concurrent access prevented in SkyDB";
const higherRevisionError = "A higher revision number for this userID and path is already cached";
it("should not get old data when getJSON and setJSON are called simultaneously on the same client and getJSON doesn't fail", async () => {
// Create a new client with a fresh revision cache.
const client = new SkynetClient(portalUrl);
// Mock setJSON with the old skylink.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkOld, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Set the data.
await client.db.setJSON(privateKey, dataKey, jsonOld);
// Mock getJSON with the new entry data and the new skylink.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataNew));
mock.onGet(skylinkNewUrl).replyOnce(200, skynetJsonNew, headers);
// Mock setJSON with the new skylink.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkNew, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Try to invoke the data race.
// Get the data while also calling setJSON.
//
// Use Promise.allSettled to wait for all promises to finish, or some mocked
// requests will hang around and interfere with the later tests.
const settledResults = await Promise.allSettled([
client.db.getJSON(publicKey, dataKey),
client.db.setJSON(privateKey, dataKey, jsonNew),
]);
let data: JsonData | null;
try {
const values = getSettledValues<JSONResponse>(settledResults);
data = values[0].data;
} catch (e) {
// If any promises were rejected, check the error message.
if ((e as Error).message.includes(concurrentAccessError)) {
// The data race condition was avoided and we received the expected
// error. Return from test early.
return;
}
throw e;
}
// Data race did not occur, getJSON should have latest JSON.
expect(data).toEqual(jsonNew);
// assert our request history contains the expected amount of requests
expect(mock.history.get.length).toBe(2);
expect(mock.history.post.length).toBe(4);
});
it("should not get old data when getJSON and setJSON are called simultaneously on different clients and getJSON doesn't fail", async () => {
// Create two new clients with a fresh revision cache.
const client1 = new SkynetClient(portalUrl);
const client2 = new SkynetClient(portalUrl);
// Mock setJSON with the old skylink.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkOld, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Set the data.
await client1.db.setJSON(privateKey, dataKey, jsonOld);
// Mock getJSON with the new entry data and the new skylink.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataNew));
mock.onGet(skylinkNewUrl).replyOnce(200, skynetJsonNew, headersNew);
// Mock setJSON with the new skylink.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkNew, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Try to invoke the data race.
// Get the data while also calling setJSON.
//
// Use Promise.allSettled to wait for all promises to finish, or some mocked requests will hang around and interfere with the later tests.
const settledResults = await Promise.allSettled([
client1.db.getJSON(publicKey, dataKey),
client2.db.setJSON(privateKey, dataKey, jsonNew),
]);
let data: JsonData | null;
try {
const values = getSettledValues<JSONResponse>(settledResults);
data = values[0].data;
} catch (e) {
// If any promises were rejected, check the error message.
if ((e as Error).message.includes(higherRevisionError)) {
// The data race condition was avoided and we received the expected
// error. Return from test early.
return;
}
throw e;
}
// Data race did not occur, getJSON should have latest JSON.
expect(data).toEqual(jsonNew);
// assert our request history contains the expected amount of requests.
expect(mock.history.get.length).toBe(2);
expect(mock.history.post.length).toBe(4);
});
it("should not mess up cache when two setJSON calls are made simultaneously and one fails", async () => {
// Create a new client with a fresh revision cache.
const client = new SkynetClient(portalUrl);
// Mock a successful setJSON.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkOld, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Use Promise.allSettled to wait for all promises to finish, or some mocked
// requests will hang around and interfere with the later tests.
const values = await Promise.allSettled([
client.db.setJSON(privateKey, dataKey, jsonOld),
client.db.setJSON(privateKey, dataKey, jsonOld),
]);
try {
getSettledValues<JSONResponse>(values);
} catch (e) {
if ((e as Error).message.includes(concurrentAccessError)) {
// The data race condition was avoided and we received the expected
// error. Return from test early.
return;
}
throw e;
}
const cachedRevisionEntry = await client.db.revisionNumberCache.getRevisionAndMutexForEntry(publicKey, dataKey);
expect(cachedRevisionEntry.revision.toString()).toEqual("0");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataOld));
mock.onGet(skylinkOldUrl).replyOnce(200, skynetJsonOld, headersOld);
const { data: receivedJson1 } = await client.db.getJSON(publicKey, dataKey);
expect(receivedJson1).toEqual(jsonOld);
// Make another setJSON call - it should still work.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkNew, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
await client.db.setJSON(privateKey, dataKey, jsonNew);
expect(cachedRevisionEntry.revision.toString()).toEqual("1");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataNew));
mock.onGet(skylinkNewUrl).replyOnce(200, skynetJsonNew, headersNew);
const { data: receivedJson2 } = await client.db.getJSON(publicKey, dataKey);
expect(receivedJson2).toEqual(jsonNew);
expect(mock.history.get.length).toBe(4);
expect(mock.history.post.length).toBe(4);
});
it("should not mess up cache when two setJSON calls are made simultaneously on different clients and one fails", async () => {
// Create two new clients with a fresh revision cache.
const client1 = new SkynetClient(portalUrl);
const client2 = new SkynetClient(portalUrl);
// Run two simultaneous setJSONs on two different clients - one should work,
// one should fail due to bad revision number.
// Mock a successful setJSON.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkOld, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
// Mock a failed setJSON (bad revision number).
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkOld, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(400);
// Use Promise.allSettled to wait for all promises to finish, or some mocked
// requests will hang around and interfere with the later tests.
const values = await Promise.allSettled([
client1.db.setJSON(privateKey, dataKey, jsonOld),
client2.db.setJSON(privateKey, dataKey, jsonOld),
]);
let successClient;
let failClient;
if (values[0].status === "rejected") {
successClient = client2;
failClient = client1;
} else {
successClient = client1;
failClient = client2;
}
// Test that the client that succeeded has a consistent cache.
const cachedRevisionEntrySuccess = await successClient.db.revisionNumberCache.getRevisionAndMutexForEntry(
publicKey,
dataKey
);
expect(cachedRevisionEntrySuccess.revision.toString()).toEqual("0");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataOld));
mock.onGet(skylinkOldUrl).replyOnce(200, skynetJsonOld, headersOld);
const { data: receivedJson1 } = await successClient.db.getJSON(publicKey, dataKey);
expect(receivedJson1).toEqual(jsonOld);
// Make another setJSON call - it should still work.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkNew, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
await successClient.db.setJSON(privateKey, dataKey, jsonNew);
expect(cachedRevisionEntrySuccess.revision.toString()).toEqual("1");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataNew));
mock.onGet(skylinkNewUrl).replyOnce(200, skynetJsonNew, headersNew);
const { data: receivedJson2 } = await successClient.db.getJSON(publicKey, dataKey);
expect(receivedJson2).toEqual(jsonNew);
// Test that the client that failed has a consistent cache.
const cachedRevisionEntryFail = await failClient.db.revisionNumberCache.getRevisionAndMutexForEntry(
publicKey,
dataKey
);
expect(cachedRevisionEntryFail.revision.toString()).toEqual("-1");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataOld));
mock.onGet(skylinkOldUrl).replyOnce(200, skynetJsonOld, headersOld);
const { data: receivedJsonFail1 } = await failClient.db.getJSON(publicKey, dataKey);
expect(receivedJsonFail1).toEqual(jsonOld);
// Make another setJSON call - it should still work.
mock.onPost(uploadUrl).replyOnce(200, { skylink: skylinkNew, merkleroot, bitfield });
mock.onPost(registryPostUrl).replyOnce(204);
await failClient.db.setJSON(privateKey, dataKey, jsonNew);
expect(cachedRevisionEntrySuccess.revision.toString()).toEqual("1");
// Make a getJSON call.
mock.onGet(registryGetUrl).replyOnce(200, JSON.stringify(entryDataNew));
mock.onGet(skylinkNewUrl).replyOnce(200, skynetJsonNew, headersNew);
const { data: receivedJsonFail2 } = await failClient.db.getJSON(publicKey, dataKey);
expect(receivedJsonFail2).toEqual(jsonNew);
// Check final request counts.
expect(mock.history.get.length).toBe(8);
expect(mock.history.post.length).toBe(8);
});
}); | the_stack |
import { AnimatedSprite } from '@pixi/sprite-animated';
import { Texture } from '@pixi/core';
import { expect } from 'chai';
describe('AnimatedSprite', function ()
{
describe('instance', function ()
{
beforeEach(function ()
{
this.textures = [Texture.EMPTY];
});
afterEach(function ()
{
expect(this.sprite.animationSpeed).to.be.equal(1);
expect(this.sprite.loop).to.be.true;
expect(this.sprite.onComplete).to.be.null;
expect(this.sprite.onFrameChange).to.be.null;
expect(this.sprite.onLoop).to.be.null;
expect(this.sprite.playing).to.be.false;
this.sprite.destroy();
this.sprite = null;
});
it('should be correct with default options', function ()
{
this.sprite = new AnimatedSprite(this.textures);
expect(this.sprite._autoUpdate).to.be.true;
});
it('should be correct with autoUpdate=false', function ()
{
this.sprite = new AnimatedSprite(this.textures, false);
expect(this.sprite._autoUpdate).to.be.false;
});
it('should be correct with autoUpdate=true but then turned off via setter', function ()
{
this.sprite = new AnimatedSprite(this.textures, true);
expect(this.sprite._autoUpdate).to.be.true;
this.sprite.autoUpdate = false;
expect(this.sprite._autoUpdate).to.be.false;
});
});
describe('.stop()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.EMPTY], false);
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
afterEach(function ()
{
this.sprite.stop();
expect(this.sprite.playing).to.be.false;
});
it('should stop playing if it is playing', function ()
{
this.sprite._playing = true;
});
it('should do nothing if it is not playing', function ()
{
this.sprite._playing = false;
});
});
describe('.play()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.EMPTY], false);
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
afterEach(function ()
{
this.sprite.play();
expect(this.sprite.playing).to.be.true;
});
it('should start playing if it is not playing', function ()
{
this.sprite._playing = false;
});
it('should do nothing if it is playing', function ()
{
this.sprite._playing = true;
});
});
describe('.onComplete()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.WHITE, Texture.WHITE, Texture.EMPTY]);
this.sprite.animationSpeed = 0.5;
this.sprite.loop = false;
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
it('should fire onComplete', function (done)
{
this.timeout((
this.sprite.textures.length * 1000 / 60 / this.sprite.animationSpeed)
+ (1000 / 60 / this.sprite.animationSpeed * 0.9)
);
this.sprite.onComplete = () =>
{
this.sprite.onComplete = null;
done();
};
this.sprite.play();
expect(this.sprite.playing).to.be.true;
});
it('should the current texture be the last item in textures', function (done)
{
this.sprite.play();
this.sprite.onComplete = () =>
{
expect(this.sprite.texture === this.sprite.textures[this.sprite.currentFrame]).to.be.true;
this.sprite.onComplete = null;
done();
};
});
});
describe('.gotoAndPlay()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.EMPTY, Texture.EMPTY, Texture.EMPTY]);
this.sprite.animationSpeed = 0.5;
this.sprite.loop = false;
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
it('should fire frame after start frame during one play and fire onComplete', function (done)
{
const frameIds = [];
this.sprite.onComplete = () =>
{
expect(frameIds).to.deep.equal([1, 2]);
expect(this.sprite.playing).to.be.false;
this.sprite.onComplete = null;
this.sprite.onFrameChange = null;
done();
};
this.sprite.onFrameChange = (frame) =>
{
frameIds.push(frame);
};
this.sprite.gotoAndPlay(1);
expect(this.sprite.playing).to.be.true;
});
});
describe('.gotoAndStop()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.EMPTY, Texture.EMPTY, Texture.EMPTY]);
this.sprite.animationSpeed = 0.5;
this.sprite.loop = false;
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
beforeEach(function ()
{
this.sprite._playing = false;
});
it('should fire onFrameChange on target frame', function (done)
{
const targetFrame = 1;
this.sprite.onFrameChange = (frame) =>
{
expect(frame).to.equal(targetFrame);
expect(this.sprite.playing).to.be.false;
this.sprite.onComplete = null;
this.sprite.onFrameChange = null;
done();
};
this.sprite.gotoAndStop(targetFrame);
expect(this.sprite.playing).to.be.false;
});
it('should not fire onFrameChange on target frame if current is already target', function ()
{
let fired = false;
const targetFrame = 1;
this.sprite.gotoAndStop(targetFrame);
this.sprite.onFrameChange = () =>
{
fired = true;
};
this.sprite.gotoAndStop(targetFrame);
expect(this.sprite.playing).to.be.false;
expect(fired).to.be.false;
});
});
describe('.onFrameChange()', function ()
{
before(function ()
{
this.sprite = new AnimatedSprite([Texture.EMPTY, Texture.WHITE, Texture.EMPTY]);
this.sprite.animationSpeed = 0.5;
this.sprite.loop = false;
});
after(function ()
{
this.sprite.destroy();
this.sprite = null;
});
beforeEach(function ()
{
this.sprite._playing = false;
});
it('should fire every frame(except current) during one play', function (done)
{
const frameIds = [];
this.sprite.gotoAndStop(0);
this.sprite.onComplete = () =>
{
expect(frameIds).to.deep.equal([1, 2]); // from 0 to 2, triggers onFrameChange at 1,2.
expect(this.sprite.currentFrame).to.equal(2);
this.sprite.onComplete = null;
this.sprite.onFrameChange = null;
done();
};
this.sprite.onFrameChange = (frame) =>
{
frameIds.push(frame);
};
this.sprite.play();
expect(this.sprite.playing).to.be.true;
});
it('should fire every frame(except current) during one play - reverse', function (done)
{
const frameIds = [];
this.sprite.gotoAndStop(2);
this.sprite.animationSpeed = -0.5;
this.sprite.onComplete = () =>
{
expect(frameIds).to.deep.equal([1, 0]); // from 2 to 0, triggers onFrameChange at 1,0.
expect(this.sprite.currentFrame).to.equal(0);
this.sprite.onComplete = null;
this.sprite.onFrameChange = null;
done();
};
this.sprite.onFrameChange = (frame) =>
{
frameIds.push(frame);
};
this.sprite.play();
expect(this.sprite.playing).to.be.true;
});
it('should fire every frame(except current) during one play - from not start/end', function (done)
{
const frameIds = [];
this.sprite.gotoAndStop(1);
this.sprite.animationSpeed = -0.5;
this.sprite.onComplete = () =>
{
expect(frameIds).to.deep.equal([0]); // from 1 to 0, triggers onFrameChange at 0.
expect(this.sprite.currentFrame).to.equal(0);
this.sprite.onComplete = null;
this.sprite.onFrameChange = null;
done();
};
this.sprite.onFrameChange = (frame) =>
{
frameIds.push(frame);
};
this.sprite.play();
expect(this.sprite.playing).to.be.true;
});
});
describe('.textures', function ()
{
it('should set the first frame when setting new textures', function (done)
{
const orig1 = Texture.EMPTY.clone();
const orig2 = Texture.EMPTY.clone();
const orig3 = Texture.EMPTY.clone();
const sprite = new AnimatedSprite([orig1, orig2, orig3]);
sprite.gotoAndPlay(0);
sprite.loop = false;
sprite.onComplete = () =>
{
sprite.gotoAndStop(0);
const frame1 = Texture.EMPTY.clone();
const frame2 = Texture.EMPTY.clone();
const frame3 = Texture.EMPTY.clone();
sprite.textures = [frame1, frame2, frame3];
expect(sprite.currentFrame).to.equal(0);
expect(sprite._texture).to.equal(frame1);
done();
};
});
});
}); | the_stack |
import { StringEncodingOptions } from "./string-encoding-options";
/**
* Represents a request to read a number of bits
*/
export interface BitstreamRequest {
resolve : (buffer : number) => void;
length : number;
peek : boolean;
}
/**
* A class which lets you read through one or more Buffers bit-by-bit. All data is read in big-endian (network) byte
* order
*/
export class BitstreamReader {
private buffers : Uint8Array[] = [];
private bufferedLength : number = 0;
private blockedRequest : BitstreamRequest = null;
private _offsetIntoBuffer = 0;
private _bufferIndex = 0;
private _offset = 0;
private _spentBufferSize = 0;
/**
* Get the index of the buffer currently being read. This will always be zero unless retainBuffers=true
*/
get bufferIndex() {
return this._bufferIndex;
}
/**
* Get the current offset in bits, starting from the very first bit read by this reader (across all
* buffers added)
*/
get offset() {
return this._offset;
}
/**
* The total number of bits which were in buffers that have previously been read, and have since been discarded.
*/
get spentBufferSize() {
return this._spentBufferSize;
}
/**
* Set the current offset in bits, as measured from the very first bit read by this reader (across all buffers
* added). If the given offset points into a previously discarded buffer, an error will be thrown. See the
* retainBuffers option if you need to seek back into previous buffers. If the desired offset is in a previous
* buffer which has not been discarded, the current read head is moved into the appropriate offset of that buffer.
*/
set offset(value) {
if (value < this._spentBufferSize) {
throw new Error(
`Offset ${value} points into a discarded buffer! `
+ `If you need to seek backwards outside the current buffer, make sure to set retainBuffers=true`
);
}
value -= this._spentBufferSize;
let bufferIndex = 0;
for (let buf of this.buffers) {
let size = buf.length * 8;
if (value < size) {
this._bufferIndex = bufferIndex;
this._offset = value;
return;
}
value -= size;
++bufferIndex;
}
}
/**
* When true, buffers are not removed, which allows the user to
* "rewind" the current offset back into buffers that have already been
* visited. If you enable this, you will need to remove buffers manually using
* clean()
*/
retainBuffers : boolean = false;
/**
* Remove any fully used up buffers. Only has an effect if retainBuffers is true.
* Optional `count` parameter lets you control how many buffers can be freed.
*/
clean(count?) {
let buffers = this.buffers.splice(0, count !== void 0 ? Math.min(count, this._bufferIndex) : this._bufferIndex);
this._spentBufferSize += buffers.map(b => b.length * 8).reduce((pv, cv) => pv + cv, 0);
this._bufferIndex -= buffers.length;
}
/**
* The number of bits that are currently available.
*/
get available() {
return this.bufferedLength - this.skippedLength;
}
/**
* Check if the given number of bits are currently available.
* @param length The number of bits to check for
* @returns True if the required number of bits is available, false otherwise
*/
isAvailable(length : number) {
return this.bufferedLength >= length;
}
private ensureNoReadPending() {
if (this.blockedRequest)
throw new Error(`Only one read() can be outstanding at a time.`);
}
private textDecoder = new TextDecoder();
/**
* Asynchronously read the given number of bytes, encode it into a string, and return the result,
* optionally using a specific text encoding.
* @param length The number of bytes to read
* @param options A set of options to control conversion into a string. @see StringEncodingOptions
* @returns The resulting string
*/
async readString(length : number, options? : StringEncodingOptions): Promise<string> {
this.ensureNoReadPending();
await this.assure(8*length);
return this.readStringSync(length, options);
}
/**
* Synchronously read the given number of bytes, encode it into a string, and return the result,
* optionally using a specific text encoding.
* @param length The number of bytes to read
* @param options A set of options to control conversion into a string. @see StringEncodingOptions
* @returns The resulting string
*/
readStringSync(length : number, options? : StringEncodingOptions): string {
if (!options)
options = {};
this.ensureNoReadPending();
let buffer = new Uint8Array(length);
let firstNullByte = -1;
for (let i = 0, max = length; i < max; ++i) {
buffer[i] = this.readSync(8);
if (buffer[i] === 0 && firstNullByte < 0)
firstNullByte = i;
}
if (options.nullTerminated !== false) {
if (firstNullByte >= 0) {
buffer = buffer.subarray(0, firstNullByte);
}
}
if (options.encoding === 'utf-8') {
return this.textDecoder.decode(buffer);
} else {
if (typeof Buffer === 'undefined')
throw new Error(`Encoding '${options.encoding}' is not supported: No Node.js Buffer implementation and TextDecoder only supports utf-8`);
return Buffer.from(buffer).toString(<any>options.encoding || 'utf-8');
}
}
/**
* Read a number of the given bitlength synchronously without advancing
* the read head.
* @param length The number of bits to read
* @returns The number read from the bitstream
*/
peekSync(length : number) {
return this.readCoreSync(length, false);
}
private skippedLength = 0;
/**
* Skip the given number of bits.
* @param length The number of bits to skip
*/
skip(length : number) {
this.skippedLength += length;
}
/**
* Read a number of the given bitlength synchronously. If there are not enough
* bits available, an error is thrown.
* @param length The number of bits to read
* @returns The number read from the bitstream
*/
readSync(length : number): number {
return this.readCoreSync(length, true);
}
private readCoreSync(length : number, consume : boolean): number {
this.ensureNoReadPending();
let value : bigint = BigInt(0);
let remainingLength = length;
if (this.available < length)
throw new Error(`underrun: Not enough bits are available (requested=${length}, available=${this.bufferedLength}, buffers=${this.buffers.length})`);
this.adjustSkip();
let offset = this._offsetIntoBuffer;
let bufferIndex = this._bufferIndex;
let bitLength = 0;
while (remainingLength > 0) {
let buffer = this.buffers[bufferIndex];
let byte = BigInt(buffer[Math.floor(offset / 8)]);
let bitOffset = offset % 8;
let bitContribution = Math.min(8 - bitOffset, remainingLength);
let mask = Math.pow(0x2, bitContribution) - 1;
value = (value << BigInt(bitContribution)) | ((byte >> (BigInt(8) - BigInt(bitContribution) - BigInt(bitOffset))) & BigInt(mask));
// update counters
offset += bitContribution;
remainingLength -= bitContribution;
bitLength += bitContribution;
if (offset >= buffer.length*8) {
bufferIndex += 1;
offset = 0;
}
}
if (consume) {
this.bufferedLength -= length;
this._offsetIntoBuffer = offset;
this._offset += bitLength;
this._bufferIndex = bufferIndex;
if (!this.retainBuffers) {
this.clean();
}
}
return Number(value);
}
private adjustSkip() {
if (this.skippedLength <= 0)
return;
// First, remove any buffers that are completely skipped
while (this.buffers && this.skippedLength > this.buffers[0].length*8-this._offsetIntoBuffer) {
this.skippedLength -= (this.buffers[0].length*8 - this._offsetIntoBuffer);
this._offsetIntoBuffer = 0;
this.buffers.shift();
}
// If any buffers are left, then the amount of remaining skipped bits is
// less than the full length of the buffer, so entirely consume the skipped length
// by putting it into the offset.
if (this.buffers.length > 0) {
this._offsetIntoBuffer += this.skippedLength;
this.skippedLength = 0;
}
}
/**
* Wait until the given number of bits is available
* @param length The number of bits to wait for
* @returns A promise which will resolve once the given number of bits is available
*/
assure(length : number) : Promise<void> {
this.ensureNoReadPending();
if (this.bufferedLength >= length) {
return Promise.resolve();
}
let request : BitstreamRequest = { resolve: null, length, peek: true };
let promise = new Promise<number>(resolve => request.resolve = resolve);
this.blockedRequest = request;
return promise.then(() => {});
}
/**
* Asynchronously read a number of the given bitlength. If there are not enough bits available
* to complete the operation, the operation is delayed until enough bits become available
* @param length The number of bits to read
* @returns A promise which resolves with the number read from the bitstream
*/
read(length : number) : Promise<number> {
this.ensureNoReadPending();
if (this.available >= length) {
return Promise.resolve(this.readSync(length));
} else {
let request : BitstreamRequest = { resolve: null, length, peek: false };
let promise = new Promise<number>(resolve => request.resolve = resolve);
this.blockedRequest = request;
return promise;
}
}
/**
* Asynchronously read a number of the given bitlength without advancing the read head.
* @param length The number of bits to read. If there are not enough bits available
* to complete the operation, the operation is delayed until enough bits become available.
* @returns A promise which resolves iwth the number read from the bitstream
*/
async peek(length : number): Promise<number> {
await this.assure(length);
return this.peekSync(length);
}
/**
* Add a buffer onto the end of the bitstream. Important: This method does not insert the data at the
* current read head, it places it at the end of the bitstream.
* @param buffer The buffer to add to the bitstream
* @deprecated Use addBuffer() instead
*/
unread(buffer : Uint8Array) {
this.buffers.unshift(buffer);
}
/**
* Add a buffer onto the end of the bitstream.
* @param buffer The buffer to add to the bitstream
*/
addBuffer(buffer : Uint8Array) {
this.buffers.push(buffer);
this.bufferedLength += buffer.length * 8;
if (this.blockedRequest && this.blockedRequest.length <= this.available) {
let request = this.blockedRequest;
this.blockedRequest = null;
if (request.peek) {
request.resolve(0);
} else {
request.resolve(this.readSync(request.length));
}
}
}
} | the_stack |
import _ from 'lodash'
import moment from 'moment'
import onlineRender, { IOnlineData } from './online_render'
import onlineWeekRender, { IOnlineWeekOptions } from './online_week_render'
import developmentWeekRender, { IDevelopmentOptions } from './development_week_render'
import Transporter from '~/src/library/email'
import knex from '~/src/library/mysql'
import env from '~/src/config/env'
type ICacheOptions = {
expire?: number
}
class Cache<T> {
constructor(fn: () => Promise<T>, options: ICacheOptions = {}) {
if (typeof fn !== 'function') {
throw new TypeError(`fn must be a function`)
}
this.getNew = fn
const keys = Object.keys(options) as (keyof ICacheOptions)[]
keys.forEach((key) => {
this[key] = options[key] as any
})
}
// 缓存的有效时间, 单位ms
expire: number = 1 * 24 * 60 * 60 * 1000
// 上一次修改时间, 单位ms
lastModify?: number
// 缓存值
value: any
// 获取值
async get(): Promise<T> {
let now = new Date().getTime()
if (!this.lastModify || now - this.lastModify > this.expire) {
this.lastModify = now
this.value = await this.getNew()
}
return this.value
}
// 获取最新值
getNew: Function
}
type IEmailType = 'online' | 'online-week' | 'development' | 'development-week'
type IEmail = string
type IRangeTime = {
startTime: number
endTime: number
}
/**
* 发送邮件报告
* @param type
* @param title
* @param users
* @param options
*/
async function sendEmail(type: 'online', title: string, users: IUcid[], options: IOnlineData): Promise<any>
async function sendEmail(type: 'online-week', title: string, users: IUcid[], options: IOnlineWeekOptions): Promise<any>
async function sendEmail(
type: 'development-week',
title: string,
users: IUcid[],
options: IDevelopmentOptions,
): Promise<any>
async function sendEmail(type: IEmailType, title: string, users: IUcid[], options: any): Promise<any> {
try {
if (users.length === 0) {
throw new Error(`users 不能为空`)
}
let to = await User.getEmailsFromUcids(users)
if (env === 'dev') {
to = ['1024371442@qq.com']
}
if (to.length === 0) {
throw new Error(`to 不能为空`)
}
let sentMessageInfo
let html
switch (type) {
case 'online':
sentMessageInfo = await Transporter.sendEmail({
to,
subject: title || '上线报告',
text: title || '上线报告',
html: onlineRender(options),
})
break
case 'online-week':
html = onlineWeekRender(options)
sentMessageInfo = await Transporter.sendEmail({
to,
subject: title || `上线周报`,
text: title || `上线周报`,
html,
})
break
case 'development-week':
html = developmentWeekRender(options)
sentMessageInfo = await Transporter.sendEmail({
to,
subject: title,
text: title,
html,
})
break
}
return sentMessageInfo
} catch (e) {
e.message = `${type}邮件发送失败 ${e.message}`
throw e
}
}
// 16位ucid
type IUcid = string
class User {
static emailCache: { [ucid: string]: Cache<string> } = {}
static defaultUsers: string[] = []
/**
* 根据ucid获取email
* @param users
*/
static async getEmailsFromUcids(users: IUcid[]): Promise<IEmail[]> {
let emailMap: { [key: string]: string } = {}
let result = []
for (let ucid of users) {
if (_.get(emailMap, ucid)) {
// 如果缓存中已存在
result.push(_.get(emailMap, ucid))
} else {
// 如果缓存中不存在, 则调用接口获取
const email = await this.getEmailFromUcid(ucid)
if (email) {
result.push(email)
emailMap[ucid] = email
}
}
}
return result
}
static async getEmailFromUcid(ucid: string): Promise<string | null> {
if (!this.emailCache[ucid]) {
this.emailCache[ucid] = new Cache(async () => {
const user = await knex('user').where('id', ucid).first()
return _.get(user, 'email')
})
}
return this.emailCache[ucid].get()
}
/**
* 获取项目的所有用户
*/
static async getProjectUsers(projectCode: string) {
const project = await knex('project_new').where('project_code', projectCode).first()
const users = await knex('project_user').where('project_id', project.id)
const _users = users.map((v: any) => v.user_id)
return _users
}
}
class Project {
static projectCache: { [departmentId: string]: any } = {}
static projectOnlineDataCache: { [projectId: string]: Cache<any> } = {}
/**
* 获取用户相关的项目
* @param ucidgetUserDevelopData
*/
static async getProjectsByUser(ucid: string) {
let users = await knex('project_user').where('user_id', ucid)
if (_.isArray(users)) {
const projectIds = users.map((v) => v.project_id)
const projects = await knex('project_new').whereIn('id', projectIds).andWhere('order', '>', '9')
return projects
}
return []
}
/**
* 获取部门内的项目
* @param projectId
*/
static async getProjects(departmentId: string) {
if (!_.get(this.projectCache, 'departmentId')) {
let projects = await knex('project_new')
.where('order', '>', 9)
.andWhere('department', +departmentId)
this.projectCache[departmentId] = projects
}
return this.projectCache[departmentId]
}
/**
* 获取某项目的研发提效数据
* @param projectCode
* @param options
*/
static async getProjectDevelopData(projectId: string, options: IRangeTime) {
const project = await knex('project_new').where('id', projectId).first()
const pages = await knex('page_record').where('project_id', projectId)
project.pagesTotal = pages.length
// 是否为新项目
project.isNew = project.create_at >= options.startTime
// 新增页面
const newPages = pages.filter((v: any) => v.create_at >= options.startTime && v.create_at <= options.endTime)
project.newPagesTotal = newPages.length
if (newPages.length) {
// 获取项目内所有的用户
const _users = await knex('project_user').where('project_id', project.id).orderBy('role', 'desc')
project.users = _users
// 计算发布次数
let publishCounts = 0
for (let page of pages) {
const publishs = await knex('page_publish_history')
.where('page_id', page.id)
.andWhere('env', 'test')
.andWhereBetween('update_at', [options.startTime, options.endTime])
if (publishs.length) {
publishCounts += publishs.length
}
}
project.publishCounts = publishCounts
}
return project
}
/**
* 获取某项目的上线数据
* @param projectCode
* @param options
*/
static async getOnlineData(projectId: string, options: IRangeTime) {
if (!this.projectOnlineDataCache[projectId]) {
this.projectOnlineDataCache[projectId] = new Cache(async () => {
// 2. 获取所有的用户
const users = await knex('project_user').where('project_id', projectId).orderBy('role', 'desc')
// 3. 获取项目内所有的页面
const pages = await knex('page_record').where('project_id', projectId)
let onlineData: any[] = []
let updateAtMap: any = {}
if (_.isArray(pages) && pages.length) {
// 4. 获取页面的发布记录
for (let page of pages) {
const publishs = await knex('page_publish_history')
.where('page_id', page.id)
.andWhere('env', 'prod')
.andWhereBetween('update_at', [options.startTime, options.endTime])
if (publishs && publishs.length) {
// 以发布时间分组
for (let i = 0; i < publishs.length; i++) {
let { update_at, release_note, update_user_name } = publishs[i]
if (updateAtMap[update_at]) {
updateAtMap[update_at].pages.push(page)
} else {
updateAtMap[update_at] = {
pages: [page],
online_time: moment(update_at * 1000).format('MM.DD HH:mm'),
online_remark: release_note,
online_user_name: update_user_name,
}
}
}
}
}
// 按照上线时间排序
let updateAtList = Object.keys(updateAtMap).sort((a, b) => +b - +a)
// 合并上线记录
for (let key of updateAtList) {
let list = updateAtMap[key]
if (list.pages.length) {
onlineData.push(list)
}
}
}
return {
users,
onlineData,
}
})
}
return this.projectOnlineDataCache[projectId].get()
}
}
type IGlobalData = {
globalPagesTotal: number
globalProjectsTotal: number
globalNewProjectTotal: number
globalNewPagesTotal: number
}
class Department {
static departmentCache: { [departmentId: string]: any } = {}
static globalDataCache: Cache<IGlobalData>
static projectDevelopDataCache: { [key: string]: Cache<any> } = {}
/**
* 获取所有部门的总项目数和总页面数
* @param knex
*/
static async getGlobalData(startTime: number, entTime: number) {
if (!this.globalDataCache) {
this.globalDataCache = new Cache<IGlobalData>(async () => {
const departments = await knex('department').select('*')
let week_start = startTime || moment('2019-01-01').unix()
let week_end = entTime || moment().unix()
let globalNewProjectTotal = 0
let globalNewPagesTotal = 0
for (let i = 0; i < departments.length; i++) {
let department = departments[i]
let { newPagesTotal, newProjectTotal } = await this.getDepartmentDevData(department.id, week_start, week_end)
globalNewProjectTotal += newProjectTotal
globalNewPagesTotal += newPagesTotal
}
const projects = await knex('project_new').where('order', '>', 9)
let projectIds = projects.map((p: any) => p.id)
let globalProjectsTotal = projects.length
const pages = await knex('page_record').whereIn('project_id', projectIds)
let globalPagesTotal = pages.length
return { globalPagesTotal, globalProjectsTotal, globalNewProjectTotal, globalNewPagesTotal }
})
}
return this.globalDataCache.get()
}
/**
* 获取所有的部门
* @param knex
*/
static async getAllDepartment() {
return knex('department').select('*').orderBy('order', 'desc')
}
/**
* 根据departmentId获取部门信息
* 无需区分环境,不同环境对应的数据是一致的
* @param departmentId
*/
static async getDepartment(departmentId: string) {
if (!_.get(this.departmentCache, 'departmentId')) {
let department = await knex('department')
.where('id', +departmentId)
.first()
this.departmentCache[departmentId] = department
}
return this.departmentCache[departmentId]
}
/**
* 获取某时间范围内部门上线数据
* @param departmentId
* @param start
* @param end
*/
static async getDepartmentOnlineData(departmentId: string, startTime: number, endTime: number) {
const department = await this.getDepartment(departmentId)
// 1. 获取部门内的项目
let projects: any[] = await Project.getProjects(departmentId)
let res = await this.getProjectsOnlineData(projects, startTime, endTime)
return { ...res, department }
}
static async getProjectsOnlineData(projects: any, startTime: number, endTime: number) {
let publishCounts = 0
let pageCounts = 0
let result: any[] = []
let users = []
for (let project of projects) {
// 是否为新项目
project.isNew = project.create_at >= startTime
const { users: _users, onlineData } = await Project.getOnlineData(project.id, {
startTime,
endTime,
})
project.users = _users
Array.isArray(_users) && users.push(..._users.map((v: any) => v.user_id))
if (onlineData.length) {
project.onlineData = onlineData
result.push(project)
}
}
users.push(...User.defaultUsers)
// 去重
users = Array.from(new Set(users))
return { projects: result, pageCounts, publishCounts, users }
}
/**
* 获取某时间范围内个人相关上线数据
* @param departmentId
* @param start
* @param end
*/
static async getUserOnlineData(ucid: string, startTime: number, endTime: number) {
// 1. 获取项目
let projects: any[] = await Project.getProjectsByUser(ucid)
return this.getProjectsOnlineData(projects, startTime, endTime)
}
static async getProjectsDevData(projects: any[], startTime: number, endTime: number) {
let result: any[] = []
let newPagesTotal = 0
let pagesTotal = 0
let newProjectTotal = 0
let projectsTotal = projects.length
let users = []
for (let p of projects) {
// 2. 获取项目内的页面
if (!this.projectDevelopDataCache[p.id]) {
this.projectDevelopDataCache[p.id] = new Cache(async () => {
return Project.getProjectDevelopData(p.id, { startTime, endTime })
})
}
// 从缓存中获取
const project = await this.projectDevelopDataCache[p.id].get()
pagesTotal += project.pagesTotal
newProjectTotal += project.isNew ? 1 : 0
newPagesTotal += project.newPagesTotal
Array.isArray(project.users) && users.push(project.users.map((v: any) => v.user_id))
if (project.newPagesTotal) {
result.push(project)
}
}
result = result.sort((a, b) => b.newPagesTotal - a.newPagesTotal)
users.push(...User.defaultUsers)
// 去重
users = Array.from(new Set(users))
return { projectsTotal, projects: result, users, newPagesTotal, pagesTotal, newProjectTotal }
}
/**
* 获取某时间范围内部门开发数据
* @param departmentId
* @param start
* @param end
*/
static async getDepartmentDevData(departmentId: string, start: number, end: number) {
// 1. 获取部门内的项目
let projects: any[] = await Project.getProjects(departmentId)
return this.getProjectsDevData(projects, start, end)
}
/**
* 获取某时间范围内个人相关研发提效数据
* @param departmentId
* @param start
* @param end
*/
static async getUserDevelopData(ucid: string, startTime: number, endTime: number) {
// 1. 获取用户所在的项目
let projects: any[] = await Project.getProjectsByUser(ucid)
return this.getProjectsDevData(projects, startTime, endTime)
}
}
class EmailUtils {
static User = User
static Project = Project
static Department = Department
static format(start: number, end: number) {
return moment(start * 1000).format('YYYY.MM.DD') + '-' + moment(end * 1000).format('MM.DD')
}
static sendEmail = sendEmail
}
export default EmailUtils | the_stack |
'use strict'
import User from 'App/Models/User'
import Customer from 'App/Models/Customer'
import PermissionHelper from '../Helpers/PermissionHelper'
import Company from 'App/Models/Company'
import Bouncer from '@ioc:Adonis/Addons/Bouncer'
import AttributeSet from 'App/Models/AttributeSet'
import Product from 'App/Models/Product'
import InvoiceQuotation from 'App/Models/InvoiceQuotation'
const accessCompany = async (
resourcePermission: string,
authUser: User,
requestedCompany: Company
) => {
const isPermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
await authUser.load('companies')
const serialisedUser = authUser.serialize()
if (
serialisedUser.companies.some(
(serialisedCompany) => serialisedCompany.id === requestedCompany.id
) &&
isPermitted
) {
return true
}
return Bouncer.deny('You are not permitted to perform this action!')
}
const accessCompanyUser = async (
resourcePermission: string,
authUser: User,
requestedCompany: Company | null,
requestedUser: User
) => {
const isPermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
const authUserCompanyIds = await serialisedAuthUserCompanyIds(authUser)
await requestedUser.load('companies')
const reqUserCompanies = requestedUser.companies
const serialisedReqUserCompanyIds = reqUserCompanies.map((company) => {
company.serialize()
return company.id
})
/* console.log({
authUserCompanyIds,
serialisedReqUserCompanyIds,
}) */
if (!requestedCompany) {
// If no requested company, check if the requested user and
// auth user belong to the same company
const belongToSameCompany = authUserCompanyIds.some(
(authUserCompanyId) =>
serialisedReqUserCompanyIds[serialisedReqUserCompanyIds.indexOf(authUserCompanyId)]
)
//console.log(belongToSameCompany)
return belongToSameCompany && isPermitted
} else {
if (
reqUserCompanies.some((reqCompany) => reqCompany.id === requestedCompany.id) &&
isPermitted
) {
return true
}
}
return Bouncer.deny('You are not permitted to perform this action!')
}
/**
* Helper function to determine access to a requested company, customer,
* as permitted by the resource permission
* @param resourcePermission The resource permission required for the operation
* @param authUser The authenticated user
* @param requestedCompany The company whose access is being requested
* @param requestedCustomer The customer whose access is being requested
* @returns {Boolean} True/false
*/
const accessCompanyCustomer = async (
resourcePermission: string,
authUser: User,
requestedCompany: Company | null,
requestedCustomer: Customer
) => {
const isPermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
const authUserCompanyIds = await serialisedAuthUserCompanyIds(authUser)
if (!requestedCompany) {
// If no requested company, check if the requested customer and
// auth user belong to the same company
const belongToSameCompany = authUserCompanyIds.some(
(authUserCompanyId) => authUserCompanyId === requestedCustomer.companyId
)
//console.log(belongToSameCompany)
return belongToSameCompany && isPermitted
} else {
if (requestedCustomer.companyId === requestedCompany?.id && isPermitted) {
return true
}
}
return Bouncer.deny('You are not permitted to perform this action!')
}
export const accessCustomers = async (
resourcePermission: string,
authUser: User,
customers: Customer | string[]
) => {
const resourcePermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
await authUser.load('companies')
const authUserCompanies = authUser.companies
if (customers && Array.isArray(customers)) {
/**
* Array to hold each permitted customer
*/
const permitted: boolean[] = []
for (let i = 0; i < customers.length; i++) {
const customerId = customers[i]
const customer = await Customer.findOrFail(customerId)
// Load customer company
await customer.load('company')
const customerCompany = customer.company
if (
authUserCompanies.some((authUserCompany) => authUserCompany.id === customerCompany.id) &&
resourcePermitted
) {
permitted.push(true)
} else permitted.push(false)
}
if (permitted.every((value) => value === true)) return true
else return Bouncer.deny('You are not permitted to perform this action!')
} else {
const customer = customers
// Load customer company
await customer.load('company')
const customerCompany = customer.company
if (
authUserCompanies.some((authUserCompany) => authUserCompany.id === customerCompany.id) &&
resourcePermitted
) {
return true
} else return Bouncer.deny('You are not permitted to perform this action!')
}
}
/**
* Checks if the authenticated user has access to the requested products
* @param resourcePermission The resource permission
* @param authUser The authenticated user
* @param requestedCompany The company whose product(s) are requested
* @param requestedProducts An array of Products or Product IDs
* @returns {Promise<boolean>} Returns true/false
*/
export const accessProducts = async (
resourcePermission: string,
authUser: User,
requestedProducts: Product | string[],
mode: 'edit' | 'view' = 'view'
): Promise<boolean | [string, number]> => {
const resourcePermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
const authUserCompanyIds = await serialisedAuthUserCompanyIds(authUser)
if (requestedProducts && Array.isArray(requestedProducts)) {
if (requestedProducts.every((product) => typeof product === 'string')) {
/**
* Array to hold each permitted customer
*/
const permitted: boolean[] = []
for (let i = 0; i < requestedProducts.length; i++) {
const productId = requestedProducts[i]
const product = await Product.findOrFail(productId)
// Load product companies
await product.load('companies')
const productCompanies = product.companies
const productCompaniesIds: string[] = productCompanies.map((company) => company.id)
// Check is user belongs to any of the product companies
const belongToSameCompany = authUserCompanyIds.some(
(authUserCompanyId) => productCompaniesIds[productCompaniesIds.indexOf(authUserCompanyId)]
)
if (mode === 'view') {
if (belongToSameCompany && resourcePermitted) {
permitted.push(true)
} else permitted.push(false)
} else {
// Check if user belongs to a company which can edit the product
// 1. Get the company with `edit` privilege for the product
const companyWithEditAccess = await product
.related('companies')
.query()
.whereInPivot('ownership', ['owner'])
.first()
// 2. Now check if the authUser belongs to this company
const authUserBelongsToEditAccessCompany = authUserCompanyIds.some(
(authUserCompanyId) => authUserCompanyId === companyWithEditAccess?.id
)
if (belongToSameCompany && authUserBelongsToEditAccessCompany && resourcePermitted) {
permitted.push(true)
} else permitted.push(false)
}
}
if (permitted.every((value) => value)) return true
else return Bouncer.deny('You are not permitted to perform this action!')
//
} else throw new Error('Array of string ids expected')
} else {
const product = requestedProducts
// Load product companies
await product.load('companies')
const productCompanies = product.companies
const productCompaniesIds: string[] = productCompanies.map((company) => company.id)
// Check is user belongs to any of the product companies
const belongToSameCompany = authUserCompanyIds.some(
(authUserCompanyId) => productCompaniesIds[productCompaniesIds.indexOf(authUserCompanyId)]
)
if (mode === 'view') {
if (belongToSameCompany && resourcePermitted) {
return true
} else return Bouncer.deny('You are not permitted to perform this action!')
} else {
// Check if user belongs to a company which can edit the product
// 1. Get the company with `edit` privilege for the product
const companyWithEditAccess = await product
.related('companies')
.query()
.whereInPivot('ownership', ['owner'])
.first()
// 2. Now check if the authUser belongs to this company
const authUserBelongsToEditAccessCompany = authUserCompanyIds.some(
(authUserCompanyId) => authUserCompanyId === companyWithEditAccess?.id
)
if (belongToSameCompany && authUserBelongsToEditAccessCompany && resourcePermitted) {
return true
} else return Bouncer.deny('You are not permitted to perform this action!')
}
}
}
export const accessInvoicesQuotations = async (
resourcePermission: string,
authUser: User,
invoices_quotations: InvoiceQuotation | string[],
ownerCompany: Company
) => {
const resourcePermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
await authUser.load('companies')
const authUserCompanies = authUser.companies
if (invoices_quotations && Array.isArray(invoices_quotations)) {
/**
* Array to hold each permitted invoice_quotation
*/
const permitted: boolean[] = []
for (let i = 0; i < invoices_quotations.length; i++) {
const invoiceQuotationId = invoices_quotations[i]
const invoiceQuotation = await InvoiceQuotation.findOrFail(invoiceQuotationId)
// Load invoice_quotation company
await invoiceQuotation.load('company')
const invoiceQuotationCompany = invoiceQuotation.company
if (invoiceQuotationCompany.id !== ownerCompany.id) {
permitted.push(false)
continue
}
if (
authUserCompanies.some(
(authUserCompany) => authUserCompany.id === invoiceQuotationCompany.id
) &&
resourcePermitted
) {
permitted.push(true)
} else permitted.push(false)
}
if (permitted.every((value) => value === true)) return true
else return Bouncer.deny('You are not permitted to perform this action!')
} else {
const invoiceQuotation = invoices_quotations
// Load invoice_quotation company
await invoiceQuotation.load('company')
const invoiceQuotationCompany = invoiceQuotation.company
if (invoiceQuotationCompany.id !== ownerCompany.id) {
return Bouncer.deny(
'You are not permitted to perform this action! Make sure you have selected the right company.'
)
}
if (
authUserCompanies.some(
(authUserCompany) => authUserCompany.id === invoiceQuotationCompany.id
) &&
resourcePermitted
) {
return true
} else return Bouncer.deny('You are not permitted to perform this action!')
}
}
const serialisedAuthUserCompanyIds = async function (authUser: User) {
await authUser.load('companies')
const authUserCompanies = authUser.companies
if (!authUserCompanies.length) return []
const serialisedUser = authUserCompanies.map((company) => {
company.serialize()
return company.id
})
return serialisedUser
}
const serialisedAttributeSetCompanyIds = async function (attributeSet: AttributeSet) {
await attributeSet.load('companies')
const attributeSetCompanies = attributeSet.companies
if (!attributeSetCompanies.length) return []
const serialisedIds = attributeSetCompanies.map((company) => {
company.serialize()
return company.id
})
return serialisedIds
}
/**
* Helper function to determine access to a requested company
* and attribute set, as permitted by the resource permission
* @param resourcePermission The resource permission required for the operation
* @param authUser The authenticated user
* @param requestedCompany The company whose access is being requested
* @param requestedAttributeSet The customer whose access is being requested
* @returns {Boolean} True/false
*/
export const accessCompanyAttributeSet = async (
resourcePermission: string,
authUser: User,
requestedCompany: Company | null,
requestedAttributeSet: AttributeSet
) => {
const isPermitted = await PermissionHelper.hasResourcePermission({
resourcePermission,
user: authUser,
loggable: true,
})
if (requestedAttributeSet.isSystem) {
return isPermitted
}
const authUserCompanyIds = await serialisedAuthUserCompanyIds(authUser)
const attributeSetCompanyIds = await serialisedAttributeSetCompanyIds(requestedAttributeSet)
if (!requestedCompany) {
// If no requested company, check if the requested attribute and
// auth user belong to the same company
const belongToSameCompany = authUserCompanyIds.some(
(authUserCompanyId) =>
attributeSetCompanyIds[attributeSetCompanyIds.indexOf(authUserCompanyId)]
)
return belongToSameCompany && isPermitted
} else {
if (
authUserCompanyIds.some((authCompanyId) => authCompanyId === requestedCompany?.id) &&
authUserCompanyIds.some(
(authUserCompanyId) =>
attributeSetCompanyIds[attributeSetCompanyIds.indexOf(authUserCompanyId)]
) &&
isPermitted
) {
return true
}
}
return Bouncer.deny('You are not permitted to perform this action!')
}
export { accessCompany, accessCompanyUser, accessCompanyCustomer } | the_stack |
import { Injectable } from '@angular/core';
import { Animation, AnimationBuilder, AnimationController } from '@ionic/angular';
import { KirbyAnimation } from '../../../animation/kirby-animation';
import { PlatformService } from '../../../helpers/platform.service';
@Injectable({ providedIn: 'root' })
export class ModalAnimationBuilderService {
constructor(private animationCtrl: AnimationController, private platform: PlatformService) {}
private readonly easingEnter = KirbyAnimation.Easing.modal.enter;
private readonly easingLeave = KirbyAnimation.Easing.modal.exit;
private readonly duration = KirbyAnimation.Duration.LONG;
private readonly SwipeToCloseDefaults = {
MIN_PRESENTING_SCALE: 0.93,
};
public enterAnimation(currentBackdrop?: HTMLIonBackdropElement): AnimationBuilder {
return (baseEl: HTMLElement, presentingEl?: HTMLElement): Animation => {
const backdropAnimation = this.animationCtrl
.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', 0.01, 'var(--backdrop-opacity)')
.beforeStyles({
'pointer-events': 'none',
})
.afterClearStyles(['pointer-events']);
const wrapperAnimation = this.animationCtrl
.create()
.addElement(baseEl.querySelectorAll('.modal-wrapper, .modal-shadow')!)
.beforeStyles({ opacity: 1 })
.fromTo('transform', 'translateY(100vh)', 'translateY(0vh)');
const baseAnimation = this.animationCtrl
.create()
.addElement(baseEl)
.easing(this.easingEnter)
.duration(this.duration)
.addAnimation(wrapperAnimation);
let currentBackdropAnimation: Animation;
if (currentBackdrop) {
currentBackdropAnimation = this.animationCtrl
.create()
.addElement(currentBackdrop)
.fromTo('opacity', 'var(--backdrop-opacity)', 0.01);
}
if (presentingEl) {
const isMobile = !this.platform.isPhabletOrBigger();
const hasCardModal =
presentingEl.tagName === 'ION-MODAL' &&
(presentingEl as HTMLIonModalElement).presentingElement !== undefined;
const presentingAnimation = this.animationCtrl.create().beforeStyles({
transform: 'translateY(0)',
'transform-origin': 'top center',
overflow: 'hidden',
});
const bodyEl = document.body;
if (isMobile) {
/**
* Fallback for browsers that does not support `max()` (ex: Firefox)
* No need to worry about statusbar padding since engines like Gecko
* are not used as the engine for standlone Cordova/Capacitor apps
*/
const transformOffset = !CSS.supports('width', 'max(0px, 1px)')
? '30px'
: 'max(30px, var(--ion-safe-area-top))';
const modalTransform = hasCardModal ? '-10px' : transformOffset;
const toPresentingScale = this.SwipeToCloseDefaults.MIN_PRESENTING_SCALE;
const finalTransform = `translateY(${modalTransform}) scale(${toPresentingScale})`;
presentingAnimation
.afterStyles({
transform: finalTransform,
})
.beforeAddWrite(() => bodyEl.style.setProperty('background-color', 'black'))
.addElement(presentingEl)
.keyframes([
{
offset: 0,
filter: 'contrast(1)',
transform: 'translateY(0px) scale(1)',
borderRadius: '0px',
},
{
offset: 1,
filter: 'contrast(0.85)',
transform: finalTransform,
borderRadius: '10px 10px 0 0',
},
]);
baseAnimation.addAnimation(presentingAnimation);
} else {
baseAnimation.addAnimation(backdropAnimation);
if (currentBackdropAnimation) {
baseAnimation.addAnimation(currentBackdropAnimation);
}
if (!hasCardModal) {
wrapperAnimation.fromTo('opacity', '0', '1');
} else {
const toPresentingScale = hasCardModal
? this.SwipeToCloseDefaults.MIN_PRESENTING_SCALE
: 1;
const finalTransform = `translateY(-10px) scale(${toPresentingScale})`;
presentingAnimation
.afterStyles({
transform: finalTransform,
})
.addElement(presentingEl.querySelector('.modal-wrapper')!)
.keyframes([
{ offset: 0, filter: 'contrast(1)', transform: 'translateY(0) scale(1)' },
{ offset: 1, filter: 'contrast(0.85)', transform: finalTransform },
]);
const shadowAnimation = this.animationCtrl
.create()
.afterStyles({
transform: finalTransform,
})
.addElement(presentingEl.querySelector('.modal-shadow')!)
.keyframes([
{ offset: 0, opacity: '1', transform: 'translateY(0) scale(1)' },
{ offset: 1, opacity: '0', transform: finalTransform },
]);
baseAnimation.addAnimation([presentingAnimation, shadowAnimation]);
}
}
} else {
baseAnimation.addAnimation(backdropAnimation);
if (currentBackdropAnimation) {
baseAnimation.addAnimation(currentBackdropAnimation);
}
}
return baseAnimation;
};
}
public leaveAnimation(currentBackdrop?: HTMLIonBackdropElement): AnimationBuilder {
return (baseEl: HTMLElement, presentingEl?: HTMLElement): Animation => {
const backdropAnimation = this.animationCtrl
.create()
.addElement(baseEl.querySelector('ion-backdrop')!)
.fromTo('opacity', 'var(--backdrop-opacity)', 0.0);
const wrapperAnimation = this.animationCtrl
.create()
.addElement(baseEl.querySelectorAll('.modal-wrapper, .modal-shadow')!)
.beforeStyles({ opacity: 1 })
.fromTo('transform', 'translateY(0vh)', 'translateY(100vh)');
const baseAnimation = this.animationCtrl
.create()
.addElement(baseEl)
.easing(this.easingLeave)
.duration(this.duration)
.addAnimation(wrapperAnimation);
let currentBackdropAnimation: Animation;
if (currentBackdrop) {
currentBackdropAnimation = this.animationCtrl
.create()
.addElement(currentBackdrop)
.fromTo('opacity', 0.01, 'var(--backdrop-opacity)')
.afterStyles({ opacity: 'var(--backdrop-opacity)' }); //Ensures backdrop is reset to default opacity after swipe to close
}
if (presentingEl) {
const isMobile = !this.platform.isPhabletOrBigger();
const hasCardModal =
presentingEl.tagName === 'ION-MODAL' &&
(presentingEl as HTMLIonModalElement).presentingElement !== undefined;
const presentingAnimation = this.animationCtrl
.create()
.beforeClearStyles(['transform'])
.afterClearStyles(['transform'])
.onFinish((currentStep) => {
// only reset background color if this is the last card-style modal
if (currentStep !== 1) {
return;
}
presentingEl.style.setProperty('overflow', '');
const numModals = Array.from(bodyEl.querySelectorAll('ion-modal')).filter(
(m) => m.presentingElement !== undefined
).length;
if (numModals <= 1) {
bodyEl.style.setProperty('background-color', '');
}
});
const bodyEl = document.body;
if (isMobile) {
const transformOffset = !CSS.supports('width', 'max(0px, 1px)')
? '30px'
: 'max(30px, var(--ion-safe-area-top))';
const modalTransform = hasCardModal ? '-10px' : transformOffset;
const toPresentingScale = this.SwipeToCloseDefaults.MIN_PRESENTING_SCALE;
const finalTransform = `translateY(${modalTransform}) scale(${toPresentingScale})`;
presentingAnimation.addElement(presentingEl).keyframes([
{
offset: 0,
filter: 'contrast(0.85)',
transform: finalTransform,
borderRadius: '10px 10px 0 0',
},
{
offset: 1,
filter: 'contrast(1)',
transform: 'translateY(0px) scale(1)',
borderRadius: '0px',
},
]);
baseAnimation.addAnimation(presentingAnimation);
} else {
baseAnimation.addAnimation(backdropAnimation);
if (currentBackdropAnimation) {
baseAnimation.addAnimation(currentBackdropAnimation);
}
if (!hasCardModal) {
wrapperAnimation.fromTo('opacity', '1', '0');
} else {
const toPresentingScale = hasCardModal
? this.SwipeToCloseDefaults.MIN_PRESENTING_SCALE
: 1;
const finalTransform = `translateY(-10px) scale(${toPresentingScale})`;
presentingAnimation
.addElement(presentingEl.querySelector('.modal-wrapper')!)
.afterStyles({
transform: 'translate3d(0, 0, 0)',
})
.keyframes([
{ offset: 0, filter: 'contrast(0.85)', transform: finalTransform },
{ offset: 1, filter: 'contrast(1)', transform: 'translateY(0) scale(1)' },
]);
const shadowAnimation = this.animationCtrl
.create()
.addElement(presentingEl.querySelector('.modal-shadow')!)
.afterStyles({
transform: 'translateY(0) scale(1)',
})
.keyframes([
{ offset: 0, opacity: '0', transform: finalTransform },
{ offset: 1, opacity: '1', transform: 'translateY(0) scale(1)' },
]);
baseAnimation.addAnimation([presentingAnimation, shadowAnimation]);
}
}
} else {
baseAnimation.addAnimation(backdropAnimation);
if (currentBackdropAnimation) {
baseAnimation.addAnimation(currentBackdropAnimation);
}
}
return baseAnimation;
};
}
} | the_stack |
import * as React from 'react'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PasswordField } from './'
import { axe } from 'jest-axe'
describe('PasswordField', () => {
it('supports having an externally provided id attribute', () => {
render(<PasswordField data-testid="password-field" id="custom-id" label="New Password" />)
expect(screen.getByTestId('password-field').id).toBe('custom-id')
// Makes sure that even with the custom id, the label is still associated to the input element
expect(screen.getByTestId('password-field')).toHaveAccessibleName('New Password')
})
it('is labelled by its label and secondary label', () => {
const { rerender } = render(<PasswordField data-testid="password-field" label="Phone" />)
expect(screen.getByTestId('password-field')).toHaveAccessibleName('Phone')
rerender(<PasswordField data-testid="password-field" label="Phone" secondaryLabel="home" />)
expect(screen.getByTestId('password-field')).toHaveAccessibleName('Phone (home)')
})
it('can be labelled via aria-label', () => {
render(
<PasswordField
data-testid="password-field"
label="Phone"
aria-label="Your phone number"
/>,
)
expect(screen.getByTestId('password-field')).toHaveAccessibleName('Your phone number')
})
it('can be labelled via aria-labelledby', () => {
render(
<>
<PasswordField
data-testid="password-field"
label="Phone"
aria-labelledby="custom-label"
/>
<div id="custom-label">Your phone number</div>
</>,
)
expect(screen.getByTestId('password-field')).toHaveAccessibleName('Your phone number')
})
it('is described by its hint when provided', () => {
render(
<PasswordField data-testid="password-field" label="Phone" hint="So we can call you" />,
)
expect(screen.getByTestId('password-field')).toHaveAccessibleDescription(
'So we can call you',
)
})
it('can be described by something else via aria-describedby', () => {
render(
<>
<PasswordField
data-testid="password-field"
label="Phone"
hint="So we can call you"
aria-describedby="custom-hint"
/>
<div id="custom-hint">This is the phone where we will call you</div>
</>,
)
expect(screen.getByTestId('password-field')).toHaveAccessibleDescription(
'This is the phone where we will call you',
)
})
it('renders its auxiliary label', () => {
render(
<PasswordField
label="New Password"
auxiliaryLabel={<a href="/help">Whatʼs this?</a>}
/>,
)
expect(screen.getByRole('link', { name: 'Whatʼs this?' })).toBeInTheDocument()
})
it('does not use the auxiliary label for semantic labelling purposes', () => {
render(
<PasswordField
data-testid="password-field"
label="New Password"
auxiliaryLabel={<a href="/help">Whatʼs this?</a>}
/>,
)
expect(screen.getByTestId('password-field')).toHaveAccessibleName('New Password')
expect(screen.getByTestId('password-field')).not.toHaveAccessibleDescription()
})
it('can have a placeholder text', () => {
render(
<PasswordField
label="Email"
data-testid="password-field"
placeholder="Enter your email address"
/>,
)
expect(screen.getByTestId('password-field')).toBe(
screen.getByPlaceholderText('Enter your email address'),
)
})
it('renders an input with type="password" and does not allow providing an alternative type', () => {
const { rerender } = render(<PasswordField data-testid="password-field" label="Password" />)
const passwordField = screen.getByTestId('password-field')
expect(passwordField).toHaveAttribute('type', 'password')
rerender(
<PasswordField
label="Password"
// @ts-expect-error
type="text"
/>,
)
expect(passwordField).toHaveAttribute('type', 'password')
})
it('allows to toggle visibility of the password value', () => {
render(<PasswordField data-testid="password-field" label="Password" />)
const passwordField = screen.getByTestId('password-field')
const togglePasswordButton = screen.getByRole('button', {
name: 'Toggle password visibility',
})
expect(passwordField).toHaveAttribute('type', 'password')
userEvent.click(togglePasswordButton)
expect(passwordField).toHaveAttribute('type', 'text')
userEvent.click(togglePasswordButton)
expect(passwordField).toHaveAttribute('type', 'password')
})
it('allows to customize the toggle password visibility button', () => {
render(
<PasswordField
data-testid="password-field"
label="Password"
togglePasswordLabel="Switch password visibility on/off"
/>,
)
const passwordField = screen.getByTestId('password-field')
expect(
screen.queryByRole('button', { name: 'Toggle password visibility' }),
).not.toBeInTheDocument()
const togglePasswordButton = screen.getByRole('button', {
name: 'Switch password visibility on/off',
})
expect(passwordField).toHaveAttribute('type', 'password')
userEvent.click(togglePasswordButton)
expect(passwordField).toHaveAttribute('type', 'text')
userEvent.click(togglePasswordButton)
expect(passwordField).toHaveAttribute('type', 'password')
})
it('is hidden when hidden={true}', () => {
const { rerender } = render(
<PasswordField
data-testid="password-field"
label="New Password"
hint="Must be at least 8 characters long"
hidden
/>,
)
const inputField = screen.getByTestId('password-field')
const hintElement = screen.getByText('Must be at least 8 characters long')
// check that it is rendered but not visible
expect(inputField).not.toBeVisible()
expect(hintElement).not.toBeVisible()
// check that it becomes visible when hidden is removed
rerender(
<PasswordField
data-testid="password-field"
label="New Password"
hint="Must be at least 8 characters long"
/>,
)
expect(inputField).toBeVisible()
expect(hintElement).toBeVisible()
})
it('forwards to the input element any extra props provided to it', () => {
render(
<PasswordField
label="Visual label"
aria-label="Non-visual label"
data-testid="password-field"
data-something="whatever"
/>,
)
const inputElement = screen.getByTestId('password-field')
expect(inputElement.tagName).toBe('INPUT')
expect(inputElement).toHaveAttribute('aria-label', 'Non-visual label')
expect(inputElement).toHaveAttribute('data-testid', 'password-field')
expect(inputElement).toHaveAttribute('data-something', 'whatever')
})
it('allows to type text into it', () => {
render(<PasswordField data-testid="password-field" label="Confirm Password" />)
const inputElement = screen.getByTestId('password-field')
expect(inputElement).toHaveValue('')
userEvent.type(inputElement, 'super-p4$$w0rd')
expect(inputElement).toHaveValue('super-p4$$w0rd')
})
it('can be disabled', () => {
render(<PasswordField data-testid="password-field" label="Confirm Password" disabled />)
const inputElement = screen.getByTestId('password-field')
expect(inputElement).toBeDisabled()
expect(inputElement).toHaveValue('')
userEvent.type(inputElement, 'Software developer')
expect(inputElement).toHaveValue('')
})
it('can be readonly', () => {
render(<PasswordField data-testid="password-field" label="Confirm Password" readOnly />)
const inputElement = screen.getByTestId('password-field')
expect(inputElement).not.toBeDisabled()
expect(inputElement).toHaveValue('')
userEvent.type(inputElement, 'Software developer')
expect(inputElement).toHaveValue('')
})
it('can be a controlled input field', () => {
function TestCase() {
const [value, setValue] = React.useState('')
return (
<>
<PasswordField
data-testid="password-field"
label="New Password"
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<div data-testid="value">{value}</div>
</>
)
}
render(<TestCase />)
const inputElement = screen.getByTestId('password-field')
expect(inputElement).toHaveValue('')
userEvent.type(inputElement, 'password value')
expect(inputElement).toHaveValue('password value')
expect(screen.getByTestId('value')).toHaveTextContent('password value')
})
describe('a11y', () => {
it('renders with no a11y violations', async () => {
const { container } = render(
<>
<PasswordField label="New Password" />
<PasswordField label="New Password" disabled />
<PasswordField label="New Password" hint="Enter a new password" />
</>,
)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
})
}) | the_stack |
import {TypedNodeConnection} from './NodeConnection';
import {CoreGraphNode} from '../../../../core/graph/CoreGraphNode';
import {NodeEvent} from '../../../poly/NodeEvent';
import {NodeContext} from '../../../poly/NodeContext';
import {ConnectionPointTypeMap} from './connections/ConnectionMap';
import {TypedNode} from '../../_Base';
import {ContainerMap, NodeTypeMap} from '../../../containers/utils/ContainerMap';
import {ClonedStatesController} from './utils/ClonedStatesController';
import {InputCloneMode} from '../../../poly/InputCloneMode';
import {BaseConnectionPoint} from './connections/_Base';
import {CoreType} from '../../../../core/Type';
type OnUpdateHook = () => void;
const MAX_INPUTS_COUNT_UNSET = 0;
export class InputsController<NC extends NodeContext> {
private _graph_node: CoreGraphNode | undefined;
private _graph_node_inputs: CoreGraphNode[] = [];
private _inputs: Array<NodeTypeMap[NC] | null> = [];
private _has_named_inputs: boolean = false;
private _named_input_connection_points: ConnectionPointTypeMap[NC][] | undefined;
private _min_inputs_count: number = 0;
private _max_inputs_count: number = MAX_INPUTS_COUNT_UNSET;
private _maxInputsCountOnInput: number = MAX_INPUTS_COUNT_UNSET;
private _depends_on_inputs: boolean = true;
// hooks
private _on_update_hooks: OnUpdateHook[] | undefined;
private _on_update_hook_names: string[] | undefined;
// clonable
dispose() {
if (this._graph_node) {
this._graph_node.dispose();
}
for (let graph_node of this._graph_node_inputs) {
if (graph_node) {
graph_node.dispose();
}
}
// hooks
this._on_update_hooks = undefined;
this._on_update_hook_names = undefined;
}
// private _user_inputs_clonable_states: InputCloneMode[] | undefined;
// private _inputs_clonable_states: InputCloneMode[] | undefined;
// private _inputs_cloned_state: boolean[] = [];
// private _override_clonable_state: boolean = false;
constructor(public node: TypedNode<NC, any>) {}
set_depends_on_inputs(depends_on_inputs: boolean) {
this._depends_on_inputs = depends_on_inputs;
}
private set_min_inputs_count(min_inputs_count: number) {
this._min_inputs_count = min_inputs_count;
}
private set_max_inputs_count(max_inputs_count: number) {
if (this._max_inputs_count == MAX_INPUTS_COUNT_UNSET) {
this._maxInputsCountOnInput = max_inputs_count;
}
this._max_inputs_count = max_inputs_count;
this.init_graph_node_inputs();
}
namedInputConnectionPointsByName(name: string): ConnectionPointTypeMap[NC] | undefined {
if (this._named_input_connection_points) {
for (let connection_point of this._named_input_connection_points) {
if (connection_point && connection_point.name() == name) {
return connection_point;
}
}
}
}
setNamedInputConnectionPoints(connection_points: ConnectionPointTypeMap[NC][]) {
this._has_named_inputs = true;
const connections = this.node.io.connections.inputConnections();
if (connections) {
for (let connection of connections) {
if (connection) {
// assume we only work with indices for now, not with connection point names
// so we only need to check again the new max number of connection points.
if (connection.input_index >= connection_points.length) {
connection.disconnect({setInput: true});
}
}
}
}
// update connections
this._named_input_connection_points = connection_points;
this.set_min_inputs_count(0);
this.set_max_inputs_count(connection_points.length);
this.init_graph_node_inputs();
this.node.emit(NodeEvent.NAMED_INPUTS_UPDATED);
}
// private _has_connected_inputs() {
// for (let input of this._inputs) {
// if (input != null) {
// return true;
// }
// }
// return false;
// }
// private _check_name_changed(connection_points: ConnectionPointTypeMap[NC][]) {
// if (this._named_input_connection_points) {
// if (this._named_input_connection_points.length != connection_points.length) {
// return true;
// } else {
// for (let i = 0; i < this._named_input_connection_points.length; i++) {
// if (this._named_input_connection_points[i]?.name != connection_points[i]?.name) {
// return true;
// }
// }
// }
// }
// return false;
// }
hasNamedInputs() {
return this._has_named_inputs;
}
namedInputConnectionPoints(): ConnectionPointTypeMap[NC][] {
return this._named_input_connection_points || [];
}
private init_graph_node_inputs() {
for (let i = 0; i < this._max_inputs_count; i++) {
this._graph_node_inputs[i] = this._graph_node_inputs[i] || this._create_graph_node_input(i);
}
}
private _create_graph_node_input(index: number): CoreGraphNode {
const graph_input_node = new CoreGraphNode(this.node.scene(), `input_${index}`);
// graph_input_node.setScene(this.node.scene);
if (!this._graph_node) {
this._graph_node = new CoreGraphNode(this.node.scene(), 'inputs');
this.node.addGraphInput(this._graph_node, false);
}
this._graph_node.addGraphInput(graph_input_node, false);
return graph_input_node;
}
maxInputsCount(): number {
return this._max_inputs_count || 0;
}
maxInputsCountOverriden(): boolean {
return this._max_inputs_count != this._maxInputsCountOnInput;
}
input_graph_node(input_index: number): CoreGraphNode {
return this._graph_node_inputs[input_index];
}
setCount(min: number, max?: number) {
if (max == null) {
max = min;
}
this.set_min_inputs_count(min);
this.set_max_inputs_count(max);
// this._clonable_states_controller.init_inputs_clonable_state();
this.init_connections_controller_inputs();
}
private init_connections_controller_inputs() {
this.node.io.connections.initInputs();
}
is_any_input_dirty() {
return this._graph_node?.isDirty() || false;
// if (this._max_inputs_count > 0) {
// for (let i = 0; i < this._inputs.length; i++) {
// if (this._inputs[i]?.isDirty()) {
// return true;
// }
// }
// } else {
// return false;
// }
}
async containers_without_evaluation() {
const containers: Array<ContainerMap[NC] | undefined> = [];
for (let i = 0; i < this._inputs.length; i++) {
const input_node = this._inputs[i];
let container: ContainerMap[NC] | undefined = undefined;
if (input_node) {
container = (await input_node.compute()) as ContainerMap[NC];
}
containers.push(container);
}
return containers;
}
existing_input_indices() {
const existing_input_indices: number[] = [];
if (this._max_inputs_count > 0) {
for (let i = 0; i < this._inputs.length; i++) {
if (this._inputs[i]) {
existing_input_indices.push(i);
}
}
}
return existing_input_indices;
}
async eval_required_inputs() {
let containers: Array<ContainerMap[NC] | null | undefined> = [];
if (this._max_inputs_count > 0) {
const existing_input_indices = this.existing_input_indices();
if (existing_input_indices.length < this._min_inputs_count) {
this.node.states.error.set('inputs are missing');
} else {
if (existing_input_indices.length > 0) {
const promises: Promise<ContainerMap[NC] | null>[] = [];
let input: NodeTypeMap[NC] | null;
for (let i = 0; i < this._inputs.length; i++) {
input = this._inputs[i];
if (input) {
// I tried here to only use a promise for dirty inputs,
// but that messes up with the order
// if (input.isDirty()) {
// containers.push(input.containerController.container as ContainerMap[NC]);
// } else {
promises.push(this.eval_required_input(i) as Promise<ContainerMap[NC]>);
// }
}
}
containers = await Promise.all(promises);
// containers = containers.concat(promised_containers);
this._graph_node?.removeDirtyState();
}
}
}
return containers;
}
async eval_required_input(input_index: number) {
let container: ContainerMap[NC] | undefined = undefined;
const input_node = this.input(input_index);
// if (input_node && !input_node.isDirty()) {
// container = input_node.containerController.container as ContainerMap[NC] | null;
// } else {
// container = await this.node.containerController.requestInputContainer(input_index);
// this._graph_node_inputs[input_index].removeDirtyState();
// }
if (input_node) {
container = (await input_node.compute()) as ContainerMap[NC];
this._graph_node_inputs[input_index].removeDirtyState();
}
// we do not clone here, as we just check if a group is present
if (container && container.coreContent()) {
// return container;
} else {
const input_node = this.input(input_index);
if (input_node) {
const input_error_message = input_node.states.error.message();
if (input_error_message) {
this.node.states.error.set(`input ${input_index} is invalid (error: ${input_error_message})`);
}
}
}
return container;
}
get_named_input_index(name: string): number {
if (this._named_input_connection_points) {
for (let i = 0; i < this._named_input_connection_points.length; i++) {
if (this._named_input_connection_points[i]?.name() == name) {
return i;
}
}
}
return -1;
}
get_input_index(input_index_or_name: number | string): number {
if (CoreType.isString(input_index_or_name)) {
if (this.hasNamedInputs()) {
return this.get_named_input_index(input_index_or_name);
} else {
throw new Error(`node ${this.node.path()} has no named inputs`);
}
} else {
return input_index_or_name;
}
}
setInput(
input_index_or_name: number | string,
node: NodeTypeMap[NC] | null,
output_index_or_name: number | string = 0
) {
const input_index = this.get_input_index(input_index_or_name) || 0;
if (input_index < 0) {
const message = `invalid input (${input_index_or_name}) for node ${this.node.path()}`;
console.warn(message);
throw new Error(message);
}
let output_index = 0;
if (node) {
if (node.io.outputs.hasNamedOutputs()) {
output_index = node.io.outputs.getOutputIndex(output_index_or_name);
if (output_index == null || output_index < 0) {
const connection_points = node.io.outputs.namedOutputConnectionPoints() as BaseConnectionPoint[];
const names = connection_points.map((cp) => cp.name());
console.warn(
`node ${node.path()} does not have an output named ${output_index_or_name}. inputs are: ${names.join(
', '
)}`
);
return;
}
}
}
const graph_input_node = this._graph_node_inputs[input_index];
if (graph_input_node == null) {
const message = `graph_input_node not found at index ${input_index}`;
console.warn(message);
throw new Error(message);
}
if (node && this.node.parent() != node.parent()) {
return;
}
const old_input_node = this._inputs[input_index];
let old_output_index: number | null = null;
let old_connection: TypedNodeConnection<NC> | undefined = undefined;
if (this.node.io.connections) {
old_connection = this.node.io.connections.inputConnection(input_index);
}
if (old_connection) {
old_output_index = old_connection.output_index;
}
if (node !== old_input_node || output_index != old_output_index) {
// TODO: test: add test to make sure this is necessary
if (old_input_node != null) {
if (this._depends_on_inputs) {
graph_input_node.removeGraphInput(old_input_node);
}
}
if (node != null) {
if (graph_input_node.addGraphInput(node)) {
// we do test if we can create the graph connection
// to ensure we are not in a cyclical graph,
// but we delete it right after
if (!this._depends_on_inputs) {
graph_input_node.removeGraphInput(node);
}
//this._input_connections[input_index] = new NodeConnection(node, this.self, output_index, input_index);
if (old_connection) {
old_connection.disconnect({setInput: false});
}
this._inputs[input_index] = node;
new TypedNodeConnection<NC>(
(<unknown>node) as TypedNode<NC, any>,
this.node,
output_index,
input_index
);
} else {
console.warn(`cannot connect ${node.path()} to ${this.node.path()}`);
}
} else {
this._inputs[input_index] = null;
if (old_connection) {
old_connection.disconnect({setInput: false});
}
// this._input_connections[input_index] = null;
}
this._run_on_set_input_hooks();
graph_input_node.setSuccessorsDirty();
// this.node.set_dirty(node);
this.node.emit(NodeEvent.INPUTS_UPDATED);
}
}
remove_input(node: NodeTypeMap[NC]) {
const inputs = this.inputs();
let input: NodeTypeMap[NC] | null;
for (let i = 0; i < inputs.length; i++) {
input = inputs[i];
if (input != null && node != null) {
if (input.graphNodeId() === node.graphNodeId()) {
this.setInput(i, null);
}
}
}
}
input(input_index: number): NodeTypeMap[NC] | null {
return this._inputs[input_index];
}
named_input(input_name: string): NodeTypeMap[NC] | null {
if (this.hasNamedInputs()) {
const input_index = this.get_input_index(input_name);
return this._inputs[input_index];
} else {
return null;
}
}
named_input_connection_point(input_name: string): ConnectionPointTypeMap[NC] | undefined {
if (this.hasNamedInputs() && this._named_input_connection_points) {
const input_index = this.get_input_index(input_name);
return this._named_input_connection_points[input_index];
}
}
has_named_input(name: string): boolean {
return this.get_named_input_index(name) >= 0;
}
has_input(input_index: number): boolean {
return this._inputs[input_index] != null;
}
inputs() {
return this._inputs;
}
//
//
// CLONABLE STATES
//
//
private _cloned_states_controller: ClonedStatesController<NC> | undefined;
initInputsClonedState(states: InputCloneMode | InputCloneMode[]) {
if (!this._cloned_states_controller) {
this._cloned_states_controller = new ClonedStatesController(this);
this._cloned_states_controller.initInputsClonedState(states);
}
}
overrideClonedStateAllowed(): boolean {
return this._cloned_states_controller?.overrideClonedStateAllowed() || false;
}
overrideClonedState(state: boolean) {
this._cloned_states_controller?.overrideClonedState(state);
}
clonedStateOverriden() {
return this._cloned_states_controller?.overriden() || false;
}
cloneRequired(index: number) {
const state = this._cloned_states_controller?.cloneRequiredState(index);
if (state != null) {
return state;
}
return true;
}
cloneRequiredStates(): boolean | boolean[] {
const states = this._cloned_states_controller?.cloneRequiredStates();
if (states != null) {
return states;
}
return true;
}
//
//
// HOOKS
//
//
add_on_set_input_hook(name: string, hook: OnUpdateHook) {
this._on_update_hooks = this._on_update_hooks || [];
this._on_update_hook_names = this._on_update_hook_names || [];
if (!this._on_update_hook_names.includes(name)) {
this._on_update_hooks.push(hook);
this._on_update_hook_names.push(name);
} else {
console.warn(`hook with name ${name} already exists`, this.node);
}
}
private _run_on_set_input_hooks() {
if (this._on_update_hooks) {
for (let hook of this._on_update_hooks) {
hook();
}
}
}
} | the_stack |
import * as _ from "lodash";
import { ClientSession } from "mongodb";
import * as dot from "dot-object";
import {
SPECIAL_PARAM_FIELD,
ALIAS_FIELD,
SCHEMA_FIELD,
SCHEMA_BSON_AGGREGATE_DECODER_STORAGE,
SCHEMA_BSON_DOCUMENT_SERIALIZER,
} from "../../constants";
import {
QueryBodyType,
IReducerOption,
QuerySubBodyType,
IQueryContext,
} from "../../defs";
import {
getLinker,
getReducerConfig,
getExpanderConfig,
hasLinker,
} from "../../api";
import Linker from "../Linker";
import { INode } from "./INode";
import FieldNode from "./FieldNode";
import ReducerNode from "./ReducerNode";
import { Collection, ObjectId } from "mongodb";
import { ClassSchema, t } from "@deepkit/type";
import { getBSONDecoder } from "@deepkit/bson";
import {
SCHEMA_STORAGE,
SCHEMA_AGGREGATE_STORAGE,
ALL_FIELDS,
} from "../../constants";
import { BSONLeftoverSerializer } from "./utils/BSONLeftoverSerializer";
import { SCHEMA_BSON_OBJECT_DECODER_STORAGE } from "../../constants";
import { Session } from "inspector";
export interface CollectionNodeOptions {
collection: Collection<any>;
body: QueryBodyType;
explain?: boolean;
name?: string;
parent?: CollectionNode;
linker?: Linker;
}
export enum NodeLinkType {
COLLECTION,
FIELD,
REDUCER,
EXPANDER,
}
export default class CollectionNode implements INode {
public body: QuerySubBodyType;
public name: string;
public collection: Collection<any>;
public parent: CollectionNode;
public alias: string;
public schema: ClassSchema;
public scheduledForDeletion: boolean = false;
public nodes: INode[] = [];
public props: any; // TODO: refator to: ValueOrValueResolver<ICollectionQueryConfig>
public isVirtual?: boolean;
public isOneResult?: boolean;
/**
* We use session when we're searching through Nova inside a transaction.
*/
public session?: ClientSession;
/**
* When doing .fetchOne() from the Query and forgetting about hard-coding a limit, we should put that limit ourselves to avoid accidentally large queries
*/
public forceSingleResult: boolean = false;
/**
* Whether to just dump the fields without a projection
*/
public queryAllFields: boolean = false;
/**
* When this is true, we are explaining the pipeline, and the given results
*/
public readonly explain: boolean;
/**
* The linker represents how the parent collection node links to the child collection
*/
public linker: Linker;
public linkStorageField: string;
public results: any = [];
constructor(
options: CollectionNodeOptions,
public readonly context: IQueryContext
) {
const { collection, body, name, parent, linker, explain = false } = options;
if (collection && !_.isObject(body)) {
throw new Error(
`The field "${name}" is a collection link, and should have its body defined as an object.`
);
}
this.props = body[SPECIAL_PARAM_FIELD] || {};
this.alias = body[ALIAS_FIELD];
this.schema = body[SCHEMA_FIELD];
this.queryAllFields = Boolean(body[ALL_FIELDS]);
this.body = _.cloneDeep(body);
delete this.body[SPECIAL_PARAM_FIELD];
delete this.body[ALIAS_FIELD];
delete this.body[SCHEMA_FIELD];
delete this.body[ALL_FIELDS];
this.explain = explain;
this.name = name;
this.collection = collection;
this.parent = parent;
this.linker = linker;
if (parent) {
this.handleSetupForChild();
}
// Store the session for transaction if it exists
if (context.session) {
this.session = context.session;
} else {
if (parent && parent.session) {
this.session = parent.session;
}
}
this.spread(this.body);
}
/**
* For non-roots,
*/
private handleSetupForChild() {
const linker = this.linker;
const parent = this.parent;
this.isVirtual = linker.isVirtual();
this.isOneResult = linker.isOneResult();
this.linkStorageField = linker.linkStorageField;
if (this.isVirtual) {
this.addField(this.linkStorageField, {}, true);
} else {
parent.addField(this.linkStorageField, {}, true);
}
}
get collectionNodes(): CollectionNode[] {
return this.nodes.filter(
(n) => n instanceof CollectionNode
) as CollectionNode[];
}
get fieldNodes(): FieldNode[] {
return this.nodes.filter((n) => n instanceof FieldNode) as FieldNode[];
}
get reducerNodes(): ReducerNode[] {
return this.nodes.filter((n) => n instanceof ReducerNode) as ReducerNode[];
}
/**
* Returns the linker with the field you want
* @param name {string}
*/
public getLinker(name: string): Linker {
if (hasLinker(this.collection, name)) {
return getLinker(this.collection, name);
}
return null;
}
public getReducer(name: string): ReducerNode {
return this.reducerNodes.find((node) => node.name === name);
}
public getReducerConfig(name: string): IReducerOption {
return getReducerConfig(this.collection, name);
}
public getExpanderConfig(name: string): QueryBodyType {
return getExpanderConfig(this.collection, name);
}
/**
* Returns the filters and options needed to fetch this node
* The argument parentObject is given when we perform recursive fetches
*/
public getPropsForQuerying(parentObject?: any): {
filters: any;
options: any;
pipeline: any[];
} {
let props =
typeof this.props === "function"
? this.props(parentObject)
: _.cloneDeep(this.props);
let { filters = {}, options = {}, pipeline = [], decoder } = props;
if (!this.queryAllFields) {
options.projection = this.blendInProjection(options.projection);
}
if (this.linker) {
Object.assign(
filters,
this.linker.getHardwiredFilters({
filters,
})
);
}
return {
filters,
options,
pipeline,
};
}
/**
* Creates the projection object based on all the fields and reducers
* @param projection
*/
public blendInProjection(projection) {
if (!projection) {
projection = {};
}
this.fieldNodes.forEach((fieldNode) => {
fieldNode.blendInProjection(projection);
});
this.reducerNodes.forEach((reducerNode) => {
reducerNode.blendInProjection(projection);
});
if (!projection._id) {
projection._id = 1;
}
return projection;
}
/**
* @param fieldName
* @returns {boolean}
*/
public hasField(fieldName) {
return this.fieldNodes.find((fieldNode) => fieldNode.name === fieldName);
}
/**
* @param fieldName
* @returns {FieldNode}
*/
public getFirstLevelField(fieldName) {
return this.fieldNodes.find((fieldNode) => {
return fieldNode.name === fieldName;
});
}
/**
* @param name
* @returns {boolean}
*/
public hasCollectionNode(name) {
return !!this.collectionNodes.find((node) => {
return node.name === name;
});
}
/**
* @param name
* @returns {boolean}
*/
public hasReducerNode(name) {
return !!this.reducerNodes.find((node) => node.name === name);
}
/**
* @param name
* @returns {ReducerNode}
*/
public getReducerNode(name) {
return this.reducerNodes.find((node) => node.name === name);
}
/**
* @param name
* @returns {CollectionNode}
*/
public getCollectionNode(name) {
return this.collectionNodes.find((node) => node.name === name);
}
/**
* Fetches the data accordingly
*/
public async toArray(additionalFilters = {}, parentObject?: any) {
const pipeline = this.getAggregationPipeline(
additionalFilters,
parentObject
);
if (this.explain) {
console.log(
`[${this.name}] Pipeline:\n`,
JSON.stringify(pipeline, null, 2)
);
}
let { schema, aggregateDecoder, serializer } = this.getJITSchemaInfo();
if (schema) {
// @types/mongodb complains about `batchSize` not being a valid option, it's a false issue
// @ts-ignore
const buffers = await this.collection
.aggregate(pipeline, {
allowDiskUse: true,
raw: true,
batchSize: 1_000_000,
session: this.session,
})
.toArray();
const result = aggregateDecoder(buffers[0]);
if (result.errmsg) {
throw new Error(JSON.stringify(result));
}
const firstBatchResults = result.cursor.firstBatch;
const results = firstBatchResults.map((result) =>
serializer.deserialize(result)
);
return results;
} else {
// @ts-ignore
return this.collection
.aggregate(pipeline, {
allowDiskUse: true,
batchSize: 1_000_000,
session: this.session,
})
.toArray();
}
}
private getJITSchemaInfo() {
let schema = this.schema,
aggregateDecoder,
serializer,
aggregateSchema,
documentDecoder;
if (schema) {
aggregateSchema = CollectionNode.getAggregateSchema(schema);
aggregateDecoder = getBSONDecoder(aggregateSchema);
documentDecoder = getBSONDecoder(schema);
serializer = CollectionNode.getSchemaSerializer(schema);
} else if (schema === undefined) {
// Fallback to collection schema if $schema: null isn't specified
if (this.collection[SCHEMA_STORAGE]) {
schema = this.collection[SCHEMA_STORAGE];
aggregateSchema = this.collection[SCHEMA_AGGREGATE_STORAGE];
aggregateDecoder =
this.collection[SCHEMA_BSON_AGGREGATE_DECODER_STORAGE];
documentDecoder = this.collection[SCHEMA_BSON_OBJECT_DECODER_STORAGE];
serializer = this.collection[SCHEMA_BSON_DOCUMENT_SERIALIZER];
}
}
return { schema, aggregateDecoder, serializer, documentDecoder };
}
/**
* @param fieldName
*/
public getLinkingType(fieldName): NodeLinkType {
if (this.getLinker(fieldName)) {
return NodeLinkType.COLLECTION;
}
if (this.getReducerConfig(fieldName)) {
return NodeLinkType.REDUCER;
}
if (this.getExpanderConfig(fieldName)) {
return NodeLinkType.EXPANDER;
}
return NodeLinkType.FIELD;
}
public getFiltersAndOptions(additionalFilters = {}, parentObject?: any) {
const { filters, options } = this.getPropsForQuerying(parentObject);
Object.assign(filters, additionalFilters);
return {
filters,
options,
};
}
/**
* Based on the current configuration fetches the pipeline
*/
public getAggregationPipeline(
additionalFilters = {},
parentObject?: any
): any[] {
const {
filters,
options,
pipeline: pipelineFromProps,
} = this.getPropsForQuerying(parentObject);
const pipeline = [];
Object.assign(filters, additionalFilters);
if (!_.isEmpty(filters)) {
pipeline.push({ $match: filters });
}
// TODO: transform filters to extract $geoNear, $near and $nearSphere
pipeline.push(...pipelineFromProps);
if (options.sort) {
pipeline.push({ $sort: options.sort });
}
this.reducerNodes.forEach((reducerNode) => {
pipeline.push(...reducerNode.pipeline);
});
let limit = options.limit;
if (this.forceSingleResult) {
limit = 1;
}
if (limit) {
if (!options.skip) {
options.skip = 0;
}
pipeline.push({
$limit: limit + options.skip,
});
}
if (options.skip) {
pipeline.push({
$skip: options.skip,
});
}
if (options.projection) {
pipeline.push({
$project: options.projection,
});
}
return pipeline;
}
/**
* This function creates the children properly for my root.
*/
protected spread(
body: QuerySubBodyType,
fromReducerNode?: ReducerNode,
scheduleForDeletion?: boolean
) {
_.forEach(body, (fieldBody, fieldName) => {
if (!fieldBody) {
return;
}
if (
fieldName === SPECIAL_PARAM_FIELD ||
fieldName === SCHEMA_FIELD ||
fieldName === ALL_FIELDS
) {
return;
}
let alias = fieldName;
if (fieldBody[ALIAS_FIELD]) {
alias = fieldBody[ALIAS_FIELD];
delete fieldBody[ALIAS_FIELD];
}
let linkType = this.getLinkingType(alias);
scheduleForDeletion = fromReducerNode
? true
: Boolean(scheduleForDeletion);
/**
* This allows us to have reducer with the same name as the field
*/
if (fromReducerNode && fromReducerNode.name === fieldName) {
linkType = NodeLinkType.FIELD;
scheduleForDeletion = false;
}
switch (linkType) {
case NodeLinkType.COLLECTION:
if (this.hasCollectionNode(alias)) {
this.getCollectionNode(alias).spread(
fieldBody as QueryBodyType,
null,
scheduleForDeletion
);
} else {
const linker = this.getLinker(alias);
const collectionNode = new CollectionNode(
{
body: fieldBody as QueryBodyType,
collection: linker.getLinkedCollection(),
linker,
name: fieldName,
parent: this,
},
this.context
);
collectionNode.scheduledForDeletion = scheduleForDeletion;
this.nodes.push(collectionNode);
}
break;
case NodeLinkType.REDUCER:
if (!this.hasReducerNode(fieldName)) {
const reducerConfig = this.getReducerConfig(fieldName);
const reducerNode = new ReducerNode(
fieldName,
{
body: fieldBody as QueryBodyType,
...reducerConfig,
},
this.context
);
reducerNode.scheduledForDeletion = scheduleForDeletion;
/**
* This scenario is when a reducer is using another reducer
*/
if (fromReducerNode) {
fromReducerNode.dependencies.push(reducerNode);
}
this.nodes.push(reducerNode);
} else {
// The logic here is that if we specify a reducer in the body, and other reducer depends on it
// When we spread the body of that other reducer we also need to add it to its deps
if (fromReducerNode) {
const reducerNode = this.getReducerNode(fieldName);
if (
!fromReducerNode.dependencies.find((n) => n === reducerNode)
) {
fromReducerNode.dependencies.push(reducerNode);
}
}
}
break;
case NodeLinkType.EXPANDER:
const expanderConfig = this.getExpanderConfig(fieldName);
_.merge(this.body, expanderConfig);
delete this.body[fieldName];
this.spread(expanderConfig);
break;
case NodeLinkType.FIELD:
this.addField(fieldName, fieldBody, scheduleForDeletion);
break;
default:
throw new Error(`We could not process the type: ${linkType}`);
}
});
// If by the end of parsing the body, we have no fields, we add one regardless
if (this.fieldNodes.length === 0 && !this.queryAllFields) {
const fieldNode = new FieldNode("_id", {});
this.nodes.push(fieldNode);
}
this.blendReducers();
}
/**
*
* @param fieldName
* @param body
* @param scheduleForDeletion
*/
protected addField(fieldName: string, body, scheduleForDeletion = false) {
if (this.queryAllFields) {
return;
}
if (fieldName.indexOf(".") > -1) {
// transform 'profile.firstName': body => { "profile" : { "firstName": body } }
const newBody = dot.object({ [fieldName]: body });
fieldName = fieldName.split(".")[0];
body = newBody[fieldName];
}
if (!this.hasField(fieldName)) {
const fieldNode = new FieldNode(fieldName, body);
fieldNode.scheduledForDeletion = scheduleForDeletion;
this.nodes.push(fieldNode);
} else {
// In case it contains some sub fields
const fieldNode = this.getFirstLevelField(fieldName);
if (
scheduleForDeletion === false &&
fieldNode.scheduledForDeletion === true
) {
fieldNode.scheduledForDeletion = false;
}
if (FieldNode.canBodyRepresentAField(body)) {
if (fieldNode.subfields.length > 0) {
// We override it, so we include everything
fieldNode.subfields = [];
}
} else {
fieldNode.spread(body, scheduleForDeletion);
}
}
}
protected blendReducers() {
this.reducerNodes
.filter((node) => !node.isSpread)
.forEach((reducerNode) => {
reducerNode.isSpread = true;
this.spread(reducerNode.dependency, reducerNode, true);
});
}
/**
* After all data has been cleared up whe begin projection so the dataset is what matches the request body
*/
public project() {
this.collectionNodes.forEach((collectionNode) => {
if (collectionNode.scheduledForDeletion) {
const field = collectionNode.name;
for (const result of this.results) {
delete result[field];
}
} else {
collectionNode.project();
}
});
this.reducerNodes.forEach((reducerNode) => {
if (reducerNode.scheduledForDeletion) {
const field = reducerNode.name;
for (const result of this.results) {
delete result[field];
}
}
});
if (this.queryAllFields) {
return;
}
for (const field of this.fieldNodes) {
field.project(this.results);
}
}
/**
* Returns the BSON serializer for the schema
* @param resultSchema
* @returns
*/
public static getSchemaSerializer(resultSchema: ClassSchema) {
return BSONLeftoverSerializer.for(resultSchema);
}
/**
* Returns the schema for the response of an aggregate
* @param resultSchema
* @returns
*/
public static getAggregateSchema(resultSchema: ClassSchema) {
return t.schema({
ok: t.number,
errmsg: t.string.optional,
code: t.number.optional,
codeName: t.string.optional,
cursor: {
id: t.number,
firstBatch: t.array(t.partial(resultSchema)),
nextBatch: t.array(t.partial(resultSchema)),
},
});
}
protected hasPipeline() {
return this.props.pipeline && this.props.pipeline.length > 0;
}
} | the_stack |
import { signalRoomName, offerRequestDecrypted, KeyPair, genKeyPair, offerEncrypted, answerDecrypted, debug, randomPhrase, clientUrl, suggestedRTCConfig, getScreenCaptureUnsupportedWarning } from './util'
import { PubSub, createDefaultPubSub } from './pubsub'
export default class HostPage {
elem: HTMLElement
errElem: HTMLElement
settingsElem: HTMLElement
phraseElem: HTMLInputElement
passwordElem: HTMLInputElement
workingElem: HTMLElement
sharingElem: HTMLElement
shareUrlElem: HTMLAnchorElement
shareClientCountElem: HTMLElement
sharePauseElem: HTMLElement
shareVideoElem: HTMLVideoElement
stream?: MediaStream
hostSignalers?: [HostSignaler, HostSignaler, HostSignaler]
peerConns: RTCPeerConnection[] = []
constructor() {
this.elem = document.getElementById('host')!
this.errElem = document.getElementById('hostErr')!
this.settingsElem = document.getElementById('hostSettings')!
this.phraseElem = document.getElementById('hostPhrase') as HTMLInputElement
this.passwordElem = document.getElementById('hostPassword') as HTMLInputElement
this.workingElem = document.getElementById('hostWorking')!
this.sharingElem = document.getElementById('hostSharing')!
this.shareUrlElem = document.getElementById('hostShareUrl') as HTMLAnchorElement
this.shareClientCountElem = document.getElementById('hostShareClientCount')!
this.sharePauseElem = document.getElementById('hostSharePause')!
this.shareVideoElem = document.getElementById('hostShareVideo') as HTMLVideoElement
// Set warning if unsupported
const shareWarning = getScreenCaptureUnsupportedWarning()
if (shareWarning != null) document.getElementById('hostWarning')!.innerText = shareWarning
// Handlers
document.getElementById('hostRegenerate')!.onclick = () =>
this.regeneratePhrase()
this.phraseElem.onchange = () =>
document.getElementById('hostPotentialUrl')!.innerText = clientUrl(this.phraseElem.value)
this.phraseElem.oninput = () =>
document.getElementById('hostPotentialUrl')!.innerText = clientUrl(this.phraseElem.value)
document.getElementById('hostChooseScreen')!.onclick = async () => {
try {
await this.startShare()
} catch (err) {
console.error(err)
this.stop()
this.displayErr(err)
}
}
this.sharePauseElem.onclick = () => {
if (this.stream != null) {
const enabled = this.sharePauseElem.innerText != 'Pause Video'
this.stream.getTracks().forEach(t => t.enabled = enabled)
this.sharePauseElem.innerText = enabled ? 'Pause Video' : 'Resume Video'
}
}
document.getElementById('hostShareStop')!.onclick = () =>
this.stop()
}
displayErr(err: any) {
if (err) {
this.errElem.innerText = '' + err
this.errElem.style.display = 'block'
} else {
this.errElem.innerText = ''
this.errElem.style.display = 'none'
}
}
show() {
this.elem.style.display = 'flex'
this.regeneratePhrase()
}
reset() {
this.elem.style.display = 'none'
this.phraseElem.value = ''
this.passwordElem.value = ''
this.stop()
}
stop() {
// Remove error, only show settings
this.displayErr(null)
this.workingElem.style.display = 'none'
this.sharingElem.style.display = 'none'
this.settingsElem.style.display = 'flex'
// Reset some element values
this.sharePauseElem.innerText = 'Pause Video'
// Close and remove all peer conns
this.peerConns.forEach(p => p.close())
this.peerConns = []
// Close and remove all signal sockets
if (this.hostSignalers != null) {
this.hostSignalers.forEach(s => s.close())
this.hostSignalers = undefined
}
// Stop and remove the stream
if (this.stream != null) {
this.stream.getTracks().forEach(t => t.stop())
this.stream = undefined
}
// Stop the video if we can
// ref: https://stackoverflow.com/questions/3258587/how-to-properly-unload-destroy-a-video-element
this.shareVideoElem.pause()
this.shareVideoElem.removeAttribute('src')
this.shareVideoElem.load()
}
regeneratePhrase() {
this.phraseElem.value = randomPhrase()
this.phraseElem.dispatchEvent(new Event('change', { bubbles: true }))
}
async startShare() {
this.shareUrlElem.innerText = clientUrl(this.phraseElem.value)
this.shareUrlElem.href = this.shareUrlElem.innerText
this.shareClientCountElem.innerText = '0'
this.settingsElem.style.display = 'none'
this.sharingElem.style.display = 'none'
this.workingElem.style.display = 'flex'
// Make sure there's a valid phrase
if (!this.phraseElem.reportValidity()) return
// Hide the settings, show the "working"
// Request the screen capture
this.stream = await navigator.mediaDevices.getDisplayMedia({
video: { cursor: 'always' },
audio: false
})
this.shareVideoElem.srcObject = this.stream!
await this.shareVideoElem.play()
this.workingElem.style.display = 'none'
this.sharingElem.style.display = 'flex'
// Listen on signal sockets for yesterday, today, and tomorrow just in case
this.hostSignalers = [
await HostSignaler.create(this.stream, this.phraseElem.value, new Date(), -1,
this.passwordElem.value, peerConn => this.onNewClient(peerConn)),
await HostSignaler.create(this.stream, this.phraseElem.value, new Date(), 0,
this.passwordElem.value, peerConn => this.onNewClient(peerConn)),
await HostSignaler.create(this.stream, this.phraseElem.value, new Date(), 1,
this.passwordElem.value, peerConn => this.onNewClient(peerConn))
]
}
onNewClient(peerConn: RTCPeerConnection) {
this.peerConns.push(peerConn)
this.shareClientCountElem.innerText = '' + this.peerConns.length
peerConn.oniceconnectionstatechange = () => {
debug('RTC browser state change: ' + peerConn.iceConnectionState)
if (peerConn.iceConnectionState == 'closed' || peerConn.iceConnectionState == 'disconnected') {
const index = this.peerConns.indexOf(peerConn)
if (index >= 0) {
this.peerConns.splice(index, 1)
this.shareClientCountElem.innerText = '' + this.peerConns.length
}
}
}
}
}
interface PendingAnswer {
myKey: KeyPair
theirPub: Uint8Array
peerConn: RTCPeerConnection
}
// 1 minute is our max for now which is fine
const maxMsForAnswer = 60 * 1000
class HostSignaler {
stream: MediaStream
phrase: string
date: Date
pubSub: PubSub
password: string
onNewClient: (answer: RTCPeerConnection) => void
pendingAnswers: PendingAnswer[] = []
static async create(stream: MediaStream, phrase: string, d: Date, yearDiff: number, password: string,
onNewClient: (answer: RTCPeerConnection) => void) {
d.setUTCFullYear(d.getUTCFullYear() + yearDiff)
const roomName = signalRoomName(phrase, d)
debug('Starting signaler on room ' + roomName)
const signaler = await createDefaultPubSub(roomName)
return new HostSignaler(stream, phrase, d, password, onNewClient, signaler)
}
constructor(stream: MediaStream, phrase: string, date: Date, password: string,
onNewClient: (answer: RTCPeerConnection) => void, pubSub: PubSub) {
this.stream = stream
this.phrase = phrase
this.date = date
this.password = password
this.onNewClient = onNewClient
this.pubSub = pubSub
this.pubSub.setSub(msg => {
// This can be an offer request or an answer. What we try to do is decrypt
// the offer request and if that fails, we try each pending answer.
const offerRequest = offerRequestDecrypted(msg, this.phrase, this.date, this.password)
if (offerRequest != null) {
debug('Message was valid offer request', offerRequest)
this.onOfferRequest(offerRequest)
} else {
for (const pendingAnswer of this.pendingAnswers) {
const answer = answerDecrypted(msg, pendingAnswer.myKey.privateKey, pendingAnswer.theirPub)
if (answer != null) {
debug('Message was valid answer', answer)
this.onAnswerReceived(pendingAnswer, answer)
return
}
}
debug('Message was unrecognized')
}
})
}
onOfferRequest(theirPub: Uint8Array) {
// Create the connection
const peerConn = new RTCPeerConnection(suggestedRTCConfig)
// Create the answer (add it later) and closer
const myKey = genKeyPair()
const pendingAnswer = { myKey, theirPub, peerConn }
const closePendingAnswer = () => {
const answerIndex = this.pendingAnswers.indexOf(pendingAnswer)
if (answerIndex >= 0) {
peerConn.close()
this.pendingAnswers.splice(answerIndex, 1)
}
}
// We'll log the state changes for now
peerConn.oniceconnectionstatechange = () => debug('RTC browser state change: ' + peerConn.iceConnectionState)
// A null candidate means we're done and can send offer
peerConn.onicecandidate = event => {
if (event.candidate === null) {
if (peerConn.localDescription == null) throw new Error('Missing local desc')
// Add to waiting list
this.pendingAnswers.push(pendingAnswer)
// We're only going to wait so long before removing it
setTimeout(() => closePendingAnswer(), maxMsForAnswer)
// Send it off
this.pubSub.pub(offerEncrypted(peerConn.localDescription, myKey, theirPub))
}
}
// Create the offer when negotiation needed
peerConn.onnegotiationneeded = e =>
peerConn.createOffer().then(d => peerConn.setLocalDescription(d)).catch(err => {
closePendingAnswer()
console.error(err)
})
// Now add the stream to start it all off
this.stream.getTracks().forEach(track => peerConn.addTrack(track, this.stream))
}
async onAnswerReceived(pendingAnswer: PendingAnswer, answer: RTCSessionDescriptionInit) {
// Remove the pending answer
const answerIndex = this.pendingAnswers.indexOf(pendingAnswer)
if (answerIndex >= 0) this.pendingAnswers.splice(answerIndex, 1)
// Set the remote description and then invoke the callback if present
try {
await pendingAnswer.peerConn.setRemoteDescription(answer)
if (this.onNewClient != null) this.onNewClient(pendingAnswer.peerConn)
} catch (err) {
pendingAnswer.peerConn.close()
console.error(err)
}
}
close() {
// Close all pending answers, then close the web socket
this.pendingAnswers.forEach(p => p.peerConn.close())
this.pendingAnswers = []
this.pubSub.close()
}
} | the_stack |
import {
addComponent,
defineQuery,
enterQuery,
exitQuery,
Not,
pipe,
removeEntity,
defineComponent,
Types,
} from "bitecs";
import {
createCursorView,
CursorView,
moveCursorView,
readFloat32,
readString,
readUint16,
readUint32,
readUint8,
rewindCursorView,
scrollCursorView,
skipFloat32,
sliceCursorView,
spaceUint16,
spaceUint32,
spaceUint8,
writeFloat32,
writePropIfChanged,
writeString,
writeUint32,
writeUint8,
} from "../allocator/CursorView";
import { addChild, Transform } from "../component/transform";
import { GameState } from "../GameTypes";
import { NOOP } from "../config.common";
import { Player } from "../component/Player";
import { sendAudioPeerEntityMessage } from "../audio/audio.game";
import { defineModule, getModule, registerMessageHandler } from "../module/module.common";
import {
AddPeerIdMessage,
NetworkMessage,
NetworkMessageType,
RemovePeerIdMessage,
SetHostMessage,
SetPeerIdMessage,
} from "./network.common";
import { createPrefabEntity } from "../prefab";
import { checkBitflag } from "../utils/checkBitflag";
// type hack for postMessage(data, transfers) signature in worker
const worker: Worker = self as any;
/*********
* Types *
********/
export interface GameNetworkState {
hosting: boolean;
incoming: ArrayBuffer[];
peerIdToEntityId: Map<string, number>;
networkIdToEntityId: Map<number, number>;
peerId: string;
peers: string[];
newPeers: string[];
peerIdCount: number;
peerIdToIndex: Map<string, number>;
indexToPeerId: Map<number, string>;
localIdCount: number;
removedLocalIds: number[];
messageHandlers: { [key: number]: (input: [GameState, CursorView]) => void };
cursorView: CursorView;
}
export enum NetworkAction {
Create,
Delete,
UpdateChanged,
UpdateSnapshot,
FullChanged,
FullSnapshot,
Prefab,
AssignPeerIdIndex,
InformPlayerNetworkId,
NewPeerSnapshot,
}
const writeMessageType = writeUint8;
type NetPipeData = [GameState, CursorView];
/******************
* Initialization *
*****************/
export const NetworkModule = defineModule<GameState, GameNetworkState>({
name: "network",
create: (ctx): GameNetworkState => ({
hosting: false,
incoming: [],
networkIdToEntityId: new Map<number, number>(),
peerIdToEntityId: new Map(),
peerId: "",
peers: [],
newPeers: [],
peerIdToIndex: new Map(),
indexToPeerId: new Map(),
peerIdCount: 0,
localIdCount: 0,
removedLocalIds: [],
messageHandlers: {},
cursorView: createCursorView(),
}),
init(ctx: GameState) {
const network = getModule(ctx, NetworkModule);
registerInboundMessageHandler(network, NetworkAction.Create, deserializeCreates);
registerInboundMessageHandler(network, NetworkAction.UpdateChanged, deserializeUpdatesChanged);
registerInboundMessageHandler(network, NetworkAction.UpdateSnapshot, deserializeUpdatesSnapshot);
registerInboundMessageHandler(network, NetworkAction.Delete, deserializeDeletes);
registerInboundMessageHandler(network, NetworkAction.FullSnapshot, deserializeSnapshot);
registerInboundMessageHandler(network, NetworkAction.FullChanged, deserializeFullUpdate);
registerInboundMessageHandler(network, NetworkAction.AssignPeerIdIndex, deserializePeerIdIndex);
registerInboundMessageHandler(network, NetworkAction.InformPlayerNetworkId, deserializePlayerNetworkId);
registerInboundMessageHandler(network, NetworkAction.NewPeerSnapshot, deserializeNewPeerSnapshot);
const disposables = [
registerMessageHandler(ctx, NetworkMessageType.SetHost, onSetHost),
registerMessageHandler(ctx, NetworkMessageType.SetPeerId, onSetPeerId),
registerMessageHandler(ctx, NetworkMessageType.AddPeerId, onAddPeerId),
registerMessageHandler(ctx, NetworkMessageType.RemovePeerId, onRemovePeerId),
registerMessageHandler(ctx, NetworkMessageType.NetworkMessage, onInboundNetworkMessage),
];
return () => {
for (const dispose of disposables) {
dispose();
}
};
},
});
/********************
* Message Handlers *
*******************/
const onInboundNetworkMessage = (ctx: GameState, message: NetworkMessage) => {
const network = getModule(ctx, NetworkModule);
const { packet } = message;
network.incoming.push(packet);
};
const onAddPeerId = (ctx: GameState, message: AddPeerIdMessage) => {
const network = getModule(ctx, NetworkModule);
const { peerId } = message;
if (network.peers.includes(peerId) || network.peerId === peerId) return;
network.peers.push(peerId);
network.newPeers.push(peerId);
if (network.hosting) mapPeerIdAndIndex(ctx, peerId);
};
const onRemovePeerId = (ctx: GameState, message: RemovePeerIdMessage) => {
const network = getModule(ctx, NetworkModule);
const { peerId } = message;
const i = network.peers.indexOf(peerId);
if (i > -1) {
const eid = network.peerIdToEntityId.get(peerId);
if (eid) removeEntity(ctx.world, eid);
network.peers.splice(i, 1);
network.peerIdToIndex.delete(peerId);
} else {
console.warn(`cannot remove peerId ${peerId}, does not exist in peer list`);
}
};
const onSetPeerId = (ctx: GameState, message: SetPeerIdMessage) => {
const network = getModule(ctx, NetworkModule);
const { peerId } = message;
network.peerId = peerId;
if (network.hosting) mapPeerIdAndIndex(ctx, peerId);
};
const onSetHost = (ctx: GameState, message: SetHostMessage) => {
const network = getModule(ctx, NetworkModule);
network.hosting = message.value;
};
/* Utils */
const mapPeerIdAndIndex = (ctx: GameState, peerId: string) => {
const network = getModule(ctx, NetworkModule);
const peerIdIndex = network.peerIdCount++;
network.peerIdToIndex.set(peerId, peerIdIndex);
network.indexToPeerId.set(peerIdIndex, peerId);
};
const isolateBits = (val: number, n: number, offset = 0) => val & (((1 << n) - 1) << offset);
export const getPeerIdFromNetworkId = (nid: number) => isolateBits(nid, 16);
export const getLocalIdFromNetworkId = (nid: number) => isolateBits(nid >>> 16, 16);
// hack - could also temporarily send whole peerId string to avoid potential collisions
const rndRange = (min: number, max: number) => Math.random() * (max - min) + min;
const peerIdIndex = rndRange(0, 0xffff);
export const createNetworkId = (state: GameState) => {
const network = getModule(state, NetworkModule);
const localId = network.removedLocalIds.shift() || network.localIdCount++;
// const peerIdIndex = network.peerIdToIndex.get(network.peerId);
if (peerIdIndex === undefined) {
// console.error("could not create networkId, peerId not set in peerIdToIndex map");
throw new Error("could not create networkId, peerId not set in peerIdToIndex map");
}
// bitwise operations in JS are limited to 32 bit integers (https://developer.mozilla.org/en-US/docs/web/javascript/reference/operators#binary_bitwise_operators)
// logical right shift by 0 to treat as an unsigned integer
return ((localId << 16) | peerIdIndex) >>> 0;
};
export const deleteNetworkId = (ctx: GameState, nid: number) => {
const network = getModule(ctx, NetworkModule);
const localId = getLocalIdFromNetworkId(nid);
network.removedLocalIds.push(localId);
};
/* Components */
export const Networked = defineComponent({
// networkId contains both peerIdIndex (owner) and localNetworkId
networkId: Types.ui32,
});
export const Owned = defineComponent();
export const NetworkTransform = defineComponent({
position: [Types.f32, 3],
quaternion: [Types.f32, 4],
});
/* Queries */
export const networkedQuery = defineQuery([Networked]);
export const enteredNetworkedQuery = enterQuery(networkedQuery);
export const exitedNetworkedQuery = exitQuery(networkedQuery);
export const ownedNetworkedQuery = defineQuery([Networked, Owned]);
export const createdOwnedNetworkedQuery = enterQuery(ownedNetworkedQuery);
export const deletedOwnedNetworkedQuery = exitQuery(ownedNetworkedQuery);
export const remoteNetworkedQuery = defineQuery([Networked, Not(Owned)]);
// bitecs todo: add defineQueue to bitECS / allow multiple enter/exit queries to avoid duplicate query
export const networkIdQuery = defineQuery([Networked, Owned]);
export const enteredNetworkIdQuery = enterQuery(networkIdQuery);
export const exitedNetworkIdQuery = exitQuery(networkIdQuery);
export const ownedPlayerQuery = defineQuery([Player, Owned]);
export const enteredOwnedPlayerQuery = enterQuery(ownedPlayerQuery);
export const exitedOwnedPlayerQuery = exitQuery(ownedPlayerQuery);
export const remotePlayerQuery = defineQuery([Player, Not(Owned)]);
export const enteredRemotePlayerQuery = enterQuery(remotePlayerQuery);
export const exitedRemotePlayerQuery = exitQuery(remotePlayerQuery);
/* Transform serialization */
export const serializeTransformSnapshot = (v: CursorView, eid: number) => {
const position = Transform.position[eid];
writeFloat32(v, position[0]);
writeFloat32(v, position[1]);
writeFloat32(v, position[2]);
const quaternion = Transform.quaternion[eid];
writeFloat32(v, quaternion[0]);
writeFloat32(v, quaternion[1]);
writeFloat32(v, quaternion[2]);
writeFloat32(v, quaternion[3]);
return v;
};
export const deserializeTransformSnapshot = (v: CursorView, eid: number | undefined) => {
if (eid !== undefined) {
// const position = NetworkTransform.position[eid];
const position = Transform.position[eid];
position[0] = readFloat32(v);
position[1] = readFloat32(v);
position[2] = readFloat32(v);
// const quaternion = NetworkTransform.quaternion[eid];
const quaternion = Transform.quaternion[eid];
quaternion[0] = readFloat32(v);
quaternion[1] = readFloat32(v);
quaternion[2] = readFloat32(v);
quaternion[3] = readFloat32(v);
} else {
scrollCursorView(v, Float32Array.BYTES_PER_ELEMENT * 7);
}
return v;
};
const defineChangedSerializer = (...fns: ((v: CursorView, eid: number) => boolean)[]) => {
const spacer = fns.length <= 8 ? spaceUint8 : fns.length <= 16 ? spaceUint16 : spaceUint32;
return (v: CursorView, eid: number) => {
const writeChangeMask = spacer(v);
let changeMask = 0;
let b = 0;
for (let i = 0; i < fns.length; i++) {
const fn = fns[i];
changeMask |= fn(v, eid) ? 1 << b++ : b++ && 0;
}
writeChangeMask(changeMask);
return changeMask > 0;
};
};
export const serializeTransformChanged = defineChangedSerializer(
(v, eid) => writePropIfChanged(v, Transform.position[eid], 0),
(v, eid) => writePropIfChanged(v, Transform.position[eid], 1),
(v, eid) => writePropIfChanged(v, Transform.position[eid], 2),
(v, eid) => writePropIfChanged(v, Transform.quaternion[eid], 0),
(v, eid) => writePropIfChanged(v, Transform.quaternion[eid], 1),
(v, eid) => writePropIfChanged(v, Transform.quaternion[eid], 2),
(v, eid) => writePropIfChanged(v, Transform.quaternion[eid], 3)
);
// todo: bench performance of defineChangedSerializer vs raw function
// export const serializeTransformChanged = (v: CursorView, eid: number) => {
// const writeChangeMask = spaceUint8(v);
// let changeMask = 0;
// let b = 0;
// const position = Transform.position[eid];
// changeMask |= writePropIfChanged(v, position, 0) ? 1 << b++ : b++ && 0;
// changeMask |= writePropIfChanged(v, position, 1) ? 1 << b++ : b++ && 0;
// changeMask |= writePropIfChanged(v, position, 2) ? 1 << b++ : b++ && 0;
// const rotation = Transform.rotation[eid];
// changeMask |= writePropIfChanged(v, rotation, 0) ? 1 << b++ : b++ && 0;
// changeMask |= writePropIfChanged(v, rotation, 1) ? 1 << b++ : b++ && 0;
// changeMask |= writePropIfChanged(v, rotation, 2) ? 1 << b++ : b++ && 0;
// writeChangeMask(changeMask);
// return changeMask > 0;
// };
export const defineChangedDeserializer = (...fns: ((v: CursorView, eid: number | undefined) => void)[]) => {
const readChangeMask = fns.length <= 8 ? readUint8 : fns.length <= 16 ? readUint16 : readUint32;
return (v: CursorView, eid: number | undefined) => {
const changeMask = readChangeMask(v);
let b = 0;
for (let i = 0; i < fns.length; i++) {
const fn = fns[i];
if (checkBitflag(changeMask, 1 << b++)) fn(v, eid);
}
};
};
// export const deserializeTransformChanged = defineChangedDeserializer(
// (v, eid) => (eid ? (NetworkTransform.position[eid][0] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.position[eid][1] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.position[eid][2] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.quaternion[eid][0] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.quaternion[eid][1] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.quaternion[eid][2] = readFloat32(v)) : skipFloat32(v)),
// (v, eid) => (eid ? (NetworkTransform.quaternion[eid][3] = readFloat32(v)) : skipFloat32(v))
// );
export const deserializeTransformChanged = defineChangedDeserializer(
(v, eid) => (eid ? (Transform.position[eid][0] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.position[eid][1] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.position[eid][2] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.quaternion[eid][0] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.quaternion[eid][1] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.quaternion[eid][2] = readFloat32(v)) : skipFloat32(v)),
(v, eid) => (eid ? (Transform.quaternion[eid][3] = readFloat32(v)) : skipFloat32(v))
);
// export const deserializeTransformChanged = (v: CursorView, eid: number) => {
// const changeMask = readUint8(v);
// let b = 0;
// const position = Transform.position[eid];
// if (checkBitflag(changeMask, 1 << b++)) position[0] = readFloat32(v);
// if (checkBitflag(changeMask, 1 << b++)) position[1] = readFloat32(v);
// if (checkBitflag(changeMask, 1 << b++)) position[2] = readFloat32(v);
// const rotation = Transform.rotation[eid];
// if (checkBitflag(changeMask, 1 << b++)) rotation[0] = readFloat32(v);
// if (checkBitflag(changeMask, 1 << b++)) rotation[1] = readFloat32(v);
// if (checkBitflag(changeMask, 1 << b++)) rotation[2] = readFloat32(v);
// return v;
// };
/* Create */
export function serializeCreatesSnapshot(input: NetPipeData) {
const [state, v] = input;
const entities = ownedNetworkedQuery(state.world);
// todo: optimize length written with maxEntities config
writeUint32(v, entities.length);
for (let i = 0; i < entities.length; i++) {
const eid = entities[i];
const nid = Networked.networkId[eid];
const prefabName = state.entityPrefabMap.get(eid) || "cube";
if (prefabName) {
writeUint32(v, nid);
writeString(v, prefabName);
} else {
console.error("could not write entity prefab name,", eid, "does not exist in entityPrefabMap");
}
}
return input;
}
export function serializeCreates(input: NetPipeData) {
const [state, v] = input;
const entities = createdOwnedNetworkedQuery(state.world);
writeUint32(v, entities.length);
for (let i = 0; i < entities.length; i++) {
const eid = entities[i];
const nid = Networked.networkId[eid];
const prefabName = state.entityPrefabMap.get(eid) || "cube";
if (prefabName) {
writeUint32(v, nid);
writeString(v, prefabName);
console.log("serializing creation for nid", nid, "eid", eid, "prefab", prefabName);
} else {
console.error("could not write entity prefab name,", eid, "does not exist in entityPrefabMap");
}
}
return input;
}
export function createRemoteNetworkedEntity(state: GameState, nid: number, prefab: string) {
const network = getModule(state, NetworkModule);
const eid = createPrefabEntity(state, prefab);
// remote entity not owned by default so lock the rigidbody
// const body = RigidBody.store.get(eid);
// if (body) {
// body.lockTranslations(true, true);
// body.lockRotations(true, true);
// }
addComponent(state.world, Networked, eid);
// addComponent(state.world, NetworkTransform, eid);
Networked.networkId[eid] = nid;
network.networkIdToEntityId.set(nid, eid);
addChild(state.scene, eid);
return eid;
}
export function deserializeCreates(input: NetPipeData) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const count = readUint32(v);
for (let i = 0; i < count; i++) {
const nid = readUint32(v);
const prefabName = readString(v);
const existingEntity = network.networkIdToEntityId.get(nid);
if (existingEntity) continue;
const eid = createRemoteNetworkedEntity(state, nid, prefabName);
console.log("deserializing creation - nid", nid, "eid", eid, "prefab", prefabName);
}
return input;
}
/* Update */
export function serializeUpdatesSnapshot(input: NetPipeData) {
const [state, v] = input;
const entities = ownedNetworkedQuery(state.world);
writeUint32(v, entities.length);
for (let i = 0; i < entities.length; i++) {
const eid = entities[i];
const nid = Networked.networkId[eid];
writeUint32(v, nid);
serializeTransformSnapshot(v, eid);
}
return input;
}
export function serializeUpdatesChanged(input: NetPipeData) {
const [state, v] = input;
const entities = ownedNetworkedQuery(state.world);
const writeCount = spaceUint32(v);
let count = 0;
for (let i = 0; i < entities.length; i++) {
const eid = entities[i];
const nid = Networked.networkId[eid];
const rewind = rewindCursorView(v);
const writeNid = spaceUint32(v);
const written = serializeTransformChanged(v, eid);
if (written) {
writeNid(nid);
count += 1;
} else {
rewind();
}
}
writeCount(count);
return input;
}
export function deserializeUpdatesSnapshot(input: NetPipeData) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const count = readUint32(v);
for (let i = 0; i < count; i++) {
const nid = readUint32(v);
const eid = network.networkIdToEntityId.get(nid);
if (!eid) {
console.warn(`could not deserialize update for non-existent entity for networkId ${nid}`);
// continue;
// createRemoteNetworkedEntity(state, nid);
}
deserializeTransformSnapshot(v, eid);
}
return input;
}
export function deserializeUpdatesChanged(input: NetPipeData) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const count = readUint32(v);
for (let i = 0; i < count; i++) {
const nid = readUint32(v);
const eid = network.networkIdToEntityId.get(nid);
if (!eid) {
console.warn(`could not deserialize update for non-existent entity for networkId ${nid}`);
// continue;
// createRemoteNetworkedEntity(state, nid);
}
deserializeTransformChanged(v, eid);
}
return input;
}
/* Delete */
export function serializeDeletes(input: NetPipeData) {
const [state, v] = input;
const entities = deletedOwnedNetworkedQuery(state.world);
writeUint32(v, entities.length);
for (let i = 0; i < entities.length; i++) {
const eid = entities[i];
const nid = Networked.networkId[eid];
writeUint32(v, nid);
console.log("serialized deletion for nid", nid, "eid", eid);
}
return input;
}
export function deserializeDeletes(input: NetPipeData) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const count = readUint32(v);
for (let i = 0; i < count; i++) {
const nid = readUint32(v);
const eid = network.networkIdToEntityId.get(nid);
if (!eid) {
console.warn(`could not remove networkId ${nid}, no matching entity`);
} else {
console.log("deserialized deletion for nid", nid, "eid", eid);
removeEntity(state.world, eid);
network.networkIdToEntityId.delete(nid);
}
}
return input;
}
/* PeerId Message */
// host sends peerIdIndex to new peers
export function serializePeerIdIndex(input: NetPipeData, peerId: string) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const peerIdIndex = network.peerIdToIndex.get(peerId);
console.log("sending peerIdIndex", peerId, peerIdIndex);
if (peerIdIndex === undefined) {
// console.error(`unable to serialize peerIdIndex message - peerIdIndex not set for ${peerId}`);
throw new Error(`unable to serialize peerIdIndex message - peerIdIndex not set for ${peerId}`);
}
writeString(v, peerId);
writeUint8(v, peerIdIndex);
return input;
}
// peer decodes the peerIdIndex
export function deserializePeerIdIndex(input: NetPipeData) {
const [state, v] = input;
const network = getModule(state, NetworkModule);
const peerId = readString(v);
const peerIdIndex = readUint8(v);
network.peerIdToIndex.set(peerId, peerIdIndex);
network.indexToPeerId.set(peerIdIndex, peerId);
console.log("recieving peerIdIndex", peerId, peerIdIndex);
return input;
}
// ad-hoc messages view
const messageView = createCursorView(new ArrayBuffer(1000));
export function createPeerIdIndexMessage(state: GameState, peerId: string) {
const input: NetPipeData = [state, messageView];
writeMessageType(messageView, NetworkAction.AssignPeerIdIndex);
serializePeerIdIndex(input, peerId);
return sliceCursorView(messageView);
}
/* Player NetworkId Message */
export function serializePlayerNetworkId(input: NetPipeData) {
const [state, cv] = input;
const network = getModule(state, NetworkModule);
const peerId = network.peerId;
const peerEid = network.peerIdToEntityId.get(peerId);
const peerIdIndex = network.peerIdToIndex.get(peerId);
console.log(`serializePlayerNetworkId`, peerId, peerEid, peerIdIndex);
if (peerEid === undefined || peerIdIndex === undefined) {
console.error(
`could not send NetworkMessage.AssignPlayerEntity, ${peerId} not set on peerIdToEntity/peerIdToIndex map`
);
return input;
}
const peerNid = Networked.networkId[peerEid];
writeString(cv, peerId);
writeUint32(cv, peerNid);
return input;
}
export function deserializePlayerNetworkId(input: NetPipeData) {
const [state, cv] = input;
const network = getModule(state, NetworkModule);
// read
const peerId = readString(cv);
const peerNid = readUint32(cv);
const peid = network.networkIdToEntityId.get(peerNid);
if (peid !== undefined) {
network.peerIdToEntityId.set(peerId, peid);
console.log("deserializePlayerNetworkId", network.peerIdToEntityId);
sendAudioPeerEntityMessage(peerId, peid);
} else {
console.error("could not find peer's entityId within network.networkIdToEntityId");
}
return input;
}
export function createPlayerNetworkIdMessage(state: GameState) {
const input: NetPipeData = [state, messageView];
writeMessageType(messageView, NetworkAction.InformPlayerNetworkId);
serializePlayerNetworkId(input);
return sliceCursorView(messageView);
}
/* Message Factories */
const setMessageType = (type: NetworkAction) => (input: NetPipeData) => {
const [, v] = input;
writeMessageType(v, type);
return input;
};
// playerNetIdMsg + createMsg + deleteMsg
export const createNewPeerSnapshotMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.NewPeerSnapshot),
serializeCreatesSnapshot,
serializeUpdatesSnapshot,
serializePlayerNetworkId,
([_, v]) => sliceCursorView(v)
);
// reliably send all entities and their data to newly seen clients on-join
export const createFullSnapshotMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.FullSnapshot),
serializeCreatesSnapshot,
serializeUpdatesSnapshot,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 2 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
// reilably send creates/updates/deletes in one message
export const createFullChangedMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.FullChanged),
serializeCreates,
serializeUpdatesChanged,
serializeDeletes,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 3 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
// reliably send creates
export const createCreateMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.Create),
serializeCreates,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 1 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
// unreliably send updates
export const createUpdateChangedMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.UpdateChanged),
serializeUpdatesChanged,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 1 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
// unreliably send updates
export const createUpdateSnapshotMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.UpdateSnapshot),
serializeUpdatesSnapshot,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 1 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
// reliably send deletes
export const createDeleteMessage: (input: NetPipeData) => ArrayBuffer = pipe(
setMessageType(NetworkAction.Delete),
serializeDeletes,
([_, v]) => {
if (v.cursor <= Uint8Array.BYTES_PER_ELEMENT + 1 * Uint32Array.BYTES_PER_ELEMENT) {
moveCursorView(v, 0);
}
return sliceCursorView(v);
}
);
/* Send */
export const broadcastReliable = (state: GameState, packet: ArrayBuffer) => {
// state.network.peers.forEach((peerId: string) => {
// sendReliable(state, peerId, packet);
// });
worker.postMessage(
{
type: NetworkMessageType.NetworkBroadcast,
packet,
reliable: true,
},
[packet]
);
};
export const broadcastUnreliable = (state: GameState, packet: ArrayBuffer) => {
// state.network.peers.forEach((peerId: string) => {
// sendUnreliable(peerId, packet);
// });
worker.postMessage(
{
type: NetworkMessageType.NetworkBroadcast,
packet,
reliable: false,
},
[packet]
);
};
export const sendReliable = (state: GameState, peerId: string, packet: ArrayBuffer) => {
// todo: headers
// packet = writeHeaders(state, peerId, packet);
worker.postMessage(
{
type: NetworkMessageType.NetworkMessage,
peerId,
packet,
reliable: true,
},
[packet]
);
};
export const sendUnreliable = (peerId: string, packet: ArrayBuffer) => {
worker.postMessage(
{
type: NetworkMessageType.NetworkMessage,
peerId,
packet,
reliable: false,
},
[packet]
);
};
const assignNetworkIds = (state: GameState) => {
const entered = enteredNetworkIdQuery(state.world);
for (let i = 0; i < entered.length; i++) {
const eid = entered[i];
Networked.networkId[eid] = createNetworkId(state) || 0;
console.log("networkId", Networked.networkId[eid], "assigned to eid", eid);
}
return state;
};
const deleteNetworkIds = (state: GameState) => {
const exited = exitedNetworkIdQuery(state.world);
for (let i = 0; i < exited.length; i++) {
const eid = exited[i];
deleteNetworkId(state, Networked.networkId[eid]);
Networked.networkId[eid] = NOOP;
}
return state;
};
const sendUpdates = (ctx: GameState) => {
const network = getModule(ctx, NetworkModule);
const data: NetPipeData = [ctx, network.cursorView];
// only send updates when:
// - we have connected peers
// - peerIdIndex has been assigned
// - player rig has spawned
const haveConnectedPeers = network.peers.length > 0;
const spawnedPlayerRig = ownedPlayerQuery(ctx.world).length > 0;
if (haveConnectedPeers && spawnedPlayerRig) {
// send snapshot update to all new peers
const haveNewPeers = network.newPeers.length > 0;
if (haveNewPeers) {
const newPeerSnapshotMsg = createNewPeerSnapshotMessage(data);
while (network.newPeers.length) {
const theirPeerId = network.newPeers.shift();
if (theirPeerId) {
// if hosting, broadcast peerIdIndex message
if (network.hosting) broadcastReliable(ctx, createPeerIdIndexMessage(ctx, theirPeerId));
sendReliable(ctx, theirPeerId, newPeerSnapshotMsg);
}
}
} else {
// reliably send full messages for now
const msg = createFullChangedMessage(data);
if (msg.byteLength) broadcastReliable(ctx, msg);
}
}
return ctx;
};
export function OutboundNetworkSystem(state: GameState) {
const network = getModule(state, NetworkModule);
const hasPeerIdIndex = network.peerIdToIndex.has(network.peerId);
if (!hasPeerIdIndex) return state;
// assign networkIds before serializing game state
assignNetworkIds(state);
// serialize and send all outgoing updates
sendUpdates(state);
// delete networkIds after serializing game state (deletes serialization needs to know the nid before removal)
deleteNetworkIds(state);
return state;
}
/* Inbound */
const deserializeNewPeerSnapshot = pipe(deserializeCreates, deserializeUpdatesSnapshot, deserializePlayerNetworkId);
const deserializeSnapshot = pipe(deserializeCreates, deserializeUpdatesSnapshot);
const deserializeFullUpdate = pipe(deserializeCreates, deserializeUpdatesChanged, deserializeDeletes);
const processNetworkMessage = (state: GameState, msg: ArrayBuffer) => {
const cursorView = createCursorView(msg);
const messageType = readUint8(cursorView);
const input: NetPipeData = [state, cursorView];
const { messageHandlers } = getModule(state, NetworkModule);
const handler = messageHandlers[messageType];
if (!handler) {
console.error(
"could not process network message, no handler registered for messageType",
NetworkAction[messageType]
);
return;
}
handler(input);
};
const processNetworkMessages = (state: GameState) => {
const network = getModule(state, NetworkModule);
while (network.incoming.length) {
const msg = network.incoming.pop();
if (msg) processNetworkMessage(state, msg);
}
};
const registerInboundMessageHandler = (network: GameNetworkState, type: number, cb: (input: NetPipeData) => void) => {
network.messageHandlers[type] = cb;
};
export function InboundNetworkSystem(state: GameState) {
processNetworkMessages(state);
} | the_stack |
import { App } from './view/components/App';
import { Automaton, AutomatonOptions, ChannelUpdateEvent, FxDefinition, FxParam, SerializedAutomaton, SerializedChannel, SerializedCurve } from '@0b5vr/automaton';
import { BiMap } from './utils/BiMap';
import { ChannelWithGUI } from './ChannelWithGUI';
import { ContextMenuCommand } from './view/states/ContextMenu'; // 🔥🔥🔥🔥🔥🔥
import { CurveWithGUI } from './CurveWithGUI';
import { EventEmittable } from './mixins/EventEmittable';
import { GUIRemocon } from './GUIRemocon';
import { GUISettings, defaultGUISettings } from './types/GUISettings';
import { MinimizeOptions } from './types/MinimizeOptions';
import { Serializable } from './types/Serializable';
import { SerializedAutomatonWithGUI, defaultDataWithGUI } from './types/SerializedAutomatonWithGUI';
import { WithID } from './types/WithID';
import { applyMixins } from './utils/applyMixins';
import { compat } from './compat/compat';
import { createStore } from './view/states/store';
import { jsonCopy } from './utils/jsonCopy';
import { lofi } from './utils/lofi';
import { minimizeData } from './minimizeData';
import { reorderArray } from './utils/reorderArray';
import React from 'react';
import ReactDOM from 'react-dom';
import produce from 'immer';
import type { ToastyParams } from './types/ToastyParams';
/**
* Interface for options of {@link AutomatonWithGUI}.
*/
export interface AutomatonWithGUIOptions extends AutomatonOptions {
/**
* DOM element where you want to attach the Automaton GUI.
*/
gui?: HTMLElement;
/**
* Initial state of play / pause. `false` by default.
*/
isPlaying?: boolean;
/**
* Disable warnings for not used channels.
* Intended to be used by automaton-electron.
*/
disableChannelNotUsedWarning?: boolean;
/**
* Overrides the save procedure.
* Originally intended to be used by automaton-electron.
*/
overrideSave?: () => void;
/**
* Define what to do with the context menu when you click the save icon on the header.
* Originally intended to be used by automaton-electron.
*/
saveContextMenuCommands?: Array<ContextMenuCommand>;
}
/**
* IT'S AUTOMATON!
*/
export interface AutomatonWithGUI extends EventEmittable<AutomatonWithGUIEvents> {}
export class AutomatonWithGUI extends Automaton
implements Serializable<SerializedAutomatonWithGUI> {
/**
* Minimize serialized data for prod use.
* @param data The original data
*/
public static minimizeData(
data: SerializedAutomatonWithGUI,
options: MinimizeOptions
): SerializedAutomaton {
return minimizeData( data, options );
}
/**
* Compat serialized data.
* Use along with {@link deserialize}.
* @param data The data
*/
public static compat( data?: any ): SerializedAutomatonWithGUI {
return compat( data );
}
/**
* Overrided save procedure.
* Originally intended to be used by automaton-electron.
* Can also be specified via {@link AutomatonWithGUIOptions}.
*/
public overrideSave?: () => void;
/**
* Define what to do with the context menu when you click the save icon on the header.
* Originally intended to be used by automaton-electron.
* Can also be specified via {@link AutomatonWithGUIOptions}.
*/
public saveContextMenuCommands?: Array<ContextMenuCommand>;
/**
* Curves of the automaton.
*/
public readonly curves!: CurveWithGUI[]; // is initialized in super constructor
/**
* Channels of the timeline.
*/
public readonly channels!: ChannelWithGUI[]; // is initialized in super constructor
/**
* Map of channels, name vs. channel itself.
*/
public readonly mapNameToChannel!: BiMap<string, ChannelWithGUI>; // is initialized as a Map in super constructor, will be converted to BiMap later in its constructor
/**
* Labels.
*/
protected __labels!: { [ name: string ]: number }; // will be initialized @ deserialize
/**
* Version of the automaton.
*/
protected __version: string = process.env.VERSION!;
/**
* It's currently playing or not.
*/
protected __isPlaying: boolean;
/**
* Whether it disables not used warning for channels or not.
* Can be specified via {@link AutomatonWithGUIOptions}.
*/
private __isDisabledChannelNotUsedWarning: boolean = false;
/**
* Whether it has any changes that is not saved yet or not.
*/
private __shouldSave = false;
/**
* GUI settings for this automaton.
*/
private __guiSettings!: GUISettings; // will be initialized @ deserialize
/**
* Mounted point of its GUI.
*/
private __parentNode?: HTMLElement | null;
/**
* This enables the Automaton instance to be able to communicate with GUI.
*/
private __guiRemocon?: GUIRemocon | null;
/**
* A cache of previous {@link length}.
* You should not touch this from any place but {@link __tryUpdateLength}.
*/
private __lengthPrev = 1.0;
/**
* Timeline will loop between these timepoints.
*/
private __loopRegion: { begin: number; end: number } | null = null;
public get loopRegion(): { begin: number; end: number } | null {
return this.__loopRegion;
}
/**
* It's currently playing or not.
*/
public get isPlaying(): boolean {
return this.__isPlaying;
}
/**
* Length of the automaton i.e. the length of longest channel.
*/
public get length(): number {
let result = 0.0;
this.channels.forEach( ( channel ) => {
result = Math.max( result, channel.length );
} );
return result;
}
/**
* Channel names, ordered.
*/
public get channelNames(): string[] {
return this.channels.map( ( channel ) => this.mapNameToChannel.getFromValue( channel )! );
}
/**
* A map of fx definitions.
*/
public get fxDefinitions(): { [ name: string ]: FxDefinition } {
return this.__fxDefinitions;
}
/**
* A map of labels.
*/
public get labels(): { [ name: string ]: number } {
return this.__labels;
}
/**
* Whether it has any changes that is not saved yet or not.
*/
public get shouldSave(): boolean {
return this.__shouldSave;
}
/**
* Whether it has any changes that is not saved yet or not.
*/
public set shouldSave( shouldSave: boolean ) {
this.__shouldSave = shouldSave;
this.__emit( 'changeShouldSave', { shouldSave } );
}
/**
* GUI settings for this automaton.
*/
public get guiSettings(): GUISettings {
return jsonCopy( this.__guiSettings );
}
/**
* Create a new Automaton instance.
* @param data Serialized data of the automaton
* @param options Options for this Automaton instance
*/
public constructor(
data: SerializedAutomatonWithGUI = defaultDataWithGUI,
options: AutomatonWithGUIOptions = {}
) {
super( compat( data ), options );
this.mapNameToChannel = new BiMap<string, ChannelWithGUI>( this.mapNameToChannel );
this.__isPlaying = options.isPlaying || false;
this.overrideSave = options.overrideSave;
this.saveContextMenuCommands = options.saveContextMenuCommands;
this.__isDisabledChannelNotUsedWarning = options.disableChannelNotUsedWarning || false;
// if `options.disableChannelNotUsedWarning` is true, mark every channels as used
if ( this.__isDisabledChannelNotUsedWarning ) {
Object.values( this.channels ).forEach( ( channel ) => {
channel.markAsUsed();
} );
}
if ( options.gui ) {
this.mountGUI( options.gui );
}
if ( typeof window !== 'undefined' ) {
window.addEventListener( 'beforeunload', ( event ) => {
if ( this.shouldSave ) {
const confirmationMessage = 'Automaton: Did you saved your progress?';
event.returnValue = confirmationMessage;
return confirmationMessage;
}
} );
}
}
/**
* Emit the `seek` event.
* **The function itself doesn't do the seek operation**, as Automaton doesn't have a clock.
* It will be performed via GUI.
* @param time Time
*/
public seek( time: number ): void {
this.__emit( 'seek', { time } );
}
/**
* Emit the `play` event.
* **The function itself doesn't do the play operation**, as Automaton doesn't have a clock.
* Can be performed via GUI.
*/
public play(): void {
this.__emit( 'play' );
this.__isPlaying = true;
}
/**
* Emit the `pause` event.
* **The function itself doesn't do the pause operation**, as Automaton doesn't have a clock.
* Can be performed via GUI.
*/
public pause(): void {
this.__emit( 'pause' );
this.__isPlaying = false;
}
/**
* Add fx definitions.
* @param fxDefinitions A map of id - fx definition
*/
public addFxDefinitions( fxDefinitions: { [ id: string ]: FxDefinition } ): void {
super.addFxDefinitions( fxDefinitions );
this.__emit( 'addFxDefinitions', { fxDefinitions } );
}
/**
* Mark this channel as should be reset in next update call.
* Almost same as {@link update}, but not instant.
*/
public cueReset(): void {
Object.values( this.channels ).map( ( channel ) => {
channel.cueReset();
} );
}
/**
* Update the entire automaton.
* **You may want to call this in your update loop.**
* @param time Current time
*/
public update( time: number ): void {
super.update( time );
this.__emit( 'update', { time: this.time } );
if ( this.__loopRegion ) {
const { begin, end } = this.__loopRegion;
if ( time < begin || end <= time ) {
const newTime = time - begin - lofi( time - begin, end - begin ) + begin;
this.seek( newTime );
}
}
}
/**
* Generate default fx params object.
* @param id Id of the fx
* @returns Default fx params object
*/
public generateDefaultFxParams( id: string ): { [ key: string ]: any } {
const fxDef = this.__fxDefinitions[ id ];
if ( !fxDef ) { throw new Error( `Fx definition called ${id} is not defined` ); }
const ret: { [ key: string ]: any } = {};
const params = fxDef.params;
if ( params != null ) {
Object.keys( params ).forEach( ( key ) => {
ret[ key ] = params[ key ].default;
} );
}
return ret;
}
/**
* Toggle play / pause.
*/
public togglePlay(): void {
if ( this.isPlaying ) { this.pause(); }
else { this.play(); }
}
/**
* Change its resolution.
* Can be performed via GUI.
* @param resolution New resolution for the automaton
*/
public setResolution( resolution: number ): void {
// if the resolution is invalid then throw error
if ( isNaN( resolution ) || resolution < 1 ) {
throw new Error( 'Automaton.setResolution: resolution is invalid' );
}
// if both length and resolution are not changed then do fast-return
if ( resolution === this.resolution ) { return; }
// set the resolution
this.__resolution = resolution;
// update every curves
this.precalcAll();
// emit an event
this.__emit( 'changeResolution', { resolution } );
// mark as should save
this.shouldSave = true;
}
/**
* Create a new channel.
* @param name Name of channel
* @param data Serialized data of the channel
* @returns Created channel
*/
public createChannel( name: string, data?: SerializedChannel, index?: number ): ChannelWithGUI {
if ( this.mapNameToChannel.has( name ) ) {
throw new Error( 'AutomatonWithGUI: A channel for the given name already exists' );
}
const actualIndex = index ?? this.channels.length;
const channel = new ChannelWithGUI( this, data );
this.channels.splice( actualIndex, 0, channel );
this.mapNameToChannel.set( name, channel );
// if `options.disableChannelNotUsedWarning` is true, mark the created channels as used
if ( this.__isDisabledChannelNotUsedWarning ) {
channel.markAsUsed();
}
channel.on( 'changeLength', () => {
this.__tryUpdateLength();
} );
this.__emit( 'createChannel', { name, channel, index: actualIndex } );
this.shouldSave = true;
return channel;
}
/**
* Create a new channel, or overwrite the existing one.
* Intended to be used by GUI.
* @param name Name of channel
* @param data Serialized data of the channel
* @returns Created channel
*/
public createOrOverwriteChannel(
name: string,
data?: SerializedChannel,
index?: number
): ChannelWithGUI {
let prevIndex: number | undefined;
if ( this.mapNameToChannel.has( name ) ) {
prevIndex = this.getChannelIndex( name );
this.removeChannel( name );
}
return this.createChannel( name, data, index ?? prevIndex );
}
/**
* Remove a channel.
* @param name Name of channel
*/
public removeChannel( name: string ): void {
const channel = this.mapNameToChannel.get( name );
if ( channel ) {
this.channels.splice( this.channels.indexOf( channel ), 1 );
this.mapNameToChannel.delete( name );
this.__emit( 'removeChannel', { name } );
this.shouldSave = true;
}
}
/**
* Get a channel.
* @param name Name of the channel
* @returns The channel
*/
public getChannel( name: string ): ChannelWithGUI | null {
return this.mapNameToChannel.get( name ) ?? null;
}
/**
* Get a channel.
* If the channel doesn't exist, create immediately.
* @param name Name of the channel
* @returns The channel
*/
public getOrCreateChannel( name: string ): ChannelWithGUI {
let channel = this.getChannel( name );
if ( !channel ) { channel = this.createChannel( name ); }
return channel;
}
/**
* Get the index of a channel.
* @param name Name of the channel
* @returns The index of the channel
*/
public getChannelIndex( name: string ): number {
const channel = this.mapNameToChannel.get( name );
if ( !channel ) {
throw new Error( `getChannelIndex: A channel called ${ name } is not defined!` );
}
const index = this.channels.indexOf( channel );
return index;
}
/**
* Reorder channels.
* @param name Name of the channel
* @param isRelative Will interpret given index relatively if it's `true`
* @returns A function to reorder channels. Give a new index
*/
public reorderChannels(
name: string,
isRelative = false
): ( index: number ) => ChannelWithGUI[] {
const index0 = this.getChannelIndex( name );
return reorderArray(
this.channels,
index0,
1,
( { index, length, newIndex } ) => {
if ( isRelative ) {
newIndex += index0;
}
this.__emit( 'reorderChannels', { index, length, newIndex } );
return newIndex;
}
);
}
/**
* Create a new curve.
* @returns Created channel
*/
public createCurve( data?: SerializedCurve & Partial<WithID> ): CurveWithGUI {
const curve = new CurveWithGUI( this, data );
this.curves.push( curve );
this.__emit( 'createCurve', { id: curve.$id, curve } );
this.shouldSave = true;
return curve;
}
/**
* Remove a curve.
* @param index Index of the curve
*/
public removeCurve( curveId: string ): void {
const index = this.curves.findIndex( ( curve ) => curve.$id === curveId );
if ( index === -1 ) { return; }
const curve = this.curves[ index ];
if ( curve.isUsed ) {
const error = new Error( 'removeCurve: The curve is still used in somewhere!' );
error.name = 'CurveUsedError';
throw error;
}
const id = curve.$id;
this.curves.splice( index, 1 );
this.__emit( 'removeCurve', { id } );
this.shouldSave = true;
}
/**
* Get a curve.
* @param index Index of the curve
* @returns The curve
*/
public getCurve( index: number ): CurveWithGUI | null {
return this.curves[ index ] || null;
}
/**
* Get a curve by id.
* @param id Id of the curve
* @returns The curve
*/
public getCurveById( id: string ): CurveWithGUI {
const index = this.getCurveIndexById( id );
return this.curves[ index ];
}
/**
* Search for a curve that has given id then return index of it.
* If it couldn't find the curve, it will throw an error instead.
* @param id Id of the curve you want to grab
* @returns The index of the curve
*/
public getCurveIndexById( id: string ): number {
const index = this.curves.findIndex( ( curve ) => curve.$id === id );
if ( index === -1 ) { throw new Error( `Searched for item id: ${id} but not found` ); }
return index;
}
/**
* Return list of id of fx definitions. Sorted.
* @returns List of id of fx definitions
*/
public getFxDefinitionIds(): string[] {
return Object.keys( this.__fxDefinitions ).sort();
}
/**
* Return display name of a fx definition.
* If it can't find the fx definition, it returns `null` instead.
* @param id Id of the fx definition you want to grab
* @returns Name of the fx definition
*/
public getFxDefinitionName( id: string ): string | null {
if ( this.__fxDefinitions[ id ] ) {
return this.__fxDefinitions[ id ].name || id;
} else {
return null;
}
}
/**
* Return description of a fx definition.
* If it can't find the fx definition, it returns `null` instead.
* @param id Id of the fx definition you want to grab
* @returns Description of the fx definition
*/
public getFxDefinitionDescription( id: string ): string | null {
if ( this.__fxDefinitions[ id ] ) {
return this.__fxDefinitions[ id ].description || '';
} else {
return null;
}
}
/**
* Return params section of a fx definition.
* If it can't find the fx definition, it returns `null` instead.
* @param id Id of the fx definition you want to grab
* @returns Params section
*/
public getFxDefinitionParams( id: string ): { [ key: string ]: FxParam } | null {
if ( this.__fxDefinitions[ id ] ) {
return jsonCopy( this.__fxDefinitions[ id ].params || {} );
} else {
return null;
}
}
/**
* Return count of channels.
* @returns Count of channels
*/
public countChannels(): number {
return Object.keys( this.channels ).length;
}
/**
* Return the index of a given curve.
* return `-1` if it couldn't find the curve.
* @param curve A curve you want to look up its index
* @returns the index of the curve
*/
public getCurveIndex( curve: CurveWithGUI ): number {
return this.curves.indexOf( curve );
}
/**
* Set a label.
* @param name Name of the label
* @param time Timepoint of the label
*/
public setLabel( name: string, time: number ): void {
const actualTime = Math.max( 0.0, time );
this.__labels[ name ] = actualTime;
this.__emit( 'setLabel', { name, time: actualTime } );
}
/**
* Remove a label.
* @param name Name of the label
*/
public deleteLabel( name: string ): void {
delete this.__labels[ name ];
this.__emit( 'deleteLabel', { name } );
}
/**
* Load automaton state data.
* You might want to use {@link compat} beforehand to upgrade data made in previous versions.
* @param data Object contains automaton data.
*/
public deserialize( data: SerializedAutomatonWithGUI ): void {
this.__resolution = data.resolution;
this.curves.splice( 0 );
this.curves.push(
...data.curves.map(
( curve ) => new CurveWithGUI( this, curve )
),
);
this.mapNameToChannel.clear();
this.channels.splice( 0 );
this.channels.push(
...data.channels.map( ( [ name, channelData ] ) => {
const channel = new ChannelWithGUI( this, channelData );
this.mapNameToChannel.set( name, channel );
// if `options.disableChannelNotUsedWarning` is true, mark every channels as used
if ( this.__isDisabledChannelNotUsedWarning ) {
channel.markAsUsed();
}
channel.on( 'changeLength', () => {
this.__tryUpdateLength();
} );
return channel;
} )
);
this.__labels = data.labels ?? {};
this.__guiSettings = {
...defaultGUISettings,
...data.guiSettings
};
this.__emit( 'load' );
this.shouldSave = false;
}
/**
* Serialize its current state.
* @returns Serialized state
*/
public serialize(): SerializedAutomatonWithGUI {
return {
version: this.version,
resolution: this.resolution,
curves: this.__serializeCurves(),
channels: this.__serializeChannels(),
labels: this.__labels,
guiSettings: this.__guiSettings,
};
}
/**
* Set a property of gui settings.
* @param key The parameter key you want to set
* @param value The parameter value you want to set
*/
public setGUISettings<T extends keyof GUISettings>( key: T, value: GUISettings[ T ] ): void {
this.__guiSettings = produce( this.__guiSettings, ( newState ) => { // 🔥 Why????
newState[ key ] = value;
} );
this.__emit( 'updateGUISettings', { settings: this.__guiSettings } );
this.shouldSave = true;
}
/**
* Mount a GUI to specified DOM.
*/
public mountGUI( target: HTMLElement ): void {
if ( this.__parentNode ) {
throw Error( 'Automaton.mountGUI: GUI is already mounted!' );
}
this.__guiRemocon = new GUIRemocon();
const store = createStore();
ReactDOM.render(
<App
store={ store }
automaton={ this }
guiRemocon={ this.__guiRemocon! }
/>,
target
);
this.__parentNode = target;
}
/**
* Unmount a GUI.
*/
public unmountGUI(): void {
if ( !this.__parentNode ) {
throw Error( 'Automaton.unmountGUI: GUI is not mounted!' );
}
ReactDOM.unmountComponentAtNode( this.__parentNode );
this.__guiRemocon = null;
this.__parentNode = null;
}
/**
* Set a loop region.
*/
public setLoopRegion( loopRegion: { begin: number; end: number } | null ): void {
this.__loopRegion = loopRegion;
this.__emit( 'setLoopRegion', { loopRegion } );
}
/**
* Undo a step.
* Intended to be used by automaton-electron.
* You cannot call this function when you are not using GUI.
*/
public undo(): void {
if ( !this.__guiRemocon ) {
throw new Error( 'Automaton: You cannot call `undo` when you are not using GUI!' );
}
this.__guiRemocon.undo();
}
/**
* Redo a step.
* Intended to be used by automaton-electron.
* You cannot call this function when you are not using GUI.
*/
public redo(): void {
if ( !this.__guiRemocon ) {
throw new Error( 'Automaton: You cannot call `redo` when you are not using GUI!' );
}
this.__guiRemocon.redo();
}
/**
* Open an about screen.
* Intended to be used by automaton-electron.
* You cannot call this function when you are not using GUI.
*/
public openAbout(): void {
if ( !this.__guiRemocon ) {
throw new Error( 'Automaton: You cannot call `openAbout` when you are not using GUI!' );
}
this.__guiRemocon.openAbout();
}
/**
* Open a toasty notification.
* Intended to be used by automaton-electron.
* You cannot call this function when you are not using GUI.
*/
public toasty( params: ToastyParams ): void {
if ( !this.__guiRemocon ) {
throw new Error( 'Automaton: You cannot call `toasty` when you are not using GUI!' );
}
this.__guiRemocon.toasty( params );
}
private __serializeCurves(): SerializedCurve[] {
return this.curves.map( ( curve ) => curve.serialize() );
}
private __serializeChannels(): [ name: string, channel: SerializedChannel ][] {
return this.channels.map( ( channel ) => [
this.mapNameToChannel.getFromValue( channel )!,
channel.serialize(),
] );
}
private __tryUpdateLength(): void {
const length = this.length;
if ( length !== this.__lengthPrev ) {
this.__emit( 'changeLength', { length } );
this.__lengthPrev = length;
}
}
/**
* Assigned to `Automaton.auto` at constructor.
* @param name The name of the channel
* @param listener A function that will be executed when the channel changes its value
* @returns Current value of the channel
*/
protected __auto(
name: string,
listener?: ( event: ChannelUpdateEvent ) => void
): number {
const channel = this.getOrCreateChannel( name );
if ( listener ) {
channel.subscribe( listener );
}
channel.markAsUsed();
return channel.currentValue;
}
}
export interface AutomatonWithGUIEvents {
play: void;
pause: void;
seek: { time: number };
load: void;
update: { time: number };
createChannel: { name: string; channel: ChannelWithGUI; index: number };
removeChannel: { name: string };
reorderChannels: { index: number; length: number; newIndex: number };
createCurve: { id: string; curve: CurveWithGUI };
removeCurve: { id: string };
addFxDefinitions: { fxDefinitions: { [ id: string ]: FxDefinition } };
setLabel: { name: string; time: number };
deleteLabel: { name: string };
changeLength: { length: number };
changeResolution: { resolution: number };
updateGUISettings: { settings: GUISettings };
changeShouldSave: { shouldSave: boolean };
setLoopRegion: { loopRegion: { begin: number; end: number } | null };
}
applyMixins( AutomatonWithGUI, [ EventEmittable ] ); | the_stack |
import assert from "assert";
import http from "http";
import https from "https";
import { Transform, Writable } from "stream";
import { ReadableStream } from "stream/web";
import { URL } from "url";
import zlib from "zlib";
import {
CorePluginSignatures,
IncomingRequestCfProperties,
MiniflareCore,
Request,
Response,
_getBodyLength,
_headersFromIncomingRequest,
logResponse,
} from "@miniflare/core";
import { prefixError, randomHex } from "@miniflare/shared";
import { coupleWebSocket } from "@miniflare/web-sockets";
import { BodyInit, Headers } from "undici";
import { getAccessibleHosts } from "./helpers";
import { HTTPPlugin, RequestMeta } from "./plugin";
export * from "./helpers";
export * from "./plugin";
export const DEFAULT_PORT = 8787;
export type HTTPPluginSignatures = CorePluginSignatures & {
HTTPPlugin: typeof HTTPPlugin;
};
const liveReloadScript = `<script defer type="application/javascript">
(function () {
// Miniflare Live Reload
var url = new URL("/cdn-cgi/mf/reload", location.origin);
url.protocol = url.protocol.replace("http", "ws");
function reload() { location.reload(); }
function connect(reconnected) {
var ws = new WebSocket(url);
if (reconnected) ws.onopen = reload;
ws.onclose = function(e) {
e.code === 1012 ? reload() : e.code === 1000 || e.code === 1001 || setTimeout(connect, 1000, true);
}
}
connect();
})();
</script>`;
const liveReloadScriptLength = Buffer.byteLength(liveReloadScript);
export async function convertNodeRequest(
req: http.IncomingMessage,
meta?: RequestMeta
): Promise<{ request: Request; url: URL }> {
// @ts-expect-error encrypted is only defined in tls.TLSSocket
const protocol = req.socket.encrypted ? "https" : "http";
const origin = `${protocol}://${req.headers.host ?? "localhost"}`;
const url = new URL(req.url ?? "", origin);
let body: BodyInit | null = null;
if (req.method !== "GET" && req.method !== "HEAD") {
// Adapted from https://github.com/nodejs/undici/blob/ebea0f7084bb1efdb66c46409d1bfc87054b2870/lib/core/util.js#L269-L304
// to create a byte stream instead of a regular one. This means we don't
// create another "byte-TransformStream" later on to allow byob reads.
let iterator: AsyncIterableIterator<any>;
body = new ReadableStream({
type: "bytes",
start() {
iterator = req[Symbol.asyncIterator]();
},
async pull(controller) {
const { done, value } = await iterator.next();
if (done) {
queueMicrotask(() => {
controller.close();
// Not documented in MDN but if there's an ongoing request that's waiting,
// we need to tell it that there was 0 bytes delivered so that it unblocks
// and notices the end of stream.
controller.byobRequest?.respond(0);
});
} else {
const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value);
controller.enqueue(new Uint8Array(buffer));
}
},
async cancel() {
await iterator.return?.();
},
});
}
// Add additional Cloudflare specific headers:
// https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-
const proto = meta?.forwardedProto ?? "https";
let ip = meta?.realIp ?? req.socket.remoteAddress ?? "";
// Convert IPv6 loopback address to IPv4 address
if (ip === "::1") ip = "127.0.0.1";
// Remove IPv6 prefix for IPv4 addresses
if (ip.startsWith("::ffff:")) ip = ip.substring("::ffff:".length);
// We're a bit naughty here mutating the incoming request, but this ensures
// the headers are included in the pretty-error page. If we used the new
// converted Request instance's headers, we wouldn't have connection, keep-
// alive, etc as we strip those. We need to take ownership of the request
// anyway though, since we're consuming its body.
req.headers["x-forwarded-proto"] ??= proto;
req.headers["x-real-ip"] ??= ip;
req.headers["cf-connecting-ip"] ??= ip;
req.headers["cf-ipcountry"] ??= meta?.cf?.country ?? "US";
req.headers["cf-ray"] ??= randomHex(16);
req.headers["cf-visitor"] ??= `{"scheme":"${proto}"}`;
req.headers["host"] = url.host;
// Keep it to use later
const clientAcceptEncoding = req.headers["accept-encoding"];
// This should be fixed
req.headers["accept-encoding"] = "gzip";
// Build Headers object from request
const headers = _headersFromIncomingRequest(req);
// Create Request with additional Cloudflare specific properties:
// https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
const request = new Request(url, {
method: req.method,
headers,
body,
cf: {
...meta?.cf,
clientAcceptEncoding,
} as IncomingRequestCfProperties,
// Incoming requests always have their redirect mode set to manual:
// https://developers.cloudflare.com/workers/runtime-apis/request#requestinit
redirect: "manual",
});
return { request, url };
}
export type RequestListener = (
req: http.IncomingMessage,
res?: http.ServerResponse
) => Promise<Response | undefined>;
export function createRequestListener<Plugins extends HTTPPluginSignatures>(
mf: MiniflareCore<Plugins>
): RequestListener {
return async (req, res) => {
const { HTTPPlugin } = await mf.getPlugins();
const start = process.hrtime();
const { request, url } = await convertNodeRequest(
req,
await HTTPPlugin.getRequestMeta(req)
);
let response: Response | undefined;
let waitUntil: Promise<unknown[]> | undefined;
let status = 500;
// Check if path matches /cdn-cgi/* ignoring trailing slash. These paths
// can't be handled by workers and are used for utility interfaces.
const pathname = url.pathname.replace(/\/$/, "");
if (pathname.startsWith("/cdn-cgi/")) {
// TODO (someday): consider adding other utility interfaces for KV, DO, etc
// (maybe add another Plugin field/method/decorator for contributes)
if (pathname === "/cdn-cgi/mf/scheduled") {
req.method = "SCHD";
const time = url.searchParams.get("time");
const cron = url.searchParams.get("cron");
waitUntil = mf.dispatchScheduled(
time ? parseInt(time) : undefined,
cron ?? undefined,
url
);
status = 200;
} else {
status = 404;
}
res?.writeHead(status, { "Content-Type": "text/plain; charset=UTF-8" });
res?.end();
} else {
try {
response = await mf.dispatchFetch(request);
waitUntil = response.waitUntil();
status = response.status;
const headers: http.OutgoingHttpHeaders = {};
// eslint-disable-next-line prefer-const
for (let [key, value] of response.headers) {
key = key.toLowerCase();
if (key === "set-cookie") {
// Multiple Set-Cookie headers should be treated as separate headers
// @ts-expect-error getAll is added to the Headers prototype by
// importing @miniflare/core
headers["set-cookie"] = response.headers.getAll("set-cookie");
} else {
headers[key] = value;
}
}
// Use body's actual length instead of the Content-Length header if set,
// see https://github.com/cloudflare/miniflare/issues/148. We also might
// need to adjust this later for live reloading so hold onto it.
const contentLengthHeader = response.headers.get("Content-Length");
const contentLength =
_getBodyLength(response) ??
(contentLengthHeader === null ? null : parseInt(contentLengthHeader));
if (contentLength !== null) headers["content-length"] = contentLength;
// If a Content-Encoding is set, and the user hasn't encoded the body,
// we're responsible for doing so.
const encoders: Transform[] = [];
if (headers["content-encoding"] && response.encodeBody === "auto") {
// Content-Length will be wrong as it's for the decoded length
delete headers["content-length"];
// Reverse of https://github.com/nodejs/undici/blob/48d9578f431cbbd6e74f77455ba92184f57096cf/lib/fetch/index.js#L1660
const codings = headers["content-encoding"]
.toString()
.toLowerCase()
.split(",")
.map((x) => x.trim());
for (const coding of codings) {
if (/(x-)?gzip/.test(coding)) {
encoders.push(zlib.createGzip());
} else if (/(x-)?deflate/.test(coding)) {
encoders.push(zlib.createDeflate());
} else if (coding === "br") {
encoders.push(zlib.createBrotliCompress());
} else {
// Unknown encoding, don't do any encoding at all
mf.log.warn(
`Unknown encoding \"${coding}\", sending plain response...`
);
delete headers["content-encoding"];
encoders.length = 0;
break;
}
}
}
// Add live reload script if enabled, this isn't an already encoded
// response, and it's HTML
const liveReloadEnabled =
HTTPPlugin.liveReload &&
response.encodeBody === "auto" &&
response.headers
.get("content-type")
?.toLowerCase()
.includes("text/html");
// If Content-Length is specified, and we're live-reloading, we'll
// need to adjust it to make room for the live reload script
if (liveReloadEnabled && contentLength !== null) {
if (!isNaN(contentLength)) {
// Append length of live reload script
headers["content-length"] = contentLength + liveReloadScriptLength;
}
}
res?.writeHead(status, headers);
// Response body may be null if empty
if (res) {
// `initialStream` is the stream we'll write the response to. It
// should end up as the first encoder, piping to the next encoder,
// and finally piping to the response:
//
// encoders[0] (initialStream) -> encoders[1] -> res
//
// Not using `pipeline(passThrough, ...encoders, res)` here as that
// gives a premature close error with server sent events. This also
// avoids creating an extra stream even when we're not encoding.
let initialStream: Writable = res;
for (let i = encoders.length - 1; i >= 0; i--) {
encoders[i].pipe(initialStream);
initialStream = encoders[i];
}
if (response.body) {
for await (const chunk of response.body) {
if (chunk) initialStream.write(chunk);
}
if (liveReloadEnabled) {
initialStream.write(liveReloadScript);
}
}
initialStream.end();
}
} catch (e: any) {
// MIME types aren't case sensitive
const accept = req.headers.accept?.toLowerCase() ?? "";
const userAgent = req.headers["user-agent"]?.toLowerCase() ?? "";
if (
!userAgent.includes("curl/") &&
(accept.includes("text/html") ||
accept.includes("*/*") ||
accept.includes("text/*"))
) {
// Send pretty HTML error page if client accepts it
const Youch: typeof import("youch").default = require("youch");
const youch = new Youch(e, req);
youch.addLink(() => {
const links = [
'<a href="https://developers.cloudflare.com/workers/" target="_blank" style="text-decoration:none">📚 Workers Docs</a>',
'<a href="https://discord.gg/cloudflaredev" target="_blank" style="text-decoration:none">💬 Workers Discord</a>',
'<a href="https://miniflare.dev" target="_blank" style="text-decoration:none">🔥 Miniflare Docs</a>',
];
// Live reload is basically a link right?
if (HTTPPlugin.liveReload) links.push(liveReloadScript);
return links.join("");
});
const errorHtml = await youch.toHTML();
res?.writeHead(500, { "Content-Type": "text/html; charset=UTF-8" });
res?.end(errorHtml, "utf8");
} else {
// Otherwise, send plaintext stack trace
res?.writeHead(500, { "Content-Type": "text/plain; charset=UTF-8" });
res?.end(e.stack, "utf8");
}
// Add method and URL to stack trace
mf.log.error(prefixError(`${req.method} ${req.url}`, e));
}
}
assert(req.method && req.url);
await logResponse(mf.log, {
start,
method: req.method,
url: req.url,
status,
waitUntil,
});
return response;
};
}
const restrictedWebSocketUpgradeHeaders = [
"upgrade",
"connection",
"sec-websocket-accept",
];
export async function createServer<Plugins extends HTTPPluginSignatures>(
mf: MiniflareCore<Plugins>,
options?: http.ServerOptions & https.ServerOptions
): Promise<http.Server | https.Server> {
const plugins = await mf.getPlugins();
const listener = createRequestListener(mf);
// Setup HTTP server
let server: http.Server | https.Server;
if (plugins.HTTPPlugin.httpsEnabled) {
const httpsOptions = plugins.HTTPPlugin.httpsOptions;
assert(httpsOptions);
server = https.createServer({ ...httpsOptions, ...options }, listener);
} else {
server = http.createServer(options ?? {}, listener);
}
const { WebSocketServer }: typeof import("ws") = require("ws");
// Setup WebSocket servers
const webSocketServer = new WebSocketServer({ noServer: true });
const liveReloadServer = new WebSocketServer({ noServer: true });
// Add custom headers included in response to WebSocket upgrade requests
const extraHeaders = new WeakMap<http.IncomingMessage, Headers>();
webSocketServer.on("headers", (headers, req) => {
const extra = extraHeaders.get(req);
extraHeaders.delete(req);
if (extra) {
for (const [key, value] of extra) {
if (!restrictedWebSocketUpgradeHeaders.includes(key.toLowerCase())) {
headers.push(`${key}: ${value}`);
}
}
}
});
server.on("upgrade", async (request, socket, head) => {
// Only interested in pathname so base URL doesn't matter
const { pathname } = new URL(request.url ?? "", "http://localhost");
if (pathname === "/cdn-cgi/mf/reload") {
// If this is the for live-reload, handle the request ourselves
liveReloadServer.handleUpgrade(request, socket as any, head, (ws) => {
liveReloadServer.emit("connection", ws, request);
});
} else {
// Otherwise, handle the request in the worker
const response = await listener(request);
// Check web socket response was returned
const webSocket = response?.webSocket;
if (response?.status !== 101 || !webSocket) {
socket.write("HTTP/1.1 500 Internal Server Error\r\n\r\n");
socket.destroy();
mf.log.error(
new TypeError(
"Web Socket request did not return status 101 Switching Protocols response with Web Socket"
)
);
return;
}
// Accept and couple the Web Socket
extraHeaders.set(request, response.headers);
webSocketServer.handleUpgrade(request, socket as any, head, (ws) => {
void coupleWebSocket(ws, webSocket);
webSocketServer.emit("connection", ws, request);
});
}
});
const reloadListener = () => {
// Reload all connected live reload clients
for (const ws of liveReloadServer.clients) {
ws.close(1012, "Service Restart");
}
// Close all existing web sockets on reload
for (const ws of webSocketServer.clients) {
ws.close(1012, "Service Restart");
}
};
mf.addEventListener("reload", reloadListener);
server.on("close", () => mf.removeEventListener("reload", reloadListener));
return server;
}
export async function startServer<Plugins extends HTTPPluginSignatures>(
mf: MiniflareCore<Plugins>,
options?: http.ServerOptions & https.ServerOptions
): Promise<http.Server | https.Server> {
const server = await createServer(mf, options);
const plugins = await mf.getPlugins();
const { httpsEnabled, host, port = DEFAULT_PORT } = plugins.HTTPPlugin;
return new Promise((resolve) => {
server.listen(port, host, () => {
const log = mf.log;
const protocol = httpsEnabled ? "https" : "http";
const accessibleHosts = host ? [host] : getAccessibleHosts(true);
log.info(`Listening on ${host ?? ""}:${port}`);
for (const accessibleHost of accessibleHosts) {
log.info(`- ${protocol}://${accessibleHost}:${port}`);
}
resolve(server);
});
});
} | the_stack |
import { expect } from "chai";
import { BeDuration } from "@itwin/core-bentley";
import { Range3d, Transform } from "@itwin/core-geometry";
import { ServerTimeoutError } from "@itwin/core-common";
import { IModelConnection } from "../../IModelConnection";
import { IModelApp } from "../../IModelApp";
import { Viewport } from "../../Viewport";
import { MockRender } from "../../render/MockRender";
import { createBlankConnection } from "../createBlankConnection";
import {
Tile, TileContent, TileLoadPriority, TileLoadStatus, TileRequest, TileRequestChannel, TileRequestChannelStatistics, TileTree,
} from "../../tile/internal";
async function runMicroTasks(): Promise<void> {
return BeDuration.wait(1);
}
class TestTile extends Tile {
public priority;
public requestChannel: LoggingChannel;
public requestContentCalled = false;
public readContentCalled = false;
private _resolveRequest?: (response: TileRequest.Response) => void;
private _rejectRequest?: (error: Error) => void;
private _resolveRead?: (content: TileContent) => void;
private _rejectRead?: (error: Error) => void;
public empty?: boolean;
public displayable?: boolean;
public constructor(tree: TestTree, channel: LoggingChannel, priority = 0) {
super({
contentId: priority.toString(),
range: new Range3d(0, 0, 0, 1, 1, 1),
maximumSize: 42,
}, tree);
this.requestChannel = channel;
this.priority = priority;
}
public expectStatus(expected: TileLoadStatus) {
expect(this.loadStatus).to.equal(expected);
}
public get awaitingRequest() {
return undefined !== this._resolveRequest;
}
public get awaitingRead() {
return undefined !== this._resolveRead;
}
public get isActive() {
return this.channel.isActive(this);
}
public override get isDisplayable(): boolean {
return this.displayable ?? super.isDisplayable;
}
public override get isEmpty(): boolean {
return this.empty ?? super.isEmpty;
}
protected _loadChildren(resolve: (children: Tile[] | undefined) => void): void {
resolve(undefined);
}
public get channel() {
return this.requestChannel;
}
public override computeLoadPriority() {
return this.priority;
}
public async requestContent(): Promise<TileRequest.Response> {
this.requestContentCalled = true;
expect(this._resolveRequest).to.be.undefined;
expect(this._rejectRequest).to.be.undefined;
return new Promise((resolve, reject) => {
this._resolveRequest = resolve;
this._rejectRequest = reject;
});
}
public async readContent(): Promise<TileContent> {
this.readContentCalled = true;
expect(this._resolveRead).to.be.undefined;
expect(this._rejectRead).to.be.undefined;
return new Promise((resolve, reject) => {
this._resolveRead = resolve;
this._rejectRead = reject;
});
}
public resolveRequest(response: TileRequest.Response | "undefined" = new Uint8Array(1)): void {
if ("undefined" === response)
response = undefined; // passing `undefined` to resolveRequest uses the default arg instead...
expect(this._resolveRequest).not.to.be.undefined;
this._resolveRequest!(response);
this.clearPromises();
}
public rejectRequest(error: Error = new Error("requestContent")): void {
expect(this._rejectRequest).not.to.be.undefined;
this._rejectRequest!(error);
this.clearPromises();
}
public resolveRead(content: TileContent = {}): void {
expect(this._resolveRead).not.to.be.undefined;
this._resolveRead!(content);
this.clearPromises();
}
public async resolveBoth(): Promise<void> {
this.resolveRequest();
await runMicroTasks();
this.resolveRead();
await runMicroTasks();
}
public rejectRead(error: Error = new Error("readContent")): void {
expect(this._rejectRead).not.to.be.undefined;
this._rejectRead!(error);
this.clearPromises();
}
private clearPromises(): void {
this._resolveRequest = undefined;
this._rejectRequest = undefined;
this._resolveRead = undefined;
this._rejectRead = undefined;
}
}
class TestTree extends TileTree {
private readonly _rootTile: TestTile;
public constructor(iModel: IModelConnection, channel: LoggingChannel, priority = TileLoadPriority.Primary) {
super({
iModel,
id: "test",
modelId: "0",
location: Transform.createIdentity(),
priority,
});
this._rootTile = new TestTile(this, channel);
}
public get rootTile(): TestTile { return this._rootTile; }
public get is3d() { return true; }
public get maxDepth() { return undefined; }
public get viewFlagOverrides() { return {}; }
protected _selectTiles(): Tile[] { return []; }
public draw() { }
public prune() { }
}
function mockViewport(iModel: IModelConnection, viewportId = 1): Viewport {
return {
viewportId,
iModel,
invalidateScene: () => { },
} as Viewport;
}
function requestTiles(vp: Viewport, tiles: TestTile[]): void {
IModelApp.tileAdmin.clearTilesForViewport(vp);
IModelApp.tileAdmin.clearUsageForViewport(vp);
IModelApp.tileAdmin.requestTiles(vp, new Set<Tile>(tiles));
}
async function processOnce(): Promise<void> {
IModelApp.tileAdmin.process();
return runMicroTasks();
}
class LoggingChannel extends TileRequestChannel {
public readonly calledFunctions: string[] = [];
public constructor(maxActive: number, name = "test") {
super(name, maxActive);
IModelApp.tileAdmin.channels.add(this);
}
protected log(functionName: string) {
this.calledFunctions.push(functionName);
}
public clear() {
this.calledFunctions.length = 0;
}
public expect(functionNames: string[]) {
expect(this.calledFunctions).to.deep.equal(functionNames);
}
public expectRequests(active: number, pending: number) {
expect(this.numActive).to.equal(active);
expect(this.numPending).to.equal(pending);
}
public get active(): Set<TileRequest> {
return this._active;
}
public isActive(tile: Tile): boolean {
for (const active of this.active)
if (active.tile === tile)
return true;
return false;
}
public override recordCompletion(tile: Tile, content: TileContent): void {
this.log("recordCompletion");
super.recordCompletion(tile, content);
}
public override recordTimeout() {
this.log("recordTimeout");
super.recordTimeout();
}
public override recordFailure() {
this.log("recordFailure");
super.recordFailure();
}
public override swapPending() {
this.log("swapPending");
super.swapPending();
}
public override append(request: TileRequest) {
this.log("append");
super.append(request);
}
public override process() {
this.log("process");
super.process();
}
protected override dispatch(request: TileRequest) {
this.log("dispatch");
super.dispatch(request);
}
public override cancelAndClearAll() {
this.log("cancelAndClearAll");
super.cancelAndClearAll();
}
public override onNoContent(request: TileRequest): boolean {
this.log("onNoContent");
return super.onNoContent(request);
}
public override onActiveRequestCanceled(request: TileRequest): void {
this.log("onActiveRequestCanceled");
super.onActiveRequestCanceled(request);
}
public override onIModelClosed(iModel: IModelConnection) {
this.log("onIModelClosed");
super.onIModelClosed(iModel);
}
protected override dropActiveRequest(request: TileRequest) {
this.log("dropActiveRequest");
super.dropActiveRequest(request);
}
protected override cancel(request: TileRequest) {
this.log("cancel");
super.cancel(request);
}
public override async requestContent(tile: Tile, isCanceled: () => boolean): Promise<TileRequest.Response> {
this.log("requestContent");
return super.requestContent(tile, isCanceled);
}
public override processCancellations() {
this.log("processCancellations");
super.processCancellations();
}
}
describe("TileRequestChannel", () => {
let imodel: IModelConnection;
beforeEach(async () => {
await MockRender.App.startup();
imodel = createBlankConnection();
});
afterEach(async () => {
await imodel.close();
if (IModelApp.initialized)
await MockRender.App.shutdown();
});
it("completes one request", async () => {
const channel = new LoggingChannel(1);
const tree = new TestTree(imodel, channel);
const vp = mockViewport(imodel);
tree.rootTile.expectStatus(TileLoadStatus.NotLoaded);
channel.expectRequests(0, 0);
requestTiles(vp, [tree.rootTile]);
tree.rootTile.expectStatus(TileLoadStatus.NotLoaded);
channel.expectRequests(0, 0);
channel.expect([]);
IModelApp.tileAdmin.process();
tree.rootTile.expectStatus(TileLoadStatus.Queued);
channel.expect(["swapPending", "append", "process", "processCancellations", "dispatch", "requestContent"]);
channel.expectRequests(1, 0);
channel.clear();
tree.rootTile.resolveRequest();
await processOnce();
channel.expect(["swapPending", "process", "processCancellations", "dropActiveRequest"]);
channel.expectRequests(0, 0);
tree.rootTile.expectStatus(TileLoadStatus.Loading);
channel.clear();
tree.rootTile.resolveRead();
await processOnce();
channel.expect(["swapPending", "process", "processCancellations", "recordCompletion"]);
channel.expectRequests(0, 0);
tree.rootTile.expectStatus(TileLoadStatus.Ready);
});
it("observes limits on max active requests", async () => {
const channel = new LoggingChannel(2);
const tree = new TestTree(imodel, channel);
const tiles = [0, 1, 2, 3, 4].map((x) => new TestTile(tree, channel, x));
const vp = mockViewport(imodel);
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
tiles.forEach((x) => x.expectStatus(TileLoadStatus.Queued));
channel.expectRequests(2, 3);
tiles[0].resolveRequest();
await processOnce();
tiles.forEach((x) => x.expectStatus(x === tiles[0] ? TileLoadStatus.Loading : TileLoadStatus.Queued));
channel.expectRequests(1, 3);
tiles[0].resolveRead();
await processOnce();
tiles.forEach((x) => x.expectStatus(x === tiles[0] ? TileLoadStatus.Ready : TileLoadStatus.Queued));
channel.expectRequests(2, 2);
tiles[1].rejectRequest();
await processOnce();
tiles[1].expectStatus(TileLoadStatus.NotFound);
tiles.slice(2).forEach((x) => x.expectStatus(TileLoadStatus.Queued));
channel.expectRequests(1, 2);
tiles.push(new TestTile(tree, channel, 5));
requestTiles(vp, tiles);
await processOnce();
channel.expectRequests(2, 2);
tiles[2].resolveRequest();
tiles[3].resolveRequest();
await processOnce();
channel.expectRequests(0, 2);
tiles.slice(2, 4).forEach((x) => x.expectStatus(TileLoadStatus.Loading));
tiles.slice(4).forEach((x) => x.expectStatus(TileLoadStatus.Queued));
tiles[2].resolveRead();
tiles[3].resolveRead();
await processOnce();
channel.expectRequests(2, 0);
tiles.slice(2, 4).forEach((x) => x.expectStatus(TileLoadStatus.Ready));
tiles.slice(4).forEach((x) => x.expectStatus(TileLoadStatus.Queued));
tiles[4].rejectRequest();
tiles[5].rejectRequest();
await processOnce();
channel.expectRequests(0, 0);
tiles.slice(4).forEach((x) => x.expectStatus(TileLoadStatus.NotFound));
});
it("dispatches requests in order by priority", async () => {
const channel = new LoggingChannel(1);
const tr0 = new TestTree(imodel, channel, TileLoadPriority.Dynamic);
const tr1 = new TestTree(imodel, channel, TileLoadPriority.Terrain);
const t00 = new TestTile(tr0, channel, 0);
const t04 = new TestTile(tr0, channel, 4);
const t10 = new TestTile(tr1, channel, 0);
const t14 = new TestTile(tr1, channel, 4);
const vp = mockViewport(imodel);
requestTiles(vp, [t10, t04, t00, t14]);
async function waitFor(tile: TestTile) {
await processOnce();
expect(channel.numActive).to.equal(1);
expect(tile.isActive).to.be.true;
tile.expectStatus(TileLoadStatus.Queued);
tile.resolveRequest();
await processOnce();
tile.expectStatus(TileLoadStatus.Loading);
tile.resolveRead();
await processOnce();
tile.expectStatus(TileLoadStatus.Ready);
}
await processOnce();
channel.expectRequests(1, 3);
await waitFor(t00);
channel.expectRequests(1, 2);
await waitFor(t04);
channel.expectRequests(1, 1);
await waitFor(t10);
// t14 is now the actively-loading tile. Enqueue some additional ones. The priorities only apply to the queue, not the active set.
channel.expectRequests(1, 0);
expect(t14.isActive).to.be.true;
const t15 = new TestTile(tr1, channel, 5);
const t03 = new TestTile(tr0, channel, 3);
const t12 = new TestTile(tr1, channel, 2);
requestTiles(vp, [t14, t15, t03, t12]);
await processOnce();
channel.expectRequests(1, 3);
await waitFor(t14);
channel.expectRequests(1, 2);
await waitFor(t03);
channel.expectRequests(1, 1);
await waitFor(t12);
channel.expectRequests(1, 0);
await waitFor(t15);
channel.expectRequests(0, 0);
});
it("cancels requests", async () => {
const channel = new LoggingChannel(1);
const tree = new TestTree(imodel, channel);
const tiles = [0, 1, 2, 3].map((x) => new TestTile(tree, channel, x));
const vp = mockViewport(imodel);
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 3);
expect(tiles[0].awaitingRequest).to.be.true;
// Cancel all of the requests
requestTiles(vp, []);
IModelApp.tileAdmin.process();
// Canceled active requests are not removed until the promise resolves or rejects.
channel.expectRequests(1, 0);
expect(tiles[0].awaitingRequest).to.be.true;
expect(tiles[0].isActive).to.be.true;
tiles[0].rejectRequest();
await processOnce();
expect(tiles[0].awaitingRead).to.be.false;
tiles[0].expectStatus(TileLoadStatus.NotFound);
tiles[0] = new TestTile(tree, channel, 0); // reset to an unloaded tile
channel.expectRequests(0, 0);
tiles.forEach((x) => x.expectStatus(TileLoadStatus.NotLoaded));
requestTiles(vp, tiles);
await processOnce();
expect(tiles[0].isActive).to.be.true;
requestTiles(vp, tiles.slice(1, 3));
tiles[0].rejectRequest();
await processOnce();
channel.expectRequests(0, 2);
tiles[0].expectStatus(TileLoadStatus.NotFound);
await processOnce();
channel.expectRequests(1, 1);
expect(tiles[1].isActive).to.be.true;
// Cancel all requests.
requestTiles(vp, []);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 0);
expect(tiles[1].isActive).to.be.true;
expect(tiles[1].awaitingRequest).to.be.true;
tiles[1].resolveRequest();
await processOnce();
channel.expectRequests(0, 0);
expect(tiles[1].awaitingRequest).to.be.false;
// If we've already received a response, we process it even if request was canceled.
expect(tiles[1].awaitingRead).to.be.true;
tiles[1].resolveRead();
await processOnce();
tiles[1].expectStatus(TileLoadStatus.Ready);
tiles.slice(2).forEach((x) => x.expectStatus(TileLoadStatus.NotLoaded));
});
it("changes max active requests", async () => {
const channel = new LoggingChannel(3);
const tree = new TestTree(imodel, channel);
const tiles = [0, 1, 2, 3, 4].map((x) => new TestTile(tree, channel, x));
const vp = mockViewport(imodel);
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
channel.expectRequests(3, 2);
channel.concurrency = 1;
await processOnce();
channel.expectRequests(3, 2);
tiles[0].rejectRequest();
await processOnce();
channel.expectRequests(2, 2);
tiles[1].resolveRequest();
await processOnce();
tiles[1].resolveRead();
await processOnce();
channel.expectRequests(1, 2);
tiles[2].rejectRequest();
await processOnce();
channel.expectRequests(0, 2);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 1);
tiles[3].rejectRequest();
await processOnce();
channel.expectRequests(0, 1);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 0);
const tile = new TestTile(tree, channel, 5);
requestTiles(vp, [tiles[4], tile]);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 1);
tiles[4].resolveRequest();
await processOnce();
tiles[4].resolveRead();
await processOnce();
channel.expectRequests(1, 0);
tile.rejectRequest();
await processOnce();
channel.expectRequests(0, 0);
});
// A canceled active request is not removed from the active set until its promise is settled.
// It is included in `statistics.numCanceled` for every call to `process` during which it is active and canceled.
// However, onActiveRequestCanceled is only called once - when the request is initially canceled.
it("calls onActiveRequestCanceled only once per cancellation", async () => {
class Channel extends LoggingChannel {
public numActiveCanceled = 0;
public numProcessed = 0;
public override onActiveRequestCanceled() {
++this.numActiveCanceled;
}
public override processCancellations() {
this.numProcessed += this.statistics.numCanceled;
}
}
const channel = new Channel(2);
const tree = new TestTree(imodel, channel);
const tile = tree.rootTile;
const tiles = [tile];
const vp = mockViewport(imodel);
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
expect(tile.isActive).to.be.true;
expect(channel.numActiveCanceled).to.equal(0);
expect(channel.numProcessed).to.equal(0);
expect(channel.statistics.numCanceled).to.equal(0);
for (let i = 1; i < 4; i++) {
requestTiles(vp, []);
IModelApp.tileAdmin.process();
expect(tile.isActive).to.be.true;
expect(channel.numActiveCanceled).to.equal(1);
expect(channel.statistics.numCanceled).to.equal(1);
expect(channel.numProcessed).to.equal(i);
}
await tile.resolveBoth();
IModelApp.tileAdmin.process();
expect(tile.isActive).to.be.false;
expect(channel.numActiveCanceled).to.equal(1);
expect(channel.statistics.numCanceled).to.equal(0);
tile.expectStatus(TileLoadStatus.Ready);
});
it("can retry on server timeout", async () => {
const channel = new LoggingChannel(10);
const tree = new TestTree(imodel, channel);
const t1 = new TestTile(tree, channel, 1);
const t2 = new TestTile(tree, channel, 2);
const vp = mockViewport(imodel);
requestTiles(vp, [t1, t2]);
IModelApp.tileAdmin.process();
channel.expectRequests(2, 0);
t1.rejectRequest(new Error("Not a server timeout"));
t2.rejectRequest(new ServerTimeoutError("Server timeout"));
await processOnce();
channel.expectRequests(0, 0);
t1.expectStatus(TileLoadStatus.NotFound);
t2.expectStatus(TileLoadStatus.NotLoaded);
requestTiles(vp, [t1, t2]);
IModelApp.tileAdmin.process();
channel.expectRequests(1, 0);
expect(t1.isActive).to.be.false;
expect(t2.isActive).to.be.true;
await t2.resolveBoth();
channel.expectRequests(0, 0);
expect(t2.isActive).to.be.false;
t2.expectStatus(TileLoadStatus.Ready);
});
it("records statistics", async () => {
const channel = new LoggingChannel(4);
function expectStats(expected: Partial<TileRequestChannelStatistics>) {
const stats = channel.statistics;
for (const propName in expected) { // eslint-disable-line guard-for-in
const key = propName as keyof TileRequestChannelStatistics;
expect(stats[key]).to.equal(expected[key]);
}
}
const vp = mockViewport(imodel);
const tree = new TestTree(imodel, channel);
const tiles = [0, 1, 2, 3, 4, 5, 6].map((x) => {
const tile = new TestTile(tree, channel, x);
tile.empty = false;
tile.displayable = true;
return tile;
});
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
expectStats({ numActiveRequests: 4, numPendingRequests: 3, totalDispatchedRequests: 4 });
requestTiles(vp, []);
IModelApp.tileAdmin.process();
expectStats({ numActiveRequests: 4, numPendingRequests: 0, numCanceled: 7 });
tiles[0].rejectRequest(new ServerTimeoutError("oh no!"));
await runMicroTasks();
expectStats({ numActiveRequests: 3, numPendingRequests: 0, totalCompletedRequests: 0, totalFailedRequests: 0, totalTimedOutRequests: 1 });
await tiles[1].resolveBoth();
expectStats({ numActiveRequests: 2, numPendingRequests: 0, totalCompletedRequests: 1 });
tiles[2].rejectRequest();
await runMicroTasks();
expectStats({ numActiveRequests: 1, numPendingRequests: 0, totalFailedRequests: 1 });
tiles[3].resolveRequest();
await runMicroTasks();
tiles[3].rejectRead();
await runMicroTasks();
expectStats({ numActiveRequests: 0, numPendingRequests: 0, totalFailedRequests: 2 });
expectStats({ totalUndisplayableTiles: 0, totalEmptyTiles: 0 });
tiles[4].empty = true;
tiles[5].displayable = false;
tiles[6].empty = true;
tiles[6].displayable = false;
requestTiles(vp, tiles.slice(4));
IModelApp.tileAdmin.process();
expectStats({ numActiveRequests: 3, numPendingRequests: 0 });
await Promise.all(tiles.slice(4).map(async (x) => x.resolveBoth()));
expectStats({ numActiveRequests: 0, numPendingRequests: 0, totalEmptyTiles: 2, totalUndisplayableTiles: 1 });
IModelApp.tileAdmin.process();
expectStats({
numPendingRequests: 0,
numActiveRequests: 0,
numCanceled: 0,
totalCompletedRequests: 4,
totalFailedRequests: 2,
totalTimedOutRequests: 1,
totalEmptyTiles: 2,
totalUndisplayableTiles: 1,
totalCacheMisses: 0,
totalDispatchedRequests: 7,
totalAbortedRequests: 0,
});
});
it("can retry using a different channel", async () => {
const channel2 = new LoggingChannel(10, "channel 2");
class Channel1 extends LoggingChannel {
public constructor() {
super(10, "channel 1");
}
public override onNoContent(req: TileRequest): boolean {
expect(req.channel).to.equal(this);
(req.tile as TestTile).requestChannel = channel2;
return true;
}
}
const channel1 = new Channel1();
const tree = new TestTree(imodel, channel1);
const tiles = [0, 1, 2, 3].map((x) => new TestTile(tree, channel1, x));
const vp = mockViewport(imodel);
requestTiles(vp, tiles);
IModelApp.tileAdmin.process();
channel1.expectRequests(4, 0);
channel2.expectRequests(0, 0);
tiles.forEach((x) => expect(x.channel).to.equal(channel1));
tiles[0].rejectRequest();
tiles[1].resolveRequest();
tiles[2].resolveRequest("undefined");
tiles[3].resolveRequest("undefined");
await processOnce();
tiles.slice(0, 2).forEach((x) => expect(x.channel).to.equal(channel1));
tiles.slice(2).forEach((x) => expect(x.channel).to.equal(channel2));
channel1.expectRequests(0, 0);
channel2.expectRequests(0, 0);
requestTiles(vp, tiles.slice(1));
IModelApp.tileAdmin.process();
channel1.expectRequests(0, 0);
channel2.expectRequests(2, 0);
expect(tiles[1].awaitingRead).to.be.true;
expect(tiles[2].awaitingRequest).to.be.true;
expect(tiles[3].awaitingRequest).to.be.true;
tiles[2].resolveRequest();
tiles[3].resolveRequest();
await processOnce();
tiles.slice(1).forEach((x) => expect(x.awaitingRead).to.be.true);
tiles[1].resolveRead();
tiles[2].resolveRead();
tiles[3].rejectRead();
await processOnce();
channel1.expectRequests(0, 0);
channel2.expectRequests(0, 0);
expect(tiles.map((x) => x.loadStatus)).to.deep.equal([TileLoadStatus.NotFound, TileLoadStatus.Ready, TileLoadStatus.Ready, TileLoadStatus.NotFound]);
});
}); | the_stack |
import React from 'react'
import throttle from 'lodash.throttle'
import {
getBlockIcon,
getTextContent,
getPageTableOfContents,
getBlockParentPage,
uuidToId
} from 'notion-utils'
import * as types from 'notion-types'
import { PageIcon } from './components/page-icon'
import { PageTitle } from './components/page-title'
import { LinkIcon } from './icons/link-icon'
import { PageHeader } from './components/page-header'
import { GoogleDrive } from './components/google-drive'
import { Audio } from './components/audio'
import { File } from './components/file'
import { Equation } from './components/equation'
import { GracefulImage } from './components/graceful-image'
import { LazyImage } from './components/lazy-image'
import { useNotionContext } from './context'
import { cs, getListNumber, isUrl } from './utils'
import { Text } from './components/text'
import { SyncPointerBlock } from './components/sync-pointer-block'
import { AssetWrapper } from './components/asset-wrapper'
interface BlockProps {
block: types.Block
level: number
className?: string
bodyClassName?: string
footer?: React.ReactNode
pageHeader?: React.ReactNode
pageFooter?: React.ReactNode
pageAside?: React.ReactNode
pageCover?: React.ReactNode
hideBlockId?: boolean
}
const tocIndentLevelCache: {
[blockId: string]: number
} = {}
export const Block: React.FC<BlockProps> = (props) => {
const {
components,
fullPage,
darkMode,
recordMap,
mapPageUrl,
mapImageUrl,
showTableOfContents,
minTableOfContentsItems,
defaultPageIcon,
defaultPageCover,
defaultPageCoverPosition
} = useNotionContext()
const {
block,
children,
level,
className,
bodyClassName,
footer,
pageHeader,
pageFooter,
pageAside,
pageCover,
hideBlockId
} = props
if (!block) {
return null
}
// ugly hack to make viewing raw collection views work properly
// e.g., 6d886ca87ab94c21a16e3b82b43a57fb
if (level === 0 && block.type === 'collection_view') {
;(block as any).type = 'collection_view_page'
}
const blockId = hideBlockId
? 'notion-block'
: `notion-block-${uuidToId(block.id)}`
switch (block.type) {
case 'collection_view_page':
// fallthrough
case 'page':
if (level === 0) {
const {
page_icon = defaultPageIcon,
page_cover = defaultPageCover,
page_cover_position = defaultPageCoverPosition,
page_full_width,
page_small_text
} = block.format || {}
if (fullPage) {
const properties =
block.type === 'page'
? block.properties
: {
title: recordMap.collection[block.collection_id]?.value?.name
}
const coverPosition = (1 - (page_cover_position || 0.5)) * 100
const pageIcon = getBlockIcon(block, recordMap) ?? defaultPageIcon
const isPageIconUrl = pageIcon && isUrl(pageIcon)
const toc = getPageTableOfContents(block as types.PageBlock, recordMap)
const hasToc =
showTableOfContents && toc.length >= minTableOfContentsItems
const hasAside = (hasToc || pageAside) && !page_full_width
const [activeSection, setActiveSection] = React.useState(null)
const throttleMs = 100
// this scrollspy logic was originally based on
// https://github.com/Purii/react-use-scrollspy
const actionSectionScrollSpy = throttle(() => {
const sections = document.getElementsByClassName('notion-h')
let prevBBox: DOMRect = null
let currentSectionId = activeSection
for (let i = 0; i < sections.length; ++i) {
const section = sections[i]
if (!section || !(section instanceof Element)) continue
if (!currentSectionId) {
currentSectionId = section.getAttribute('data-id')
}
const bbox = section.getBoundingClientRect()
const prevHeight = prevBBox ? bbox.top - prevBBox.bottom : 0
const offset = Math.max(150, prevHeight / 4)
// GetBoundingClientRect returns values relative to viewport
if (bbox.top - offset < 0) {
currentSectionId = section.getAttribute('data-id')
prevBBox = bbox
continue
}
// No need to continue loop, if last element has been detected
break
}
setActiveSection(currentSectionId)
}, throttleMs)
if (hasToc) {
React.useEffect(() => {
window.addEventListener('scroll', actionSectionScrollSpy)
actionSectionScrollSpy()
return () => {
window.removeEventListener('scroll', actionSectionScrollSpy)
}
}, [])
}
const hasPageCover = pageCover || page_cover
return (
<div
className={cs(
'notion',
'notion-app',
darkMode ? 'dark-mode' : 'light-mode',
blockId,
className
)}
>
<div className='notion-viewport' />
<div className='notion-frame'>
<PageHeader />
<div className='notion-page-scroller'>
{hasPageCover ? (
pageCover ? (
pageCover
) : (
<LazyImage
src={mapImageUrl(page_cover, block)}
alt={getTextContent(properties?.title)}
className='notion-page-cover'
style={{
objectPosition: `center ${coverPosition}%`
}}
/>
)
) : null}
<main
className={cs(
'notion-page',
hasPageCover
? 'notion-page-has-cover'
: 'notion-page-no-cover',
page_icon
? 'notion-page-has-icon'
: 'notion-page-no-icon',
isPageIconUrl
? 'notion-page-has-image-icon'
: 'notion-page-has-text-icon',
'notion-full-page',
page_full_width && 'notion-full-width',
page_small_text && 'notion-small-text',
bodyClassName
)}
>
{page_icon && (
<div className='notion-page-icon-wrapper'>
<PageIcon block={block} defaultIcon={defaultPageIcon} />
</div>
)}
{pageHeader}
<h1 className='notion-title'>
<Text value={properties?.title} block={block} />
</h1>
{block.type === 'page' &&
block.parent_table === 'collection' && (
<components.collectionRow block={block} />
)}
{block.type === 'collection_view_page' && (
<components.collection block={block} />
)}
<div
className={cs(
'notion-page-content',
hasAside && 'notion-page-content-has-aside',
hasToc && 'notion-page-content-has-toc'
)}
>
<article className='notion-page-content-inner'>
{children}
</article>
{hasAside && (
<aside className='notion-aside'>
{hasToc && (
<div className='notion-aside-table-of-contents'>
<div className='notion-aside-table-of-contents-header'>
Table of Contents
</div>
<nav
className={cs(
'notion-table-of-contents',
!darkMode && 'notion-gray'
)}
>
{toc.map((tocItem) => {
const id = uuidToId(tocItem.id)
return (
<a
key={id}
href={`#${id}`}
className={cs(
'notion-table-of-contents-item',
`notion-table-of-contents-item-indent-level-${tocItem.indentLevel}`,
activeSection === id &&
'notion-table-of-contents-active-item'
)}
>
<span
className='notion-table-of-contents-item-body'
style={{
display: 'inline-block',
marginLeft: tocItem.indentLevel * 16
}}
>
{tocItem.text}
</span>
</a>
)
})}
</nav>
</div>
)}
{pageAside}
</aside>
)}
</div>
{pageFooter}
</main>
{footer}
</div>
</div>
</div>
)
} else {
return (
<main
className={cs(
'notion',
darkMode ? 'dark-mode' : 'light-mode',
'notion-page',
page_full_width && 'notion-full-width',
page_small_text && 'notion-small-text',
blockId,
className,
bodyClassName
)}
>
<div className='notion-viewport' />
{pageHeader}
{block.type === 'page' && block.parent_table === 'collection' && (
<components.collectionRow block={block} />
)}
{block.type === 'collection_view_page' && (
<components.collection block={block} />
)}
{children}
{pageFooter}
</main>
)
}
} else {
const blockColor = block.format?.block_color
return (
<components.pageLink
className={cs(
'notion-page-link',
blockColor && `notion-${blockColor}`,
blockId
)}
href={mapPageUrl(block.id)}
>
<PageTitle block={block} />
</components.pageLink>
)
}
case 'header':
// fallthrough
case 'sub_header':
// fallthrough
case 'sub_sub_header': {
if (!block.properties) return null
const blockColor = block.format?.block_color
const id = uuidToId(block.id)
const title =
getTextContent(block.properties.title) || `Notion Header ${id}`
// we use a cache here because constructing the ToC is non-trivial
let indentLevel = tocIndentLevelCache[block.id]
let indentLevelClass: string
if (indentLevel === undefined) {
const page = getBlockParentPage(block, recordMap)
if (page) {
const toc = getPageTableOfContents(page, recordMap)
const tocItem = toc.find((tocItem) => tocItem.id === block.id)
if (tocItem) {
indentLevel = tocItem.indentLevel
tocIndentLevelCache[block.id] = indentLevel
}
}
}
if (indentLevel !== undefined) {
indentLevelClass = `notion-h-indent-${indentLevel}`
}
const isH1 = block.type === 'header'
const isH2 = block.type === 'sub_header'
const isH3 = block.type === 'sub_sub_header'
const classNameStr = cs(
isH1 && 'notion-h notion-h1',
isH2 && 'notion-h notion-h2',
isH3 && 'notion-h notion-h3',
blockColor && `notion-${blockColor}`,
indentLevelClass,
blockId
)
const innerHeader = (
<span>
<div id={id} className='notion-header-anchor' />
<a className='notion-hash-link' href={`#${id}`} title={title}>
<LinkIcon />
</a>
<span className='notion-h-title'>
<Text value={block.properties.title} block={block} />
</span>
</span>
)
//page title takes the h1 so all header blocks are greater
if (isH1) {
return (
<h2 className={classNameStr} data-id={id}>
{innerHeader}
</h2>
)
} else if (isH2) {
return (
<h3 className={classNameStr} data-id={id}>
{innerHeader}
</h3>
)
} else {
return (
<h4 className={classNameStr} data-id={id}>
{innerHeader}
</h4>
)
}
}
case 'divider':
return <hr className={cs('notion-hr', blockId)} />
case 'text':
if (!block.properties && !block.content?.length) {
return <div className={cs('notion-blank', blockId)}> </div>
}
const blockColor = block.format?.block_color
return (
<div
className={cs(
'notion-text',
blockColor && `notion-${blockColor}`,
blockId
)}
>
{block.properties?.title && (
<Text value={block.properties.title} block={block} />
)}
{children && <div className='notion-text-children'>{children}</div>}
</div>
)
case 'bulleted_list':
// fallthrough
case 'numbered_list':
const wrapList = (content: React.ReactNode, start?: number) =>
block.type === 'bulleted_list' ? (
<ul className={cs('notion-list', 'notion-list-disc', blockId)}>
{content}
</ul>
) : (
<ol
start={start}
className={cs('notion-list', 'notion-list-numbered', blockId)}
>
{content}
</ol>
)
let output: JSX.Element | null = null
if (block.content) {
output = (
<>
{block.properties && (
<li>
<Text value={block.properties.title} block={block} />
</li>
)}
{wrapList(children)}
</>
)
} else {
output = block.properties ? (
<li>
<Text value={block.properties.title} block={block} />
</li>
) : null
}
const isTopLevel =
block.type !== recordMap.block[block.parent_id]?.value?.type
const start = getListNumber(block.id, recordMap.block)
return isTopLevel ? wrapList(output, start) : output
case 'tweet':
// fallthrough
case 'maps':
// fallthrough
case 'pdf':
// fallthrough
case 'figma':
// fallthrough
case 'typeform':
// fallthrough
case 'codepen':
// fallthrough
case 'excalidraw':
// fallthrough
case 'image':
// fallthrough
case 'gist':
// fallthrough
case 'embed':
// fallthrough
case 'video':
return <AssetWrapper blockId={blockId} block={block} />
case 'drive':
const properties = block.format?.drive_properties
if (!properties) {
//check if this drive actually needs to be embeded ex. google sheets.
if (block.format?.display_source) {
return <AssetWrapper blockId={blockId} block={block} />
}
}
return (
<GoogleDrive
block={block as types.GoogleDriveBlock}
className={blockId}
/>
)
case 'audio':
return <Audio block={block as types.AudioBlock} className={blockId} />
case 'file':
return <File block={block as types.FileBlock} className={blockId} />
case 'equation':
const math = block.properties.title[0][0]
if (!math) return null
return <Equation math={math} block className={blockId} />
case 'code': {
if (block.properties.title) {
const content = block.properties.title[0][0]
const language = block.properties.language
? block.properties.language[0][0]
: ''
const caption = block.properties.caption
// TODO: add className
return (
<>
<components.code
key={block.id}
language={language || ''}
code={content}
/>
{caption && (
<figcaption className='notion-asset-caption'>
<Text value={caption} block={block} />
</figcaption>
)}
</>
)
}
break
}
case 'column_list':
return <div className={cs('notion-row', blockId)}>{children}</div>
case 'column':
// note: notion uses 46px
const spacerWidth = `min(32px, 4vw)`
const ratio = block.format?.column_ratio || 0.5
const parent = recordMap.block[block.parent_id]?.value
const columns =
parent?.content?.length || Math.max(2, Math.ceil(1.0 / ratio))
const width = `calc((100% - (${
columns - 1
} * ${spacerWidth})) * ${ratio})`
const style = { width }
return (
<>
<div className={cs('notion-column', blockId)} style={style}>
{children}
</div>
<div className='notion-spacer' />
</>
)
case 'quote': {
if (!block.properties) return null
const blockColor = block.format?.block_color
return (
<blockquote
className={cs(
'notion-quote',
blockColor && `notion-${blockColor}`,
blockId
)}
>
<Text value={block.properties.title} block={block} />
</blockquote>
)
}
case 'collection_view':
return <components.collection block={block} className={blockId} />
case 'callout':
return (
<div
className={cs(
'notion-callout',
block.format?.block_color &&
`notion-${block.format?.block_color}_co`,
blockId
)}
>
<PageIcon block={block} />
<div className='notion-callout-text'>
<Text value={block.properties?.title} block={block} />
{children}
</div>
</div>
)
case 'bookmark':
if (!block.properties) return null
let title = getTextContent(block.properties?.title)
if (!title) {
title = getTextContent(block.properties?.link)
}
if (title) {
if (title.startsWith('http')) {
try {
const url = new URL(title)
title = url.hostname
} catch (err) {
// ignore invalid links
}
}
}
return (
<div className='notion-row'>
<components.link
target='_blank'
rel='noopener noreferrer'
className={cs(
'notion-bookmark',
block.format?.block_color && `notion-${block.format.block_color}`,
blockId
)}
href={block.properties.link[0][0]}
>
<div>
{title && (
<div className='notion-bookmark-title'>
<Text value={[[title]]} block={block} />
</div>
)}
{block.properties?.description && (
<div className='notion-bookmark-description'>
<Text value={block.properties?.description} block={block} />
</div>
)}
<div className='notion-bookmark-link'>
{block.format?.bookmark_icon && (
<GracefulImage
src={block.format?.bookmark_icon}
alt={title}
loading='lazy'
/>
)}
<div>
<Text value={block.properties?.link} block={block} />
</div>
</div>
</div>
{block.format?.bookmark_cover && (
<div className='notion-bookmark-image'>
<GracefulImage
src={block.format?.bookmark_cover}
alt={getTextContent(block.properties?.title)}
loading='lazy'
/>
</div>
)}
</components.link>
</div>
)
case 'toggle':
return (
<details className={cs('notion-toggle', blockId)}>
<summary>
<Text value={block.properties?.title} block={block} />
</summary>
<div>{children}</div>
</details>
)
case 'table_of_contents': {
const page = getBlockParentPage(block, recordMap)
if (!page) return null
const toc = getPageTableOfContents(page, recordMap)
const blockColor = block.format?.block_color
return (
<div
className={cs(
'notion-table-of-contents',
blockColor && `notion-${blockColor}`,
blockId
)}
>
{toc.map((tocItem) => (
<a
key={tocItem.id}
href={`#${uuidToId(tocItem.id)}`}
className='notion-table-of-contents-item'
>
<span
className='notion-table-of-contents-item-body'
style={{
display: 'inline-block',
marginLeft: tocItem.indentLevel * 24
}}
>
{tocItem.text}
</span>
</a>
))}
</div>
)
}
case 'to_do':
const isChecked = block.properties?.checked?.[0]?.[0] === 'Yes'
return (
<div className={cs('notion-to-do', blockId)}>
<div className='notion-to-do-item'>
<components.checkbox
blockId={blockId}
isChecked={isChecked}
/>
<div
className={cs(
'notion-to-do-body',
isChecked && `notion-to-do-checked`
)}
>
<Text value={block.properties?.title} block={block} />
</div>
</div>
<div className='notion-to-do-children'>{children}</div>
</div>
)
case 'transclusion_container':
return <div className={cs('notion-sync-block', blockId)}>{children}</div>
case 'transclusion_reference':
return <SyncPointerBlock block={block} level={level + 1} {...props} />
default:
if (process.env.NODE_ENV !== 'production') {
console.log(
'Unsupported type ' + (block as any).type,
JSON.stringify(block, null, 2)
)
}
return <div />
}
return null
} | the_stack |
import type {
GraphQLResolveInfo,
GraphQLScalarType,
GraphQLScalarTypeConfig,
} from 'graphql';
import type { EZContext } from 'graphql-ez';
import type { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';
export type Maybe<T> = T | null;
export type InputMaybe<T> = Maybe<T>;
export type Exact<T extends { [key: string]: unknown }> = {
[K in keyof T]: T[K];
};
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & {
[SubKey in K]?: Maybe<T[SubKey]>;
};
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {
[SubKey in K]: Maybe<T[SubKey]>;
};
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) =>
| Promise<import('graphql-ez').DeepPartial<TResult>>
| import('graphql-ez').DeepPartial<TResult>;
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type RequireFields<T, K extends keyof T> = {
[X in Exclude<keyof T, K>]?: T[X];
} & { [P in K]-?: NonNullable<T[P]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
ExampleScalar: any;
};
export type NamedEntity = {
name: Scalars['String'];
};
export enum GreetingsEnum {
Hello = 'Hello',
Hi = 'Hi',
Hey = 'Hey',
}
export type GreetingsInput = {
language: Scalars['String'];
value?: InputMaybe<Scalars['String']>;
scal?: InputMaybe<Scalars['ExampleScalar']>;
};
export type Query = {
__typename?: 'Query';
simpleString: Scalars['String'];
stringWithArgs: Scalars['String'];
stringNullableWithArgs?: Maybe<Scalars['String']>;
stringNullableWithArgsArray?: Maybe<Scalars['String']>;
object?: Maybe<Human>;
objectArray?: Maybe<Array<Maybe<Human>>>;
objectWithArgs: Human;
arrayString: Array<Scalars['String']>;
arrayObjectArgs: Array<Human>;
greetings: GreetingsEnum;
giveGreetingsInput: Scalars['String'];
number: Scalars['Int'];
union: Array<TestUnion>;
};
export type QueryStringWithArgsArgs = {
hello: Scalars['String'];
};
export type QueryStringNullableWithArgsArgs = {
hello: Scalars['String'];
helloTwo?: InputMaybe<Scalars['String']>;
};
export type QueryStringNullableWithArgsArrayArgs = {
hello: Array<InputMaybe<Scalars['String']>>;
};
export type QueryObjectWithArgsArgs = {
who: Scalars['String'];
};
export type QueryArrayObjectArgsArgs = {
limit: Scalars['Int'];
};
export type QueryGiveGreetingsInputArgs = {
input: GreetingsInput;
};
export type Mutation = {
__typename?: 'Mutation';
increment: Scalars['Int'];
};
export type MutationIncrementArgs = {
n: Scalars['Int'];
};
export type Human = NamedEntity & {
__typename?: 'Human';
name: Scalars['String'];
father: Human;
fieldWithArgs: Scalars['Int'];
sons?: Maybe<Array<Human>>;
union: Array<TestUnion>;
args?: Maybe<Scalars['Int']>;
};
export type HumanFieldWithArgsArgs = {
id: Scalars['Int'];
};
export type HumanArgsArgs = {
a?: InputMaybe<Scalars['String']>;
};
export type Dog = NamedEntity & {
__typename?: 'Dog';
name: Scalars['String'];
owner: Human;
};
export type A = {
__typename?: 'A';
a: Scalars['String'];
common?: Maybe<Scalars['Int']>;
z?: Maybe<Scalars['String']>;
};
export type ACommonArgs = {
a?: InputMaybe<Scalars['String']>;
};
export type B = {
__typename?: 'B';
b: Scalars['Int'];
common?: Maybe<Scalars['String']>;
z?: Maybe<Scalars['String']>;
};
export type BCommonArgs = {
b?: InputMaybe<Scalars['Int']>;
};
export type C = {
__typename?: 'C';
c: GreetingsEnum;
z?: Maybe<Scalars['String']>;
};
export type TestUnion = A | B | C;
export type ResolverTypeWrapper<T> = Promise<T> | T;
export type ResolverWithResolve<TResult, TParent, TContext, TArgs> = {
resolve: ResolverFn<TResult, TParent, TContext, TArgs>;
};
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| ResolverWithResolve<TResult, TParent, TContext, TArgs>;
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterable<TResult> | Promise<AsyncIterable<TResult>>;
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
export interface SubscriptionSubscriberObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> {
subscribe: SubscriptionSubscribeFn<
{ [key in TKey]: TResult },
TParent,
TContext,
TArgs
>;
resolve?: SubscriptionResolveFn<
TResult,
{ [key in TKey]: TResult },
TContext,
TArgs
>;
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>;
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>;
}
export type SubscriptionObject<
TResult,
TKey extends string,
TParent,
TContext,
TArgs
> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>;
export type SubscriptionResolver<
TResult,
TKey extends string,
TParent = {},
TContext = {},
TArgs = {}
> =
| ((
...args: any[]
) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>;
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>;
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (
obj: T,
context: TContext,
info: GraphQLResolveInfo
) => boolean | Promise<boolean>;
export type NextResolverFn<T> = () => Promise<T>;
export type DirectiveResolverFn<
TResult = {},
TParent = {},
TContext = {},
TArgs = {}
> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>;
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
NamedEntity: ResolversTypes['Human'] | ResolversTypes['Dog'];
String: ResolverTypeWrapper<Scalars['String']>;
ExampleScalar: ResolverTypeWrapper<Scalars['ExampleScalar']>;
GreetingsEnum: GreetingsEnum;
GreetingsInput: GreetingsInput;
Query: ResolverTypeWrapper<{}>;
Int: ResolverTypeWrapper<Scalars['Int']>;
Mutation: ResolverTypeWrapper<{}>;
Human: ResolverTypeWrapper<
Omit<Human, 'union'> & { union: Array<ResolversTypes['TestUnion']> }
>;
Dog: ResolverTypeWrapper<Dog>;
A: ResolverTypeWrapper<A>;
B: ResolverTypeWrapper<B>;
C: ResolverTypeWrapper<C>;
TestUnion: ResolversTypes['A'] | ResolversTypes['B'] | ResolversTypes['C'];
Boolean: ResolverTypeWrapper<Scalars['Boolean']>;
};
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
NamedEntity: ResolversParentTypes['Human'] | ResolversParentTypes['Dog'];
String: Scalars['String'];
ExampleScalar: Scalars['ExampleScalar'];
GreetingsInput: GreetingsInput;
Query: {};
Int: Scalars['Int'];
Mutation: {};
Human: Omit<Human, 'union'> & {
union: Array<ResolversParentTypes['TestUnion']>;
};
Dog: Dog;
A: A;
B: B;
C: C;
TestUnion:
| ResolversParentTypes['A']
| ResolversParentTypes['B']
| ResolversParentTypes['C'];
Boolean: Scalars['Boolean'];
};
export type NamedEntityResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['NamedEntity'] = ResolversParentTypes['NamedEntity']
> = {
__resolveType: TypeResolveFn<'Human' | 'Dog', ParentType, ContextType>;
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
};
export interface ExampleScalarScalarConfig
extends GraphQLScalarTypeConfig<ResolversTypes['ExampleScalar'], any> {
name: 'ExampleScalar';
}
export type QueryResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']
> = {
simpleString?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
stringWithArgs?: Resolver<
ResolversTypes['String'],
ParentType,
ContextType,
RequireFields<QueryStringWithArgsArgs, 'hello'>
>;
stringNullableWithArgs?: Resolver<
Maybe<ResolversTypes['String']>,
ParentType,
ContextType,
RequireFields<QueryStringNullableWithArgsArgs, 'hello'>
>;
stringNullableWithArgsArray?: Resolver<
Maybe<ResolversTypes['String']>,
ParentType,
ContextType,
RequireFields<QueryStringNullableWithArgsArrayArgs, 'hello'>
>;
object?: Resolver<Maybe<ResolversTypes['Human']>, ParentType, ContextType>;
objectArray?: Resolver<
Maybe<Array<Maybe<ResolversTypes['Human']>>>,
ParentType,
ContextType
>;
objectWithArgs?: Resolver<
ResolversTypes['Human'],
ParentType,
ContextType,
RequireFields<QueryObjectWithArgsArgs, 'who'>
>;
arrayString?: Resolver<
Array<ResolversTypes['String']>,
ParentType,
ContextType
>;
arrayObjectArgs?: Resolver<
Array<ResolversTypes['Human']>,
ParentType,
ContextType,
RequireFields<QueryArrayObjectArgsArgs, 'limit'>
>;
greetings?: Resolver<
ResolversTypes['GreetingsEnum'],
ParentType,
ContextType
>;
giveGreetingsInput?: Resolver<
ResolversTypes['String'],
ParentType,
ContextType,
RequireFields<QueryGiveGreetingsInputArgs, 'input'>
>;
number?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
union?: Resolver<Array<ResolversTypes['TestUnion']>, ParentType, ContextType>;
};
export type MutationResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']
> = {
increment?: Resolver<
ResolversTypes['Int'],
ParentType,
ContextType,
RequireFields<MutationIncrementArgs, 'n'>
>;
};
export type HumanResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['Human'] = ResolversParentTypes['Human']
> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
father?: Resolver<ResolversTypes['Human'], ParentType, ContextType>;
fieldWithArgs?: Resolver<
ResolversTypes['Int'],
ParentType,
ContextType,
RequireFields<HumanFieldWithArgsArgs, 'id'>
>;
sons?: Resolver<
Maybe<Array<ResolversTypes['Human']>>,
ParentType,
ContextType
>;
union?: Resolver<Array<ResolversTypes['TestUnion']>, ParentType, ContextType>;
args?: Resolver<
Maybe<ResolversTypes['Int']>,
ParentType,
ContextType,
RequireFields<HumanArgsArgs, never>
>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type DogResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['Dog'] = ResolversParentTypes['Dog']
> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
owner?: Resolver<ResolversTypes['Human'], ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type AResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['A'] = ResolversParentTypes['A']
> = {
a?: Resolver<ResolversTypes['String'], ParentType, ContextType>;
common?: Resolver<
Maybe<ResolversTypes['Int']>,
ParentType,
ContextType,
RequireFields<ACommonArgs, never>
>;
z?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type BResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['B'] = ResolversParentTypes['B']
> = {
b?: Resolver<ResolversTypes['Int'], ParentType, ContextType>;
common?: Resolver<
Maybe<ResolversTypes['String']>,
ParentType,
ContextType,
RequireFields<BCommonArgs, never>
>;
z?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type CResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['C'] = ResolversParentTypes['C']
> = {
c?: Resolver<ResolversTypes['GreetingsEnum'], ParentType, ContextType>;
z?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
export type TestUnionResolvers<
ContextType = EZContext,
ParentType extends ResolversParentTypes['TestUnion'] = ResolversParentTypes['TestUnion']
> = {
__resolveType: TypeResolveFn<'A' | 'B' | 'C', ParentType, ContextType>;
};
export type Resolvers<ContextType = EZContext> = {
NamedEntity?: NamedEntityResolvers<ContextType>;
ExampleScalar?: GraphQLScalarType;
Query?: QueryResolvers<ContextType>;
Mutation?: MutationResolvers<ContextType>;
Human?: HumanResolvers<ContextType>;
Dog?: DogResolvers<ContextType>;
A?: AResolvers<ContextType>;
B?: BResolvers<ContextType>;
C?: CResolvers<ContextType>;
TestUnion?: TestUnionResolvers<ContextType>;
};
export type SimpleStringQueryVariables = Exact<{ [key: string]: never }>;
export type SimpleStringQuery = {
__typename?: 'Query';
simpleString: string;
union: Array<
| { __typename: 'A'; a: string }
| { __typename: 'B'; b: number }
| { __typename: 'C'; c: GreetingsEnum }
>;
};
export type ArrayObjectArgsQueryVariables = Exact<{ [key: string]: never }>;
export type ArrayObjectArgsQuery = {
__typename?: 'Query';
arrayObjectArgs: Array<{
__typename?: 'Human';
name: string;
father: {
__typename?: 'Human';
name: string;
father: { __typename?: 'Human'; name: string };
};
}>;
};
export type MultipleArgsQueryVariables = Exact<{ [key: string]: never }>;
export type MultipleArgsQuery = {
__typename?: 'Query';
a1: { __typename?: 'Human'; zxc: string; abc: string };
a2: { __typename?: 'Human'; name: string };
};
export const SimpleStringDocument = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: { kind: 'Name', value: 'simpleString' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'simpleString' } },
{
kind: 'Field',
name: { kind: 'Name', value: 'union' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: '__typename' } },
{
kind: 'InlineFragment',
typeCondition: {
kind: 'NamedType',
name: { kind: 'Name', value: 'A' },
},
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'a' } },
],
},
},
{
kind: 'InlineFragment',
typeCondition: {
kind: 'NamedType',
name: { kind: 'Name', value: 'B' },
},
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'b' } },
],
},
},
{
kind: 'InlineFragment',
typeCondition: {
kind: 'NamedType',
name: { kind: 'Name', value: 'C' },
},
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'c' } },
],
},
},
],
},
},
],
},
},
],
} as unknown as DocumentNode<SimpleStringQuery, SimpleStringQueryVariables>;
export const ArrayObjectArgsDocument = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: { kind: 'Name', value: 'arrayObjectArgs' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
name: { kind: 'Name', value: 'arrayObjectArgs' },
arguments: [
{
kind: 'Argument',
name: { kind: 'Name', value: 'limit' },
value: { kind: 'IntValue', value: '2' },
},
],
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'name' } },
{
kind: 'Field',
name: { kind: 'Name', value: 'father' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'name' } },
{
kind: 'Field',
name: { kind: 'Name', value: 'father' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
name: { kind: 'Name', value: 'name' },
},
],
},
},
],
},
},
],
},
},
],
},
},
],
} as unknown as DocumentNode<
ArrayObjectArgsQuery,
ArrayObjectArgsQueryVariables
>;
export const MultipleArgsDocument = {
kind: 'Document',
definitions: [
{
kind: 'OperationDefinition',
operation: 'query',
name: { kind: 'Name', value: 'multipleArgs' },
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
alias: { kind: 'Name', value: 'a1' },
name: { kind: 'Name', value: 'objectWithArgs' },
arguments: [
{
kind: 'Argument',
name: { kind: 'Name', value: 'who' },
value: { kind: 'StringValue', value: 'hello', block: false },
},
],
selectionSet: {
kind: 'SelectionSet',
selections: [
{
kind: 'Field',
alias: { kind: 'Name', value: 'zxc' },
name: { kind: 'Name', value: 'name' },
},
{
kind: 'Field',
alias: { kind: 'Name', value: 'abc' },
name: { kind: 'Name', value: 'name' },
},
],
},
},
{
kind: 'Field',
alias: { kind: 'Name', value: 'a2' },
name: { kind: 'Name', value: 'objectWithArgs' },
arguments: [
{
kind: 'Argument',
name: { kind: 'Name', value: 'who' },
value: { kind: 'StringValue', value: 'hello2', block: false },
},
],
selectionSet: {
kind: 'SelectionSet',
selections: [
{ kind: 'Field', name: { kind: 'Name', value: 'name' } },
],
},
},
],
},
},
],
} as unknown as DocumentNode<MultipleArgsQuery, MultipleArgsQueryVariables>;
declare module 'graphql-ez' {
interface EZResolvers extends Resolvers<import('graphql-ez').EZContext> {}
} | the_stack |
import rule from '../../src/rules/comma-spacing';
import { RuleTester } from '../RuleTester';
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});
ruleTester.run('comma-spacing', rule, {
valid: [
"foo(1, true/* comment */, 'text');",
"foo(1, true /* comment */, 'text');",
"foo(1, true/* comment *//* comment */, 'text');",
"foo(1, true/* comment */ /* comment */, 'text');",
"foo(1, true, /* comment */ 'text');",
"foo(1, // comment\n true, /* comment */ 'text');",
{
code: "foo(1, // comment\n true,/* comment */ 'text');",
options: [{ before: false, after: false }],
},
'const a = 1, b = 2;',
'const foo = [, ];',
'const foo = [1, ];',
'const foo = [, 2];',
'const foo = [1, 2];',
'const foo = [, , ];',
'const foo = [1, , ];',
'const foo = [, 2, ];',
'const foo = [, , 3];',
'const foo = [1, 2, ];',
'const foo = [, 2, 3];',
'const foo = [1, , 3];',
'const foo = [1, 2, 3];',
"const foo = {'foo':'foo', 'baz':'baz'};",
"const foo = {'foo':'foo', 'baz':\n'baz'};",
"const foo = {'foo':\n'foo', 'baz':\n'baz'};",
'function foo(a, b){}',
'function foo(a, b = 1){}',
'function foo(a = 1, b, c){}',
'const foo = (a, b) => {}',
'const foo = (a=1, b) => {}',
'const foo = a => a + 2',
'a, b',
'const a = (1 + 2, 2)',
'a(b, c)',
'new A(b, c)',
'foo((a), b)',
'const b = ((1 + 2), 2)',
'parseInt((a + b), 10)',
'go.boom((a + b), 10)',
'go.boom((a + b), 10, (4))',
'const x = [ (a + c), (b + b) ]',
"[' , ']",
'[` , `]',
'`${[1, 2]}`',
'fn(a, b,)',
'const fn = (a, b,) => {}',
'const fn = function (a, b,) {}',
"foo(/,/, 'a')",
"const x = ',,,,,';",
"const code = 'var foo = 1, bar = 3;'",
"['apples', \n 'oranges'];",
"{x: 'var x,y,z'}",
{
code: "const foo = {'foo':\n'bar' ,'baz':\n'qur'};",
options: [{ before: true, after: false }],
},
{
code: 'const a = 1 ,b = 2;',
options: [{ before: true, after: false }],
},
{
code: 'function foo(a ,b){}',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 ,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [ ,2];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 ,2];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [,,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 , ,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [ ,2 ,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [ , ,3];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 ,2 ,];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [ ,2 ,3];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 , ,3];',
options: [{ before: true, after: false }],
},
{
code: 'const arr = [1 ,2 ,3];',
options: [{ before: true, after: false }],
},
{
code: "const obj = {'foo':'bar' , 'baz':'qur'};",
options: [{ before: true, after: true }],
},
{
code: 'const a = 1 , b = 2;',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [, ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [ , 2];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , 2];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [, , ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , , ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [ , 2 , ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [ , , 3];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , 2 , ];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [, 2 , 3];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , , 3];',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [1 , 2 , 3];',
options: [{ before: true, after: true }],
},
{
code: 'a , b',
options: [{ before: true, after: true }],
},
{
code: 'const arr = [,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [ ,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [,2];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [ ,2];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,2];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [,,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [ ,,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [,2,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [ ,2,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [,,3];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,2,];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [,2,3];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,,3];',
options: [{ before: false, after: false }],
},
{
code: 'const arr = [1,2,3];',
options: [{ before: false, after: false }],
},
{
code: 'const a = (1 + 2,2)',
options: [{ before: false, after: false }],
},
'const a; console.log(`${a}`, "a");',
'const [a, b] = [1, 2];',
'const [a, b, ] = [1, 2];',
'const [a, , b] = [1, 2, 3];',
'const [ , b] = a;',
'const [, b] = a;',
{
code: '<a>,</a>',
parserOptions: {
ecmaFeatures: { jsx: true },
},
},
{
code: '<a> , </a>',
parserOptions: {
ecmaFeatures: { jsx: true },
},
},
{
code: '<a>Hello, world</a>',
options: [{ before: true, after: false }],
parserOptions: { ecmaFeatures: { jsx: true } },
},
'const Foo = <T,>(foo: T) => {}',
'function foo<T,>() {}',
'class Foo<T, T1> {}',
'interface Foo<T, T1,>{}',
'interface A<> {}',
],
invalid: [
{
code: 'a(b,c)',
output: 'a(b , c)',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 4,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 4,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'new A(b,c)',
output: 'new A(b , c)',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 8,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 8,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const a = 1 ,b = 2;',
output: 'const a = 1, b = 2;',
errors: [
{
messageId: 'unexpected',
column: 13,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 13,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1 , 2];',
output: 'const arr = [1, 2];',
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: 'const arr = [1 , ];',
output: 'const arr = [1, ];',
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: 'const arr = [1 , ];',
output: 'const arr = [1 ,];',
options: [{ before: true, after: false }],
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1 ,2];',
output: 'const arr = [1, 2];',
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
{
messageId: `missing`,
column: 16,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [(1) , 2];',
output: 'const arr = [(1), 2];',
errors: [
{
messageId: 'unexpected',
column: 18,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: 'const arr = [1, 2];',
output: 'const arr = [1 ,2];',
options: [{ before: true, after: false }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'unexpected',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1\n , 2];',
output: 'const arr = [1\n ,2];',
options: [{ before: false, after: false }],
errors: [
{
messageId: 'unexpected',
column: 3,
line: 2,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1,\n 2];',
output: 'const arr = [1 ,\n 2];',
options: [{ before: true, after: false }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: "const obj = {'foo':\n'bar', 'baz':\n'qur'};",
output: "const obj = {'foo':\n'bar' ,'baz':\n'qur'};",
options: [{ before: true, after: false }],
errors: [
{
messageId: 'missing',
column: 6,
line: 2,
data: { loc: 'before' },
},
{
messageId: 'unexpected',
column: 6,
line: 2,
data: { loc: 'after' },
},
],
},
{
code: 'const obj = {a: 1\n ,b: 2};',
output: 'const obj = {a: 1\n , b: 2};',
options: [{ before: false, after: true }],
errors: [
{
messageId: 'missing',
column: 3,
line: 2,
data: { loc: 'after' },
},
],
},
{
code: 'const obj = {a: 1 ,\n b: 2};',
output: 'const obj = {a: 1,\n b: 2};',
options: [{ before: false, after: false }],
errors: [
{
messageId: 'unexpected',
column: 19,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: 'const arr = [1 ,2];',
output: 'const arr = [1 , 2];',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 16,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1,2];',
output: 'const arr = [1 , 2];',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: "const obj = {'foo':\n'bar','baz':\n'qur'};",
output: "const obj = {'foo':\n'bar' , 'baz':\n'qur'};",
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 6,
line: 2,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 6,
line: 2,
data: { loc: 'after' },
},
],
},
{
code: 'const arr = [1 , 2];',
output: 'const arr = [1,2];',
options: [{ before: false, after: false }],
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'a ,b',
output: 'a, b',
options: [{ before: false, after: true }],
errors: [
{
messageId: 'unexpected',
column: 3,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 3,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function foo(a,b){}',
output: 'function foo(a , b){}',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const foo = (a,b) => {}',
output: 'const foo = (a , b) => {}',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'const foo = (a = 1,b) => {}',
output: 'const foo = (a = 1 , b) => {}',
options: [{ before: true, after: true }],
errors: [
{
messageId: 'missing',
column: 19,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 19,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function foo(a = 1 ,b = 2) {}',
output: 'function foo(a = 1, b = 2) {}',
options: [{ before: false, after: true }],
errors: [
{
messageId: 'unexpected',
column: 20,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 20,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: '<a>{foo(1 ,2)}</a>',
output: '<a>{foo(1, 2)}</a>',
parserOptions: {
ecmaFeatures: { jsx: true },
},
errors: [
{
messageId: 'unexpected',
column: 11,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 11,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: "foo(1, true/* comment */ , 'foo');",
output: "foo(1, true/* comment */, 'foo');",
errors: [
{
messageId: 'unexpected',
column: 26,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: "foo(1, true,/* comment */ 'foo');",
output: "foo(1, true, /* comment */ 'foo');",
errors: [
{
messageId: 'missing',
column: 12,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: "foo(404,// comment\n true, 'hello');",
output: "foo(404, // comment\n true, 'hello');",
errors: [
{
messageId: 'missing',
column: 8,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function Foo<T,T1>() {}',
output: 'function Foo<T, T1>() {}',
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function Foo<T , T1>() {}',
output: 'function Foo<T, T1>() {}',
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
],
},
{
code: 'function Foo<T ,T1>() {}',
output: 'function Foo<T, T1>() {}',
errors: [
{
messageId: 'unexpected',
column: 16,
line: 1,
data: { loc: 'before' },
},
{
messageId: 'missing',
column: 16,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function Foo<T, T1>() {}',
output: 'function Foo<T,T1>() {}',
options: [{ before: false, after: false }],
errors: [
{
messageId: 'unexpected',
column: 15,
line: 1,
data: { loc: 'after' },
},
],
},
{
code: 'function Foo<T,T1>() {}',
output: 'function Foo<T ,T1>() {}',
options: [{ before: true, after: false }],
errors: [
{
messageId: 'missing',
column: 15,
line: 1,
data: { loc: 'before' },
},
],
},
],
}); | the_stack |
import { SourceMapGenerator, RawSourceMap } from 'source-map'
import Node, {
Position,
Source,
ChildNode,
NodeProps,
ChildProps,
AnyNode
} from './node.js'
import Declaration, { DeclarationProps } from './declaration.js'
import Root, { RootProps } from './root.js'
import Comment, { CommentProps } from './comment.js'
import AtRule, { AtRuleProps } from './at-rule.js'
import Result, { Message } from './result.js'
import Rule, { RuleProps } from './rule.js'
import Container, { ContainerProps } from './container.js'
import Warning, { WarningOptions } from './warning.js'
import Input, { FilePosition } from './input.js'
import CssSyntaxError from './css-syntax-error.js'
import list, { List } from './list.js'
import Processor from './processor.js'
export {
WarningOptions,
FilePosition,
Position,
Source,
ChildNode,
AnyNode,
Message,
NodeProps,
DeclarationProps,
ContainerProps,
CommentProps,
RuleProps,
ChildProps,
AtRuleProps,
RootProps,
Warning,
CssSyntaxError,
Node,
Container,
list,
Declaration,
Comment,
AtRule,
Rule,
Root,
Result,
Input
}
export type SourceMap = SourceMapGenerator & {
toJSON(): RawSourceMap
}
export type Helpers = { result: Result; postcss: Postcss } & Postcss
type RootProcessor = (root: Root, helper: Helpers) => Promise<void> | void
type DeclarationProcessor = (
decl: Declaration,
helper: Helpers
) => Promise<void> | void
type RuleProcessor = (rule: Rule, helper: Helpers) => Promise<void> | void
type AtRuleProcessor = (atRule: AtRule, helper: Helpers) => Promise<void> | void
type CommentProcessor = (
comment: Comment,
helper: Helpers
) => Promise<void> | void
interface Processors {
/**
* Will be called on `Root` node once.
*/
Once?: RootProcessor
/**
* Will be called on `Root` node once, when all children will be processed.
*/
OnceExit?: RootProcessor
/**
* Will be called on `Root` node.
*
* Will be called again on children changes.
*/
Root?: RootProcessor
/**
* Will be called on `Root` node, when all children will be processed.
*
* Will be called again on children changes.
*/
RootExit?: RootProcessor
/**
* Will be called on all `Declaration` nodes after listeners
* for `Declaration` event.
*
* Will be called again on node or children changes.
*/
Declaration?: DeclarationProcessor | { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Declaration` nodes.
*
* Will be called again on node or children changes.
*/
DeclarationExit?:
| DeclarationProcessor
| { [prop: string]: DeclarationProcessor }
/**
* Will be called on all `Rule` nodes.
*
* Will be called again on node or children changes.
*/
Rule?: RuleProcessor
/**
* Will be called on all `Rule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
RuleExit?: RuleProcessor
/**
* Will be called on all`AtRule` nodes.
*
* Will be called again on node or children changes.
*/
AtRule?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `AtRule` nodes, when all children will be processed.
*
* Will be called again on node or children changes.
*/
AtRuleExit?: AtRuleProcessor | { [name: string]: AtRuleProcessor }
/**
* Will be called on all `Comment` nodes.
*
* Will be called again on node or children changes.
*/
Comment?: CommentProcessor
/**
* Will be called on all `Comment` nodes after listeners
* for `Comment` event.
*
* Will be called again on node or children changes.
*/
CommentExit?: CommentProcessor
/**
* Will be called when all other listeners processed the document.
*
* This listener will not be called again.
*/
Exit?: RootProcessor
}
export interface Plugin extends Processors {
postcssPlugin: string
prepare?: (result: Result) => Processors
}
export interface PluginCreator<PluginOptions> {
(opts?: PluginOptions): Plugin
postcss: true
}
export interface Transformer extends TransformCallback {
postcssPlugin: string
postcssVersion: string
}
export interface TransformCallback {
(root: Root, result: Result): Promise<void> | void
}
export interface OldPlugin<T> extends Transformer {
(opts?: T): Transformer
postcss: Transformer
}
export type AcceptedPlugin =
| Plugin
| PluginCreator<any>
| OldPlugin<any>
| TransformCallback
| {
postcss: TransformCallback | Processor
}
| Processor
export interface Parser {
(
css: string | { toString(): string },
opts?: Pick<ProcessOptions, 'map' | 'from'>
): Root
}
export interface Builder {
(part: string, node?: AnyNode, type?: 'start' | 'end'): void
}
export interface Stringifier {
(node: AnyNode, builder: Builder): void
}
export interface Syntax {
/**
* Function to generate AST by string.
*/
parse?: Parser
/**
* Class to generate string by AST.
*/
stringify?: Stringifier
}
export interface SourceMapOptions {
/**
* Indicates that the source map should be embedded in the output CSS
* as a Base64-encoded comment. By default, it is `true`.
* But if all previous maps are external, not inline, PostCSS will not embed
* the map even if you do not set this option.
*
* If you have an inline source map, the result.map property will be empty,
* as the source map will be contained within the text of `result.css`.
*/
inline?: boolean
/**
* Source map content from a previous processing step (e.g., Sass).
*
* PostCSS will try to read the previous source map
* automatically (based on comments within the source CSS), but you can use
* this option to identify it manually.
*
* If desired, you can omit the previous map with prev: `false`.
*/
prev?: string | boolean | object | ((file: string) => string)
/**
* Indicates that PostCSS should set the origin content (e.g., Sass source)
* of the source map. By default, it is true. But if all previous maps do not
* contain sources content, PostCSS will also leave it out even if you
* do not set this option.
*/
sourcesContent?: boolean
/**
* Indicates that PostCSS should add annotation comments to the CSS.
* By default, PostCSS will always add a comment with a path
* to the source map. PostCSS will not add annotations to CSS files
* that do not contain any comments.
*
* By default, PostCSS presumes that you want to save the source map as
* `opts.to + '.map'` and will use this path in the annotation comment.
* A different path can be set by providing a string value for annotation.
*
* If you have set `inline: true`, annotation cannot be disabled.
*/
annotation?: string | boolean | ((file: string, root: Root) => string)
/**
* Override `from` in map’s sources.
*/
from?: string
/**
* Use absolute path in generated source map.
*/
absolute?: boolean
}
export interface ProcessOptions {
/**
* The path of the CSS source file. You should always set `from`,
* because it is used in source map generation and syntax error messages.
*/
from?: string
/**
* The path where you'll put the output CSS file. You should always set `to`
* to generate correct source maps.
*/
to?: string
/**
* Function to generate AST by string.
*/
parser?: Syntax | Parser
/**
* Class to generate string by AST.
*/
stringifier?: Syntax | Stringifier
/**
* Object with parse and stringify.
*/
syntax?: Syntax
/**
* Source map options
*/
map?: SourceMapOptions | boolean
}
export interface Postcss {
/**
* Create a new `Processor` instance that will apply `plugins`
* as CSS processors.
*
* ```js
* let postcss = require('postcss')
*
* postcss(plugins).process(css, { from, to }).then(result => {
* console.log(result.css)
* })
* ```
*
* @param plugins PostCSS plugins.
* @return Processor to process multiple CSS.
*/
(plugins?: AcceptedPlugin[]): Processor
(...plugins: AcceptedPlugin[]): Processor
/**
* Default function to convert a node tree into a CSS string.
*/
stringify: Stringifier
/**
* Parses source css and returns a new `Root` node,
* which contains the source CSS nodes.
*
* ```js
* // Simple CSS concatenation with source map support
* const root1 = postcss.parse(css1, { from: file1 })
* const root2 = postcss.parse(css2, { from: file2 })
* root1.append(root2).toResult().css
* ```
*/
parse: Parser
/**
* Contains the `list` module.
*/
list: List
/**
* Creates a new `Comment` node.
*
* @param defaults Properties for the new node.
* @return New comment node
*/
comment(defaults?: CommentProps): Comment
/**
* Creates a new `AtRule` node.
*
* @param defaults Properties for the new node.
* @return New at-rule node.
*/
atRule(defaults?: AtRuleProps): AtRule
/**
* Creates a new `Declaration` node.
*
* @param defaults Properties for the new node.
* @return New declaration node.
*/
decl(defaults?: DeclarationProps): Declaration
/**
* Creates a new `Rule` node.
*
* @param default Properties for the new node.
* @return New rule node.
*/
rule(defaults?: RuleProps): Rule
/**
* Creates a new `Root` node.
*
* @param defaults Properties for the new node.
* @return New root node.
*/
root(defaults?: RootProps): Root
CssSyntaxError: typeof CssSyntaxError
Declaration: typeof Declaration
Container: typeof Container
Comment: typeof Comment
Warning: typeof Warning
AtRule: typeof AtRule
Result: typeof Result
Input: typeof Input
Rule: typeof Rule
Root: typeof Root
Node: typeof Node
}
export const stringify: Stringifier
export const atRule: Postcss['atRule']
export const parse: Parser
export const decl: Postcss['decl']
export const rule: Postcss['rule']
export const root: Postcss['root']
declare const postcss: Postcss
export default postcss | the_stack |
import {
expect
} from 'chai';
import {
ArrayExt, IIterator, every, iter, toArray
} from '@phosphor/algorithm';
import {
Message, MessageLoop
} from '@phosphor/messaging';
import {
Layout, Widget
} from '@phosphor/widgets';
import {
LogWidget
} from './widget.spec';
class LogLayout extends Layout {
methods: string[] = [];
widgets = [new LogWidget(), new LogWidget()];
dispose(): void {
while (this.widgets.length !== 0) {
this.widgets.pop()!.dispose();
}
super.dispose();
}
iter(): IIterator<Widget> {
return iter(this.widgets);
}
removeWidget(widget: Widget): void {
this.methods.push('removeWidget');
ArrayExt.removeFirstOf(this.widgets, widget);
}
protected init(): void {
this.methods.push('init');
super.init();
}
protected onResize(msg: Widget.ResizeMessage): void {
super.onResize(msg);
this.methods.push('onResize');
}
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.methods.push('onUpdateRequest');
}
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.methods.push('onAfterAttach');
}
protected onBeforeDetach(msg: Message): void {
super.onBeforeDetach(msg);
this.methods.push('onBeforeDetach');
}
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.methods.push('onAfterShow');
}
protected onBeforeHide(msg: Message): void {
super.onBeforeHide(msg);
this.methods.push('onBeforeHide');
}
protected onFitRequest(msg: Widget.ChildMessage): void {
super.onFitRequest(msg);
this.methods.push('onFitRequest');
}
protected onChildShown(msg: Widget.ChildMessage): void {
super.onChildShown(msg);
this.methods.push('onChildShown');
}
protected onChildHidden(msg: Widget.ChildMessage): void {
super.onChildHidden(msg);
this.methods.push('onChildHidden');
}
}
describe('@phosphor/widgets', () => {
describe('Layout', () => {
describe('#iter()', () => {
it('should create an iterator over the widgets in the layout', () => {
let layout = new LogLayout();
expect(every(layout, child => child instanceof Widget)).to.equal(true);
});
});
describe('#removeWidget()', () => {
it("should be invoked when a child widget's `parent` property is set to `null`", () => {
let parent = new Widget();
let layout = new LogLayout();
parent.layout = layout;
layout.widgets[0].parent = null;
expect(layout.methods).to.contain('removeWidget');
});
});
describe('#dispose()', () => {
it('should dispose of the resource held by the layout', () => {
let widget = new Widget();
let layout = new LogLayout();
widget.layout = layout;
let children = toArray(widget.children());
layout.dispose();
expect(layout.parent).to.equal(null);
expect(every(children, w => w.isDisposed)).to.equal(true);
});
it('should be called automatically when the parent is disposed', () => {
let widget = new Widget();
let layout = new LogLayout();
widget.layout = layout;
widget.dispose();
expect(layout.parent).to.equal(null);
expect(layout.isDisposed).to.equal(true);
});
});
describe('#isDisposed', () => {
it('should test whether the layout is disposed', () => {
let layout = new LogLayout();
expect(layout.isDisposed).to.equal(false);
layout.dispose();
expect(layout.isDisposed).to.equal(true);
});
});
describe('#parent', () => {
it('should get the parent widget of the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
expect(layout.parent).to.equal(parent);
});
it('should throw an error if set to `null`', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
expect(() => { layout.parent = null; }).to.throw(Error);
});
it ('should throw an error if set to a different value', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
expect(() => { layout.parent = new Widget(); }).to.throw(Error);
});
it('should be a no-op if the parent is set to the same value', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
layout.parent = parent;
expect(layout.parent).to.equal(parent);
});
});
describe('#init()', () => {
it('should be invoked when the layout is installed on its parent widget', () => {
let widget = new Widget();
let layout = new LogLayout();
widget.layout = layout;
expect(layout.methods).to.contain('init');
});
it('should reparent the child widgets', () => {
let widget = new Widget();
let layout = new LogLayout();
widget.layout = layout;
expect(every(layout, child => child.parent === widget)).to.equal(true);
});
});
describe('#onResize()', () => {
it('should be invoked on a `resize` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.ResizeMessage.UnknownSize);
expect(layout.methods).to.contain('onResize');
});
it('should send a `resize` message to each of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.ResizeMessage.UnknownSize);
expect(layout.methods).to.contain('onResize');
expect(layout.widgets[0].methods).to.contain('onResize');
expect(layout.widgets[1].methods).to.contain('onResize');
});
});
describe('#onUpdateRequest()', () => {
it('should be invoked on an `update-request` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.UpdateRequest);
expect(layout.methods).to.contain('onUpdateRequest');
});
it('should send a `resize` message to each of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.UpdateRequest);
expect(layout.methods).to.contain('onUpdateRequest');
expect(layout.widgets[0].methods).to.contain('onResize');
expect(layout.widgets[1].methods).to.contain('onResize');
});
});
describe('#onAfterAttach()', () => {
it('should be invoked on an `after-attach` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.AfterAttach);
expect(layout.methods).to.contain('onAfterAttach');
});
it('should send an `after-attach` message to each of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.AfterAttach);
expect(layout.methods).to.contain('onAfterAttach');
expect(layout.widgets[0].methods).to.contain('onAfterAttach');
expect(layout.widgets[1].methods).to.contain('onAfterAttach');
});
});
describe('#onBeforeDetach()', () => {
it('should be invoked on an `before-detach` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.BeforeDetach);
expect(layout.methods).to.contain('onBeforeDetach');
});
it('should send a `before-detach` message to each of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.BeforeDetach);
expect(layout.methods).to.contain('onBeforeDetach');
expect(layout.widgets[0].methods).to.contain('onBeforeDetach');
expect(layout.widgets[1].methods).to.contain('onBeforeDetach');
});
});
describe('#onAfterShow()', () => {
it('should be invoked on an `after-show` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.AfterShow);
expect(layout.methods).to.contain('onAfterShow');
});
it('should send an `after-show` message to non hidden of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
layout.widgets[0].hide();
MessageLoop.sendMessage(parent, Widget.Msg.AfterShow);
expect(layout.methods).to.contain('onAfterShow');
expect(layout.widgets[0].methods).to.not.contain('onAfterShow');
expect(layout.widgets[1].methods).to.contain('onAfterShow');
});
});
describe('#onBeforeHide()', () => {
it('should be invoked on a `before-hide` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.BeforeHide);
expect(layout.methods).to.contain('onBeforeHide');
});
it('should send a `before-hide` message to non hidden of the widgets in the layout', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
layout.widgets[0].hide();
MessageLoop.sendMessage(parent, Widget.Msg.BeforeHide);
expect(layout.methods).to.contain('onBeforeHide');
expect(layout.widgets[0].methods).to.not.contain('onBeforeHide');
expect(layout.widgets[1].methods).to.contain('onBeforeHide');
});
});
describe('#onFitRequest()', () => {
it('should be invoked on an `fit-request` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
MessageLoop.sendMessage(parent, Widget.Msg.FitRequest);
expect(layout.methods).to.contain('onFitRequest');
});
});
describe('#onChildShown()', () => {
it('should be invoked on an `child-shown` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
let msg = new Widget.ChildMessage('child-shown', new Widget());
MessageLoop.sendMessage(parent, msg);
expect(layout.methods).to.contain('onChildShown');
});
});
describe('#onChildHidden()', () => {
it('should be invoked on an `child-hidden` message', () => {
let layout = new LogLayout();
let parent = new Widget();
parent.layout = layout;
let msg = new Widget.ChildMessage('child-hidden', new Widget());
MessageLoop.sendMessage(parent, msg);
expect(layout.methods).to.contain('onChildHidden');
});
});
});
}); | the_stack |
export interface IEvent {
/** Defines type of event. Should be 'message' for an IMessage. */
type: string;
/** SDK thats processing the event. Will always be 'botbuilder'. */
agent: string;
/** The original source of the event (i.e. 'facebook', 'skype', 'slack', etc.) */
source: string;
/** The original event in the sources native schema. For outgoing messages can be used to pass source specific event data like custom attachments. */
sourceEvent: any;
/** Address routing information for the event. Save this field to external storage somewhere to later compose a proactive message to the user. */
address: IAddress;
/**
* For incoming messages this is the user that sent the message. By default this is a copy of [address.user](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iaddress.html#user) but you can configure your bot with a
* [lookupUser](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iuniversalbotsettings.html#lookupuser) function that lets map the incoming user to an internal user id.
*/
user: IIdentity;
}
/** The Properties of a conversation have changed. */
export interface IConversationUpdate extends IEvent {
/** Array of members added to the conversation. */
membersAdded?: IIdentity[];
/** Array of members removed from the conversation. */
membersRemoved?: IIdentity[];
/** The conversations new topic name. */
topicName?: string;
/** If true then history was disclosed. */
historyDisclosed?: boolean;
}
/** A user has updated their contact list. */
export interface IContactRelationUpdate extends IEvent {
/** The action taken. Valid values are "add" or "remove". */
action: string;
}
/**
* A chat message sent between a User and a Bot. Messages from the bot to the user come in two flavors:
*
* * __reactive messages__ are messages sent from the Bot to the User as a reply to an incoming message from the user.
* * __proactive messages__ are messages sent from the Bot to the User in response to some external event like an alarm triggering.
*
* In the reactive case the you should copy the [address](#address) field from the incoming message to the outgoing message (if you use the [Message]( /en-us/node/builder/chat-reference/classes/_botbuilder_d_.message.html) builder class and initialize it with the
* [session](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html) this will happen automatically) and then set the [text](#text) or [attachments](#attachments). For proactive messages you’ll need save the [address](#address) from the incoming message to
* an external storage somewhere. You can then later pass this in to [UniversalBot.beginDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot.html#begindialog) or copy it to an outgoing message passed to
* [UniversalBot.send()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot.html#send).
*
* Composing a message to the user using the incoming address object will by default send a reply to the user in the context of the current conversation. Some channels allow for the starting of new conversations with the user. To start a new proactive conversation with the user simply delete
* the [conversation](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iaddress.html#conversation) field from the address object before composing the outgoing message.
*/
export interface IMessage extends IEvent {
/** Timestamp of message given by chat service for incoming messages. */
timestamp: string;
/** Text to be displayed by as fall-back and as short description of the message content in e.g. list of recent conversations. */
summary: string;
/** Message text. */
text: string;
/** Identified language of the message text if known. */
textLocale: string;
/** For incoming messages contains attachments like images sent from the user. For outgoing messages contains objects like cards or images to send to the user. */
attachments: IAttachment[];
/** Structured objects passed to the bot or user. */
entities: any[];
/** Format of text fields. The default value is 'markdown'. */
textFormat: string;
/** Hint for how clients should layout multiple attachments. The default value is 'list'. */
attachmentLayout: string;
}
/** Implemented by classes that can be converted into a message. */
export interface IIsMessage {
/** Returns the JSON object for the message. */
toMessage(): IMessage;
}
/** Represents a user, bot, or conversation. */
export interface IIdentity {
/** Channel specific ID for this identity. */
id: string;
/** Friendly name for this identity. */
name?: string;
/** If true the identity is a group. Typically only found on conversation identities. */
isGroup?: boolean;
}
/**
* Address routing information for a [message](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imessage.html#address).
* Addresses are bidirectional meaning they can be used to address both incoming and outgoing messages. They're also connector specific meaning that
* [connectors](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iconnector.html) are free to add their own fields.
*/
export interface IAddress {
/** Unique identifier for channel. */
channelId: string;
/** User that sent or should receive the message. */
user: IIdentity;
/** Bot that either received or is sending the message. */
bot: IIdentity;
/**
* Represents the current conversation and tracks where replies should be routed to.
* Can be deleted to start a new conversation with a [user](#user) on channels that support new conversations.
*/
conversation?: IIdentity;
}
/** Chat connector specific address. */
export interface IChatConnectorAddress extends IAddress {
/** Incoming Message ID. */
id?: string;
/** Specifies the URL to post messages back. */
serviceUrl?: string;
}
/**
* Many messaging channels provide the ability to attach richer objects. Bot Builder lets you express these attachments in a cross channel way and [connectors](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iconnector.html) will do their best to render the
* attachments using the channels native constructs. If you desire more control over the channels rendering of a message you can use [IEvent.sourceEvent](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ievent.html#sourceevent) to provide attachments using
* the channels native schema. The types of attachments that can be sent varies by channel but these are the basic types:
*
* * __Media and Files:__ Basic files can be sent by setting [contentType](#contenttype) to the MIME type of the file and then passing a link to the file in [contentUrl](#contenturl).
* * __Cards and Keyboards:__ A rich set of visual cards and custom keyboards can by setting [contentType](#contenttype) to the cards type and then passing the JSON for the card in [content](#content). If you use one of the rich card builder classes like
* [HeroCard](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.herocard.html) the attachment will automatically filled in for you.
*/
export interface IAttachment {
/** MIME type string which describes type of attachment. */
contentType: string;
/** (Optional) object structure of attachment. */
content?: any;
/** (Optional) reference to location of attachment content. */
contentUrl?: string;
}
/** Implemented by classes that can be converted into an attachment. */
export interface IIsAttachment {
/** Returns the JSON object for the attachment. */
toAttachment(): IAttachment;
}
/** Displays a signin card and button to the user. Some channels may choose to render this as a text prompt and link to click. */
export interface ISigninCard {
/** Title of the Card. */
title: string;
/** Sign in action. */
buttons: ICardAction[];
}
/**
* Displays a card to the user using either a smaller thumbnail layout or larger hero layout (the attachments [contentType](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iattachment.html#contenttype) determines which).
* All of the cards fields are optional so this card can be used to specify things like a keyboard on certain channels. Some channels may choose to render a lower fidelity version of the card or use an alternate representation.
*/
export interface IThumbnailCard {
/** Title of the Card. */
title?: string;
/** Subtitle appears just below Title field, differs from Title in font styling only. */
subtitle?: string;
/** Text field appears just below subtitle, differs from Subtitle in font styling only. */
text?: string;
/** Messaging supports all media formats: audio, video, images and thumbnails as well to optimize content download. */
images?: ICardImage[];
/** This action will be activated when user taps on the card. Not all channels support tap actions and some channels may choose to render the tap action as the titles link. */
tap?: ICardAction;
/** Set of actions applicable to the current card. Not all channels support buttons or cards with buttons. Some channels may choose to render the buttons using a custom keyboard. */
buttons?: ICardAction[];
}
/** Displays a rich receipt to a user for something they've either bought or are planning to buy. */
export interface IReceiptCard {
/** Title of the Card. */
title: string;
/** Array of receipt items. */
items: IReceiptItem[];
/** Array of additional facts to display to user (shipping charges and such.) Not all facts will be displayed on all channels. */
facts: IFact[];
/** This action will be activated when user taps on the card. Not all channels support tap actions. */
tap: ICardAction;
/** Total amount of money paid (or should be paid.) */
total: string;
/** Total amount of TAX paid (or should be paid.) */
tax: string;
/** Total amount of VAT paid (or should be paid.) */
vat: string;
/** Set of actions applicable to the current card. Not all channels support buttons and the number of allowed buttons varies by channel. */
buttons: ICardAction[];
}
/** An individual item within a [receipt](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ireceiptcard.html). */
export interface IReceiptItem {
/** Title of the item. */
title: string;
/** Subtitle appears just below Title field, differs from Title in font styling only. On some channels may be combined with the [title](#title) or [text](#text). */
subtitle: string;
/** Text field appears just below subtitle, differs from Subtitle in font styling only. */
text: string;
/** Image to display on the card. Some channels may either send the image as a seperate message or simply include a link to the image. */
image: ICardImage;
/** Amount with currency. */
price: string;
/** Number of items of given kind. */
quantity: string;
/** This action will be activated when user taps on the Item bubble. Not all channels support tap actions. */
tap: ICardAction;
}
/** Implemented by classes that can be converted into a receipt item. */
export interface IIsReceiptItem {
/** Returns the JSON object for the receipt item. */
toItem(): IReceiptItem;
}
/** The action that should be performed when a card, button, or image is tapped. */
export interface ICardAction {
/** Defines the type of action implemented by this button. Not all action types are supported by all channels. */
type: string;
/** Text description for button actions. */
title?: string;
/** Parameter for Action. Content of this property depends on Action type. */
value: string;
/** (Optional) Picture to display for button actions. Not all channels support button images. */
image?: string;
}
/** Implemented by classes that can be converted into a card action. */
export interface IIsCardAction {
/** Returns the JSON object for the card attachment. */
toAction(): ICardAction;
}
/** An image on a card. */
export interface ICardImage {
/** Thumbnail image for major content property. */
url: string;
/** Image description intended for screen readers. Not all channels will support alt text. */
alt: string;
/** Action assigned to specific Attachment. E.g. navigate to specific URL or play/open media content. Not all channels will support tap actions. */
tap: ICardAction;
}
/** Implemented by classes that can be converted into a card image. */
export interface IIsCardImage {
/** Returns the JSON object for the card image. */
toImage(): ICardImage;
}
/** A fact displayed on a card like a [receipt](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ireceiptcard.html). */
export interface IFact {
/** Display name of the fact. */
key: string;
/** Display value of the fact. */
value: string;
}
/** Implemented by classes that can be converted into a fact. */
export interface IIsFact {
/** Returns the JSON object for the fact. */
toFact(): IFact;
}
/** Settings used to initialize an ILocalizer implementation. */
interface IDefaultLocalizerSettings {
/** The path to the parent of the bot's locale directory */
botLocalePath?: string;
/** The default locale of the bot */
defaultLocale?: string;
}
/** Plugin for localizing messages sent to the user by a bot. */
export interface ILocalizer {
/**
* Loads the localied table for the supplied locale, and call's the supplied callback once the load is complete.
* @param locale The locale to load.
* @param callback callback that is called once the supplied locale has been loaded, or an error if the load fails.
*/
load(locale: string, callback: (err: Error) => void): void;
/**
* Loads a localized string for the specified language.
* @param locale Desired locale of the string to return.
* @param msgid String to use as a key in the localized string table. Typically this will just be the english version of the string.
* @param namespace (Optional) namespace for the msgid keys.
*/
trygettext(locale: string, msgid: string, namespace?: string): string;
/**
* Loads a localized string for the specified language.
* @param locale Desired locale of the string to return.
* @param msgid String to use as a key in the localized string table. Typically this will just be the english version of the string.
* @param namespace (Optional) namespace for the msgid keys.
*/
gettext(locale: string, msgid: string, namespace?: string): string;
/**
* Loads the plural form of a localized string for the specified language.
* @param locale Desired locale of the string to return.
* @param msgid Singular form of the string to use as a key in the localized string table.
* @param msgid_plural Plural form of the string to use as a key in the localized string table.
* @param count Count to use when determining whether the singular or plural form of the string should be used.
* @param namespace (Optional) namespace for the msgid and msgid_plural keys.
*/
ngettext(locale: string, msgid: string, msgid_plural: string, count: number, namespace?: string): string;
}
/** Persisted session state used to track a conversations dialog stack. */
export interface ISessionState {
/** Dialog stack for the current session. */
callstack: IDialogState[];
/** Timestamp of when the session was last accessed. */
lastAccess: number;
/** Version number of the current callstack. */
version: number;
}
/** An entry on the sessions dialog stack. */
export interface IDialogState {
/** ID of the dialog. */
id: string;
/** Persisted state for the dialog. */
state: any;
}
/**
* Results returned by a child dialog to its parent via a call to session.endDialog().
*/
export interface IDialogResult<T> {
/** The reason why the current dialog is being resumed. Defaults to {ResumeReason.completed} */
resumed?: ResumeReason;
/** ID of the child dialog thats ending. */
childId?: string;
/** If an error occured the child dialog can return the error to the parent. */
error?: Error;
/** The users response. */
response?: T;
}
/** Context of the received message passed to the Dialog.recognize() method. */
export interface IRecognizeContext {
/** Message that was received. */
message: IMessage;
/** The users preferred locale for the message. */
locale: string;
/** If true the Dialog is the active dialog on the callstack. */
activeDialog: boolean;
/** Data persisted for the current dialog. */
dialogData: any;
}
/** Results from a call to a recognize() function. The implementation is free to add any additional properties to the result. */
export interface IRecognizeResult {
/** Confidence that the users utterance was understood on a scale from 0.0 - 1.0. */
score: number;
}
/** Options passed when binding a dialog action handler. */
export interface IDialogActionOptions {
/** (Optional) regular expression that should be matched against the users utterance to trigger an action. If this is ommitted the action can only be invoked from a button. */
matches?: RegExp;
/** Minimum score needed to trigger the action using the value of [expression](#expression). The default value is 0.1. */
intentThreshold?: number;
/** (Optional) arguments to pass to the dialog spawned when the action is triggered. */
dialogArgs?: any;
}
/** Results for a recognized dialog action. */
export interface IRecognizeActionResult extends IRecognizeResult {
/** Named dialog action that was matched. */
action?: string;
/** A regular expression that was matched. */
expression?: RegExp;
/** The results of the [expression](#expression) that was matched. matched[0] will be the text that was matched and matched[1...n] is the result of capture groups. */
matched?: string[];
/** Optional data passed as part of the action binding. */
data?: string;
/** ID of the dialog the action is bound to. */
dialogId?: string;
/** Index on the dialog stack of the dialog the action is bound to. */
dialogIndex?: number;
}
/** Options passed to built-in prompts. */
export interface IPromptOptions {
/**
* (Optional) retry prompt to send if the users response isn't understood. Default is to just
* reprompt with the configured [defaultRetryPrompt](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ipromptsoptions.html#defaultretryprompt)
* plus the original prompt.
*
* Note that if the original prompt is an _IMessage_ the retry prompt will be sent as a seperate
* message followed by the original message. If the retryPrompt is also an _IMessage_ it will
* instead be sent in place of the original message.
* * _{string}_ - Initial message to send the user.
* * _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * _{IMessage}_ - Initial message to send the user. Message can contain attachments.
* * _{IIsMessage}_ - Instance of the [Message](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.message.html) builder class.
*/
retryPrompt?: string|string[]|IMessage|IIsMessage;
/** (Optional) maximum number of times to reprompt the user. By default the user will be reprompted indefinitely. */
maxRetries?: number;
/** (Optional) reference date when recognizing times. Date expressed in ticks using Date.getTime(). */
refDate?: number;
/** (Optional) type of list to render for PromptType.choice. Default value is ListStyle.auto. */
listStyle?: ListStyle;
/** (Optional) flag used to control the reprompting of a user after a dialog started by an action ends. The default value is true. */
promptAfterAction?: boolean;
/** (Optional) namespace to use when localizing a passed in prompt. */
localizationNamespace?: string;
}
/** Arguments passed to the built-in prompts beginDialog() call. */
export interface IPromptArgs extends IPromptOptions {
/** Type of prompt invoked. */
promptType: PromptType;
/**
* Initial message to send to user.
* * _{string}_ - Initial message to send the user.
* * _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * _{IMessage}_ - Initial message to send the user. Message can contain attachments.
* * _{IIsMessage}_ - Instance of the [Message](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.message.html) builder class.
*/
prompt: string|string[]|IMessage|IIsMessage;
/** Enum values for a choice prompt. */
enumsValues?: string[];
}
/** Dialog result returned by a system prompt. */
export interface IPromptResult<T> extends IDialogResult<T> {
/** Type of prompt completing. */
promptType?: PromptType;
}
/** Result returned from an IPromptRecognizer. */
export interface IPromptRecognizerResult<T> extends IPromptResult<T> {
/** Returned from a prompt recognizer to indicate that a parent dialog handled (or captured) the utterance. */
handled?: boolean;
}
/** Strongly typed Text Prompt Result. */
export interface IPromptTextResult extends IPromptResult<string> { }
/** Strongly typed Number Prompt Result. */
export interface IPromptNumberResult extends IPromptResult<number> { }
/** Strongly typed Confirm Prompt Result. */
export interface IPromptConfirmResult extends IPromptResult<boolean> { }
/** Strongly typed Choice Prompt Result. */
export interface IPromptChoiceResult extends IPromptResult<IFindMatchResult> { }
/** Strongly typed Time Prompt Result. */
export interface IPromptTimeResult extends IPromptResult<IEntity> { }
/** Strongly typed Attachment Prompt Result. */
export interface IPromptAttachmentResult extends IPromptResult<IAttachment[]> { }
/** Plugin for recognizing prompt responses received by a user. */
export interface IPromptRecognizer {
/**
* Attempts to match a users reponse to a given prompt.
* @param args Arguments passed to the recognizer including that language, text, and prompt choices.
* @param callback Function to invoke with the result of the recognition attempt.
* @param callback.result Returns the result of the recognition attempt.
*/
recognize<T>(args: IPromptRecognizerArgs, callback: (result: IPromptRecognizerResult<T>) => void): void;
}
/** Arguments passed to the IPromptRecognizer.recognize() method.*/
export interface IPromptRecognizerArgs {
/** Type of prompt being responded to. */
promptType: PromptType;
/** Text of the users response to the prompt. */
text: string;
/** Language of the text if known. */
language?: string;
/** For choice prompts the list of possible choices. */
enumValues?: string[];
/** (Optional) reference date when recognizing times. */
refDate?: number;
}
/** Global configuration options for the Prompts dialog. */
export interface IPromptsOptions {
/** Replaces the default recognizer (SimplePromptRecognizer) used to recognize prompt replies. */
recognizer?: IPromptRecognizer
}
/** A recognized intent. */
export interface IIntent {
/** Intent that was recognized. */
intent: string;
/** Confidence on a scale from 0.0 - 1.0 that the proper intent was recognized. */
score: number;
}
/** A recognized entity. */
export interface IEntity {
/** Type of entity that was recognized. */
type: string;
/** Value of the recognized entity. */
entity: string;
/** Start position of entity within text utterance. */
startIndex?: number;
/** End position of entity within text utterance. */
endIndex?: number;
/** Confidence on a scale from 0.0 - 1.0 that the proper entity was recognized. */
score?: number;
}
/** Options used to configure an [IntentDialog](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.intentdialog.html). */
export interface IIntentDialogOptions {
/** Minimum score needed to trigger the recognition of an intent. The default value is 0.1. */
intentThreshold?: number;
/** Controls the dialogs processing of incomming user utterances. The default is RecognizeMode.onBeginIfRoot. The default prior to v3.2 was RecognizeMode.onBegin. */
recognizeMode?: RecognizeMode;
/** The order in which the configured [recognizers](#recognizers) should be evaluated. The default order is parallel. */
recognizeOrder?: RecognizeOrder;
/** (Optional) list of intent recognizers to run the users utterance through. */
recognizers?: IIntentRecognizer[];
/** Maximum number of recognizers to evaluate at one time when [recognizerOrder](#recognizerorder) is parallel. */
processLimit?: number;
}
/** export interface implemented by intent recognizers like the LuisRecognizer class. */
export interface IIntentRecognizer {
/** Attempts to match a users text utterance to an intent. */
recognize(context: IRecognizeContext, callback: (err: Error, result: IIntentRecognizerResult) => void): void;
}
/** Results returned by an intent recognizer. */
export interface IIntentRecognizerResult extends IRecognizeResult {
/** Top intent that was matched. */
intent: string;
/** A regular expression that was matched. */
expression?: RegExp;
/** The results of the [expression](#expression) that was matched. matched[0] will be the text that was matched and matched[1...n] is the result of capture groups. */
matched?: string[];
/** Full list of intents that were matched. */
intents?: IIntent[];
/** List of entities recognized. */
entities?: IEntity[];
}
/** Options passed to the constructor of a session. */
export interface ISessionOptions {
/** Function to invoke when the sessions state is saved. */
onSave: (done: (err: Error) => void) => void;
/** Function to invoke when a batch of messages are sent. */
onSend: (messages: IMessage[], done: (err: Error) => void) => void;
/** The bots root library of dialogs. */
library: Library;
/** The localizer to use for the session. */
localizer: ILocalizer;
/** Array of session middleware to execute prior to each request. */
middleware: ISessionMiddleware[];
/** Unique ID of the dialog to use when starting a new conversation with a user. */
dialogId: string;
/** (Optional) arguments to pass to the conversations initial dialog. */
dialogArgs?: any;
/** (Optional) time to allow between each message sent as a batch. The default value is 250ms. */
autoBatchDelay?: number;
/** Default error message to send users when a dialog error occurs. */
dialogErrorMessage?: string|string[]|IMessage|IIsMessage;
/** Global actions registered for the bot. */
actions?: ActionSet;
}
/** result returnd from a call to EntityRecognizer.findBestMatch() or EntityRecognizer.findAllMatches(). */
export interface IFindMatchResult {
/** Index of the matched value. */
index: number;
/** Value that was matched. */
entity: string;
/** Confidence score on a scale from 0.0 - 1.0 that an value matched the users utterance. */
score: number;
}
/** Context object passed to IBotStorage calls. */
export interface IBotStorageContext {
/** (Optional) ID of the user being persisted. If missing __userData__ won't be persisted. */
userId?: string;
/** (Optional) ID of the conversation being persisted. If missing __conversationData__ and __privateConversationData__ won't be persisted. */
conversationId?: string;
/** (Optional) Address of the message received by the bot. */
address?: IAddress;
/** If true IBotStorage should persist __userData__. */
persistUserData: boolean;
/** If true IBotStorage should persist __conversationData__. */
persistConversationData: boolean;
}
/** Data values persisted to IBotStorage. */
export interface IBotStorageData {
/** The bots data about a user. This data is global across all of the users conversations. */
userData?: any;
/** The bots shared data for a conversation. This data is visible to every user within the conversation. */
conversationData?: any;
/**
* The bots private data for a conversation. This data is only visible to the given user within the conversation.
* The session stores its session state using privateConversationData so it should always be persisted.
*/
privateConversationData?: any;
}
/** Replacable storage system used by UniversalBot. */
export interface IBotStorage {
/** Reads in data from storage. */
getData(context: IBotStorageContext, callback: (err: Error, data: IBotStorageData) => void): void;
/** Writes out data to storage. */
saveData(context: IBotStorageContext, data: IBotStorageData, callback?: (err: Error) => void): void;
}
/** Options used to initialize a ChatConnector instance. */
export interface IChatConnectorSettings {
/** The bots App ID assigned in the Bot Framework portal. */
appId?: string;
/** The bots App Password assigned in the Bot Framework Portal. */
appPassword?: string;
/** If true the bots userData, privateConversationData, and conversationData will be gzipped prior to writing to storage. */
gzipData?: boolean;
}
/** Options used to initialize a UniversalBot instance. */
export interface IUniversalBotSettings {
/** (Optional) dialog to launch when a user initiates a new conversation with a bot. Default value is '/'. */
defaultDialogId?: string;
/** (Optional) arguments to pass to the initial dialog for a conversation. */
defaultDialogArgs?: any;
/** (Optional) settings used to configure the frameworks built in default localizer. */
localizerSettings?: IDefaultLocalizerSettings;
/** (Optional) function used to map the user ID for an incoming message to another user ID. This can be used to implement user account linking. */
lookupUser?: (address: IAddress, done: (err: Error, user: IIdentity) => void) => void;
/** (Optional) maximum number of async options to conduct in parallel. */
processLimit?: number;
/** (Optional) time to allow between each message sent as a batch. The default value is 150ms. */
autoBatchDelay?: number;
/** (Optional) storage system to use for storing user & conversation data. */
storage?: IBotStorage;
/** (optional) if true userData will be persisted. The default value is true. */
persistUserData?: boolean;
/** (Optional) if true shared conversationData will be persisted. The default value is false. */
persistConversationData?: boolean;
/** (Optional) message to send the user should an unexpected error occur during a conversation. A default message is provided. */
dialogErrorMessage?: string|string[]|IMessage|IIsMessage;
}
/** Implemented by connector plugins for the UniversalBot. */
export interface IConnector {
/** Called by the UniversalBot at registration time to register a handler for receiving incoming events from a channel. */
onEvent(handler: (events: IEvent[], callback?: (err: Error) => void) => void): void;
/** Called by the UniversalBot to deliver outgoing messages to a user. */
send(messages: IMessage[], callback: (err: Error) => void): void;
/** Called when a UniversalBot wants to start a new proactive conversation with a user. The connector should return a properly formated __address__ object with a populated __conversation__ field. */
startConversation(address: IAddress, callback: (err: Error, address?: IAddress) => void): void;
}
/** Function signature for a piece of middleware that hooks the 'receive' or 'send' events. */
export interface IEventMiddleware {
(event: IEvent, next: Function): void;
}
/** Function signature for a piece of middleware that hooks the 'botbuilder' event. */
export interface ISessionMiddleware {
(session: Session, next: Function): void;
}
/**
* Map of middleware hooks that can be registered in a call to __UniversalBot.use()__.
*/
export interface IMiddlewareMap {
/** Called in series when an incoming event is received. */
receive?: IEventMiddleware|IEventMiddleware[];
/** Called in series before an outgoing event is sent. */
send?: IEventMiddleware|IEventMiddleware[];
/** Called in series once an incoming message has been bound to a session. Executed after [receive](#receive) middleware. */
botbuilder?: ISessionMiddleware|ISessionMiddleware[];
}
/**
* Signature for functions passed as steps to [DialogAction.waterfall()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialogaction.html#waterfall).
*
* Waterfalls let you prompt a user for information using a sequence of questions. Each step of the
* waterfall can either execute one of the built-in [Prompts](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.prompts.html),
* start a new dialog by calling [session.beginDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#begindialog),
* advance to the next step of the waterfall manually using `skip()`, or terminate the waterfall.
*
* When either a dialog or built-in prompt is called from a waterfall step, the results from that
* dialog or prompt will be passed via the `results` parameter to the next step of the waterfall.
* Users can say things like "nevermind" to cancel the built-in prompts so you should guard against
* that by at least checking for [results.response](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult.html#response)
* before proceeding. A more detailed explination of why the waterfall is being continued can be
* determined by looking at the [code](/en-us/node/builder/chat-reference/enums/_botbuilder_d_.resumereason.html)
* returned for [results.resumed](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult.html#resumed).
*
* You can manually advance to the next step of the waterfall using the `skip()` function passed
* in. Calling `skip({ response: "some text" })` with an [IDialogResult](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult.html)
* lets you more accurately mimic the results from a built-in prompt and can simplify your overall
* waterfall logic.
*
* You can terminate a waterfall early by either falling through every step of the waterfall using
* calls to `skip()` or simply not starting another prompt or dialog.
*
* __note:__ Waterfalls have a hidden last step which will automatically end the current dialog if
* if you call a prompt or dialog from the last step. This is useful where you have a deep stack of
* dialogs and want a call to [session.endDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#enddialog)
* from the last child on the stack to end the entire stack. The close of the last child will trigger
* all of its parents to move to this hidden step which will cascade the close all the way up the stack.
* This is typically a desired behaviour but if you want to avoid it or stop it somewhere in the
* middle you'll need to add a step to the end of your waterfall that either does nothing or calls
* something liek [session.send()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#send)
* which isn't going to advance the waterfall forward.
* @example
* <pre><code>
* var bot = new builder.BotConnectorBot();
* bot.add('/', [
* function (session) {
* builder.Prompts.text(session, "Hi! What's your name?");
* },
* function (session, results) {
* if (results && results.response) {
* // User answered question.
* session.send("Hello %s.", results.response);
* } else {
* // User said nevermind.
* session.send("OK. Goodbye.");
* }
* }
* ]);
* </code></pre>
*/
export interface IDialogWaterfallStep {
/**
* @param session Session object for the current conversation.
* @param result
* * __result:__ _{any}_ - For the first step of the waterfall this will be `null` or the value of any arguments passed to the handler.
* * __result:__ _{IDialogResult}_ - For subsequent waterfall steps this will be the result of the prompt or dialog called in the previous step.
* @param skip Fuction used to manually skip to the next step of the waterfall.
* @param skip.results (Optional) results to pass to the next waterfall step. This lets you more accurately mimic the results returned from a prompt or dialog.
*/
(session: Session, result?: any | IDialogResult<any>, skip?: (results?: IDialogResult<any>) => void): any;
}
/** A per/local mapping of LUIS service url's to use for a LuisRecognizer. */
export interface ILuisModelMap {
[local: string]: string;
}
/** A per/source mapping of custom event data to send. */
export interface ISourceEventMap {
[source: string]: any;
}
/** Options passed to Middleware.dialogVersion(). */
export interface IDialogVersionOptions {
/** Current major.minor version for the bots dialogs. Major version increments result in existing conversations between the bot and user being restarted. */
version: number;
/** Optional message to send the user when their conversation is ended due to a version number change. A default message is provided. */
message?: string|string[]|IMessage|IIsMessage;
/** Optional regular expression to listen for to manually detect a request to reset the users session state. */
resetCommand?: RegExp;
}
/** Options passed to Middleware.firstRun(). */
export interface IFirstRunOptions {
/** Current major.minor version for the bots first run experience. Major version increments result in redirecting users to [dialogId](#dialogid) and minor increments redirect users to [upgradeDialogId](#upgradedialogid). */
version: number;
/** Dialog to redirect users to when the major [version](#version) changes. */
dialogId: string;
/** (Optional) args to pass to [dialogId](#dialogid). */
dialogArgs?: any;
/** (Optional) dialog to redirect users to when the minor [version](#version) changes. Useful for minor Terms of Use changes. */
upgradeDialogId?: string;
/** (Optional) args to pass to [upgradeDialogId](#upgradedialogid). */
upgradeDialogArgs?: string;
}
//=============================================================================
//
// ENUMS
//
//=============================================================================
/** Reason codes for why a dialog was resumed. */
export enum ResumeReason {
/** The user completed the child dialog and a result was returned. */
completed,
/** The user did not complete the child dialog for some reason. They may have exceeded maxRetries or canceled. */
notCompleted,
/** The dialog was canceled in response to some user initiated action. */
canceled,
/** The user requested to return to the previous step in a dialog flow. */
back,
/** The user requested to skip the current step of a dialog flow. */
forward
}
/** Order in which an [IntentDialogs](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.intentdialog.html) recognizers should be evaluated. */
export enum RecognizeOrder {
/** All recognizers will be evaluated in parallel. */
parallel,
/** Recognizers will be evaluated in series. Any recognizer that returns a score of 1.0 will prevent the evaluation of the remaining recognizers. */
series
}
/** Controls an [IntentDialogs](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.intentdialog.html) processing of the users text utterances. */
export enum RecognizeMode {
/** Process text utterances whenever the dialog is first loaded through a call to session.beginDialog() and anytime a reply from the user is received. This was the default behaviour prior to version 3.2. */
onBegin,
/** Processes text utterances anytime a reply is received but only when the dialog is first loaded if it's the root dialog. This is the default behaviour as of 3.2. */
onBeginIfRoot,
/** Only process text utterances when a reply is received. */
onReply
}
/**
* Type of prompt invoked.
*/
export enum PromptType {
/** The user is prompted for a string of text. */
text,
/** The user is prompted to enter a number. */
number,
/** The user is prompted to confirm an action with a yes/no response. */
confirm,
/** The user is prompted to select from a list of choices. */
choice,
/** The user is prompted to enter a time. */
time,
/** The user is prompted to upload an attachment. */
attachment
}
/** Type of list to render for PromptType.choice prompt. */
export enum ListStyle {
/** No list is rendered. This is used when the list is included as part of the prompt. */
none,
/** Choices are rendered as an inline list of the form "1. red, 2. green, or 3. blue". */
inline,
/** Choices are rendered as a numbered list. */
list,
/** Choices are rendered as buttons for channels that support buttons. For other channels they will be rendered as text. */
button,
/** The style is selected automatically based on the channel and number of options. */
auto
}
/** Identifies the type of text being sent in a message. */
export var TextFormat: {
/** Text fields should be treated as plain text. */
plain: string;
/** Text fields may contain markdown formatting information. */
markdown: string;
/** Text fields may contain xml formatting information. */
xml: string;
};
/** Identities how the client should render attachments for a message. */
export var AttachmentLayout: {
/** Attachments should be rendred as a list. */
list: string;
/** Attachments should be rendered as a carousel. */
carousel: string;
};
//=============================================================================
//
// CLASSES
//
//=============================================================================
/**
* Manages the bots conversation with a user.
*/
export class Session {
/**
* Registers an event listener.
* @param event Name of the event. Event types:
* - __error:__ An error occured. Passes a JavaScript `Error` object.
* @param listener Function to invoke.
* @param listener.data The data for the event. Consult the list above for specific types of data you can expect to receive.
*/
on(event: string, listener: (data: any) => void): void;
/**
* Creates an instance of the session.
* @param options Sessions configuration options.
*/
constructor(options: ISessionOptions);
/**
* Dispatches a message for processing. The session will call any installed middleware before
* the message to the active dialog for processing.
* @param sessionState The current session state. If _null_ a new conversation will be started beginning with the configured [dialogId](#dialogid).
* @param message The message to dispatch.
*/
dispatch(sessionState: ISessionState, message: IMessage): Session;
/** The bots root library of dialogs. */
library: Library;
/** Sessions current state information. */
sessionState: ISessionState;
/** The message received from the user. For bot originated messages this may only contain the "to" & "from" fields. */
message: IMessage;
/** Data for the user that's persisted across all conversations with the bot. */
userData: any;
/** Shared conversation data that's visible to all members of the conversation. */
conversationData: any;
/** Private conversation data that's only visible to the user. */
privateConversationData: any;
/** Data that's only visible to the current dialog. */
dialogData: any;
/** The localizer (if available) to use. */
localizer:ILocalizer ;
/**
* Signals that an error occured. The bot will signal the error via an on('error', err) event.
* @param err Error that occured.
*/
error(err: Error): Session;
/**
* Returns the preferred locale when no parameters are supplied, otherwise sets the preferred locale.
* @param locale (Optional) the locale to use for localizing messages.
* @param callback (Optional) function called when the localization table has been loaded for the supplied locale.
*/
preferredLocale(locale?: string, callback?: (err: Error) => void): string;
/**
* Loads a localized string for the messages language. If arguments are passed the localized string
* will be treated as a template and formatted using [sprintf-js](https://github.com/alexei/sprintf.js) (see their docs for details.)
* @param msgid String to use as a key in the localized string table. Typically this will just be the english version of the string.
* @param args (Optional) arguments used to format the final output string.
*/
gettext(msgid: string, ...args: any[]): string;
/**
* Loads the plural form of a localized string for the messages language. The output string will be formatted to
* include the count by replacing %d in the string with the count.
* @param msgid Singular form of the string to use as a key in the localized string table. Use %d to specify where the count should go.
* @param msgid_plural Plural form of the string to use as a key in the localized string table. Use %d to specify where the count should go.
* @param count Count to use when determining whether the singular or plural form of the string should be used.
*/
ngettext(msgid: string, msgid_plural: string, count: number): string;
/** Triggers saving of changes made to [dialogData](#dialogdata), [userData](#userdata), [conversationdata](#conversationdata), or [privateConversationData'(#privateconversationdata). */
save(): Session;
/**
* Sends a message to the user.
* @param message
* * __message:__ _{string}_ - Text of the message to send. The message will be localized using the sessions configured localizer. If arguments are passed in the message will be formatted using [sprintf-js](https://github.com/alexei/sprintf.js).
* * __message:__ _{string[]}_ - The sent message will be chosen at random from the array.
* * __message:__ _{IMessage|IIsMessage}_ - Message to send.
* @param args (Optional) arguments used to format the final output text when __message__ is a _{string|string[]}_.
*/
send(message: string|string[]|IMessage|IIsMessage, ...args: any[]): Session;
/**
* Sends the user an indication that the bot is typing. For long running operations this should be called every few seconds.
*/
sendTyping(): Session;
/**
* Returns true if a message has been sent for this session.
*/
messageSent(): boolean;
/**
* Passes control of the conversation to a new dialog. The current dialog will be suspended
* until the child dialog completes. Once the child ends the current dialog will receive a
* call to [dialogResumed()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialog.html#dialogresumed)
* where it can inspect any results returned from the child.
* @param id Unique ID of the dialog to start.
* @param args (Optional) arguments to pass to the dialogs [begin()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialog.html#begin) method.
*/
beginDialog<T>(id: string, args?: T): Session;
/**
* Ends the current dialog and starts a new one its place. The parent dialog will not be
* resumed until the new dialog completes.
* @param id Unique ID of the dialog to start.
* @param args (Optional) arguments to pass to the dialogs [begin()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialog.html#begin) method.
*/
replaceDialog<T>(id: string, args?: T): Session;
/**
* Ends the current conversation and optionally sends a message to the user.
* @param message (Optional)
* * __message:__ _{string}_ - Text of the message to send. The message will be localized using the sessions configured localizer. If arguments are passed in the message will be formatted using [sprintf-js](https://github.com/alexei/sprintf.js).
* * __message:__ _{string[]}_ - The sent message will be chosen at random from the array.
* * __message:__ _{IMessage|IIsMessage}_ - Message to send.
* @param args (Optional) arguments used to format the final output text when __message__ is a _{string|string[]}_.
*/
endConversation(message?: string|string[]|IMessage|IIsMessage, ...args: any[]): Session;
/**
* Ends the current dialog and optionally sends a message to the user. The parent will be resumed with an [IDialogResult.resumed](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult.html#resumed)
* reason of [completed](/en-us/node/builder/chat-reference/enums/_botbuilder_d_.resumereason.html#completed).
* @param message (Optional)
* * __message:__ _{string}_ - Text of the message to send. The message will be localized using the sessions configured localizer. If arguments are passed in the message will be formatted using [sprintf-js](https://github.com/alexei/sprintf.js).
* * __message:__ _{string[]}_ - The sent message will be chosen at random from the array.
* * __message:__ _{IMessage|IIsMessage}_ - Message to send.
* @param args (Optional) arguments used to format the final output text when __message__ is a _{string|string[]}_.
*/
endDialog(message?: string|string[]|IMessage|IIsMessage, ...args: any[]): Session;
/**
* Ends the current dialog and optionally returns a result to the dialogs parent.
*/
endDialogWithResult<T>(result?: IDialogResult<T>): Session;
/**
* Cancels an existing dialog and optionally starts a new one it its place. Unlike [endDialog()](#enddialog)
* and [replaceDialog()](#replacedialog) which affect the current dialog, this method lets you end a
* parent dialog anywhere on the stack. The parent of the canceled dialog will be continued as if the
* dialog had called endDialog(). A special [ResumeReason.canceled](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.resumereason#canceled)
* will be returned to indicate that the dialog was canceled.
* @param dialogId
* * __dialogId:__ _{string}_ - ID of the dialog to end. If multiple occurences of the dialog exist on the dialog stack, the last occurance will be canceled.
* * __dialogId:__ _{number}_ - Index of the dialog on the stack to cancel. This is the preferred way to cancel a dialog from an action handler as it ensures that the correct instance is canceled.
* @param replaceWithId (Optional) specifies an ID to start in the canceled dialogs place. This prevents the dialogs parent from being resumed.
* @param replaceWithArgs (Optional) arguments to pass to the new dialog.
*/
cancelDialog(dialogId: string|number, replaceWithId?: string, replaceWithArgs?: any): Session;
/**
* Clears the sessions callstack and restarts the conversation with the configured dialogId.
* @param dialogId (Optional) ID of the dialog to start.
* @param dialogArgs (Optional) arguments to pass to the dialogs [begin()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialog.html#begin) method.
*/
reset(dialogId?: string, dialogArgs?: any): Session;
/** Returns true if the session has been reset. */
isReset(): boolean;
/**
* Immediately ends the current batch and delivers any queued up messages.
* @param callback (Optional) function called when the batch was either successfully delievered or failed for some reason.
*/
sendBatch(callback?: (err: Error) => void): void;
}
/**
* Message builder class that simplifies building complex messages with attachments.
*/
export class Message implements IIsMessage {
/**
* Creates a new Message builder.
* @param session (Optional) will be used to populate the messages address and localize any text.
*/
constructor(session?: Session);
/** Language of the message. */
textLocale(locale: string): Message;
/** Format of text fields. */
textFormat(style: string): Message;
/** Sets the message text. */
text(text: string|string[], ...args: any[]): Message;
/** Conditionally set this message text given a specified count. */
ntext(msg: string|string[], msg_plural: string|string[], count: number): Message;
/** Composes a complex and randomized reply to the user. */
compose(prompts: string[][], ...args: any[]): Message;
/** Text to be displayed by as fall-back and as short description of the message content in e.g. list of recent conversations. */
summary(text: string|string[], ...args: any[]): Message;
/** Hint for how clients should layout multiple attachments. The default value is 'list'. */
attachmentLayout(style: string): Message;
/** Cards or images to send to the user. */
attachments(list: IAttachment[]|IIsAttachment[]): Message;
/**
* Adds an attachment to the message. See [IAttachment](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iattachment.html) for examples.
* @param attachment The attachment to add.
*/
addAttachment(attachment: IAttachment|IIsAttachment): Message;
/** Structured objects passed to the bot or user. */
entities(list: Object[]): Message;
/** Adds an entity to the message. */
addEntity(obj: Object): Message;
/** Address routing information for the message. Save this field to external storage somewhere to later compose a proactive message to the user. */
address(adr: IAddress): Message;
/** Timestamp of the message. If called will default the timestamp to (now). */
timestamp(time?: string): Message;
/** Message in original/native format of the channel for incoming messages. */
originalEvent(event: any): Message;
/** For outgoing messages can be used to pass source specific event data like custom attachments. */
sourceEvent(map: ISourceEventMap): Message;
/** Returns the JSON for the message. */
toMessage(): IMessage;
/** __DEPRECATED__ use [local()](#local) instead. */
setLanguage(language: string): Message;
/** __DEPRECATED__ use [text()](#text) instead. */
setText(session: Session, prompt: string|string[], ...args: any[]): Message;
/** __DEPRECATED__ use [ntext()](#ntext) instead. */
setNText(session: Session, msg: string, msg_plural: string, count: number): Message;
/** __DEPRECATED__ use [compose()](#compose) instead. */
composePrompt(session: Session, prompts: string[][], ...args: any[]): Message;
/** __DEPRECATED__ use [sourceEvent()](#sourceevent) instead. */
setChannelData(data: any): Message;
/**
* Selects a prompt at random.
* @param prompts Array of prompts to choose from. When prompts is type _string_ the prompt will simply be returned unmodified.
*/
static randomPrompt(prompts: string|string[]): string;
/**
* Combines an array of prompts into a single localized prompt and then optionally fills the
* prompts template slots with the passed in arguments.
* @param session Session object used to localize the individual prompt parts.
* @param prompts Array of prompt lists. Each entry in the array is another array of prompts
* which will be chosen at random. The combined output text will be space delimited.
* @param args (Optional) array of arguments used to format the output text when the prompt is a template.
*/
static composePrompt(session: Session, prompts: string[][], args?: any[]): string;
}
/** Builder class to simplify adding actions to a card. */
export class CardAction implements IIsCardAction {
/**
* Creates a new CardAction.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Type of card action. */
type(t: string): CardAction;
/** Title of the action. For buttons this will be the label of the button. For tap actions this may be used for accesibility purposes or shown on hover. */
title(text: string|string[], ...args: any[]): CardAction;
/** The actions value. */
value(v: string): CardAction;
/** For buttons an image to include next to the buttons label. Not supported by all channels. */
image(url: string): CardAction;
/** Returns the JSON for the action. */
toAction(): ICardAction;
/**
* Places a call to a phone number. The should include country code in +44/+1 format for Skype calls.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static call(session: Session, number: string, title?: string|string[]): CardAction;
/**
* Opens the specified URL.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static openUrl(session: Session, url: string, title?: string|string[]): CardAction;
/**
* Sends a message to the bot for processing in a way that's visible to all members of the conversation. For some channels this may get mapped to a [postBack](#postback).
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static imBack(session: Session, msg: string, title?: string|string[]): CardAction;
/**
* Sends a message to the bot for processing in a way that's hidden from all members of the conversation. For some channels this may get mapped to a [imBack](#imback).
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static postBack(session: Session, msg: string, title?: string|string[]): CardAction;
/**
* Plays the specified audio file to the user. Not currently supported for Skype.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static playAudio(session: Session, url: string, title?: string|string[]): CardAction;
/**
* Plays the specified video to the user. Not currently supported for Skype.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static playVideo(session: Session, url: string, title?: string|string[]): CardAction;
/**
* Opens the specified image in a native image viewer. For Skype only valid as a tap action on a CardImage.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static showImage(session: Session, url: string, title?: string|string[]): CardAction;
/**
* Downloads the specified file to the users device. Not currently supported for Skype.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
*/
static downloadFile(session: Session, url: string, title?: string|string[]): CardAction;
/**
* Binds a button or tap action to a named action registered for a dialog or globally off the bot.
*
* Can be used anywhere a [postBack](#postback) is valid. You may also statically bind a button
* to an action for something like Facebooks [Persistent Menus](https://developers.facebook.com/docs/messenger-platform/thread-settings/persistent-menu).
* The payload for the button should be `action?<action>` for actions without data or
* `action?<action>=<data>` for actions with data.
* @param session (Optional) Current session object for the conversation. If specified will be used to localize titles.
* @param action Name of the action to invoke when tapped.
* @param data (Optional) data to pass to the action when invoked. The [IRecognizeActionResult.data](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.irecognizeactionresult#data)
* property can be used to access this data. If using [beginDialogAction()](dlg./en-us/node/builder/chat-reference/classes/_botbuilder_d_.dialog#begindialogaction) this value will be passed
* as part of the dialogs initial arguments.
* @param title (Optional) title to assign when binding the action to a button.
*/
static dialogAction(session: Session, action: string, data?: string, title?: string|string[]): CardAction;
}
/** Builder class to simplify adding images to a card. */
export class CardImage implements IIsCardImage {
/**
* Creates a new CardImage.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** URL of the image to display. */
url(u: string): CardImage;
/** Alternate text of the image to use for accessibility pourposes. */
alt(text: string|string[], ...args: any[]): CardImage;
/** Action to take when the image is tapped. */
tap(action: ICardAction|IIsCardAction): CardImage;
/** Returns the JSON for the image. */
toImage(): ICardImage;
/** Creates a new CardImage for a given url. */
static create(session: Session, url: string): CardImage;
}
/** Card builder class that simplifies building thumbnail cards. */
export class ThumbnailCard implements IIsAttachment {
/**
* Creates a new ThumbnailCard.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Title of the Card. */
title(text: string|string[], ...args: any[]): ThumbnailCard;
/** Subtitle appears just below Title field, differs from Title in font styling only. */
subtitle(text: string|string[], ...args: any[]): ThumbnailCard;
/** Text field appears just below subtitle, differs from Subtitle in font styling only. */
text(text: string|string[], ...args: any[]): ThumbnailCard;
/** Messaging supports all media formats: audio, video, images and thumbnails as well to optimize content download. */
images(list: ICardImage[]|IIsCardImage[]): ThumbnailCard;
/** Set of actions applicable to the current card. Not all channels support buttons or cards with buttons. Some channels may choose to render the buttons using a custom keyboard. */
buttons(list: ICardAction[]|IIsCardAction[]): ThumbnailCard;
/** This action will be activated when user taps on the card. Not all channels support tap actions and some channels may choose to render the tap action as the titles link. */
tap(action: ICardAction|IIsCardAction): ThumbnailCard;
/** Returns the JSON for the card, */
toAttachment(): IAttachment;
}
/** Card builder class that simplifies building hero cards. Hero cards contain the same information as a thumbnail card, just with a larger more pronounced layout for the cards images. */
export class HeroCard extends ThumbnailCard {
/**
* Creates a new HeroCard.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
}
/** Card builder class that simplifies building signin cards. */
export class SigninCard implements IIsAttachment {
/**
* Creates a new SigninCard.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Title of the Card. */
text(prompts: string|string[], ...args: any[]): SigninCard;
/** Signin button label and link. */
button(title: string|string[], url: string): SigninCard;
/** Returns the JSON for the card, */
toAttachment(): IAttachment;
}
/** Card builder class that simplifies building receipt cards. */
export class ReceiptCard implements IIsAttachment {
/**
* Creates a new ReceiptCard.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Title of the Card. */
title(text: string|string[], ...args: any[]): ReceiptCard;
/** Array of receipt items. */
items(list: IReceiptItem[]|IIsReceiptItem[]): ReceiptCard;
/** Array of additional facts to display to user (shipping charges and such.) Not all facts will be displayed on all channels. */
facts(list: IFact[]|IIsFact[]): ReceiptCard;
/** This action will be activated when user taps on the card. Not all channels support tap actions. */
tap(action: ICardAction|IIsCardAction): ReceiptCard;
/** Total amount of money paid (or should be paid.) */
total(v: string): ReceiptCard;
/** Total amount of TAX paid (or should be paid.) */
tax(v: string): ReceiptCard;
/** Total amount of VAT paid (or should be paid.) */
vat(v: string): ReceiptCard;
/** Set of actions applicable to the current card. Not all channels support buttons and the number of allowed buttons varies by channel. */
buttons(list: ICardAction[]|IIsCardAction[]): ReceiptCard;
/** Returns the JSON for the card. */
toAttachment(): IAttachment;
}
/** Builder class to simplify adding items to a receipt card. */
export class ReceiptItem implements IIsReceiptItem {
/**
* Creates a new ReceiptItem.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Title of the item. */
title(text: string|string[], ...args: any[]): ReceiptItem;
/** Subtitle appears just below Title field, differs from Title in font styling only. On some channels may be combined with the [title](#title) or [text](#text). */
subtitle(text: string|string[], ...args: any[]): ReceiptItem;
/** Text field appears just below subtitle, differs from Subtitle in font styling only. */
text(text: string|string[], ...args: any[]): ReceiptItem;
/** Image to display on the card. Some channels may either send the image as a seperate message or simply include a link to the image. */
image(img: ICardImage|IIsCardImage): ReceiptItem;
/** Amount with currency. */
price(v: string): ReceiptItem;
/** Number of items of given kind. */
quantity(v: string): ReceiptItem;
/** This action will be activated when user taps on the Item bubble. Not all channels support tap actions. */
tap(action: ICardAction|IIsCardAction): ReceiptItem;
/** Returns the JSON for the item. */
toItem(): IReceiptItem;
/** Creates a new ReceiptItem. */
static create(session: Session, price: string, title?: string|string[]): ReceiptItem;
}
/** Builder class to simplify creating a list of facts for a card like a receipt. */
export class Fact implements IIsFact {
/**
* Creates a new Fact.
* @param session (Optional) will be used to localize any text.
*/
constructor(session?: Session);
/** Display name of the fact. */
key(text: string|string[], ...args: any[]): Fact;
/** Display value of the fact. */
value(v: string): Fact;
/** Returns the JSON for the fact. */
toFact(): IFact;
/** Creates a new Fact. */
static create(session: Session, value: string, key?: string|string[]): Fact;
}
/**
* Implement support for named actions which can be bound to a dialog to handle global utterances from the user like "help" or
* "cancel". Actions get pushed onto and off of the dialog stack as part of dialogs so these listeners can
* come into and out of scope as the conversation progresses. You can also bind named to actions to buttons
* which let your bot respond to button clicks on cards that have maybe scrolled off the screen.
*/
export class ActionSet {
/**
* Called to recognize any actions triggered by the users utterance.
* @param message The message received from the user.
* @param callback Function to invoke with the results of the recognition. The top scoring action, if any, will be returned.
*/
recognizeAction(message: IMessage, callback: (err: Error, result: IRecognizeActionResult) => void): void;
/**
* Invokes an action that had the highest confidence score for the utterance.
* @param session Session object for the current conversation.
* @param recognizeResult Results returned from call to [recognizeAction()](#recognizeaction).
*/
invokeAction(session: Session, recognizeResult: IRecognizeActionResult): void;
}
/**
* Base class for all dialogs. Dialogs are the core component of the BotBuilder
* framework. Bots use Dialogs to manage arbitrarily complex conversations with
* a user.
*/
export abstract class Dialog extends ActionSet {
/**
* Called when a new dialog session is being started.
* @param session Session object for the current conversation.
* @param args (Optional) arguments passed to the dialog by its parent.
*/
begin<T>(session: Session, args?: T): void;
/**
* Called when a new reply message has been received from a user.
*
* Derived classes should implement this to process the message received from the user.
* @param session Session object for the current conversation.
* @param recognizeResult Results returned from a prior call to the dialogs [recognize()](#recognize) method.
*/
abstract replyReceived(session: Session, recognizeResult: IRecognizeResult): void;
/**
* A child dialog has ended and the current one is being resumed.
* @param session Session object for the current conversation.
* @param result Result returned by the child dialog.
*/
dialogResumed<T>(session: Session, result: IDialogResult<T>): void;
/**
* Parses the users utterance and assigns a score from 0.0 - 1.0 indicating how confident the
* dialog is that it understood the users utterance. This method is always called for the active
* dialog on the stack. A score of 1.0 will indicate a perfect match and terminate any further
* recognition.
*
* When the score is less than 1.0, every dialog on the stack will have its
* [recognizeAction()](#recognizeaction) method called as well to see if there are any named
* actions bound to the dialog that better matches the users utterance. Global actions registered
* at the bot level will also be evaluated. If the dialog has a score higher then any bound actions,
* the dialogs [replyReceived()](#replyreceived) method will be called with the result object
* returned from the recognize() call. This lets the dialog pass additional data collected during
* the recognize phase to the replyReceived() method for handling.
*
* Should there be an action with a higher score then the dialog the action will be invoked instead
* of the dialogs replyReceived() method. The dialog will stay on the stack and may be resumed
* at some point should the action invoke a new dialog so dialogs should prepare for unexpected calls
* to [dialogResumed()](#dialogresumed).
* @param context The context of the request.
* @param callback Function to invoke with the recognition results.
*/
recognize(context: IRecognizeContext, callback: (err: Error, result: IRecognizeResult) => void): void;
/**
* Binds an action to the dialog that will cancel the dialog anytime its triggered. When canceled, the
* dialogs parent will be resumed with a [resumed](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult#resumed) code indicating that it was [canceled](/en-us/node/builder/chat-reference/enums/_botbuilder_d_.resumereason#canceled).
* @param name Unique name to assign the action.
* @param msg (Optional) message to send the user prior to canceling the dialog.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action.
*/
cancelAction(name: string, msg?: string|string[]|IMessage|IIsMessage, options?: IDialogActionOptions): Dialog;
/**
* Binds an action to the dialog that will cause the dialog to be reloaded anytime its triggered. This is
* useful to implement logic that handle user utterances like "start over".
* @param name Unique name to assign the action.
* @param msg (Optional) message to send the user prior to reloading the dialog.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action. You can also use [dialogArgs](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#dialogargs) to pass additional params to the dialog when reloaded.
*/
reloadAction(name: string, msg?: string|string[]|IMessage|IIsMessage, options?: IDialogActionOptions): Dialog;
/**
* Binds an action to the dialog that will start another dialog anytime its triggered. The new
* dialog will be pushed onto the stack so it does not automatically end the current task. The
* current task will be continued once the new dialog ends. The built-in prompts will automatically
* re-prompt the user once this happens but that behaviour can be disabled by setting the [promptAfterAction](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ipromptoptions#promptafteraction)
* flag when calling a built-in prompt.
* @param name Unique name to assign the action.
* @param id ID of the dialog to start.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action. You can also use [dialogArgs](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#dialogargs) to pass additional params to the dialog being started.
*/
beginDialogAction(name: string, id: string, options?: IDialogActionOptions): Dialog;
/**
* Binds an action that will end the conversation with the user when triggered.
* @param name Unique name to assign the action.
* @param msg (Optional) message to send the user prior to ending the conversation.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action.
*/
endConversationAction(name: string, msg?: string|string[]|IMessage|IIsMessage, options?: IDialogActionOptions): Dialog;
}
/**
* Dialog actions offer static shortcuts to implementing common actions. They also implement support for
* named actions which can be bound to a dialog to handle global utterances from the user like "help" or
* "cancel". Actions get pushed onto and off of the dialog stack as part of dialogs so these listeners can
* come into and out of scope as the conversation progresses. You can also bind named to actions to buttons
* which let your bot respond to button clicks on cards that have maybe scrolled off the screen.
*/
export class DialogAction {
/**
* Returns a closure that will send a simple text message to the user.
* @param msg Text of the message to send. The message will be localized using the sessions configured [localizer](#localizer). If arguments are passed in the message will be formatted using [sprintf-js](https://github.com/alexei/sprintf.js) (see the docs for details.)
* @param args (Optional) arguments used to format the final output string.
*/
static send(msg: string, ...args: any[]): IDialogWaterfallStep;
/**
* Returns a closure that will passes control of the conversation to a new dialog.
* @param id Unique ID of the dialog to start.
* @param args (Optional) arguments to pass to the dialogs begin() method.
*/
static beginDialog<T>(id: string, args?: T): IDialogWaterfallStep;
/**
* Returns a closure that will end the current dialog.
* @param result (Optional) results to pass to the parent dialog.
*/
static endDialog(result?: any): IDialogWaterfallStep;
/**
* Returns a closure that wraps a built-in prompt with validation logic. The closure should be used
* to define a new dialog for the prompt using bot.add('/myPrompt', builder.DialogAction.)
* @param promptType Type of built-in prompt to validate.
* @param validator Function used to validate the response. Should return true if the response is valid.
* @param validator.response The users [IDialogResult.response](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogresult.html#response) returned by the built-in prompt.
* @example
* <pre><code>
* var bot = new builder.BotConnectorBot();
* bot.add('/', [
* function (session) {
* session.beginDialog('/meaningOfLife', { prompt: "What's the meaning of life?" });
* },
* function (session, results) {
* if (results.response) {
* session.send("That's correct! The meaning of life is 42.");
* } else {
* session.send("Sorry you couldn't figure it out. Everyone knows that the meaning of life is 42.");
* }
* }
* ]);
* bot.add('/meaningOfLife', builder.DialogAction.validatedPrompt(builder.PromptType.text, function (response) {
* return response === '42';
* }));
* </code></pre>
*/
static validatedPrompt(promptType: PromptType, validator: (response: any) => boolean): Dialog;
}
/**
* A library of related dialogs used for routing purposes. Libraries can be chained together to enable
* the development of complex bots. The [UniversalBot](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot.html)
* class is itself a Library that forms the root of this chain.
*
* Libraries of reusable parts can be developed by creating a new Library instance and adding dialogs
* just as you would to a bot. Your library should have a unique name that corresponds to either your
* libraries website or NPM module name. Bots can then reuse your library by simply adding your parts
* Library instance to their bot using [UniversalBot.library()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot.html#library).
* If your library itself depends on other libraries you should add them to your library as a dependency
* using [Library.library()](#library). You can easily manage multiple versions of your library by
* adding a version number to your library name.
*
* To invoke dialogs within your library bots will need to call [session.beginDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#begindialog)
* with a fully qualified dialog id in the form of '<libName>:<dialogId>'. You'll typically hide
* this from the devloper by exposing a function from their module that starts the dialog for them.
* So calling something like `myLib.someDialog(session, { arg: '' });` would end up calling
* `session.beginDialog('myLib:someDialog', args);` under the covers.
*
* Its worth noting that dialogs are always invoked within the current dialog so once your within
* a dialog from your library you don't need to prefix every beginDialog() call your with your
* libraries name. Its only when crossing from one library context to another that you need to
* include the library name prefix.
*/
export class Library {
/**
* The libraries unique namespace. This is used to issolate the libraries dialogs and localized
* prompts.
*/
name: string;
/**
* Creates a new instance of the library.
* @param name Unique namespace for the library.
*/
constructor(name: string);
/**
* Gets or sets the path to the libraries "/locale/" folder containing its localized prompts.
* The prompts for the library should be stored in a "/locale/<IETF_TAG>/<NAMESPACE>.json" file
* under this path where "<IETF_TAG>" representes the 2-3 digit language tage for the locale and
* "<NAMESPACE>" is a filename matching the libraries namespace.
* @param path (Optional) path to the libraries "/locale/" folder. If specified this will update the libraries path.
*/
localePath(path?: string): string;
/**
* Registers or returns a dialog from the library.
* @param id Unique ID of the dialog being regsitered or retrieved.
* @param dialog (Optional) dialog or waterfall to register.
* * __dialog:__ _{Dialog}_ - Dialog to add.
* * __dialog:__ _{IDialogWaterfallStep[]}_ - Waterfall of steps to execute. See [IDialogWaterfallStep](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogwaterfallstep.html) for details.
* * __dialog:__ _{IDialogWaterfallStep}_ - Single step waterfall. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
*/
dialog(id: string, dialog?: Dialog|IDialogWaterfallStep[]|IDialogWaterfallStep): Dialog;
/**
* Registers or returns a library dependency.
* @param lib
* * __lib:__ _{Library}_ - Library to register as a dependency.
* * __lib:__ _{string}_ - Unique name of the library to lookup. All dependencies will be searched as well.
*/
library(lib: Library|string): Library;
/**
* Searches the library and all of its dependencies for a specific dialog. Returns the dialog
* if found, otherwise null.
* @param libName Name of the library containing the dialog.
* @param dialogId Unique ID of the dialog within the library.
*/
findDialog(libName: string, dialogId: string): Dialog;
/**
* Enumerates all of the libraries child libraries. The caller should take appropriate steps to
* avoid circular references when enumerating the hierarchy. Maintaining a map of visited
* libraries should be enough.
* @param callback Iterator function to call with each child.
* @param callback.library The current child.
*/
forEachLibrary(callback: (library: Library) => void): void;
}
/**
* Built in built-in prompts that can be called from any dialog.
*/
export class Prompts extends Dialog {
/**
* Processes messages received from the user. Called by the dialog system.
* @param session Session object for the current conversation.
* @param (Optional) recognition results returned from a prior call to the dialogs [recognize()](#recognize) method.
*/
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
/**
* Updates global options for the Prompts dialog.
* @param options Options to set.
*/
static configure(options: IPromptsOptions): void;
/**
* Captures from the user a raw string of text.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static text(session: Session, prompt: string|string[]|IMessage|IIsMessage, options?: IPromptOptions): void;
/**
* Prompts the user to enter a number.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static number(session: Session, prompt: string|string[]|IMessage|IIsMessage, options?: IPromptOptions): void;
/**
* Prompts the user to confirm an action with a yes/no response.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static confirm(session: Session, prompt: string|string[]|IMessage|IIsMessage, options?: IPromptOptions): void;
/**
* Prompts the user to choose from a list of options.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments. Any [listStyle](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ipromptoptions.html#liststyle) options will be ignored.
* @param choices
* * __choices:__ _{string}_ - List of choices as a pipe ('|') delimted string.
* * __choices:__ _{Object}_ - List of choices expressed as an Object map. The objects field names will be used to build the list of values.
* * __choices:__ _{string[]}_ - List of choices as an array of strings.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static choice(session: Session, prompt: string|string[]|IMessage|IIsMessage, choices: string|Object|string[], options?: IPromptOptions): void;
/**
* Prompts the user to enter a time.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static time(session: Session, prompt: string|string[]|IMessage|IIsMessage, options?: IPromptOptions): void;
/**
* Prompts the user to upload a file attachment.
* @param session Session object for the current conversation.
* @param prompt
* * __prompt:__ _{string}_ - Initial message to send the user.
* * __prompt:__ _{string[]}_ - Array of possible messages to send user. One will be chosen at random.
* * __prompt:__ _{IMessage|IIsMessage}_ - Initial message to send the user. Message can contain attachments.
* @param options (Optional) parameters to control the behaviour of the prompt.
*/
static attachment(session: Session, prompt: string|string[]|IMessage|IIsMessage, options?: IPromptOptions): void;
}
/**
* Implements a simple pattern based recognizer for parsing the built-in prompts. Derived classes can
* inherit from SimplePromptRecognizer and override the recognize() method to change the recognition
* of one or more prompt types.
*/
export class SimplePromptRecognizer implements IPromptRecognizer {
/**
* Attempts to match a users reponse to a given prompt.
* @param args Arguments passed to the recognizer including that language, text, and prompt choices.
* @param callback Function to invoke with the result of the recognition attempt.
*/
recognize(args: IPromptRecognizerArgs, callback: (result: IPromptResult<any>) => void): void;
}
/** Identifies a users intent and optionally extracts entities from a users utterance. */
export class IntentDialog extends Dialog {
/**
* Constructs a new instance of an IntentDialog.
* @param options (Optional) options used to initialize the dialog.
*/
constructor(options?: IIntentDialogOptions);
/**
* Processes messages received from the user. Called by the dialog system.
* @param session Session object for the current conversation.
* @param (Optional) recognition results returned from a prior call to the dialogs [recognize()](#recognize) method.
*/
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
/**
* Called when the dialog is first loaded after a call to [session.beginDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session#begindialog). This gives the bot an opportunity to process arguments passed to the dialog. Handlers should always call the `next()` function to continue execution of the dialogs main logic.
* @param handler Function to invoke when the dialog begins.
* @param handler.session Session object for the current conversation.
* @param handler.args Arguments passed to the dialog in the `session.beginDialog()` call.
* @param handler.next Function to call when handler is finished to continue execution of the dialog.
*/
onBegin(handler: (session: Session, args: any, next: () => void) => void): IntentDialog;
/**
* Invokes a handler when a given intent is detected in the users utterance.
*
* > __NOTE:__ The full details of the match, including the list of intents & entities detected, will be passed to the [args](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iintentrecognizerresult) of the first waterfall step or dialog that's started.
* @param intent
* * __intent:__ _{RegExp}_ - A regular expression that will be evaluated to detect the users intent.
* * __intent:__ _{string}_ - A named intent returned by an [IIntentRecognizer](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iintentrecognizer) plugin that will be used to match the users intent.
* @param dialogId
* * __dialogId:__ _{string} - The ID of a dialog to begin when the intent is matched.
* * __dialogId:__ _{IDialogWaterfallStep[]}_ - Waterfall of steps to execute when the intent is matched.
* * __dialogId:__ _{IDialogWaterfallStep}_ - Single step waterfall to execute when the intent is matched. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
* @param dialogArgs (Optional) arguments to pass the dialog that started when `dialogId` is a _{string}_.
*/
matches(intent: RegExp|string, dialogId: string|IDialogWaterfallStep[]|IDialogWaterfallStep, dialogArgs?: any): IntentDialog;
/**
* Invokes a handler when any of the given intents are detected in the users utterance.
*
* > __NOTE:__ The full details of the match, including the list of intents & entities detected, will be passed to the [args](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iintentrecognizerresult) of the first waterfall step or dialog that's started.
* @param intent
* * __intent:__ _{RegExp[]}_ - Array of regular expressions that will be evaluated to detect the users intent.
* * __intent:__ _{string[]}_ - Array of named intents returned by an [IIntentRecognizer](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iintentrecognizer) plugin that will be used to match the users intent.
* @param dialogId
* * __dialogId:__ _{string} - The ID of a dialog to begin when the intent is matched.
* * __dialogId:__ _{IDialogWaterfallStep[]}_ - Waterfall of steps to execute when the intent is matched.
* * __dialogId:__ _{IDialogWaterfallStep}_ - Single step waterfall to execute when the intent is matched. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
* @param dialogArgs (Optional) arguments to pass the dialog that started when `dialogId` is a _{string}_.
*/
matchesAny(intent: RegExp[]|string[], dialogId: string|IDialogWaterfallStep[]|IDialogWaterfallStep, dialogArgs?: any): IntentDialog;
/**
* The default handler to invoke when there are no handlers that match the users intent.
*
* > __NOTE:__ The full details of the recognition attempt, including the list of intents & entities detected, will be passed to the [args](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iintentrecognizerresult) of the first waterfall step or dialog that's started.
* @param dialogId
* * __dialogId:__ _{string} - The ID of a dialog to begin.
* * __dialogId:__ _{IDialogWaterfallStep[]}_ - Waterfall of steps to execute.
* * __dialogId:__ _{IDialogWaterfallStep}_ - Single step waterfall to execute. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
* @param dialogArgs (Optional) arguments to pass the dialog that started when `dialogId` is a _{string}_.
*/
onDefault(dialogId: string|IDialogWaterfallStep[]|IDialogWaterfallStep, dialogArgs?: any): IntentDialog;
/**
* Adds a new recognizer plugin to the intent dialog.
* @param plugin The recognizer to add.
*/
recognizer(plugin: IIntentRecognizer): IntentDialog;
}
/**
* Routes incoming messages to a LUIS app hosted on http://luis.ai for intent recognition.
* Once a messages intent has been recognized it will rerouted to a registered intent handler, along
* with any entities, for further processing.
*/
export class LuisRecognizer implements IIntentRecognizer {
/**
* Constructs a new instance of a LUIS recognizer.
* @param models Either an individual LUIS model used for all utterances or a map of per/local models conditionally used depending on the local of the utterance.
*/
constructor(models: string|ILuisModelMap);
/** Called by the IntentDialog to perform the actual recognition. */
public recognize(context: IRecognizeContext, callback: (err: Error, result: IIntentRecognizerResult) => void): void;
/**
* Calls LUIS to recognizing intents & entities in a users utterance.
* @param utterance The text to pass to LUIS for recognition.
* @param serviceUri URI for LUIS App hosted on http://luis.ai.
* @param callback Callback to invoke with the results of the intent recognition step.
* @param callback.err Error that occured during the recognition step.
* @param callback.intents List of intents that were recognized.
* @param callback.entities List of entities that were recognized.
*/
static recognize(utterance: string, modelUrl: string, callback: (err: Error, intents?: IIntent[], entities?: IEntity[]) => void): void;
}
/**
* Utility class used to parse & resolve common entities like datetimes received from LUIS.
*/
export class EntityRecognizer {
/**
* Searches for the first occurance of a specific entity type within a set.
* @param entities Set of entities to search over.
* @param type Type of entity to find.
*/
static findEntity(entities: IEntity[], type: string): IEntity;
/**
* Finds all occurrences of a specific entity type within a set.
* @param entities Set of entities to search over.
* @param type Type of entity to find.
*/
static findAllEntities(entities: IEntity[], type: string): IEntity[];
/**
* Parses a date from either a users text utterance or a set of entities.
* @param value
* * __value:__ _{string}_ - Text utterance to parse. The utterance is parsed using the [Chrono](http://wanasit.github.io/pages/chrono/) library.
* * __value:__ _{IEntity[]}_ - Set of entities to resolve.
* @returns A valid Date object if the user spoke a time otherwise _null_.
*/
static parseTime(value: string | IEntity[]): Date;
/**
* Calculates a Date from a set of datetime entities.
* @param entities List of entities to extract date from.
* @returns The successfully calculated Date or _null_ if a date couldn't be determined.
*/
static resolveTime(entities: IEntity[]): Date;
/**
* Recognizes a time from a users utterance. The utterance is parsed using the [Chrono](http://wanasit.github.io/pages/chrono/) library.
* @param utterance Text utterance to parse.
* @param refDate (Optional) reference date used to calculate the final date.
* @returns An entity containing the resolved date if successful or _null_ if a date couldn't be determined.
*/
static recognizeTime(utterance: string, refDate?: Date): IEntity;
/**
* Parses a number from either a users text utterance or a set of entities.
* @param value
* * __value:__ _{string}_ - Text utterance to parse.
* * __value:__ _{IEntity[]}_ - Set of entities to resolve.
* @returns A valid number otherwise _Number.NaN_.
*/
static parseNumber(value: string | IEntity[]): number;
/**
* Parses a boolean from a users utterance.
* @param value Text utterance to parse.
* @returns A valid boolean otherwise _undefined_.
*/
static parseBoolean(value: string): boolean;
/**
* Finds the best match for a users utterance given a list of choices.
* @param choices
* * __choices:__ _{string}_ - Pipe ('|') delimited list of values to compare against the users utterance.
* * __choices:__ _{Object}_ - Object used to generate the list of choices. The objects field names will be used to build the list of choices.
* * __choices:__ _{string[]}_ - Array of strings to compare against the users utterance.
* @param utterance Text utterance to parse.
* @param threshold (Optional) minimum score needed for a match to be considered. The default value is 0.6.
*/
static findBestMatch(choices: string | Object | string[], utterance: string, threshold?: number): IFindMatchResult;
/**
* Finds all possible matches for a users utterance given a list of choices.
* @param choices
* * __choices:__ _{string}_ - Pipe ('|') delimited list of values to compare against the users utterance.
* * __choices:__ _{Object}_ - Object used to generate the list of choices. The objects field names will be used to build the list of choices.
* * __choices:__ _{string[]}_ - Array of strings to compare against the users utterance.
* @param utterance Text utterance to parse.
* @param threshold (Optional) minimum score needed for a match to be considered. The default value is 0.6.
*/
static findAllMatches(choices: string | Object | string[], utterance: string, threshold?: number): IFindMatchResult[];
/**
* Converts a set of choices into an expanded array.
* @param choices
* * __choices:__ _{string}_ - Pipe ('|') delimited list of values.
* * __choices:__ _{Object}_ - Object used to generate the list of choices. The objects field names will be used to build the list of choices.
* * __choices:__ _{string[]}_ - Array of strings. This will just be echoed back as the output.
*/
static expandChoices(choices: string | Object | string[]): string[];
}
/**
* Allows for the creation of custom dialogs that are based on a simple closure. This is useful for
* cases where you want a dynamic conversation flow or you have a situation that just doesn’t map
* very well to using a waterfall. The things to keep in mind:
* * Your dialogs closure is can get called in two different contexts that you potentially need to
* test for. It will get called as expected when the user send your dialog a message but if you
* call another prompt or dialog from your closure it will get called a second time with the
* results from the prompt/dialog. You can typically test for this second case by checking for the
* existant of an `args.resumed` property. It's important to avoid getting yourself into an
* infinite loop which can be easy to do.
* * Unlike a waterfall your dialog will not automatically end. It will remain the active dialog
* until you call [session.endDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#enddialog).
*/
export class SimpleDialog extends Dialog {
/**
* Creates a new custom dialog based on a simple closure.
* @param handler The function closure for your dialog.
* @param handler.session Session object for the current conversation.
* @param handler.args
* * __args:__ _{any}_ - For the first call to the handler this will be either `null` or the value of any arguments passed to [Session.beginDialog()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html#begindialog).
* * __args:__ _{IDialogResult}_ - If the handler takes an action that results in a new dialog being started those results will be returned via subsequent calls to the handler.
*/
constructor(handler: (session: Session, args?: any | IDialogResult<any>) => void);
/**
* Processes messages received from the user. Called by the dialog system.
* @param session Session object for the current conversation.
*/
replyReceived(session: Session): void;
}
/** Default in memory storage implementation for storing user & session state data. */
export class MemoryBotStorage implements IBotStorage {
/** Returns data from memmory for the given context. */
getData(context: IBotStorageContext, callback: (err: Error, data: IBotStorageData) => void): void;
/** Saves data to memory for the given context. */
saveData(context: IBotStorageContext, data: IBotStorageData, callback?: (err: Error) => void): void;
/** Deletes in-memory data for the given context. */
deleteData(context: IBotStorageContext): void;
}
/** Manages your bots conversations with users across multiple channels. */
export class UniversalBot {
/**
* Creates a new instance of the UniversalBot.
* @param connector (Optional) the default connector to use for requests. If there's not a more specific connector registered for a channel then this connector will be used./**
* @param settings (Optional) settings to configure the bot with.
*/
constructor(connector?: IConnector, settings?: IUniversalBotSettings);
/**
* Registers an event listener. The bot will emit its own events as it process incoming and outgoing messages. It will also forward activity related events emitted from the connector, giving you one place to listen for all activity from your bot. The flow of events from the bot is as follows:
*
* #### Message Received
* When the bot receives a new message it will emit the following events in order:
*
* > lookupUser -> receive -> incoming -> getStorageData -> routing
*
* Any [receive middleware](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imiddlewaremap#receive) that's been installed will be executed between the 'receive' and 'incoming' events. After the 'routing' event is emmited any
* [botbuilder middleware](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imiddlewaremap#botbuilder) will be executed prior to dispatching the message to the bots active dialog.
*
* #### Connector Activity Received
* Connectors can emit activity events to signal things like a user is typing or that they friended a bot. These activities get routed through middleware like messages but they are not routed through the bots dialog system. They are only ever emitted as events.
*
* The flow of connector events is:
*
* > lookupUser -> receive -> (activity)
*
* #### Message sent
* Bots can send multiple messages so the session will batch up all outgoing message and then save the bots current state before delivering the sent messages. You'll see a single 'saveStorageData' event emitted and then for every outgoing message in the batch you'll see the following
* sequence of events:
*
* > send -> outgoing
*
* Any [send middleware](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imiddlewaremap#send) that's been installed will be executed between the 'send' and 'outgoing' events.
*
* @param event Name of the event. Bot and connector specific event types:
* #### Bot Events
* - __error:__ An error occured. Passed a JavaScript `Error` object.
* - __lookupUser:__ The user is for an address is about to be looked up. Passed an [IAddress](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iaddress.html) object.
* - __receive:__ An incoming message has been received. Passed an [IEvent](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ievent.html) object.
* - __incoming:__ An incoming message has been received and processed by middleware. Passed an [IMessage](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imessage.html) object.
* - __routing:__ An incoming message has been bound to a session and is about to be routed through any session middleware and then dispatched to the active dialog for processing. Passed a [Session](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session.html) object.
* - __send:__ An outgoing message is about to be sent to middleware for processing. Passed an [IMessage](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.imessage.html) object.
* - __getStorageData:__ The sessions persisted state data is being loaded from storage. Passed an [IBotStorageContext](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ibotstoragecontext.html) object.
* - __saveStorageData:__ The sessions persisted state data is being written to storage. Passed an [IBotStorageContext](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ibotstoragecontext.html) object.
*
* #### ChatConnector Events
* - __conversationUpdate:__ Your bot was added to a conversation or other conversation metadata changed. Passed an [IConversationUpdate](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iconversationupdate.html) object.
* - __contactRelationUpdate:__ The bot was added to or removed from a user's contact list. Passed an [IContactRelationUpdate](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.icontactrelationupdate.html) object.
* - __typing:__ The user or bot on the other end of the conversation is typing. Passed an [IEvent](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ievent.html) object.
*
* @param listener Function to invoke.
* @param listener.data The data for the event. Consult the list above for specific types of data you can expect to receive.
*/
on(event: string, listener: (data: any) => void): void;
/**
* Sets a setting on the bot.
* @param name Name of the property to set. Valid names are properties on [IUniversalBotSettings](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iuniversalbotsettings.html).
* @param value The value to assign to the setting.
*/
set(name: string, value: any): UniversalBot;
/**
* Returns the current value of a setting.
* @param name Name of the property to return. Valid names are properties on [IUniversalBotSettings](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.iuniversalbotsettings.html).
*/
get(name: string): any;
/**
* Registers or returns a connector for a specific channel.
* @param channelId Unique ID of the channel. Use a channelId of '*' to reference the default connector.
* @param connector (Optional) connector to register. If ommited the connector for __channelId__ will be returned.
*/
connector(channelId: string, connector?: IConnector): IConnector;
/**
* Registers or returns a dialog for the bot.
* @param id Unique ID of the dialog being regsitered or retrieved.
* @param dialog (Optional) dialog or waterfall to register.
* * __dialog:__ _{Dialog}_ - Dialog to add.
* * __dialog:__ _{IDialogWaterfallStep[]}_ - Waterfall of steps to execute. See [IDialogWaterfallStep](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogwaterfallstep.html) for details.
* * __dialog:__ _{IDialogWaterfallStep}_ - Single step waterfall. Calling a built-in prompt or starting a new dialog will result in the current dialog ending upon completion of the child prompt/dialog.
*/
dialog(id: string, dialog?: Dialog|IDialogWaterfallStep[]|IDialogWaterfallStep): Dialog;
/**
* Registers or returns a library dependency.
* @param lib
* * __lib:__ _{Library}_ - Library to register as a dependency.
* * __lib:__ _{string}_ - Unique name of the library to lookup. All dependencies will be searched as well.
*/
library(lib: Library|string): Library;
/**
* Installs middleware for the bot. Middleware lets you intercept incoming and outgoing events/messages.
* @param args One or more sets of middleware hooks to install.
*/
use(...args: IMiddlewareMap[]): UniversalBot;
/**
* Called when a new event is received. This can be called manually to mimic the bot receiving a message from the user.
* @param events Event or (array of events) received.
* @param done (Optional) function to invoke once the operation is completed.
*/
receive(events: IEvent|IEvent[], done?: (err: Error) => void): void;
/**
* Proactively starts a new dialog with the user. Any current conversation between the bot and user will be replaced with a new dialog stack.
* @param address Address of the user to start a new conversation with. This should be saved during a previous conversation with the user. Any existing conversation or dialog will be immediately terminated.
* @param dialogId ID of the dialog to begin.
* @param dialogArgs (Optional) arguments to pass to dialog.
* @param done (Optional) function to invoke once the operation is completed.
*/
beginDialog(address: IAddress, dialogId: string, dialogArgs?: any, done?: (err: Error) => void): void;
/**
* Sends a message to the user without disrupting the current conversations dialog stack.
* @param messages The message (or array of messages) to send the user.
* @param done (Optional) function to invoke once the operation is completed.
*/
send(messages: IIsMessage|IMessage|IMessage[], done?: (err: Error) => void): void;
/**
* Returns information about when the last turn between the user and a bot occured. This can be called
* before [beginDialog](#begindialog) to determine if the user is currently in a conversation with the
* bot.
* @param address Address of the user to lookup. This should be saved during a previous conversation with the user.
* @param callback Function to invoke with the results of the query.
*/
isInConversation(address: IAddress, callback: (err: Error, lastAccess: Date) => void): void;
/**
* Registers a global action that will start another dialog anytime its triggered. The new
* dialog will be pushed onto the stack so it does not automatically end any current task. The
* current task will be continued once the new dialog ends. The built-in prompts will automatically
* re-prompt the user once this happens but that behaviour can be disabled by setting the [promptAfterAction](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.ipromptoptions#promptafteraction)
* flag when calling a built-in prompt.
* @param name Unique name to assign the action.
* @param id ID of the dialog to start.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action. You can also use [dialogArgs](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#dialogargs) to pass additional params to the dialog being started.
*/
beginDialogAction(name: string, id: string, options?: IDialogActionOptions): Dialog;
/**
* Registers a global action that will end the conversation with the user when triggered.
* @param name Unique name to assign the action.
* @param msg (Optional) message to send the user prior to ending the conversation.
* @param options (Optional) options used to configure the action. If [matches](/en-us/node/builder/chat-reference/interfaces/_botbuilder_d_.idialogactionoptions#matches) is specified the action will listen
* for the user to say a word or phrase that triggers the action, otherwise the action needs to be bound to a button using [CardAction.dialogAction()](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.cardaction#dialogaction)
* to trigger the action.
*/
endConversationAction(name: string, msg?: string|string[]|IMessage|IIsMessage, options?: IDialogActionOptions): Dialog;
}
/** Connects a UniversalBot to multiple channels via the Bot Framework. */
export class ChatConnector implements IConnector, IBotStorage {
/**
* Creates a new instnace of the ChatConnector.
* @param settings (Optional) config params that let you specify the bots App ID & Password you were assigned in the Bot Frameworks developer portal.
*/
constructor(settings?: IChatConnectorSettings);
/** Registers an Express or Restify style hook to listen for new messages. */
listen(): (req: any, res: any) => void;
/** Called by the UniversalBot at registration time to register a handler for receiving incoming events from a channel. */
onEvent(handler: (events: IEvent[], callback?: (err: Error) => void) => void): void;
/** Called by the UniversalBot to deliver outgoing messages to a user. */
send(messages: IMessage[], done: (err: Error) => void): void;
/** Called when a UniversalBot wants to start a new proactive conversation with a user. The connector should return a properly formated __address__ object with a populated __conversation__ field. */
startConversation(address: IAddress, done: (err: Error, address?: IAddress) => void): void;
/** Reads in data from the Bot Frameworks state service. */
getData(context: IBotStorageContext, callback: (err: Error, data: IBotStorageData) => void): void;
/** Writes out data to the Bot Frameworks state service. */
saveData(context: IBotStorageContext, data: IBotStorageData, callback?: (err: Error) => void): void;
}
/** Connects a UniversalBot to the command line via a console window. */
export class ConsoleConnector implements IConnector {
/** Starts the connector listening to stdIn. */
listen(): ConsoleConnector;
/** Sends a message through the connector. */
processMessage(line: string): ConsoleConnector;
/** Called by the UniversalBot at registration time to register a handler for receiving incoming events from a channel. */
onEvent(handler: (events: IEvent[], callback?: (err: Error) => void) => void): void;
/** Called by the UniversalBot to deliver outgoing messages to a user. */
send(messages: IMessage[], callback: (err: Error, conversationId?: string) => void): void;
/** Called when a UniversalBot wants to start a new proactive conversation with a user. The connector should return a properly formated __address__ object with a populated __conversation__ field. */
startConversation(address: IAddress, callback: (err: Error, address?: IAddress) => void): void;
}
export class Middleware {
/**
* Installs a piece of middleware that manages the versioning of a bots dialogs.
* @param options Settings to configure the bahviour of the installed middleware.
*/
static dialogVersion(options: IDialogVersionOptions): IMiddlewareMap;
/**
* Adds a first run experience to a bot. The middleware uses Session.userData to store the latest version of the first run dialog the user has been through. Incrementing the version number can force users to run back through either the full or a partial first run dialog.
* @param options Settings to configure the bahviour of the installed middleware.
*/
static firstRun(options: IFirstRunOptions): IMiddlewareMap;
/**
* Installs a piece of middleware that will always send an initial typing indication to the user.
* This is useful because it lets you send the typing indication before any LUIS models are called.
* The typing indicator will only stay valid for a few seconds so if you're performing any long running
* operations you may want to send an additional typing indicator using [session.sendTyping](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.session#sendtyping).
*/
static sendTyping(): IMiddlewareMap;
}
/** __DEPRECATED__ use an [IntentDialog](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.intentdialog) with a [LuisRecognizer](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.luisrecognizer) instead. */
export class LuisDialog extends Dialog {
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
}
/** __DEPRECATED__ use an [IntentDialog](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.intentdialog) instead. */
export class CommandDialog extends Dialog {
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
}
/** __DEPRECATED__ use [UniversalBot](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot) and a [ChatConnector](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.chatconnector) instead. */
export class BotConnectorBot extends Dialog {
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
}
/** __DEPRECATED__ use [UniversalBot](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.universalbot) and a [ConsoleConnector](/en-us/node/builder/chat-reference/classes/_botbuilder_d_.consoleconnector) instead. */
export class TextBot extends Dialog {
replyReceived(session: Session, recognizeResult?: IRecognizeResult): void;
} | the_stack |
import { PureComponent } from 'react'
import TagDisplay from 'src/components/Tags/TagDisplay/TagDisplay'
import { format } from 'date-fns'
import type { IHowtoDB } from 'src/models/howto.models'
import { Heading, Text, Box, Flex, Image } from 'theme-ui'
import { ModerationStatusText } from 'src/components/ModerationStatusText/ModerationStatustext'
import { FileInfo } from 'src/components/FileInfo/FileInfo'
import StepsIcon from 'src/assets/icons/icon-steps.svg'
import TimeNeeded from 'src/assets/icons/icon-time-needed.svg'
import DifficultyLevel from 'src/assets/icons/icon-difficulty-level.svg'
import { Button, FlagIconHowTos } from 'oa-components'
import type { IUser } from 'src/models/user.models'
import {
isAllowToEditContent,
emStringToPx,
capitalizeFirstLetter,
} from 'src/utils/helpers'
import theme from 'src/themes/styled.theme'
import ArrowIcon from 'src/assets/icons/icon-arrow-select.svg'
import { VerifiedUserBadge } from 'src/components/VerifiedUserBadge/VerifiedUserBadge'
import { UsefulStatsButton } from 'src/components/UsefulStatsButton/UsefulStatsButton'
import { DownloadExternal } from 'src/pages/Howto/DownloadExternal/DownloadExternal'
import Linkify from 'react-linkify'
import { Link } from 'react-router-dom'
import type { HowtoStore } from 'src/stores/Howto/howto.store'
import { inject, observer } from 'mobx-react'
import {
retrieveHowtoDownloadCooldown,
isHowtoDownloadCooldownExpired,
addHowtoDownloadCooldown,
updateHowtoDownloadCooldown,
} from './downloadCooldown'
interface IProps {
howto: IHowtoDB
loggedInUser: IUser | undefined
needsModeration: boolean
votedUsefulCount?: number
verified?: boolean
hasUserVotedUseful: boolean
moderateHowto: (accepted: boolean) => void
onUsefulClick: () => void
}
interface IInjected extends IProps {
howtoStore: HowtoStore
}
interface IState {
fileDownloadCount: number | undefined
}
@inject('howtoStore')
@observer
export default class HowtoDescription extends PureComponent<IProps, IState> {
// eslint-disable-next-line
constructor(props: IProps) {
super(props)
this.state = {
fileDownloadCount: this.props.howto.total_downloads || 0,
}
this.handleClick = this.handleClick.bind(this)
}
get injected() {
return this.props as IInjected
}
private setFileDownloadCount = (val: number) => {
this.setState({
fileDownloadCount: val,
})
}
private dateCreatedByText(howto: IHowtoDB): string {
return format(new Date(howto._created), 'DD-MM-YYYY')
}
private dateLastEditText(howto: IHowtoDB): string {
const lastModifiedDate = format(new Date(howto._modified), 'DD-MM-YYYY')
const creationDate = format(new Date(howto._created), 'DD-MM-YYYY')
if (lastModifiedDate !== creationDate) {
return 'Last edit on ' + format(new Date(howto._modified), 'DD-MM-YYYY')
} else {
return ''
}
}
private incrementDownloadCount = async () => {
const updatedDownloadCount =
await this.injected.howtoStore.incrementDownloadCount(
this.props.howto._id,
)
this.setFileDownloadCount(updatedDownloadCount!)
}
private handleClick = async () => {
const howtoDownloadCooldown = retrieveHowtoDownloadCooldown(
this.props.howto._id,
)
if (
howtoDownloadCooldown &&
isHowtoDownloadCooldownExpired(howtoDownloadCooldown)
) {
updateHowtoDownloadCooldown(this.props.howto._id)
this.incrementDownloadCount()
} else if (!howtoDownloadCooldown) {
addHowtoDownloadCooldown(this.props.howto._id)
this.incrementDownloadCount()
}
}
public render() {
const { howto, loggedInUser } = this.props
const iconFlexDirection =
emStringToPx(theme.breakpoints[0]) > window.innerWidth ? 'column' : 'row'
return (
<Flex
data-cy="how-to-basis"
data-id={howto._id}
className="howto-description-container"
sx={{
borderRadius: theme.radii[2] + 'px',
bg: 'white',
borderColor: theme.colors.black,
borderStyle: 'solid',
borderWidth: '2px',
overflow: 'hidden',
flexDirection: ['column-reverse', 'column-reverse', 'row'],
mt: 4,
}}
>
<Flex
px={4}
py={4}
sx={{
flexDirection: 'column',
width: ['100%', '100%', `${(1 / 2) * 100}%`],
}}
>
<Flex sx={{ justifyContent: 'space-between', flexWrap: 'wrap' }}>
<Link to={'/how-to/'}>
<Button
variant="subtle"
sx={{ fontSize: '14px' }}
data-cy="go-back"
>
<Flex>
<Image
loading="lazy"
sx={{
width: '10px',
marginRight: '4px',
transform: 'rotate(90deg)',
}}
src={ArrowIcon}
/>
<Text>Back</Text>
</Flex>
</Button>
</Link>
{this.props.votedUsefulCount !== undefined && (
<Box style={{ flexGrow: 1 }}>
<UsefulStatsButton
votedUsefulCount={this.props.votedUsefulCount}
hasUserVotedUseful={this.props.hasUserVotedUseful}
isLoggedIn={this.props.loggedInUser ? true : false}
onUsefulClick={this.props.onUsefulClick}
/>
</Box>
)}
{/* Check if pin should be moderated */}
{this.props.needsModeration && (
<Flex sx={{ justifyContent: 'space-between' }}>
<Button
data-cy={'accept'}
variant={'primary'}
icon="check"
mr={1}
onClick={() => this.props.moderateHowto(true)}
/>
<Button
data-cy="reject-howto"
variant={'tertiary'}
icon="delete"
onClick={() => this.props.moderateHowto(false)}
/>
</Flex>
)}
{/* Check if logged in user is the creator of the how-to OR a super-admin */}
{loggedInUser && isAllowToEditContent(howto, loggedInUser) && (
<Link to={'/how-to/' + this.props.howto.slug + '/edit'}>
<Button variant={'primary'} data-cy={'edit'}>
Edit
</Button>
</Link>
)}
</Flex>
<Box mt={3} mb={2}>
<Flex sx={{ alignItems: 'center' }}>
{howto.creatorCountry && (
<FlagIconHowTos code={howto.creatorCountry} />
)}
<Text
my={2}
ml={1}
sx={{ ...theme.typography.auxiliary, display: 'inline-block' }}
>
By{' '}
<Link
style={{
textDecoration: 'underline',
color: 'inherit',
}}
to={'/u/' + howto._createdBy}
>
{howto._createdBy}
</Link>{' '}
<VerifiedUserBadge
userId={howto._createdBy}
height="12px"
width="12px"
/>
| Published on {this.dateCreatedByText(howto)}
</Text>
</Flex>
<Text
sx={{
...theme.typography.auxiliary,
color: `${theme.colors.lightgrey} !important`,
}}
mt={1}
mb={2}
>
{this.dateLastEditText(howto)}
</Text>
<Heading mt={2} mb={1}>
{/* HACK 2021-07-16 - new howtos auto capitalize title but not older */}
{capitalizeFirstLetter(howto.title)}
</Heading>
<Text
sx={{ ...theme.typography.paragraph, whiteSpace: 'pre-line' }}
>
<Linkify properties={{ target: '_blank' }}>
{howto.description}
</Linkify>
</Text>
</Box>
<Flex mt="4">
<Flex mr="4" sx={{ flexDirection: iconFlexDirection }}>
<Image
loading="lazy"
src={StepsIcon}
height="16"
width="23"
mr="2"
mb="2"
/>
{howto.steps.length} steps
</Flex>
<Flex mr="4" sx={{ flexDirection: iconFlexDirection }}>
<Image
loading="lazy"
src={TimeNeeded}
height="16"
width="16"
mr="2"
mb="2"
/>
{howto.time}
</Flex>
<Flex mr="4" sx={{ flexDirection: iconFlexDirection }}>
<Image
loading="lazy"
src={DifficultyLevel}
height="15"
width="16"
mr="2"
mb="2"
/>
{howto.difficulty_level}
</Flex>
</Flex>
<Flex mt={4}>
{howto.tags &&
Object.keys(howto.tags).map((tag) => {
return <TagDisplay key={tag} tagKey={tag} />
})}
</Flex>
{((howto.files && howto.files.length > 0) || howto.fileLink) && (
<Flex
className="file-container"
mt={3}
sx={{ flexDirection: 'column' }}
>
{howto.fileLink && (
<DownloadExternal
handleClick={this.handleClick}
link={howto.fileLink}
/>
)}
{howto.files.map((file, index) => (
<FileInfo
allowDownload
file={file}
key={file ? file.name : `file-${index}`}
handleClick={this.handleClick}
/>
))}
{typeof this.state.fileDownloadCount === 'number' && (
<Text
sx={{
fontSize: '12px',
color: '#61646B',
paddingLeft: '8px',
}}
>
{this.state.fileDownloadCount}
{this.state.fileDownloadCount !== 1
? ' downloads'
: ' download'}
</Text>
)}
</Flex>
)}
</Flex>
<Flex
sx={{
width: ['100%', '100%', `${(1 / 2) * 100}%`],
position: 'relative',
justifyContent: 'end',
}}
>
<Image
loading="lazy"
sx={{
objectFit: 'cover',
width: 'auto',
height: '100%',
}}
src={howto.cover_image.downloadUrl}
crossOrigin=""
alt="how-to cover"
/>
{howto.moderation !== 'accepted' && (
<ModerationStatusText
moderatedContent={howto}
contentType="howto"
top={'0px'}
/>
)}
</Flex>
</Flex>
)
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.